{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Integration with Python\n",
    "\n",
    "This cookbook explains you how to perform azimuthal integration using the Python interpreter.\n",
    "It is divided in two parts, the first part uses purely Python while the second uses some advanced features of the Jupyter notebook.\n",
    "\n",
    "We will re-use the same files as in the other tutorials.\n",
    "\n",
    "## Performing azimuthal integration with pyFAI of a bunch of images\n",
    "\n",
    "To be able to perform the azimuthal integration of some images, one needs:\n",
    "\n",
    "* The diffraction images themselves, in this example they are stored as TIFF files\n",
    "* The geometry of the experimental setup as obtained from the calibration and stored as a PONI-file\n",
    "* other files like flat-field, dark current images or detector distortion file (spline-file).\n",
    "\n",
    "Image file: http://www.silx.org/pub/pyFAI/cookbook/calibration/LaB6_29.4keV.tif\n",
    "\n",
    "Detector distortion file: http://www.silx.org/pub/pyFAI/cookbook/calibration/F_K4320T_Cam43_30012013_distorsion.spline\n",
    "\n",
    "The calibration has been performed in the previous cookbook. The geometry is saved in \"LaB6_29.4keV.poni\".\n",
    "\n",
    "### Basic usage of pyFAI\n",
    "To perform azimuthal averaging, one can use pyFAI to load the geometry and FabIO to read the image:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "image_file: /tmp/pyFAI_testdata_jerome/LaB6_29.4keV.tif\n",
      "poni_file: /tmp/pyFAI_testdata_jerome/LaB6_29.4keV.poni\n",
      "spline_file: /tmp/pyFAI_testdata_jerome/F_K4320T_Cam43_30012013_distorsion.spline\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "['F_K4320T_Cam43_30012013_distorsion.spline',\n",
       " 'integration_with_scripts.ipynb',\n",
       " 'integration_with_python.ipynb',\n",
       " 'LaB6_29.4keV.tif',\n",
       " 'integration_with_the_gui.rst',\n",
       " '.ipynb_checkpoints',\n",
       " 'calib-gui',\n",
       " 'pyFAI-integrate.png',\n",
       " 'index.rst',\n",
       " 'calib-cli',\n",
       " 'LaB6_29.4keV.poni']"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# This cell is just to download the files to perform the analysis:\n",
    "from silx.resources import ExternalResources\n",
    "downloader = ExternalResources(\"pyFAI\", \"http://www.silx.org/pub/pyFAI/cookbook/calibration/\", \"PYFAI_DATA\")\n",
    "image_file = downloader.getfile(\"LaB6_29.4keV.tif\")\n",
    "spline_file = downloader.getfile(\"F_K4320T_Cam43_30012013_distorsion.spline\")\n",
    "poni_file = downloader.getfile(\"LaB6_29.4keV.poni\")\n",
    "\n",
    "print(\"image_file:\", image_file)\n",
    "print(\"poni_file:\", poni_file)\n",
    "print(\"spline_file:\", spline_file)\n",
    "\n",
    "# Copy all files locally\n",
    "import shutil, os\n",
    "shutil.copy(spline_file, \".\")\n",
    "shutil.copy(poni_file, \".\")\n",
    "shutil.copy(image_file, \".\")\n",
    "os.listdir()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "pyFAI version: 0.20.0-dev0\n",
      "image: <fabio.edfimage.EdfImage object at 0x7f6cfc0f2970>\n",
      "\n",
      "Integrator: \n",
      " Detector Detector\t Spline= /home/jerome/workspace-ssd/pyFAI/doc/source/usage/cookbook/F_K4320T_Cam43_30012013_distorsion.spline\t PixelSize= 5.168e-05, 5.126e-05 m\n",
      "Wavelength= 4.217150e-11m\n",
      "SampleDetDist= 1.181795e-01m\tPONI= 5.396318e-02, 5.540257e-02m\trot1=0.006087  rot2= -0.008146  rot3= 0.000000 rad\n",
      "DirectBeamDist= 118.186mm\tCenter: x=1066.678, y=1025.571 pix\tTilt=0.583 deg  tiltPlanRotation= -126.767 deg\n"
     ]
    }
   ],
   "source": [
    "import pyFAI, fabio\n",
    "print(\"pyFAI version:\", pyFAI.version)\n",
    "img = fabio.open(\"LaB6_29.4keV.tif\")\n",
    "print(\"image:\", img)\n",
    "\n",
    "ai = pyFAI.load(\"LaB6_29.4keV.poni\")\n",
    "print(\"\\nIntegrator: \\n\", ai)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Azimuthal averaging using pyFAI\n",
    "\n",
    "\n",
    "One needs first to retrieve the image as a numpy array. This allows to use other libraries than FabIO for image reading, for example HDF5.\n",
    "\n",
    "This shows how to perform the azimuthal integration of one image over 1000 bins:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "img_array: <class 'numpy.ndarray'> (2048, 2048) float32\n"
     ]
    }
   ],
   "source": [
    "img_array = img.data\n",
    "print(\"img_array:\", type(img_array), img_array.shape, img_array.dtype)\n",
    "\n",
    "res = ai.integrate1d_ng(img_array, \n",
    "                     1000, \n",
    "                     unit=\"2th_deg\", \n",
    "                     filename=\"integrated.dat\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "*Note:* There are 2 mandatory parameters for this method: the 2D-numpy array with the image and the number of bins. In addition, we specified the name of the file where to save the data and the unit for performing the integration.\n",
    "\n",
    "There are many other options of `integrate1d`. The difference between the `legacy` and the `ng` flavor is mostly on the way error is propagated:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on method integrate1d_ng in module pyFAI.azimuthalIntegrator:\n",
      "\n",
      "integrate1d_ng(data, npt, filename=None, correctSolidAngle=True, variance=None, error_model=None, radial_range=None, azimuth_range=None, mask=None, dummy=None, delta_dummy=None, polarization_factor=None, dark=None, flat=None, method='csr', unit=q_nm^-1, safe=True, normalization_factor=1.0, metadata=None) method of pyFAI.azimuthalIntegrator.AzimuthalIntegrator instance\n",
      "    Calculate the azimuthal integration (1d) of a 2D image.\n",
      "    \n",
      "    Multi algorithm implementation (tries to be bullet proof), suitable for SAXS, WAXS, ... and much more\n",
      "    Takes extra care of normalization and performs proper variance propagation.\n",
      "    \n",
      "    :param ndarray data: 2D array from the Detector/CCD camera\n",
      "    :param int npt: number of points in the output pattern\n",
      "    :param str filename: output filename in 2/3 column ascii format\n",
      "    :param bool correctSolidAngle: correct for solid angle of each pixel if True \n",
      "    :param ndarray variance: array containing the variance of the data. \n",
      "    :param str error_model: When the variance is unknown, an error model can be given: \"poisson\" (variance = I), \"azimuthal\" (variance = (I-<I>)^2)\n",
      "    :param radial_range: The lower and upper range of the radial unit. If not provided, range is simply (min, max). Values outside the range are ignored.\n",
      "    :type radial_range: (float, float), optional\n",
      "    :param azimuth_range: The lower and upper range of the azimuthal angle in degree. If not provided, range is simply (min, max). Values outside the range are ignored.\n",
      "    :type azimuth_range: (float, float), optional\n",
      "    :param ndarray mask: array with  0 for valid pixels, all other are masked (static mask)\n",
      "    :param float dummy: value for dead/masked pixels (dynamic mask)\n",
      "    :param float delta_dummy: precision for dummy value \n",
      "    :param float polarization_factor: polarization factor between -1 (vertical) and +1 (horizontal).\n",
      "           0 for circular polarization or random,\n",
      "           None for no correction,\n",
      "           True for using the former correction \n",
      "    :param ndarray dark: dark noise image\n",
      "    :param ndarray flat: flat field image\n",
      "    :param IntegrationMethod method: IntegrationMethod instance or 3-tuple with (splitting, algorithm, implementation)\n",
      "    :param Unit unit: Output units, can be \"q_nm^-1\" (default), \"2th_deg\", \"r_mm\" for now.\n",
      "    :param bool safe: Perform some extra checks to ensure LUT/CSR is still valid. False is faster.\n",
      "    :param float normalization_factor: Value of a normalization monitor \n",
      "    :param metadata: JSON serializable object containing the metadata, usually a dictionary.\n",
      "    :return: Integrate1dResult namedtuple with (q,I,sigma) +extra informations in it.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(ai.integrate1d_ng)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The result file contains the integrated data with some headers as shown:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "# == pyFAI calibration ==\n",
      "# Distance Sample to Detector: 0.11817947569514631 m\n",
      "# PONI: 5.396e-02, 5.540e-02 m\n",
      "# Rotations: 0.006087 -0.008146 0.000000 rad\n",
      "#\n",
      "# == Fit2d calibration ==\n",
      "# Distance Sample-beamCenter: 118.186 mm\n",
      "# Center: x=1066.678, y=1025.571 pix\n",
      "# Tilt: 0.583 deg  TiltPlanRot: -126.767 deg\n",
      "#\n",
      "# Detector Detector\t Spline= /home/jerome/workspace-ssd/pyFAI/doc/source/usage/cookbook/F_K4320T_Cam43_30012013_distorsion.spline\t PixelSize= 5.168e-05, 5.126e-05 m\n",
      "#    Detector has a mask: False\n",
      "#    Detector has a dark current: False\n",
      "#    detector has a flat field: False\n",
      "#\n",
      "# Wavelength: 4.2171495713063666e-11 m\n",
      "# Mask applied: False\n",
      "# Dark current applied: False\n",
      "# Flat field applied: False\n",
      "# Polarization factor: None\n",
      "# Normalization factor: 1.0\n",
      "# --> integrated.dat\n",
      "#       2th_deg             I\n",
      "1.668236e-02    2.742900e+00\n",
      "5.004708e-02    2.763848e+00\n",
      "8.341179e-02    2.027442e+00\n",
      "1.167765e-01    2.828011e+00\n",
      "1.501412e-01    2.858763e+00\n",
      "1.835059e-01    2.676350e+00\n",
      "2.168707e-01    2.498867e+00\n",
      "2.502354e-01    2.823360e+00\n",
      "2.836001e-01    2.751559e+00\n",
      "3.169648e-01    2.811984e+00\n",
      "3.503295e-01    2.864720e+00\n",
      "3.836942e-01    2.790825e+00\n",
      "4.170590e-01    3.016620e+00\n",
      "4.504237e-01    3.085335e+00\n",
      "4.837884e-01    3.127223e+00\n",
      "5.171531e-01    3.036244e+00\n",
      "5.505178e-01    3.003195e+00\n",
      "5.838825e-01    3.027816e+00\n",
      "6.172473e-01    2.930266e+00\n",
      "6.506120e-01    3.160503e+00\n",
      "6.839767e-01    3.101102e+00\n",
      "7.173414e-01    2.905696e+00\n",
      "7.507061e-01    3.072507e+00\n",
      "7.840708e-01    3.025450e+00\n",
      "8.174356e-01    2.891899e+00\n",
      "8.508003e-01    2.989683e+00\n",
      "8.841650e-01    3.104964e+00\n"
     ]
    }
   ],
   "source": [
    "with open(\"integrated.dat\") as f:\n",
    "    for i in range(50):\n",
    "        print(f.readline().strip())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Azimuthal regrouping using pyFAI\n",
    "\n",
    "This option is similar to the integration but performs N integrations on various azimuthal angle (chi) sections of the space. It is also named \"caking\" in Fit2D.\n",
    "\n",
    "The azimuthal regrouping of an image over 500 radial bins in 360 angular steps (of 1 degree) can be performed like this:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "ename": "AttributeError",
     "evalue": "'AzimuthalIntegrator' object has no attribute 'integrate2d_ng'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mAttributeError\u001b[0m                            Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-6-8ac1187c71bf>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m res2 = ai.integrate2d_ng(img_array, \n\u001b[0m\u001b[1;32m      2\u001b[0m                       \u001b[0;36m500\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m360\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      3\u001b[0m                      \u001b[0munit\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m\"r_mm\"\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      4\u001b[0m                      filename=\"integrated.edf\")\n",
      "\u001b[0;31mAttributeError\u001b[0m: 'AzimuthalIntegrator' object has no attribute 'integrate2d_ng'"
     ]
    }
   ],
   "source": [
    "res2 = ai.integrate2d_ng(img_array, \n",
    "                      500, 360, \n",
    "                     unit=\"r_mm\", \n",
    "                     filename=\"integrated.edf\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cake = fabio.open(\"integrated.edf\")\n",
    "print(cake.header)\n",
    "print(\"cake:\", type(cake.data), cake.data.shape, cake.data.dtype)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "From this, it is trivial to perform a loop and integrate many images. \n",
    "\n",
    "*Attention:* The AzimuthalIntegrator object (called `ai` here) is rather large and costly to initialize. The best practice is to create it once and to use it many times, like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import glob, os\n",
    "\n",
    "all_images = glob.glob(\"LaB6*.tif\")\n",
    "ai = pyFAI.load(\"LaB6_29.4keV.poni\")\n",
    "\n",
    "for one_image in all_images:\n",
    "    fimg = fabio.open(one_image)\n",
    "    dest = os.path.splitext(one_image)[0] + \".dat\"\n",
    "    ai.integrate1d_ng(fimg.data, \n",
    "                   1000, \n",
    "                   unit=\"2th_deg\", \n",
    "                   filename=dest)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Using some advanced features of Jupyter Notebooks\n",
    "\n",
    "Jupyter notebooks offer some advanced visualization features, especially when used with *matplotlib* and *pyFAI*.\n",
    "Unfortunately, the example shown hereafter will not work properly in normal Python scipts.\n",
    "\n",
    "### Initialization of the notebook for matplotlib integration:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pyFAI.gui import jupyter"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Visualization of different types of results previously calculated"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "jupyter.display(img.data, label=img.filename)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "jupyter.plot1d(res)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "jupyter.plot2d(res2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Side note\n",
    "If you have tried to reproduce this, you may have noticed a couple of inconsistencies: \n",
    "\n",
    "* The image is called \"tif\" while the content is an \"edf\".\n",
    "* The caked image has wavy lines meaning the calibration is far from perfect.\n",
    "\n",
    "The first issue may be corrected by uploading a properly converted image. \n",
    "The second issue is related to the provided spline file which was wrong (actually it is flipped up-down).\n",
    "\n",
    "## Conclusion\n",
    "\n",
    "This cookbook explains the basic usage of pyFAI as a Python library for azimuthal integration and simple visualization in the Jupyter notebook."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "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.9.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
