Files
Jungfraujoch/image_analysis/geom_refinement/RingOptimizer.cpp
leonarski_fandClaude Opus 5 6468dd13be
Build Packages / Unit tests (push) Failing after 6m24s
Build Packages / build:rpm (rocky9_nocuda) (push) Failing after 14m5s
Build Packages / build:viewer-tgz:cpu (push) Failing after 14m34s
Build Packages / build:rpm (ubuntu2404_nocuda) (push) Failing after 14m54s
Build Packages / build:viewer-tgz:cuda (push) Failing after 16m14s
Build Packages / build:rpm (rocky8_nocuda) (push) Failing after 16m24s
Build Packages / build:rpm (ubuntu2204_nocuda) (push) Failing after 18m53s
Build Packages / build:rpm (rocky9_sls9) (push) Failing after 13m2s
Build Packages / build:rpm (rocky8_sls9) (push) Failing after 19m34s
Build Packages / build:rpm (rocky9) (push) Failing after 14m54s
Build Packages / Generate python client (push) Successful in 42s
Build Packages / build:rpm (ubuntu2404) (push) Failing after 14m10s
Build Packages / Create release (push) Skipped
Build Packages / XDS test (durin plugin) (push) Successful in 12m14s
Build Packages / XDS test (neggia plugin) (push) Successful in 11m52s
Build Packages / XDS test (JFJoch plugin) (push) Successful in 12m15s
Build Packages / Build documentation (push) Successful in 2m10s
Build Packages / build:rpm (rocky8) (push) Failing after 18m29s
Build Packages / build:rpm (ubuntu2204) (push) Failing after 17m55s
Build Packages / DIALS test (push) Successful in 17m4s
Build Packages / build:windows:nocuda (push) Canceled after 0s
Build Packages / build:windows:cuda (push) Canceled after 0s
rugnux: --mode, and detector calibration from powder rings
--azint-only and --scale are replaced by --mode mx|azint|scale|calibration, with
mx the default. The old flags are removed rather than aliased.

Calibration mode fits the detector geometry - PONI x/y, the two tilts and the
distance - to a calibrant's powder rings and writes a pyFAI .poni alongside a
report of how far each parameter moved from the header. Bragg data constrain the
beam centre worst, because it is gauge-coupled to the crystal orientation; a
powder ring has no orientation to couple to.

--calibrant takes lab6, agbh, ceo2, si or ice. A calibrant is a list of ring
positions rather than a unit cell, because hexagonal ice is P6_3/mmc: rings
enumerated from its cell would include systematically absent ones. So the
crystalline standards generate their rings from a cell and ice carries the
measured list, and RingsFromAzimuthalProfile, GuessGeometry and OptimizeGeometry
all take ring q. The calibrant table is shared with the viewer's powder panel,
which previously carried its own copy.

--calibration picks how the rings are measured: rings (default) sums the
(q x azimuth) profile over every processed image and fits the arcs in it; spots
pools the found spots and fits those. Both use the whole run, with -s/-e/-t
selecting images. rings defaults --azim-phi-bins to 32, since a profile with one
azimuthal bin has averaged the ring over every direction and cannot locate it.

Two fixes this exposed:

The extraction window is capped at half the gap to the neighbouring ring. The
background under a peak is taken from the ends of its window, so a window wider
than half that gap measures the next ring's flank as this ring's background -
and hexagonal ice has three rings within 0.06 1/A. Ice calibration was 3.5 px
out before this and 0.29 px after; LaB6 is unaffected.

RingOptimizer holds rot1/rot2 fixed when only one ring is present. A tilt and a
centre offset both move a ring as cos(phi) and are separated only by the tilt's
amplitude growing as the ring radius squared, so on a single ring they are
exactly degenerate.

Measured. LaB6 at five distances: the fitted direct beam is within 0.36 px of an
independent implementation out to 300 mm, and D = -0.046 + 1.000788 dtz with an
rms of 0.011 mm. At 500 mm one ring is fully on the detector and a second only
clips the corners, which is not enough to constrain a tilt - restricting the q
range to the resolved ring recovers 0.06 px. Ice: 5.53 -> 0.29 px on one crystal
and 4.71 -> 0.80 px on another, against XDS's refined direct beam. On an ice-free
crystal the fit is worse than the header, which is the correct outcome.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-07 10:00:03 +02:00

123 lines
4.6 KiB
C++

