This project provides a graphical user interface (GUI) for running fixed-exit calibrations on double-crystal monochromators (DCMs), intended for on-site use by beamline operators. The GUI initializes the DCM and a visualization system (e.g. an X-ray eye or camera), acquires target centroids, and performs automated calibration routines to determine polynomial relations for gap, pitch, and roll as functions of the Bragg angle.
⚠️ WARNING: This repository is not distributed as a ready-to-run application.Cloning the repository and installing its Python dependencies are not sufficient to operate the GUI. The code depends on beamline-specific implementations of the DCM and beam visualization system control interfaces.
Before the application can be used, the supplied interfaces must be adapted to the hardware and control architecture of the target beamline, including:
- the DCM gap, pitch, roll, and Bragg angle coordinates;
- the image-acquisition and beam-centroid determination procedures;
- the corresponding EPICS process variables;
- the motion conventions, limits, status signals, and synchronization logic.
git clone https://gitlab.cnpem.br/OPT/commissioning/fixed-exit.git
cd fixed-exitThe application requires:
- Python: version ≥ 3.10 and < 3.11
- EPICS runtime environment properly configured, including variables such as
EPICS_CA_ADDR_LIST
Required Python packages:
PyQt6numpyscipymatplotlibpandasipython
Adapt the control interfaces to the target DCM and visualization system. The supplied code should be treated as a reference implementation of the GUI structure and calibration workflow, not as a universal hardware-control implementation.
Before using the application for calibration, verify all process-variable mappings, coordinate signs, motion limits, image-acquisition procedures, and centroid calculations in a controlled test environment.
⚠️ CAUTION: Do not connect the application to operational hardware before these interfaces have been implemented and validated. Incorrect mappings, motion conventions, or limits may produce unintended DCM movements or invalid calibration results.
Only after the beamline-specific interfaces have been implemented and validated, launch the application with:
python gui.pyThe fixed-exit calibration procedure implemented in this GUI follows a structured workflow designed to be executed sequentially through the GUI tabs:
-
Initialization
The DCM and the visualization system are initialized using the provided PV prefixes. Device readbacks are checked to ensure that communication is established before proceeding. -
Target Centroid
Reference centroids are acquired at low and high energies using the visualization system. These measurements are used to define a target fixed-exit position, computed as the average centroid. -
Calibration Setup
The user defines the calibration mode (automated search of optimal short-stroke parameters, or manual mode — not yet implemented), selects whether to use preliminary calibration polynomials loaded from file or the currently embarked calibration (provided the embarked calibration keeps the beam within the field of view of the visualization system), and specifies the set of Bragg angles over which the calibration will be performed. -
Advanced Options
⚠️ This tab exposes parameters that directly affect how the calibration algorithm is executed. These controls are not required for normal operation and are intended only for users who understand how the calibration procedure works internally. Changing these parameters without that understanding can cause the calibration to fail to converge or not run properly at all. For standard use cases, this tab should be left at its default settings. -
Run Calibration
For each Bragg angle, the GUI drives the DCM and associated axes, adjusts the detector exposure as needed, and runs a fixed-exit optimization routine to minimize horizontal and vertical centroid errors. Calibration results are stored to file, including measured centroids, centroid standard deviations, motor positions (gap, pitch, roll), and exposure time. -
Fit Polynomials
The calibration results are loaded and used to fit polynomial models relating Bragg angle to the short-stroke parameters (gap, pitch, and roll). These polynomials can then be saved for later use as preliminary calibration files in subsequent calibration runs or for embarking in the DCM coupled mode.
This section describes the parameters available in each GUI tab and their physical or operational meaning. Tabs are intended to be used sequentially.
-
DCM PV prefix
EPICS PV prefix for the double-crystal monochromator (e.g.QUA:A:). -
Visualization system PV prefix
EPICS PV prefix for the visualization system or camera used to acquire centroids (e.g.QUA:B:BASLER02:). -
Pixel-to-micron conversion factor [µm/px]
Conversion factor between camera pixels and physical distance at the visualization plane. -
Bragg law E₀
Energy scaling constant used in the experimental Bragg law, accounting for crystal miscut and other imperfections. -
Bragg law θ₀
Angular offset used in the experimental Bragg law to account for systematic deviations.
The photon energy is computed internally as: $$ E = \frac{E_0}{\sin(\theta + \theta_0)} $$
After setting these parameters, click Initialize to establish communication with the devices and validate readbacks.
This tab is used to acquire reference centroids at low and high photon energies. Each section (low-energy and high-energy) exposes the following parameters:
-
Minimum pixel value
Lower intensity threshold. Pixel values below this threshold are ignored when computing the centroid, reducing the influence of optical aberrations, scattering, or background tails. -
Maximum pixel value
Upper intensity threshold. Pixel values above this threshold are ignored to suppress artifacts such as saturated or dead pixels. -
Number of images
Number of images acquired and averaged to compute the centroid position.
Click Acquire Centroid in each section to acquire the corresponding reference centroid. The target fixed-exit position is computed as the average of the low and high-energy centroids.
This tab defines how the calibration will be performed and over which Bragg angles.
-
Calibration mode
- Automated: performs a binary search to determine optimal short-stroke parameters (gap, pitch, roll) for each Bragg angle.
- Manual: user-defined gap, pitch, and roll values for each Bragg angle (not yet implemented).
-
DCM motion mode
- Coupled (embarked calibration): uses the currently embarked calibration polynomials to move between Bragg angles, provided the beam remains within the field of view of the visualization system.
- Uncoupled (from file): uses preliminary calibration polynomials loaded from a file to generate initial guesses.
-
Bragg angle definition
Bragg angles to be calibrated can be defined either:- as a range (initial value, final value, and step), or
- as an explicit list of Bragg angle values.
After configuring these options, click Generate Points to create the list of Bragg angles that will be used during the calibration run.
This section groups parameters that control internal aspects of the calibration procedure. These parameters influence how intermediate steps are evaluated and how the algorithm searches for valid solutions.
⚠️ WARNING: These parameters should only be modified by users who understand the calibration algorithm and its convergence behavior. Improper values may cause the calibration to stall, fail to converge to meaningful points, or terminate prematurely. For standard operation, all parameters in this tab should remain at their default values.
All mentioned limits and constraints are automatically enforced by the interface. Limits are inclusive, meaning they impose:
These parameters control the automatic exposure-adjustment routine used to keep the camera signal within a usable dynamic range during calibration. They also govern pixel filtering (to remove dead pixels and beam aberrations) and the averaging of centroid measurements.
The camera bit depth is assumed to be 255.
-
Target maximum intensity
Desired maximum pixel intensity that the exposure adjustment algorithm attempts to reach.- Range: 50 to 253
- Constraints: must respect the below mentioned Minimum pixel value and Maximum pixel value constraints, as well as
$$\text{Target maximum intensity} \leq 254 - \text{Exposure tolerance}.$$
-
Exposure tolerance
Allowed deviation (in pixel value) from the target maximum intensity when adjusting exposure.- Range: 2 to 100
-
Dead pixels threshold
Maximum number of pixels with intensity equal to the bit depth that will be set to zero. If this number is exceeded, no pixels are modified, since it may no longer be possible to reliably distinguish dead pixels from valid ones.- Range: 1 to 1000
-
Minimum pixel value
Lower bound for acceptable pixel intensities, used to filter out unwanted beam aberrations.- Range: 1 to 240
- Constraint:
$$\text{Minimum pixel value} \leq \text{Target maximum intensity} - \text{Exposure tolerance} - 1.$$
-
Maximum pixel value
Upper bound for acceptable pixel intensities, also used for filtering.- Range: 50 to 255
- Constraint:
$$\text{Maximum pixel value} \leq \text{Target maximum intensity} + \text{Exposure tolerance} + 1.$$
-
Number of centroids to average
Number of centroid measurements averaged to reduce noise in beam position estimation.- Range: 1 to 10
-
Exposure step [s]
Initial step size used when incrementing or decrementing the exposure time during adjustment.- Range: 0.001 to 1.0
-
Maximum exposure time [s]
Upper limit for the exposure time during the adjustment process.- Range: 0.01 to 10.0
-
Maximum adjust iterations
Maximum number of iterations allowed for the exposure adjustment loop.- Range: 2 to 10000
These parameters control the global behavior of the calibration search and convergence logic.
-
Tolerance to target position for each direction [µm]
The acceptable spatial error for determining if the target has been reached. This applies to vertical and horizontal directions separately, so the total Euclidean distance$d$ in the transverse plane ends up being$$d \leq \sqrt{2} \cdot \text{Tolerance}.$$ - Range: 1.0 to 20.0
-
Settling time for DCM motion [s]
Waiting time after each DCM motion before acquiring data, allowing mechanical stabilization.- Range: 1.0 to 20.0
-
Factor to reduce steps
Multiplicative factor applied to step sizes as the search progresses, controlling convergence speed.- Range: 0.1 to 0.999
-
Maximum iterations of binary search
Maximum number of iterations allowed for the binary-search-based calibration steps. Each iteration encapsulates two sub-routines: a horizontal correction (with Roll) and a vertical correction (with either Gap or Pitch). Due to the coupling between axes, a correction in one transverse plane may introduce deviations in the other. This iterative approach employs a successive approximation method to ensure the beam converges to the target coordinate within the specified tolerance.- Range: 1 to 100
-
For vertical control, use:
Selects whether Gap or Pitch is used as the active degree of freedom for vertical control. The inactive group is disabled automatically.- Options: 'Gap' or 'Pitch' (the inactive group will be disabled in the interface)
These parameters govern the iterative search for Gap or Pitch in the vertical direction and for Roll in the horizontal direction. While the units differ (mm for Gap, µrad for Pitch and Roll), the logic for parameters and its limits remains identical across these groups.
-
Gap/Pitch/Roll maximum iterations
Maximum number of iterations allowed when searching along the gap/pitch/roll axis.- Range: 1 to 10000
-
Gap/Pitch/Roll step threshold
Minimum step size below which the search is considered stalled. When the step becomes smaller than the threshold, the search is terminated without converging.- Gap range: 0.001 to 0.1
- Pitch range: 0.001 to 1.0
- Roll range: 0.001 to 1.0
-
Gap/Pitch/Roll relative bound
The maximum relative range the search is permitted to explore from the starting point.- Gap range: 0.05 to 3.0
- Pitch range: 0.1 to 10
- Roll range: 0.5 to 500.0
-
Initial gap/pitch/roll step
Initial step size used at the beginning of the search. This value is constrained to lie between the step threshold and the relative bound.- Gap range: 0.002 to 1.0
- Pitch range: 0.002 to 5.0
- Roll range: 0.002 to 100.0
- Constraint:
$$\text{Step Threshold} \leq \text{Initial Step} \leq \text{Relative Bound}.$$
-
Output file
Base name for the calibration output file. The file stores calibration results, including centroid positions, short-stroke parameters (gap, pitch, roll), and exposure time.If no name is provided, the output file is automatically generated using the format:
Fixed_Exit--YYYY-MM-DD_HH-MM.csv.
After setting the output file name, click Run Calibration to start the calibration procedure.
This tab is used to post-process calibration results and generate polynomial models for the short-stroke parameters.
-
Calibration file
Input file generated by the Run Calibration tab. The file must contain Bragg angles and the corresponding optimized gap, pitch, and roll values. -
Polynomial degree (gap, pitch, roll)
Independent polynomial degrees used to fit gap, pitch, and roll as functions of the Bragg angle. The maximum allowed degree is limited by the number of calibration points. -
Fit polynomials
Executes the polynomial fitting procedure and displays the resulting fits directly in the GUI. -
Save coefficients
Saves the fitted polynomial coefficients to a JSON file. The generated polynomial files can be reused as preliminary calibration inputs in the Calibration Setup tab.
This section describes the file formats used by the GUI. Depending on the workflow stage, the same file type may serve as output from one tab and input to another.
Polynomial files describe the relationship between Bragg angle and the DCM short-stroke parameters and may be either generated by the GUI or supplied as preliminary input.
-
Usage
-
Input:
Used in the Calibration Setup tab when operating in uncoupled mode, to provide initial estimates for gap, pitch, and roll as functions of the Bragg angle. -
Output:
Generated in the Fit Polynomials tab by fitting polynomials to calibration results.
-
-
File type: JSON
-
Structure:
Coefficients are ordered from highest to lowest degree and evaluated using standard polynomial evaluation (e.g.numpy.polyval). That is, each array represents a polynomial: $$ p(\theta) = a_n \theta^n + \dots + a_1\theta + a_0 , $$ where θ is the Bragg angle (in degrees).
{
"gap": [a_n, ..., a_1, a_0],
"pitch": [b_n, ..., b_1, b_0],
"roll": [c_n, ..., c_1, c_0]
}Calibration result files contain the measured centroids and optimized short-stroke parameters for each calibrated Bragg angle.
-
Usage
-
Output:
Written during the calibration procedure in the Run Calibration tab. -
Input: Loaded in the Fit Polynomials tab to generate polynomial models for gap, pitch, and roll.
-
-
File types
-
CSV file (.csv)
Primary output file, space-delimited, intended for post-processing and plotting. -
Text file (.txt)
Secondary output file, tab-delimited, with values written in scientific notation for archival and human-readable inspection.
If no output file name is specified, files are created automatically using the format:
-
Fixed_Exit--YYYY-MM-DD_HH-MM.csv
Fixed_Exit--YYYY-MM-DD_HH-MM.txt- Structure:
Each output file contains one row per calibrated Bragg angle, with the following columns:
| Column | Description | Units |
|---|---|---|
| Energy | Photon energy | keV |
| Bragg | Bragg angle | deg |
| X_mean | Horizontal centroid mean | px |
| X_std | Horizontal centroid standard deviation | px |
| Y_mean | Vertical centroid mean | px |
| Y_std | Vertical centroid standard deviation | px |
| Gap | DCM gap position | mm |
| Pitch | DCM pitch position | µrad |
| Roll | DCM roll position | µrad |
| ExposureTime | Detector exposure time | s |
-
Output files are overwritten if a file with the same name already exists.
-
Centroid statistics are computed from multiple images acquired at each Bragg angle.
-
The output files are written incrementally during the calibration run; partial results may be present if the procedure is interrupted.
-
gui.pyimplements a PyQt6 multi-tab graphical interface with six tabs: Initialization, Target Centroid, Set Calibration, Advanced Options, Run Calibration, and Fit Polynomials. -
CalibrationWorker(aQThread) executes the calibration procedure asynchronously to keep the GUI responsive:-
Optionally couples or uncouples the DCM using EPICS
caputcommands. -
Moves the Bragg angle and short-stroke parameters (gap, pitch, and roll) according to either uncoupled mode (using preliminary polynomial models) or coupled mode.
-
Calls
adjust_exposure()to set the detector exposure time. -
Calls
fixed_exit_binary_search()(implemented insrc/fixed_exit/binary_search.py) to determine fixed-exit positions. -
Records averaged centroid values and device readbacks (RBVs), and writes CSV and TXT output files.
-
-
The GUI receives log messages, plot updates (
update_plot), and error notifications from the worker thread via Qt signals, ensuring thread-safe communication.
- henrique.tortura@lnls.br (OPT)