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
#Skip to 7:55 in you already know jupyter notebook and you are just interested in the calibration.
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.5
notebook    :   7.0.3
matplotlib  :   3.7.2
ipympl      :   0.9.3
ipywidgets  :   8.1.0
[3]:
# The notebook interface (nbagg) is needed in jupyter-notebook while the widget is recommended for jupyer lab
# %matplotlib nbagg
# %matplotlib widget
# For the integration in the documentation, one uses `inline` to capture figures.
%matplotlib inline

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}")
WARNING:pyFAI.gui.matplotlib:matplotlib already loaded, setting its backend may not work
/home/jerome/.venv/py311/lib/python3.11/site-packages/pyopencl/cache.py:495: CompilerWarning: Non-empty compiler output encountered. Set the environment variable PYOPENCL_COMPILER_OUTPUT=1 to see more.
  _create_built_program_from_source_cached(
/home/jerome/.venv/py311/lib/python3.11/site-packages/pyopencl/cache.py:499: CompilerWarning: Non-empty compiler output encountered. Set the environment variable PYOPENCL_COMPILER_OUTPUT=1 to see more.
  prg.build(options_bytes, devices)
PyFAI version 2023.9.0-dev0
[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)
../../_images/usage_cookbook_calibration_with_jupyter_6_0.png
[6]:
%matplotlib widget
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.
[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-10 m
SampleDetDist= 1.634908e+00 m   PONI= 4.284469e-02, 3.164043e-02 m      rot1=0.000438  rot2=0.001574  rot3=0.000000 rad
DirectBeamDist= 1634.910 mm     Center: x=179.791, y=264.062 pix        Tilt= 0.094° tiltPlanRotation= 105.554° 𝛌= 1.000Å
Fixed parameters: ['wavelength', 'rot3']
Cost function: 1.7874710972552737e-07
[9]:
# re-extract all control points using the "massif" algorithm
calib.extract_cpt()
[10]:
# remove the last ring since it is outside the flight-tube
calib.remove_grp(lbl="f")
[11]:
# Switch back to `inline` mode to capture the last plot
%matplotlib inline
calib.peakPicker.widget.fig.show()
[12]:
#Those are some control points: the last column indicates the ring number
calib.geoRef.data[::100]
[12]:
array([[101.39385071, 170.99848121,   0.        ],
       [178.03264874,  40.75847282,   0.        ],
       [111.78569132, 236.20004116,   0.        ],
       [540.0697354 , 352.01612822,   1.        ],
       [685.57683897, 427.05572402,   2.        ],
       [449.77491727, 631.08768213,   2.        ],
       [574.8551335 , 752.95243961,   3.        ],
       [956.9840762 , 611.01895461,   4.        ]])
[13]:
# 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-10 m
SampleDetDist= 1.634908e+00 m   PONI= 4.284469e-02, 3.164043e-02 m      rot1=0.000438  rot2=0.001574  rot3=0.000000 rad
DirectBeamDist= 1634.910 mm     Center: x=179.791, y=264.062 pix        Tilt= 0.094° tiltPlanRotation= 105.554° 𝛌= 1.000Å
Fixed parameters: ['wavelength', 'rot3']
Cost function: 9.850905927467979e-07
[14]:
# 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()}")
Detector Pilatus 1M      PixelSize= 1.720e-04, 1.720e-04 m
Wavelength= 1.000000e-10 m
SampleDetDist= 1.635074e+00 m   PONI= 4.542393e-02, 3.093443e-02 m      rot1=0.000000  rot2=0.000000  rot3=0.000000 rad
DirectBeamDist= 1635.074 mm     Center: x=179.851, y=264.093 pix        Tilt= 0.000° tiltPlanRotation= 0.000° 𝛌= 1.000Å
Cost function = 9.618116512980923e-07
[15]:
gr.save("jupyter.poni")
gr.get_config()
[15]:
OrderedDict([('poni_version', 2),
             ('detector', 'Pilatus1M'),
             ('detector_config', OrderedDict()),
             ('dist', 1.6350736095095169),
             ('poni1', 0.04542392938641168),
             ('poni2', 0.030934426881186416),
             ('rot1', 0.0),
             ('rot2', 0.0),
             ('rot3', 0.0),
             ('wavelength', 1e-10)])
[16]:
# Create a "normal" azimuthal integrator (without fitting capabilities from the geometry-refinement object)
ai = pyFAI.load(gr)
ai
[16]:
Detector Pilatus 1M      PixelSize= 1.720e-04, 1.720e-04 m
Wavelength= 1.000000e-10 m
SampleDetDist= 1.635074e+00 m   PONI= 4.542393e-02, 3.093443e-02 m      rot1=0.000000  rot2=0.000000  rot3=0.000000 rad
DirectBeamDist= 1635.074 mm     Center: x=179.851, y=264.093 pix        Tilt= 0.000° tiltPlanRotation= 0.000° 𝛌= 1.000Å
[17]:
# 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")
../../_images/usage_cookbook_calibration_with_jupyter_18_0.png
../../_images/usage_cookbook_calibration_with_jupyter_18_1.png

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.