// SPDX-FileCopyrightText: 2025 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
// SPDX-License-Identifier: GPL-3.0-only
#include <algorithm>
#include "../../common/JFJochMath.h"
#include "RingOptimizer.h"
#include "ceres/ceres.h"
struct RingResidual {
RingResidual(double x, double y, double lambda,
double pixel_size,
double expected_q)
: obs_x(x), obs_y(y),
lambda(lambda),
pixel_size(pixel_size),
expected_len_recip_sq(expected_q * expected_q / (4.0 * PI * PI)) {}
template<typename T>
bool operator()(const T* const center_x, const T* const center_y,
const T* const distance, const T* const rot1,
const T* const rot2, T* residual) const {
// Calculate lab coordinates from observed pixel coordinates
T x_lab = (T(obs_x) - center_x[0]) * T(pixel_size); // convert to mm
T y_lab = (T(obs_y) - center_y[0]) * T(pixel_size);
T z_lab = distance[0];
// Apply rotations around y and x axes
T c1 = ceres::cos(rot1[0]);
T c2 = ceres::cos(rot2[0]);
T s1 = ceres::sin(rot1[0]);
T s2 = ceres::sin(rot2[0]);
T x = x_lab * c1 + z_lab * s1;
T y = y_lab * c2 + (-x_lab * s1 + z_lab * c1) * s2;
T z = -y_lab * s2 + (-x_lab * s1 + z_lab * c1) * c2;
// convert to recip space
T lab_norm = ceres::sqrt(x*x + y*y + z*z);
T R_x = x / (lab_norm * T(lambda));
T R_y = y / (lab_norm * T(lambda));
T R_z = (z / lab_norm - T(1.0)) / T(lambda);
T predicted_len_recip_sq = R_x * R_x + R_y * R_y + R_z * R_z;
residual[0] = predicted_len_recip_sq - T(expected_len_recip_sq);
return true;
}
const double obs_x, obs_y;
const double lambda;
const double pixel_size;
const double expected_len_recip_sq;
};
RingOptimizer::RingOptimizer(const DiffractionGeometry& geom) : reference(geom) {}
DiffractionGeometry RingOptimizer::Run(const std::vector<RingOptimizerInput> &input) {
// Initial guess for the parameters
double center_x = reference.GetBeamX_pxl();
double center_y = reference.GetBeamY_pxl();
double distance = reference.GetDetectorDistance_mm();
double rot1 = reference.GetPoniRot1_rad();
double rot2 = reference.GetPoniRot2_rad();
ceres::Problem problem;
// Add residuals for each point
for (const auto& pt : input) {
problem.AddResidualBlock(
new ceres::AutoDiffCostFunction<RingResidual, 1, 1, 1, 1, 1, 1>(
new RingResidual(pt.x, pt.y,
reference.GetWavelength_A(),
reference.GetPixelSize_mm(),
pt.q_expected)),
nullptr,
&center_x,
&center_y,
&distance,
&rot1,
&rot2
);
}
// A single ring cannot tell the beam centre from the detector tilt: both displace its radius as
// cos(phi), and what separates them is only how that amplitude scales with the ring's radius, which
// takes two rings. Hold the tilt where it was given, so the one thing a single ring does fix - where
// its centre lies - comes out rather than being traded away against an unconstrained tilt.
const bool single_ring = !input.empty()
&& std::all_of(input.begin(), input.end(), [&](const RingOptimizerInput &p) {
return p.q_expected == input.front().q_expected;
});
if (single_ring) {
problem.SetParameterBlockConstant(&rot1);
problem.SetParameterBlockConstant(&rot2);
}
// Configure solver
ceres::Solver::Options options;
options.linear_solver_type = ceres::DENSE_QR;
options.minimizer_progress_to_stdout = false;
options.logging_type = ceres::LoggingType::SILENT;
options.num_threads = 1;
ceres::Solver::Summary summary;
// Run optimization
ceres::Solve(options, &problem, &summary);
// A failed fit must not move the detector geometry. Both callers assign the result straight
// back over the geometry they passed in, so handing back the reference leaves the calibration
// where it was instead of committing a diverged beam centre and distance.
if (!summary.IsSolutionUsable())
return reference;
DiffractionGeometry refined_geom(reference);
refined_geom.BeamX_pxl(center_x).BeamY_pxl(center_y).DetectorDistance_mm(distance)
.PoniRot1_rad(rot1).PoniRot2_rad(rot2);
return refined_geom;
}