{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Example 3: Export to NeXus\n",
    "This is an example showcasing the loading of a tilt map Fermi surface mapping\n",
    "\n",
    "The band dispersion is loaded as a xarray dataframe following a conversion to the [NXmpes_arpes NeXus format](https://manual.nexusformat.org/classes/contributed_definitions/NXmpes.html#nxmpes) using the [FAIRmat pynxtools](https://github.com/FAIRMAT-nfdi/pynxtools)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "First, the SpecsScan class is imported which has the scan loader as its class method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "%load_ext autoreload\n",
    "%autoreload 2\n",
    "from specsscan import SpecsScan\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "%matplotlib widget"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Definition of manual scan metadata. These should ideally come from an Electronic Lab Notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "metadata = {}\n",
    "#General\n",
    "metadata['experiment_summary'] = 'TbTe3 tilt map around EF with 800nm pump at 20fs after pump-probe overlap'\n",
    "metadata['entry_title'] = 'TbTe3 XUV Fermi surface map at 20 fs'\n",
    "metadata['experiment_title'] = 'TbTe3 XUV Fermi surface map at 20 fs'\n",
    "\n",
    "#User\n",
    "# Fill general parameters of NXuser\n",
    "metadata['user0'] = {}\n",
    "metadata['user0']['name'] = 'Laurenz Rettig'\n",
    "metadata['user0']['role'] = 'Principal Investigator'\n",
    "metadata['user0']['affiliation'] = 'Fritz Haber Institute of the Max Planck Society'\n",
    "metadata['user0']['address'] = 'Faradayweg 4-6, 14195 Berlin'\n",
    "metadata['user0']['email'] = 'rettig@fhi-berlin.mpg.de'\n",
    "\n",
    "metadata['instrument'] = {}\n",
    "# energy resolution\n",
    "metadata['instrument']['energy_resolution'] = 150.\n",
    "metadata['instrument']['electronanalyzer'] = {}\n",
    "metadata['instrument']['electronanalyzer']['energy_resolution'] = 120.\n",
    "metadata['instrument']['electronanalyzer']['angular_resolution'] = 0.2\n",
    "metadata['instrument']['electronanalyzer']['spatial_resolution'] = 0.5\n",
    "metadata['instrument']['electronanalyzer']['slit_shape'] = \"curved slit\"\n",
    "metadata['instrument']['electronanalyzer']['slit_size'] = 1.0\n",
    "#probe beam\n",
    "metadata['instrument']['beam']={}\n",
    "metadata['instrument']['beam']['probe']={}\n",
    "metadata['instrument']['beam']['probe']['incident_energy'] = 21.7\n",
    "metadata['instrument']['beam']['probe']['incident_energy_spread'] = 0.11\n",
    "metadata['instrument']['beam']['probe']['pulse_duration'] = 20.\n",
    "metadata['instrument']['beam']['probe']['frequency'] = 500.\n",
    "metadata['instrument']['beam']['probe']['incident_polarization'] = [1, 1, 0, 0] # p pol Stokes vector\n",
    "metadata['instrument']['beam']['probe']['extent'] = [80., 80.]\n",
    "#pump beam\n",
    "metadata['instrument']['beam']['pump']={}\n",
    "metadata['instrument']['beam']['pump']['incident_energy'] = 1.55\n",
    "metadata['instrument']['beam']['pump']['incident_energy_spread'] = 0.08\n",
    "metadata['instrument']['beam']['pump']['pulse_duration'] = 35.\n",
    "metadata['instrument']['beam']['pump']['frequency'] = 500.\n",
    "metadata['instrument']['beam']['pump']['incident_polarization'] = [1, -1, 0, 0] # s pol Stokes vector\n",
    "metadata['instrument']['beam']['pump']['incident_wavelength'] = 800.\n",
    "metadata['instrument']['beam']['pump']['average_power'] = 224.\n",
    "metadata['instrument']['beam']['pump']['pulse_energy'] = metadata['instrument']['beam']['pump']['average_power']/metadata['instrument']['beam']['pump']['frequency']#µJ\n",
    "metadata['instrument']['beam']['pump']['extent'] = [300/4*2.34, 270/4*2.35] #Gaussian 4sigma -> FWHM\n",
    "metadata['instrument']['beam']['pump']['fluence'] = 1.00\n",
    "metadata['instrument']['beam']['pump']['delay'] = 0.02\n",
    "\n",
    "#sample\n",
    "metadata['sample']={}\n",
    "metadata['sample']['preparation_date'] = '2017-03-19T10:00:00+00:00'\n",
    "metadata['sample']['preparation_description'] = 'Cleaved'\n",
    "metadata['sample']['sample_history'] = 'Cleaved in UHV'\n",
    "metadata['sample']['chemical_formula'] = 'TbTe3'\n",
    "metadata['sample']['description'] = 'cleaved single crystal of TbTe3'\n",
    "metadata['sample']['name'] = 'TbTe3 Single Crystal'\n",
    "\n",
    "metadata[\"scan_info\"] = {}\n",
    "metadata[\"scan_info\"][\"trARPES:XGS600:PressureAC:P_RD\"] = 2.5E-11\n",
    "metadata[\"scan_info\"][\"trARPES:Carving:TEMP_RBV\"] = 70.\n",
    "metadata[\"scan_info\"][\"trARPES:Sample:Measure\"] = 0.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The SpecsScan instance is created from a config, that contains a rewrite entry to change names of axes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "config = {\"nexus\":{\"definition\": \"NXmpes_arpes\"}, \"spa_params\":{\"crop\":True, \"ek_range_min\":0.07597844332538181, \"ek_range_max\":0.9117413199045858, \"ang_range_min\":0.16453159041394336, \"ang_range_max\":0.8840087145969499,}}\n",
    "sps = SpecsScan(config=config, user_config=\"../src/specsscan/config/example_config_FHI.yaml\", system_config={})\n",
    "path = \"../tests/data/\" # Path to the test data set"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The load_scan method loads the scan as an xarray along with the metadata needed for nexus conversion."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "res_xarray = sps.load_scan(\n",
    "    scan=1496, # Tilt scan\n",
    "    path=path,\n",
    "    metadata=metadata,\n",
    "    collect_metadata=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The resulting 3-dimensional data cube"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "res_xarray.dims"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A Gamma-point cut"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "plt.figure()\n",
    "res_xarray[:,30,:].T.plot()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The Fermi surface"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "plt.figure()\n",
    "res_xarray.loc[{\"energy\":slice(21.6, 21.8)}].sum(axis=2).plot()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Save as nexus file"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "sps.save(\"FSmapping.nxs\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}