Calibration of a diffraction setup using Jupyter notebooks

This notebook presents a very simple GUI for doing the calibration of diffraction setup within the Jupyter lab or notebook environment with Matplotlib and Ipywidgets. It has been tested with widget and the notebook (aka nbagg) integration of matplotlib.

Despite this is in the cookbook section, this tutorial requires advanced Python programming knowledge and some good understanding of PyFAI.

This tutorial is also available as a video:

[1]:
#Video of this tutorial
from IPython.display import Video

Video("http://www.silx.org/pub/pyFAI/video/Calibration_Jupyter.mp4", width=800)
[1]:

The basic idea is to port directly the original pyFAI-calib tool which was done with matplotlib into the Jupyter notebooks. Most credits go Philipp Hans for the adaptation of the origin PeakPicker class to Jupyter.

The PeakPicker widget has been refactored and the Calibration tool adapted for the notebook usage. Several external tools were used with the following version:

[2]:
for lib in ["jupyterlab", "notebook", "matplotlib", "ipympl", "ipywidgets"]:
    mod = __import__(lib)
    print(f"{lib:12s}:   {mod.__version__}")
jupyterlab  :   4.0.0a15
notebook    :   6.4.0
matplotlib  :   3.5.1
ipympl      :   0.8.7
ipywidgets  :   7.6.5
[3]:
#%matplotlib nbagg
# The notebook interface (nbagg) is needed in jupyter-notebook while the widget is recommended for jupyer lab
%matplotlib widget

import pyFAI
import pyFAI.test.utilstest
import fabio
from matplotlib.pyplot import subplots
from pyFAI.gui import jupyter
from pyFAI.gui.jupyter.calib import Calibration

print(f"PyFAI version {pyFAI.version}")
matplotlib already loaded, setting its backend may not work
Note: NumExpr detected 12 cores but "NUMEXPR_MAX_THREADS" not set, so enforcing safe limit of 8.
NumExpr defaulting to 8 threads.
Degrading method from Method(dim=1, split='pseudo', algo='histogram', impl='*', target=None) -> Method(dim=1, split='bbox', algo='histogram', impl='*', target=None)
PyFAI version 0.22.0-dev4
[4]:
# Some parameters like the wavelength, the calibrant and the diffraction image:
wavelength = 1e-10
pilatus = pyFAI.detector_factory("Pilatus1M")
AgBh = pyFAI.calibrant.CALIBRANT_FACTORY("AgBh")
AgBh.wavelength = wavelength

#load some test data (requires an internet connection)
img = fabio.open(pyFAI.test.utilstest.UtilsTest.getimage("Pilatus1M.edf")).data
[5]:
# Simply display the scattering image:
_ = jupyter.display(img)
[6]:
calib = Calibration(img, calibrant=AgBh, wavelength=wavelength, detector=pilatus)
# This displays the calibration widget:

# 1. Set the ring number (0-based value), below the plot
# 2. Pick the ring by right-clicking with the mouse on the image.
# 3. Restart at 1. for at least a second ring
# 4. Click refine to launch the calibration.
Image size is (1043, 981)
Binning size is [1, 1]
[7]:
# Here is a screenshot of the previous widget, since it is not recoreded inside the notebook itself.
from IPython.display import Image
Image(filename='pyFAI-calib_notebook.png')
[7]:
../../_images/usage_cookbook_calibration_with_jupyter_8_0.png
[8]:
# This is the calibrated geometry:
gr = calib.geoRef
print(gr)
print(f"Fixed parameters: {calib.fixed}")
print(f"Cost function: {gr.chi2()}")
Detector Pilatus 1M      PixelSize= 1.720e-04, 1.720e-04 m
Wavelength= 1.000000e-10m
SampleDetDist= 1.633021e+00m    PONI= 1.189716e-01, 3.567691e-02m       rot1=0.002895  rot2= -0.044975  rot3= 0.000000 rad
DirectBeamDist= 1634.680mm      Center: x=179.937, y=264.404 pix        Tilt=2.582 deg  tiltPlanRotation= -93.681 deg
Fixed parameters: ['wavelength', 'rot3']
Cost function: 1.4594989592020997e-07
[11]:
# re-extract all control points using the "massif" algorithm
calib.extract_cpt()
in extract_cpt with method massif
Extracting datapoint for ring 0 (2theta = 0.98 deg); searching for 315 pts out of 7245 with I>8684.3, dmin=1.2
Extracting datapoint for ring 1 (2theta = 1.96 deg); searching for 166 pts out of 7738 with I>1454.6, dmin=2.5
Extracting datapoint for ring 2 (2theta = 2.94 deg); searching for 141 pts out of 9746 with I>861.0, dmin=3.8
Extracting datapoint for ring 3 (2theta = 3.93 deg); searching for 127 pts out of 11332 with I>319.7, dmin=5.0
Extracting datapoint for ring 4 (2theta = 4.91 deg); searching for 71 pts out of 7966 with I>232.4, dmin=5.8
Extracting datapoint for ring 5 (2theta = 5.89 deg); searching for 18 pts out of 6211 with I>0.9, dmin=1.8
[12]:
# remove the last ring since it is outside the flight-tube
calib.remove_grp(lbl="f")
[13]:
#Those are all control points: the last column indicates the ring number
calib.geoRef.data
[13]:
array([[320.98028564, 331.94351196,   0.        ],
       [399.65749097,  90.05865168,   0.        ],
       [426.02423096, 171.99751282,   0.        ],
       ...,
       [681.97485011, 880.91110347,   4.        ],
       [926.2619338 , 656.99508867,   4.        ],
       [475.91918227, 967.10317159,   4.        ]])
