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:
[1]:
for lib in ["jupyterlab", "notebook", "matplotlib", "ipympl", "ipywidgets"]:
mod = __import__(lib)
print(f"{lib:12s}: {mod.__version__}")
jupyterlab : 3.5.1
notebook : 6.5.2
matplotlib : 3.6.2
ipympl : 0.9.2
ipywidgets : 8.0.3
[2]:
#%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}")
WARNING:pyFAI.gui.matplotlib:matplotlib already loaded, setting its backend may not work
PyFAI version 0.21.3
[3]:
# 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
[4]:
# Simply display the scattering image:
_ = jupyter.display(img)
[5]:
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.
[6]:
# 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')
[6]:

[7]:
# 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.631039e+00m PONI= 5.885398e-02, -6.616794e-02m rot1=-0.059422 rot2= -0.008206 rot3= 0.000000 rad
DirectBeamDist= 1633.978mm Center: x=179.449, y=264.220 pix Tilt=3.437 deg tiltPlanRotation= -7.867 deg
Fixed parameters: ['wavelength', 'rot3']
Cost function: 1.0592137366470408e-07
[8]:
# re-extract all control points using the "massif" algorithm
calib.extract_cpt()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-3ab7187d6eca> in <module>
1 # re-extract all control points using the "massif" algorithm
----> 2 calib.extract_cpt()
~/.venv/py38/lib/python3.8/site-packages/pyFAI/gui/cli_calibration.py in extract_cpt(self, method, pts_per_deg)
703 _res = self.peakPicker.peaks_from_area(mask=mask2, Imin=upper_limit, keep=keep, method=method, ring=i, dmin=dist_min, seed=seeds)
704
--> 705 self.peakPicker.points.save(self.basename + ".npt")
706 if self.weighted:
707 self.data = self.peakPicker.points.getWeightedList(self.peakPicker.data)
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
[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.