Files
Jungfraujoch/tests/ModuleRefinementTest.cpp
T
leonarski_fandClaude Opus 5.5 0a515bb086 rc179: everything on rc178 after its merge into main (#88), except the CHANGELOG
The rc178 branch continued after #88 was squash-merged; this is its content from b9ada7914 (the tree
#88 squashed) to 094eee31a, as one change on main. The individual commits stay on the rc178 branch:

- still battery: --cold evicts each set's input from the page cache; Alvra pixel masks; manifest fixes
- AGIPD: converter to one rigid panel per module, int16 photons, mask folded in; still battery reads the converted sets
- DetectorModules: panel look-up by id, plane -> panel, plane bounds and a per-pixel walk; mask size checked
- tests: [PanelLayout] equivalence harness, stacked vs assembled panel layout
- Dense per-pixel maps through the panel table (panel layout stage 1)
- Panel id on spots and the panel table in the start message
- Viewer and preview show a panel detector as it lies on the detector plane
- Panel layout stage 3: per-panel spot finding (CPU+GPU, CCL) and raster algorithms on the plane raster
- Panel layout stage 2: prediction and Bragg integration through the panel table
- XTC reader: frames handed up as stored, streams indexed in parallel
- XFEL reader: integer frames stay integer, one gain, placement by panel
- EXTERNAL_TEST_DATA_STILLS.md: images used vs the entry for every set; drop "Not in the battery"
- still battery: EuXFEL sets read the depositors' Cheetah CXI files directly; AGIPD converter removed
- float32_to_int16.py: a non-finite pixel becomes -32768, the int16 error marker, not a zero count
- CrystFEL geometry: read the pixel masks and bad regions instead of ignoring them
- Panel layout stage 5: the XFEL reader hands up the stored frame and its panel table
- Panel table persisted in NXmx; modulation grid and pre-scan memo key on the plane
- still battery: Alvra sets take their pixel mask from the CrystFEL geometry, not --mask-good
- still battery: take the deposited model as mmCIF where the RCSB has no PDB-format file
- still battery: dimple gets PDB-format coordinates converted from an mmCIF-only deposition
- stills fixed cost: geometry refinement and pre-scan do the same work in less wall time
- stills geometry sample and trial spot finding run as many workers as the image pass
- Stills integration: background ring reach measured on empty apertures, radial curvature from the whole frame
- StillsPartialityRefine: the partiality width is the run's, measured on the crystals, not the prediction window's
- MergeOnTheFly: capture term and multiplicative outlier band for the stills merge (both opt-in)
- Stills given a cell: the written cell is the mean over the frames that are merged
- Stills: the radial curvature correction decided per run on the same empty apertures
- StillsPartialityRefine: measure the run width only on shells with signal
- Stills pre-scan: report the paired z of the radial-correction comparison
- module placement: the five concurrent fits each keep every thread
- still battery: score R-free against the deposited data through the same dimple protocol
- still battery: the R-free target is the lower of the deposition's dimple and published values
- Stills: background clip follows the radial curve; signal disk from the lattice spacing
- Stills keep an overloaded observation as a lower bound instead of dropping it
- Stills: drop the lattice-spacing signal disk; the correction decision back on the plain clip
- battery: R-free against the deposition without refinement only, one protocol for rotation and stills
- still battery: EuXFEL sets run on a 2,000-image subset for now
- stills geometry refinement: fit the detector distance and the cell together
- stills geometry refinement: a distance given with --detector-distance is held in the joint fit
- Metal integration engine: back to its panel-s5 kernels; Mac stills keep the old clip, no saturation count
- Metal integration test: the CPU comparison runs on a rotation experiment
- Stills: kept overloads go back to the drop where they are not concentrated at low resolution
- stills distance search: an absolute 30-3000 mm scan, a sample found without d-limits, the fit iterated
- battery results: XFEL still battery 20261022-1358 on rc178 0cf62452c - 12 sets, cold, R_free unrefined
- battery results: still summary gains the resolution of our merge and of the deposition
- Pre-scan masks a pixel at the saturation limit on most frames, as one holding the error value
- Stills keep an overload as a lower bound only where it has pixels at the limit; run-level gate removed
- XFEL reader: a per-frame mask is read the way the frames are, its chunk inflated outside the HDF5 lock
- stills distance search: every centre scanned with a wider acceptance, a larger sample where nothing indexes
- rugnux usage: --beam-center-check describes the absolute 30-3000 mm stills distance scan, not the old 60-160 % grid
- stills: detector tilt refined in the geometry pre-pass, kept where held-out frames agree
- CLAUDE.md: the changelog is written once, just before the merge into main - condensed one-liners of what users get
- broker: serve the placed model and its maps of the last rugnux live run (/rugnux/model.cif, /rugnux/map.ccp4)
- frontend: Mol* viewer of the placed model and its density on the Rugnux live page
- writer: _model.cif from rugnux live keeps the input model's metadata, as the served model.cif does
- rugnux live maps: one unit cell centred on the model; the viewer opens on all of it
- Anomalous difference map: ANOM/PHANOM in _maps.mtz, /rugnux/map.ccp4?type=anom, a magenta mesh in the viewer
- Mol* viewer: open with the maps drawn within 10 A of the centre of view
- Mol* viewer: aaredb's structure-viewer setup, on a black stage
- rugnux: the gain of a stills file that states none is read off its single-photon peak where the background resolves photons
- Mol* viewer: in line with AareDB's StructureView at its current head (8ece2c2)
- ACKNOWLEDGEMENT: the web frontend's Mol* viewer follows AareDB's setup (G. Gotthard, PSI)
- stills tilt decision: the modules stay where the run placed them
- still battery: no distance pins and no per-set tuning flags; gain from the data except where a file's baseline hides it
- battery results: rc178 6f6f69 - full still battery and full rotation battery with REFMAC
- Bragg integration: a CCD rotation sweep's sigmas at the measured gain, intensities in photons
- BackgroundGain: the gain of a frame that resolves photons is the spacing of its photon peaks, so a baseline left in the frame no longer hides it
- ShadowFinder: measure the background's azimuthal modulation instead of predicting it from the polarization
- BackgroundGain: one gain estimate for rotation and stills; the still battery no longer gives EuXFEL 152 its gain
- ShadowFinder: measure the modulation robustly under a wide one-sided shadow
- ShadowFinderTest: a one-sided shadow is not fitted as part of the background's modulation
- ShadowFinder: back to the predicted polarization factor, in the plane the background shows
- MXAnalysisAfterFPGA: the Bragg engine's edge mask in the image's layout, so raw / untransformed FPGA runs start again
- battery results: still battery on rc178 e54f55 replaces the earlier rc178 still tables
- XFELReader: per-frame mask and photon conversion without a library call or a branch per pixel
- stills geometry trial: the hypotheses a search asks are indexed side by side
- stills tilt decision: the fits start beside the pre-scan and the geometry trial
- XFELReader: a deflated frame is inflated and converted a piece at a time, while it is in the cache
- XFELReader: a byte-shuffled frame is unshuffled a piece at a time, a whole pixel per step
- GeometryRefiner: residuals carry only the blocks a fit moves; beam and distance one block
- GeometryRefiner: a spot's residual differentiates its observed and predicted halves apart
- docs: EXTERNAL_TEST_DATA lists every open-arm battery set, with corrected values and counts
- battery: doc_check.py cross-checks the manifests against the dataset pages
- stills module placement: the placement fit gets half the threads, each held-out fit an eighth
- still battery: the EuXFEL sets run on all their frames, as the published still runs did
- battery results: still battery on rc178 a0ce6c, cold on a quiet machine, replaces the earlier rc178 table
- macOS build: explicit size_t in the XFEL reader's row bounds; parentheses in the CPU preprocessor's select

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015CeEGgpKdfkCTJb3YNMJcu
2026-10-23 17:56:42 +02:00

220 lines
10 KiB
C++

// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
// SPDX-License-Identifier: GPL-3.0-only
#include <catch2/catch_all.hpp>
#include <cmath>
#include <random>
#include "../common/JFJochMath.h"
#include "../image_analysis/geom_refinement/GeometryRefiner.h"
#include "../image_analysis/bragg_prediction/BraggPrediction.h"
namespace {
// Frames of a 50/60/70 A orthorhombic crystal in random orientations on a detector of four modules (the
// quadrants around the beam at 1000, 1000), each displaced by the rigid move `truth` gives it: the spots are
// where the image shows them, each indexed as predicted.
std::vector<GeomRefineFrame> FramesOnMovedModules(const DiffractionExperiment &exp, const CrystalLattice &latt,
const std::vector<ModuleShift> &truth) {
auto module_of = [](double x, double y) { return (x < 1000 ? 0 : 1) + (y < 1000 ? 0 : 2); };
BraggPredictionSettings settings{.high_res_A = 2.0, .ewald_dist_cutoff = 0.001};
std::mt19937 rng(7);
std::uniform_real_distribution<float> u(-1.0f, 1.0f);
std::vector<GeomRefineFrame> frames;
for (int f = 0; f < 60; f++) {
const Coord axis = Coord(u(rng), u(rng), u(rng)).Normalize();
const CrystalLattice rotated = latt.Multiply(RotMatrix(static_cast<float>(PI) * u(rng), axis));
BraggPrediction prediction;
const int n = prediction.Calc(exp, rotated, settings);
GeomRefineFrame frame;
frame.lattice = rotated;
frame.ordinal = f;
for (int i = 0; i < n; i++) {
const auto &r = prediction.GetReflections().at(i);
const int m = module_of(r.predicted_x, r.predicted_y);
// where the image shows a spot whose true place is the prediction: the inverse of the move
const auto &t = truth[m];
const double c = std::cos(t.rot_rad), s = std::sin(t.rot_rad);
const double vx = r.predicted_x - t.x0 - t.dx, vy = r.predicted_y - t.y0 - t.dy;
GeomRefineSpot spot;
spot.x = static_cast<float>(t.x0 + c * vx + s * vy);
spot.y = static_cast<float>(t.y0 - s * vx + c * vy);
spot.h = r.h;
spot.k = r.k;
spot.l = r.l;
spot.module = static_cast<int16_t>(m);
frame.spots.push_back(spot);
}
if (frame.spots.size() >= 20)
frames.push_back(frame);
}
return frames;
}
} // namespace
// A detector of four modules (the quadrants around the beam), each displaced by a known rigid move: the
// bundle adjustment with module placement must find the moves, and the fit without it must be worse.
TEST_CASE("RefineGlobalGeometry_ModulePlacement") {
DiffractionExperiment exp;
exp.IncidentEnergy_keV(WVL_1A_IN_KEV).BeamX_pxl(1000).BeamY_pxl(1000).DetectorDistance_mm(150);
const DiffractionGeometry geom = exp.GetDiffractionGeometry();
// Moves that hold none of what the gauge takes away: zero in sum, in turn and outwards.
std::vector<ModuleShift> truth(4);
const double centre[4][2] = {{500, 500}, {1500, 500}, {500, 1500}, {1500, 1500}};
const double move[4][3] = {{2.0, -2.0, 0.2}, {2.0, 2.0, -0.2}, {-2.0, -2.0, 0.1}, {-2.0, 2.0, -0.1}};
for (int m = 0; m < 4; m++) {
truth[m].x0 = centre[m][0];
truth[m].y0 = centre[m][1];
truth[m].dx = move[m][0];
truth[m].dy = move[m][1];
truth[m].rot_rad = move[m][2] * PI / 180.0;
}
const CrystalLattice latt(50, 60, 70, 90, 90, 90);
const std::vector<GeomRefineFrame> frames = FramesOnMovedModules(exp, latt, truth);
REQUIRE(frames.size() > 30);
GeometryRefinerSettings st;
st.crystal_system = gemmi::CrystalSystem::Orthorhombic;
st.num_threads = 2;
for (const auto &t: truth) {
ModuleShift start;
start.x0 = t.x0;
start.y0 = t.y0;
st.modules.push_back(start);
}
const auto held = RefineGlobalGeometry(geom, latt.GetUnitCell(), frames, st);
REQUIRE(held.ok);
st.refine_modules = true;
const auto placed = RefineGlobalGeometry(geom, latt.GetUnitCell(), frames, st);
REQUIRE(placed.ok);
CHECK(placed.median_residual_px < 0.1);
CHECK(held.median_residual_px > 5 * placed.median_residual_px);
for (int m = 0; m < 4; m++) {
CHECK(placed.modules[m].dx == Catch::Approx(truth[m].dx).margin(0.1));
CHECK(placed.modules[m].dy == Catch::Approx(truth[m].dy).margin(0.1));
CHECK(placed.modules[m].rot_rad * 180.0 / PI == Catch::Approx(move[m][2]).margin(0.01));
}
CHECK(placed.beam_x_px == Catch::Approx(1000).margin(0.1));
CHECK(placed.beam_y_px == Catch::Approx(1000).margin(0.1));
CHECK(placed.distance_mm == Catch::Approx(150).margin(0.05));
// The distance held (it shares a block with the beam): it stays exactly where it was given.
GeometryRefinerSettings held_distance = st;
held_distance.refine_distance = false;
const auto fixed = RefineGlobalGeometry(geom, latt.GetUnitCell(), frames, held_distance);
REQUIRE(fixed.ok);
CHECK(fixed.distance_mm == geom.GetDetectorDistance_mm());
CHECK(fixed.modules[0].dx == Catch::Approx(truth[0].dx).margin(0.1));
// Only the orientations moved, on the modules as placed: the spots fit as well as in the placement.
GeometryRefinerSettings ev = st;
ev.refine_modules = false;
ev.refine_beam_distance = false;
ev.modules = placed.modules;
const auto scored = RefineGlobalGeometry(geom, latt.GetUnitCell(), frames, ev);
REQUIRE(scored.ok);
CHECK(scored.median_residual_px < 0.1);
CHECK(scored.distance_mm == geom.GetDetectorDistance_mm());
}
// The coarse search ahead of the placement: a module off by several pixels is found near where it is, and the
// search gives the same answer on any number of threads.
TEST_CASE("ScanModuleShifts_FindsShiftedModule") {
DiffractionExperiment exp;
exp.IncidentEnergy_keV(WVL_1A_IN_KEV).BeamX_pxl(1000).BeamY_pxl(1000).DetectorDistance_mm(150);
const DiffractionGeometry geom = exp.GetDiffractionGeometry();
std::vector<ModuleShift> truth(4), given(4);
const double centre[4][2] = {{500, 500}, {1500, 500}, {500, 1500}, {1500, 1500}};
for (int m = 0; m < 4; m++) {
truth[m].x0 = given[m].x0 = centre[m][0];
truth[m].y0 = given[m].y0 = centre[m][1];
}
truth[1].dx = 6.0;
truth[1].dy = -4.0;
const CrystalLattice latt(50, 60, 70, 90, 90, 90);
std::vector<GeomRefineFrame> frames = FramesOnMovedModules(exp, latt, truth);
REQUIRE(frames.size() > 30);
// The module's spots did not index where it was given: the search sees them as unindexed.
for (auto &f: frames)
for (auto &s: f.spots)
if (s.module == 1) {
s.h = s.k = s.l = 0;
f.unindexed.push_back(s);
}
for (auto &f: frames)
std::erase_if(f.spots, [](const GeomRefineSpot &s) { return s.module == 1; });
const auto one = ScanModuleShifts(geom, frames, given, 25.0, 1);
const auto many = ScanModuleShifts(geom, frames, given, 25.0, 4);
REQUIRE(one.size() == 4);
// Coarse: a spot is on its lattice within 0.15 of an index, here ~4 px of the spacing, so the search lands
// within that of the true shift and the placement takes it from there.
CHECK(one[1].dx == Catch::Approx(6.0).margin(4.0));
CHECK(one[1].dy == Catch::Approx(-4.0).margin(4.0));
CHECK(one[1].on_lattice_at_best > 2 * one[1].on_lattice_at_zero);
for (int m = 0; m < 4; m++) {
CHECK(many[m].dx == one[m].dx);
CHECK(many[m].dy == one[m].dy);
CHECK(many[m].on_lattice_at_best == one[m].on_lattice_at_best);
CHECK(many[m].on_lattice_at_zero == one[m].on_lattice_at_zero);
}
}
// A tilted detector, one panel: started from the untilted geometry with the beam where the beam really lands
// (the direct beam, which is what a beam-centre measurement gives), the refinement with the tilt must find it
// and put the PONI where the tilt has it - 10 px from the direct beam here, further than the beam's 8 px box
// would reach in PONI terms - and the fit with the tilt held must be worse. With the image mirrored and turned
// as well, the direct beam has to be taken through the image orientation.
TEST_CASE("RefineGlobalGeometry_Tilt") {
for (const auto &orientation : {DetectorOrientation(), DetectorOrientation(true, 1)}) {
DiffractionExperiment exp;
exp.IncidentEnergy_keV(WVL_1A_IN_KEV).BeamX_pxl(1000).BeamY_pxl(1000).DetectorDistance_mm(150)
.PoniRot1_rad(0.3 * PI / 180.0).PoniRot2_rad(-0.2 * PI / 180.0);
exp.Detector().ImageOrientation(orientation);
const DiffractionGeometry truth = exp.GetDiffractionGeometry();
const auto [direct_x, direct_y] = truth.GetDirectBeam_pxl();
REQUIRE(std::hypot(direct_x - 1000, direct_y - 1000) > 10);
// One module covering the whole image: the frames' spots, each where the tilted detector shows it.
ModuleShift whole;
whole.x0 = 1000;
whole.y0 = 1000;
const CrystalLattice latt(50, 60, 70, 90, 90, 90);
std::vector<GeomRefineFrame> frames = FramesOnMovedModules(exp, latt, {whole, whole, whole, whole});
REQUIRE(frames.size() > 30);
for (auto &f: frames)
for (auto &s: f.spots)
s.module = -1;
DiffractionGeometry nominal = truth;
nominal.PoniRot1_rad(0).PoniRot2_rad(0).BeamX_pxl(direct_x).BeamY_pxl(direct_y);
GeometryRefinerSettings st;
st.crystal_system = gemmi::CrystalSystem::Orthorhombic;
st.num_threads = 2;
const auto held = RefineGlobalGeometry(nominal, latt.GetUnitCell(), frames, st);
REQUIRE(held.ok);
CHECK(held.rot1_rad == 0);
CHECK(held.rot2_rad == 0);
st.refine_tilt = true;
const auto tilted = RefineGlobalGeometry(nominal, latt.GetUnitCell(), frames, st);
REQUIRE(tilted.ok);
CHECK(tilted.rot1_rad * 180.0 / PI == Catch::Approx(0.3).margin(0.01));
CHECK(tilted.rot2_rad * 180.0 / PI == Catch::Approx(-0.2).margin(0.01));
CHECK(tilted.beam_x_px == Catch::Approx(1000).margin(0.2));
CHECK(tilted.beam_y_px == Catch::Approx(1000).margin(0.2));
CHECK(tilted.distance_mm == Catch::Approx(150).margin(0.05));
CHECK(tilted.median_residual_px < 0.1);
CHECK(tilted.capped_rms_px < held.capped_rms_px);
}
}