Files
Jungfraujoch/image_analysis/bragg_integration/BackgroundGain.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

167 lines
7.3 KiB
C++

// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
// SPDX-License-Identifier: GPL-3.0-only
#include "BackgroundGain.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include <numeric>
#include <utility>
namespace background_gain {
namespace {
constexpr int PAIR_DISTANCE = 2; // columns between the two pixels of a pair
constexpr size_t ROW_STEP = 4; // every fourth row: a quarter of a frame is ample for one number
constexpr double CLIP_NSIGMA = 4.0;
constexpr int CLIP_ROUNDS = 3;
const double LOG_BIN = std::log(1.25);
}
Levels MeasureFrame(const std::vector<int32_t> &image, size_t width, size_t height,
const std::vector<uint32_t> &mask, int64_t saturation) {
const auto usable = [&](size_t i) {
return mask[i] == 0 && image[i] >= 1 && image[i] < saturation;
};
// The level of every usable pair, worked out once; -1 where the pair is not usable.
std::vector<int8_t> bin(width * height, -1);
for (size_t y = 0; y < height; y += ROW_STEP)
for (size_t x = 0; x + PAIR_DISTANCE < width; x++) {
const size_t i = y * width + x;
if (!usable(i) || !usable(i + PAIR_DISTANCE))
continue;
const double m = 0.5 * (static_cast<double>(image[i]) + image[i + PAIR_DISTANCE]);
bin[i] = static_cast<int8_t>(std::min<int>(N_BINS - 1, static_cast<int>(std::log(m) / LOG_BIN)));
}
// Clip about zero at CLIP_NSIGMA of the level's own scatter, starting from no clip at all: a few
// rounds take the Bragg peaks and zingers out without needing any idea of the gain beforehand.
std::array<double, N_BINS> limit2;
limit2.fill(std::numeric_limits<double>::infinity());
Levels out;
for (int round = 0; round <= CLIP_ROUNDS; round++) {
out = Levels{};
for (size_t i = 0; i < bin.size(); i++) {
const int b = bin[i];
if (b < 0)
continue;
const double d = static_cast<double>(image[i]) - image[i + PAIR_DISTANCE];
if (d * d > limit2[b])
continue;
out.n[b]++;
out.sum_mean[b] += 0.5 * (static_cast<double>(image[i]) + image[i + PAIR_DISTANCE]);
out.sum_diff2[b] += d * d;
}
for (int b = 0; b < N_BINS; b++)
if (out.n[b] > 0)
limit2[b] = CLIP_NSIGMA * CLIP_NSIGMA * out.sum_diff2[b] / static_cast<double>(out.n[b]);
}
return out;
}
std::optional<float> Gain(const std::vector<Levels> &frames) {
// (variance/mean, pairs) per level
std::vector<std::pair<double, uint64_t>> ratio;
uint64_t total = 0;
for (int b = 0; b < N_BINS; b++) {
uint64_t n = 0;
double sum_mean = 0.0, sum_diff2 = 0.0;
for (const auto &f : frames) {
n += f.n[b];
sum_mean += f.sum_mean[b];
sum_diff2 += f.sum_diff2[b];
}
// var(a - b) = 2 var(pixel)
if (n >= MIN_PAIRS_PER_BIN && sum_mean > 0.0) {
ratio.emplace_back(0.5 * sum_diff2 / sum_mean, n);
total += n;
}
}
if (ratio.size() < MIN_BINS)
return std::nullopt;
// The median over PAIRS, not over levels: the background holds most of the pixels in a few levels,
// and the Bragg peaks spread a few pixels over many more - an unweighted median over the levels of
// a weak-background marCCD frame lands on the peaks and reads 5.7 where the background reads 0.3.
std::sort(ratio.begin(), ratio.end());
uint64_t cum = 0;
for (const auto &[r, n] : ratio) {
cum += n;
if (2 * cum >= total)
return static_cast<float>(r);
}
return static_cast<float>(ratio.back().first);
}
void AddToHistogram(const std::vector<int32_t> &image, const std::vector<uint32_t> &mask, int64_t saturation,
std::vector<uint64_t> &histogram) {
const int64_t end = std::min<int64_t>(saturation, PEAK_HISTOGRAM_BINS);
for (size_t i = 0; i < image.size(); i++)
if (mask[i] == 0 && image[i] >= 0 && image[i] < end)
histogram[image[i]]++;
}
std::optional<GainEstimate> PhotonPeak(const std::vector<uint64_t> &histogram) {
// A float file that holds whole numbers, read at a fraction of its unit, fills only every q-th bin:
// the histogram is read at that step.
size_t q = 0;
for (size_t i = 1; i < histogram.size(); i++)
if (histogram[i] > 0)
q = std::gcd(q, i);
q = std::max<size_t>(q, 1);
std::vector<uint64_t> h;
for (size_t i = 0; i < histogram.size(); i += q)
h.push_back(histogram[i]);
// A peak stands out of a valley where it is higher by five times its own counting noise.
const auto stands = [&](size_t valley, size_t peak) {
return static_cast<double>(h[peak]) - static_cast<double>(h[valley])
> 5.0 * std::sqrt(static_cast<double>(h[peak]));
};
// Most pixels hold no photon. Down the zero peak to the first valley.
const size_t p0 = std::max_element(h.begin(), h.end()) - h.begin();
size_t v0 = p0;
while (v0 + 1 < h.size() && h[v0 + 1] <= h[v0])
v0++;
if (v0 + 1 >= h.size())
return std::nullopt;
const size_t p1 = std::max_element(h.begin() + v0, h.end()) - h.begin();
const size_t g = p1 - p0;
// The zero-photon peak is the detector's noise, so it has a width: a single bin with nothing beside it is
// a CCD's pixels outside the active area, all at zero, and what follows is its background, not a photon.
if (h[p0 + 1] == 0 || !stands(v0, p1) || p1 + 3 * g / 2 >= h.size())
return std::nullopt;
// A photon is a peak narrower than the spacing: it falls below half its height before the midpoint to
// the next. A CCD's background is a hump as wide as where it lies.
if (2 * h[p1 + g / 2] >= h[p1])
return std::nullopt;
// The two-photon peak: the histogram rises again, near one more gain on, past the valley after p1.
const size_t v2 = std::min_element(h.begin() + p1, h.begin() + p1 + g + 1) - h.begin();
const size_t p2 = std::max_element(h.begin() + v2, h.begin() + p1 + 3 * g / 2 + 1) - h.begin();
if (!stands(v2, p2) || 4 * (p2 - p1) < 3 * g || 4 * (p2 - p1) > 5 * g)
return std::nullopt;
// Within the bin: the vertex of a parabola through the log counts of the peak and its neighbours. A
// zero peak in the first bin is a subtracted baseline, cut where the values turn negative: zero.
const auto vertex = [&](size_t p) {
if (p == 0)
return 0.0;
const double a = std::log(std::max<double>(1.0, h[p - 1]));
const double b = std::log(std::max<double>(1.0, h[p]));
const double c = std::log(std::max<double>(1.0, h[p + 1]));
const double curvature = a - 2.0 * b + c;
return static_cast<double>(p) + (curvature < 0.0 ? 0.5 * (a - c) / curvature : 0.0);
};
const double pedestal = vertex(p0);
return GainEstimate{static_cast<float>(q * (vertex(p1) - pedestal)), static_cast<float>(q * pedestal)};
}
std::optional<GainEstimate> Estimate(const std::vector<Levels> &frames, const std::vector<uint64_t> &histogram) {
if (const auto peaks = PhotonPeak(histogram))
return peaks;
if (const auto g = Gain(frames))
return GainEstimate{*g, 0.0f};
return std::nullopt;
}
} // namespace background_gain