The rc178 branch continued after #88 was squash-merged; this is its content fromb9ada7914(the tree #88 squashed) to094eee31a, 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 rc1780cf62452c- 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
192 lines
9.0 KiB
C++
192 lines
9.0 KiB
C++
// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
|
|
// SPDX-License-Identifier: GPL-3.0-only
|
|
|
|
#include "SpotFootprint.h"
|
|
|
|
#include <algorithm>
|
|
#include <cmath>
|
|
#include <map>
|
|
#include <tuple>
|
|
|
|
namespace {
|
|
|
|
// The window around a spot is BRAGG_FOOTPRINT_NSIGMA-like: three of its standard deviations, at least
|
|
// a few pixels and at most this many, which is wider than any spot the integrator could hold.
|
|
constexpr float WINDOW_NSIGMA = 3.0f;
|
|
constexpr float WINDOW_MIN_PX = 3.0f;
|
|
constexpr float WINDOW_MAX_PX = 24.0f;
|
|
// The background is the median of an elliptical annulus between these multiples of the window.
|
|
constexpr float BKG_INNER = 1.5f;
|
|
constexpr float BKG_OUTER = 2.2f;
|
|
constexpr int ITERATIONS = 8;
|
|
|
|
inline bool valid(int32_t v) { return v != INT32_MIN && v != INT32_MAX; }
|
|
|
|
float median_of(std::vector<float> &v) {
|
|
const size_t m = v.size() / 2;
|
|
std::nth_element(v.begin(), v.begin() + static_cast<std::ptrdiff_t>(m), v.end());
|
|
return v[m];
|
|
}
|
|
|
|
} // namespace
|
|
|
|
FootprintOutcome MeasureFootprintSpot(const FootprintTile &tile, const BraggPanel &pn, float beam_x, float beam_y,
|
|
float x, float y, FootprintSpot &spot) {
|
|
const int half = static_cast<int>(std::ceil(BKG_OUTER * WINDOW_MAX_PX)) + 1;
|
|
std::vector<float> ring;
|
|
// The distance from the beam on the plane, and the radial direction in the panel's pixel axes.
|
|
const float rx = pn.plane_x - beam_x, ry = pn.plane_y - beam_y;
|
|
const float r = std::sqrt(rx * rx + ry * ry);
|
|
if (!(r > 1.0f)) return FootprintOutcome::LeftOut;
|
|
const float ux = rx / r * pn.fx + ry / r * pn.fy, uy = rx / r * pn.sx + ry / r * pn.sy;
|
|
const int ix = static_cast<int>(std::lround(x)), iy = static_cast<int>(std::lround(y));
|
|
if (ix - half < pn.x0 || iy - half < pn.y0 || ix + half > pn.x1 || iy + half > pn.y1)
|
|
return FootprintOutcome::LeftOut;
|
|
|
|
// Start from a compact spot at the prediction; each round re-centres on the signal and takes
|
|
// the window to three of the widths just measured.
|
|
float cx = x, cy = y;
|
|
float s2r = 1.0f, s2t = 1.0f;
|
|
for (int it = 0; it < ITERATIONS; ++it) {
|
|
const float wr = std::clamp(WINDOW_NSIGMA * std::sqrt(s2r), WINDOW_MIN_PX, WINDOW_MAX_PX);
|
|
const float wt = std::clamp(WINDOW_NSIGMA * std::sqrt(s2t), WINDOW_MIN_PX, WINDOW_MAX_PX);
|
|
const float reach = BKG_OUTER * std::max(wr, wt);
|
|
const int x0 = static_cast<int>(std::floor(cx - reach)), x1 = static_cast<int>(std::ceil(cx + reach));
|
|
const int y0 = static_cast<int>(std::floor(cy - reach)), y1 = static_cast<int>(std::ceil(cy + reach));
|
|
if (x0 < pn.x0 || y0 < pn.y0 || x1 > pn.x1 || y1 > pn.y1) return FootprintOutcome::LeftOut;
|
|
// The re-centring is not bounded, so the window can walk off a tile the frame still holds.
|
|
if (x0 < tile.x0 || y0 < tile.y0 || x1 >= tile.x0 + tile.w || y1 >= tile.y0 + tile.h)
|
|
return FootprintOutcome::OffTile;
|
|
const auto pixel = [&](int px, int py) {
|
|
return tile.pixels[static_cast<size_t>(py - tile.y0) * tile.w + (px - tile.x0)];
|
|
};
|
|
|
|
ring.clear();
|
|
for (int py = y0; py <= y1; ++py)
|
|
for (int px = x0; px <= x1; ++px) {
|
|
const float dx = px - cx, dy = py - cy;
|
|
const float rad = dx * ux + dy * uy, tn = -dx * uy + dy * ux;
|
|
const float e = rad * rad / (wr * wr) + tn * tn / (wt * wt);
|
|
const int32_t v = pixel(px, py);
|
|
if (e >= BKG_INNER * BKG_INNER && e < BKG_OUTER * BKG_OUTER && valid(v))
|
|
ring.push_back(static_cast<float>(v));
|
|
}
|
|
if (ring.size() < 10) return FootprintOutcome::LeftOut;
|
|
const double bkg = median_of(ring);
|
|
|
|
double w = 0.0, mr = 0.0, mt = 0.0, m2r = 0.0, m2t = 0.0;
|
|
for (int py = y0; py <= y1; ++py)
|
|
for (int px = x0; px <= x1; ++px) {
|
|
const float dx = px - cx, dy = py - cy;
|
|
const float rad = dx * ux + dy * uy, tn = -dx * uy + dy * ux;
|
|
if (rad * rad / (wr * wr) + tn * tn / (wt * wt) >= 1.0f) continue;
|
|
const int32_t v = pixel(px, py);
|
|
if (!valid(v)) return FootprintOutcome::LeftOut;
|
|
const double net = static_cast<double>(v) - bkg;
|
|
w += net;
|
|
mr += net * rad;
|
|
mt += net * tn;
|
|
m2r += net * rad * rad;
|
|
m2t += net * tn * tn;
|
|
}
|
|
if (!(w > 0.0)) return FootprintOutcome::LeftOut;
|
|
const double cr = mr / w, ct = mt / w;
|
|
s2r = static_cast<float>(std::max(0.25, m2r / w - cr * cr));
|
|
s2t = static_cast<float>(std::max(0.25, m2t / w - ct * ct));
|
|
cx += static_cast<float>(cr * ux - ct * uy);
|
|
cy += static_cast<float>(cr * uy + ct * ux);
|
|
}
|
|
spot = {r, std::sqrt(s2r), std::sqrt(s2t)};
|
|
return FootprintOutcome::Measured;
|
|
}
|
|
|
|
void MeasureFootprintSpots(const int32_t *img, int width, int height, float beam_x, float beam_y,
|
|
const std::vector<float> &x, const std::vector<float> &y,
|
|
std::vector<FootprintSpot> &out) {
|
|
const FootprintTile frame{img, 0, 0, width, height};
|
|
for (size_t s = 0; s < x.size(); ++s) {
|
|
FootprintSpot spot;
|
|
const BraggPanel pn = {x[s], y[s], 1.0f, 0.0f, 0.0f, 1.0f, 0, 0, width - 1, height - 1};
|
|
if (MeasureFootprintSpot(frame, pn, beam_x, beam_y, x[s], y[s], spot) == FootprintOutcome::Measured)
|
|
out.push_back(spot);
|
|
}
|
|
}
|
|
|
|
SpotFootprint FootprintFromSpots(const std::vector<FootprintSpot> &spots, float r_max) {
|
|
SpotFootprint fp;
|
|
if (!(r_max > 0.0f)) return fp;
|
|
const float bin = r_max / FOOTPRINT_BINS;
|
|
std::vector<std::vector<float>> rad(FOOTPRINT_BINS), tan(FOOTPRINT_BINS);
|
|
for (const auto &s : spots) {
|
|
const int b = std::clamp(static_cast<int>(s.r_px / bin), 0, FOOTPRINT_BINS - 1);
|
|
rad[b].push_back(s.sigma_rad);
|
|
tan[b].push_back(s.sigma_tan);
|
|
}
|
|
std::vector<int> filled;
|
|
std::vector<float> mr(FOOTPRINT_BINS, 0.0f), mt(FOOTPRINT_BINS, 0.0f);
|
|
for (int b = 0; b < FOOTPRINT_BINS; ++b)
|
|
if (static_cast<int>(rad[b].size()) >= FOOTPRINT_MIN_SPOTS_PER_BIN) {
|
|
mr[b] = median_of(rad[b]);
|
|
mt[b] = median_of(tan[b]);
|
|
filled.push_back(b);
|
|
}
|
|
if (filled.empty()) return fp;
|
|
fp.bin_px = bin;
|
|
for (int b = 0; b < FOOTPRINT_BINS; ++b) {
|
|
// The nearest bin that has enough spots; the inner one on a tie.
|
|
int best = filled.front();
|
|
for (int f : filled)
|
|
if (std::abs(f - b) < std::abs(best - b)) best = f;
|
|
fp.sigma_rad.push_back(mr[best]);
|
|
fp.sigma_tan.push_back(mt[best]);
|
|
}
|
|
return fp;
|
|
}
|
|
|
|
void MeasureFootprintOffsets(const std::vector<SpotToSave> &spots, const std::vector<Reflection> &reflections,
|
|
float beam_x, float beam_y, std::vector<FootprintOffset> &out) {
|
|
std::map<std::tuple<int, int, int>, const Reflection *> predicted;
|
|
for (const auto &r : reflections)
|
|
predicted[{r.h, r.k, r.l}] = &r;
|
|
for (const auto &s : spots) {
|
|
if (!s.indexed || s.lattice != 0) continue;
|
|
const auto it = predicted.find({static_cast<int>(s.h), static_cast<int>(s.k), static_cast<int>(s.l)});
|
|
if (it == predicted.end()) continue;
|
|
const float px = it->second->predicted_x, py = it->second->predicted_y;
|
|
const float rx = px - beam_x, ry = py - beam_y;
|
|
const float r = std::sqrt(rx * rx + ry * ry);
|
|
if (!(r > 1.0f)) continue;
|
|
const float ux = rx / r, uy = ry / r;
|
|
const float dx = s.x - px, dy = s.y - py;
|
|
out.push_back({r, dx * ux + dy * uy, -dx * uy + dy * ux});
|
|
}
|
|
}
|
|
|
|
SpotFootprint FootprintWithOffsets(const SpotFootprint &widths, std::vector<FootprintOffset> offsets) {
|
|
if (widths.empty()) return widths;
|
|
// Sorted, so the sums below do not depend on the order the frames were measured in.
|
|
std::sort(offsets.begin(), offsets.end());
|
|
const int n = static_cast<int>(widths.sigma_rad.size());
|
|
std::vector<double> s2r(n, 0.0), s2t(n, 0.0);
|
|
std::vector<int> cnt(n, 0);
|
|
for (const auto &o : offsets) {
|
|
const int b = std::clamp(static_cast<int>(o.r_px / widths.bin_px), 0, n - 1);
|
|
s2r[b] += static_cast<double>(o.off_rad) * o.off_rad;
|
|
s2t[b] += static_cast<double>(o.off_tan) * o.off_tan;
|
|
++cnt[b];
|
|
}
|
|
std::vector<int> filled;
|
|
for (int b = 0; b < n; ++b)
|
|
if (cnt[b] >= FOOTPRINT_MIN_SPOTS_PER_BIN) filled.push_back(b);
|
|
if (filled.empty()) return widths;
|
|
SpotFootprint fp = widths;
|
|
for (int b = 0; b < n; ++b) {
|
|
int best = filled.front();
|
|
for (int f : filled)
|
|
if (std::abs(f - b) < std::abs(best - b)) best = f;
|
|
fp.sigma_rad[b] = static_cast<float>(std::sqrt(widths.sigma_rad[b] * widths.sigma_rad[b] + s2r[best] / cnt[best]));
|
|
fp.sigma_tan[b] = static_cast<float>(std::sqrt(widths.sigma_tan[b] * widths.sigma_tan[b] + s2t[best] / cnt[best]));
|
|
}
|
|
return fp;
|
|
}
|