[14]:
# This is the geometry with all rings defined:
gr = calib.geoRef
print(gr)
print(f"Fixed parameters: {calib.fixed}")
print(f"Cost function: {gr.chi2()}")
Detector Pilatus 1M      PixelSize= 1.720e-04, 1.720e-04 m
Wavelength= 1.000000e-10m
SampleDetDist= 1.633021e+00m    PONI= 1.189716e-01, 3.567691e-02m       rot1=0.002895  rot2= -0.044975  rot3= 0.000000 rad
DirectBeamDist= 1634.680mm      Center: x=179.937, y=264.404 pix        Tilt=2.582 deg  tiltPlanRotation= -93.681 deg
Fixed parameters: ['wavelength', 'rot3']
Cost function: 5.2018969688769325e-06
[15]:
# Geometry refinement with some constrains: SAXS mode
# Here we enforce all rotation to be null and fit again the model:

gr.rot1 = gr.rot2 = gr.rot3 = 0
gr.refine3(fix=["rot1", "rot2", "rot3", "wavelength"])
print(gr)
print(f"Cost function = {gr.chi2()}")
Constrained Least square 0.000817615810230828 --> 1.2514266878612578e-09
maxdelta on poni1: 0.1189716010947584 --> 0.04541993175349841
Optimization terminated successfully    (Exit mode 0)
            Current function value: 9.185471888901632e-07
            Iterations: 12
            Function evaluations: 53
            Gradient evaluations: 12
Detector Pilatus 1M      PixelSize= 1.720e-04, 1.720e-04 m
Wavelength= 1.000000e-10m
SampleDetDist= 1.635029e+00m    PONI= 4.541993e-02, 3.093459e-02m       rot1=0.000000  rot2= 0.000000  rot3= 0.000000 rad
DirectBeamDist= 1635.029mm      Center: x=179.852, y=264.069 pix        Tilt=0.000 deg  tiltPlanRotation= 0.000 deg
Cost function = 9.185471888901632e-07
[16]:
gr.save("jupyter.poni")
gr.get_config()
[16]:
OrderedDict([('poni_version', 2),
             ('detector', 'Pilatus1M'),
             ('detector_config', OrderedDict()),
             ('dist', 1.635028692166198),
             ('poni1', 0.04541993175349841),
             ('poni2', 0.03093458593390723),
             ('rot1', 0.0),
             ('rot2', 0.0),
             ('rot3', 0.0),
             ('wavelength', 1e-10)])
[17]:
# Create a "normal" azimuthal integrator (without fitting capabilities from the geometry-refinement object)
ai = pyFAI.load(gr)
ai
Unable to parse Detector Pilatus 1M      PixelSize= 1.720e-04, 1.720e-04 m
Wavelength= 1.000000e-10m
SampleDetDist= 1.635029e+00m    PONI= 4.541993e-02, 3.093459e-02m       rot1=0.000000  rot2= 0.000000  rot3= 0.000000 rad
DirectBeamDist= 1635.029mm      Center: x=179.852, y=264.069 pix        Tilt=0.000 deg  tiltPlanRotation= 0.000 deg as JSON file, defaulting to PoniParser
[17]:
Detector Pilatus 1M  PixelSize= 1.720e-04, 1.720e-04 m
Wavelength= 1.000000e-10m
SampleDetDist= 1.635029e+00m        PONI= 4.541993e-02, 3.093459e-02m       rot1=0.000000  rot2= 0.000000  rot3= 0.000000 rad
DirectBeamDist= 1635.029mm  Center: x=179.852, y=264.069 pix        Tilt=0.000 deg  tiltPlanRotation= 0.000 deg
[18]:
# Display the integrated data to validate the calibration.
fig, ax = subplots(1, 2, figsize=(10, 5))
jupyter.plot1d(ai.integrate1d(img, 1000),  calibrant=AgBh, ax=ax[0])
jupyter.plot2d(ai.integrate2d(img, 1000),  calibrant=AgBh, ax=ax[1])
_ = ax[1].set_title("2D integration")
AI.integrate1d_ng: Resetting Cython integrator because of first initialization

Conclusion

This short notebook shows how to interact with a calibration image to pick some control-point from the Debye-Scherrer ring and to perform the calibration of the experimental setup.