Files
Jungfraujoch/tests/RugnuxStructureTest.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

155 lines
7.8 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 <limits>
#include <gemmi/ccp4.hpp>
#include <gemmi/symmetry.hpp>
#include "../receiver/RugnuxLiveStatus.h"
#include "../receiver/RugnuxStructure.h"
namespace {
constexpr UnitCell TEST_CELL{30.0f, 32.0f, 34.0f, 90.0f, 90.0f, 90.0f};
const gemmi::Fractional ATOM_FRACT(0.3, 0.4, 0.55);
// One carbon atom at ATOM_FRACT, in P 1.
std::shared_ptr<gemmi::Structure> OneAtomModel() {
auto st = std::make_shared<gemmi::Structure>();
st->cell = TEST_CELL;
st->spacegroup_hm = "P 1";
gemmi::Model &m = st->models.emplace_back(1);
gemmi::Chain &ch = m.chains.emplace_back("A");
gemmi::Residue &r = ch.residues.emplace_back(gemmi::ResidueId{gemmi::SeqId(1, ' '), {}, "ALA"});
r.het_flag = 'A';
gemmi::Atom &a = r.atoms.emplace_back();
a.name = "CA";
a.element = gemmi::Element("C");
a.pos = st->cell.orthogonalize(ATOM_FRACT);
a.b_iso = 20.0f;
st->setup_cell_images();
return st;
}
// The map coefficients of a point at ATOM_FRACT to 2 A, as ModelValidation lays them out: F = 1 and
// phi = 360 h.x, so that rho(x) = 1/V sum F exp(-2 pi i h.x) peaks there. The difference map is the same
// point, negative.
MtzTable PointCoefficients(bool anomalous = false) {
MtzTable mtz;
mtz.unit_cell = TEST_CELL;
mtz.space_group_name = "P 1";
for (const char *label: {"H", "K", "L", "FWT", "PHWT", "DELFWT", "PHDELWT", "ANOM", "PHANOM"})
mtz.columns.push_back({label, 'R', 0, {}});
const gemmi::UnitCell cell = TEST_CELL;
const gemmi::ReciprocalAsu asu(gemmi::find_spacegroup_by_name("P 1"));
for (int h = -15; h <= 15; h++)
for (int k = -16; k <= 16; k++)
for (int l = -17; l <= 17; l++) {
const gemmi::Miller hkl{h, k, l};
if ((h == 0 && k == 0 && l == 0) || !asu.is_in(hkl) || cell.calculate_d(hkl) < 2.0)
continue;
double phi = 360.0 * (h * ATOM_FRACT.x + k * ATOM_FRACT.y + l * ATOM_FRACT.z);
phi -= 360.0 * std::floor(phi / 360.0);
// The anomalous map the same point, missing on a fifth of the reflections (no Bijvoet pair).
const float nan = std::numeric_limits<float>::quiet_NaN();
const bool pair = (h + k + l) % 5 != 0;
const float row[] = {static_cast<float>(h), static_cast<float>(k), static_cast<float>(l),
1.0f, static_cast<float>(phi),
1.0f, static_cast<float>(std::fmod(phi + 180.0, 360.0)),
pair ? 1.0f : nan, pair ? static_cast<float>(phi) : nan};
for (size_t c = 0; c < mtz.columns.size(); c++)
mtz.columns[c].values.push_back(row[c]);
}
if (!anomalous)
mtz.columns.resize(7);
return mtz;
}
// The fractional position of the highest point of a CCP4 map read from `bytes`; lowest where `lowest`.
gemmi::Fractional Extremum(const std::string &bytes, bool lowest, size_t &points, size_t &cell_points) {
gemmi::Ccp4<float> map;
map.read_ccp4_from_memory(bytes.data(), bytes.size(), "test");
points = map.grid.data.size();
cell_points = static_cast<size_t>(map.header_i32(8)) * map.header_i32(9) * map.header_i32(10);
const auto start = map.header_3i32(5);
const auto sampling = map.header_3i32(8);
size_t best = 0;
for (size_t i = 0; i < map.grid.data.size(); i++)
if (lowest ? map.grid.data[i] < map.grid.data[best] : map.grid.data[i] > map.grid.data[best])
best = i;
const size_t u = best % map.grid.nu, v = (best / map.grid.nu) % map.grid.nv,
w = best / (static_cast<size_t>(map.grid.nu) * map.grid.nv);
return {static_cast<double>(start[0] + static_cast<int>(u)) / sampling[0],
static_cast<double>(start[1] + static_cast<int>(v)) / sampling[1],
static_cast<double>(start[2] + static_cast<int>(w)) / sampling[2]};
}
}
TEST_CASE("RugnuxStructure_MapPeaksAtTheAtom", "[RugnuxLive]") {
const RugnuxStructure structure(OneAtomModel(), TEST_CELL, *gemmi::find_spacegroup_by_name("P 1"),
PointCoefficients(true));
REQUIRE(structure.HasMaps());
REQUIRE(structure.HasAnomalousMap());
for (const auto type: {RugnuxMapType::TwoFoFc, RugnuxMapType::FoFc, RugnuxMapType::Anomalous}) {
const std::string bytes = structure.Map(type);
REQUIRE(bytes.size() > 1024);
CHECK(bytes.substr(208, 4) == "MAP ");
size_t points = 0, cell_points = 0;
const gemmi::Fractional peak = Extremum(bytes, type == RugnuxMapType::FoFc, points, cell_points);
// Within one grid step (d_min/3 = 0.67 A, i.e. at most 0.022 of these cells).
CHECK(peak.x == Catch::Approx(ATOM_FRACT.x).margin(0.025));
CHECK(peak.y == Catch::Approx(ATOM_FRACT.y).margin(0.025));
CHECK(peak.z == Catch::Approx(ATOM_FRACT.z).margin(0.025));
// One unit cell (centred on the model, which is smaller than the cell).
CHECK(points == cell_points);
// Cached: the same bytes again.
CHECK(structure.Map(type) == bytes);
}
}
TEST_CASE("RugnuxStructure_MapCoversAModelWiderThanTheCell", "[RugnuxLive]") {
// A second atom 1.4 cells along a from the first: the map reaches along a over both, plus the margin.
auto st = OneAtomModel();
gemmi::Atom far = st->models[0].chains[0].residues[0].atoms[0];
far.name = "CB";
far.pos = st->cell.orthogonalize(gemmi::Fractional(ATOM_FRACT.x + 1.4, ATOM_FRACT.y, ATOM_FRACT.z));
st->models[0].chains[0].residues[0].atoms.push_back(far);
const RugnuxStructure structure(st, TEST_CELL, *gemmi::find_spacegroup_by_name("P 1"), PointCoefficients());
CHECK(!structure.HasAnomalousMap());
const std::string bytes = structure.Map(RugnuxMapType::TwoFoFc);
gemmi::Ccp4<float> map;
map.read_ccp4_from_memory(bytes.data(), bytes.size(), "test");
const double a_span_A = TEST_CELL.a * map.grid.nu / map.header_i32(8);
CHECK(a_span_A == Catch::Approx(1.4 * TEST_CELL.a + 2 * RugnuxStructure::MAP_MARGIN_A).margin(1.5));
CHECK(map.grid.nv == map.header_i32(9)); // one cell along b and c
CHECK(map.grid.nw == map.header_i32(10));
}
TEST_CASE("RugnuxStructure_ModelCif", "[RugnuxLive]") {
const RugnuxStructure structure(OneAtomModel(), TEST_CELL, *gemmi::find_spacegroup_by_name("P 1"), {});
CHECK(!structure.HasMaps());
CHECK(!structure.HasAnomalousMap());
CHECK(structure.Map(RugnuxMapType::Anomalous).empty());
CHECK(structure.Map(RugnuxMapType::TwoFoFc).empty());
const std::string cif = structure.ModelCif();
CHECK(cif.find("_atom_site.") != std::string::npos);
CHECK(cif.find("_cell.length_a") != std::string::npos);
CHECK(cif.find("'P 1'") != std::string::npos);
}
TEST_CASE("RugnuxLiveStatus_StructureClearedAtStart", "[RugnuxLive]") {
RugnuxLiveStatus status;
status.Structure(std::make_shared<RugnuxStructure>(OneAtomModel(), TEST_CELL,
*gemmi::find_spacegroup_by_name("P 1"), std::nullopt));
CHECK(status.Get().structure);
status.Start(10, 1.0, std::chrono::steady_clock::now());
CHECK(!status.Get().structure);
status.Structure(std::make_shared<RugnuxStructure>(OneAtomModel(), TEST_CELL,
*gemmi::find_spacegroup_by_name("P 1"), std::nullopt));
status.Clear();
CHECK(!status.Get().structure);
}