diff --git a/common/PixelMask.cpp b/common/PixelMask.cpp index c59ef2dc2..a5338f4ee 100644 --- a/common/PixelMask.cpp +++ b/common/PixelMask.cpp @@ -247,6 +247,14 @@ void PixelMask::LoadBeamStopMask(const DiffractionExperiment& experiment, const UpdateDerived(experiment); } +void PixelMask::LoadHotPixelMask(const DiffractionExperiment& experiment, const std::vector &in_mask) { + if (in_mask.size() != mask.size()) + throw JFJochException(JFJochExceptionCategory::InputParameterInvalid, + "Size of input hot pixel mask invalid"); + LoadMask(in_mask, HotPixelBit); + UpdateDerived(experiment); +} + void PixelMask::ClearBeamStopMask(const DiffractionExperiment& experiment) { for (auto &i: mask) i &= ~(1u << BeamStopPixelBit); diff --git a/common/PixelMask.h b/common/PixelMask.h index eb7b2534d..5408b0789 100644 --- a/common/PixelMask.h +++ b/common/PixelMask.h @@ -41,6 +41,9 @@ public: constexpr static const uint8_t NoisyPixelBit = 4; constexpr static const uint8_t UserMaskedPixelBit = 8; constexpr static const uint8_t BeamStopPixelBit = 9; + // Found bad on the run's own frames (rugnux pre-scan, HotPixelFinder): lit above its ring on too + // many frames, or holding the error value on most of them. + constexpr static const uint8_t HotPixelBit = 10; constexpr static const uint8_t ChipGapPixelBit = 31; constexpr static const uint8_t ModuleEdgePixelBit = 30; @@ -56,6 +59,7 @@ public: // The beam-stop shadow belongs to the run that found it, not to the dataset, so a mask read back // from a file that carries one starts clear. The user mask (bit 8) is deliberately left alone. void ClearBeamStopMask(const DiffractionExperiment& experiment); + void LoadHotPixelMask(const DiffractionExperiment& experiment, const std::vector& mask); void LoadDECTRISBadPixelMask(const std::vector& mask); void LoadDarkBadPixelMask(const DiffractionExperiment& experiment, const std::vector& mask); void LoadDetectorBadPixelMask(const DiffractionExperiment& experiment, const JFCalibration *calib); diff --git a/docs/CPU_DATA_ANALYSIS_IMAGE.md b/docs/CPU_DATA_ANALYSIS_IMAGE.md index 7e1ce00d9..4175042f4 100644 --- a/docs/CPU_DATA_ANALYSIS_IMAGE.md +++ b/docs/CPU_DATA_ANALYSIS_IMAGE.md @@ -334,6 +334,33 @@ reflection — a maximum over the frames well above background, in a cluster, so zinger does not count — is given back, because a beam stop cannot have blocked a reflection that was measured. +### 1.6 Defective pixels + +A pixel that reads high frame after frame, whatever the crystal does, is integrated into whichever +reflection's box it falls in; under rotation that is one pixel collecting a different reflection on +every frame that reaches it, and a merged intensity hundreds or thousands of times its shell mean, +carried by one or two observations the merge's outlier test cannot judge. The file's mask misses +such pixels on many detectors, so on rotation data from a counting sensor Rugnux measures them on +the pre-scan's own sample of frames (`HotPixelFinder`, `rugnux/HotPixels.h`) and masks them as bit 10. +The frames are read a second time for it, once the beam-stop projection has measured where the +scattered background puts the beam: the rings have to be drawn about the true beam, and a file's +centre can be far enough out that a ring crosses the background's radial fall-off. + +On each frame a pixel is **lit** when it exceeds $b + 3.3\,\max(\sqrt{b}, 1.4826\,\mathrm{MAD}) + 2$, +with $b$ the larger of the median of its 2 px iso-$2\theta$ ring and of that ring's sixteenth in +azimuth, so ice and powder rings, the polarization dip and partial shadows set their own level. It +is **persistent** when it is lit on at least $\max(k_1, k_B)$ of the sampled frames: one reflection +stays on a pixel for $(\Delta\phi + w)/|\zeta|$ of rotation ($w = 5°$, a generous rocking width), +which covers fewer than $k_1 = 1 + \lceil (\Delta\phi + w)/(|\zeta|\,\delta) \rceil$ frames sampled +$\delta$ apart; and $k_B$ is the binomial bound, from the lit rate of the ring's other pixels, that +fewer than 0.01 pixels of the whole detector reach by chance. A persistent pixel is masked if it +stands alone (by itself or in a pair — a larger patch is a feature of the scattering, not a +defect), reads on average at least ten times its ring, and its mean excess is above the Poisson +bound; a weaker one cannot make an outlier. Pixels holding the detector's error +value on most frames (already invalid on every frame, but not in the static mask) are masked with +them. A CCD (no sensor depth: read with an offset, not Poisson) is left alone. One log line says how +many pixels were masked and why. + --- ## 2. Azimuthal integration (radial profiles) diff --git a/docs/PIXEL_MASK.md b/docs/PIXEL_MASK.md index e1e6fae5c..22f5200a4 100644 --- a/docs/PIXEL_MASK.md +++ b/docs/PIXEL_MASK.md @@ -21,6 +21,10 @@ Unlike the other bits this one belongs to the run that found it, not to the data at the start of every run, so a mask read back from a file that carries one starts clear. The user mask (bit 8) is left alone. +Bit 10 - defective pixel found on the run's own frames (rotation data from a counting sensor; see +[CPU data analysis §1.6](CPU_DATA_ANALYSIS_IMAGE.md)): lit above its resolution ring on more frames +than one reflection or chance explains, or holding the detector's error value on most frames. + Bit 30 - module edge (only for PSI systems) Bit 31 - chip edge interpolated pixel (multipixel) diff --git a/docs/RUGNUX_OVERVIEW.md b/docs/RUGNUX_OVERVIEW.md index 902a24bee..87274be27 100644 --- a/docs/RUGNUX_OVERVIEW.md +++ b/docs/RUGNUX_OVERVIEW.md @@ -9,7 +9,8 @@ rotation run with the defaults; stills differences are at the end. serial stills — nothing is asked of the user. **Pre-scan.** A projection of the first frames (60 by default) finds the beam-stop shadow and masks -it ([§1.5](CPU_DATA_ANALYSIS_IMAGE.md)), measures the beam centre from the isotropy of the +it ([§1.5](CPU_DATA_ANALYSIS_IMAGE.md)), masks pixels its frames show to be defective +([§1.6](CPU_DATA_ANALYSIS_IMAGE.md)), measures the beam centre from the isotropy of the scattered background and compares it with the file's ([§1.4](CPU_DATA_ANALYSIS_IMAGE.md)), and reads how wide this crystal's spots are, which sets the integration radius ([§9.5](CPU_DATA_ANALYSIS_INTEGRATION.md)). diff --git a/rugnux/CMakeLists.txt b/rugnux/CMakeLists.txt index a496e1088..0f7b1cac8 100644 --- a/rugnux/CMakeLists.txt +++ b/rugnux/CMakeLists.txt @@ -23,6 +23,8 @@ ADD_LIBRARY(Rugnux STATIC ReportDocument.h SpotWidth.cpp SpotWidth.h + HotPixels.cpp + HotPixels.h DiagnosticOutput.cpp DiagnosticOutput.h SpindleCuspLoss.cpp diff --git a/rugnux/HotPixels.cpp b/rugnux/HotPixels.cpp new file mode 100644 index 000000000..d8eb8b67d --- /dev/null +++ b/rugnux/HotPixels.cpp @@ -0,0 +1,231 @@ +// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute +// SPDX-License-Identifier: GPL-3.0-only + +#include "HotPixels.h" + +#include +#include +#include +#include + +#include "../common/JFJochMath.h" +#include "../common/ParallelFor.h" + +namespace { + +// The lower median of v[0..n), reordering it. +int32_t median_of(int32_t *v, size_t n) { + std::nth_element(v, v + n / 2, v + n); + return v[n / 2]; +} + +// The smallest k with npix * P(Binomial(n, q) >= k) below the family-wise rate, n + 1 if none. +int binomial_bound(int n, double q, double npix, double rate) { + double tail = 0.0; + int k = n + 1; + for (int j = n; j >= 0; j--) { + tail += std::exp(std::lgamma(n + 1.0) - std::lgamma(j + 1.0) - std::lgamma(n - j + 1.0) + + j * std::log(q) + (n - j) * std::log1p(-q)); + if (npix * tail >= rate) break; + k = j; + } + return k; +} + +} // namespace + +HotPixelFinder::HotPixelFinder(const DiffractionExperiment &experiment, const PixelMask &mask, size_t nthreads) + : geometry(experiment.GetDiffractionGeometry()), + axis(experiment.GetGoniometer() ? experiment.GetGoniometer()->GetAxis().Normalize() : Coord(0, 0, 0)), + width(experiment.GetXPixelsNumConv()), height(experiment.GetYPixelsNumConv()), + key(width * height, -1), + n_valid(width * height, 0), n_lit(width * height, 0), n_error(width * height, 0), + sum_value(width * height, 0), sum_level(width * height, 0) { + const auto &m = mask.GetMask(); + // Rings of equal 2theta, RING_WIDTH_PX wide where the beam meets the detector. + const float ring_rad = RING_WIDTH_PX * geometry.GetPixelSize_mm() / geometry.GetDetectorDistance_mm(); + ParallelChunks(static_cast(height), nthreads, [&](int y0, int y1) { + for (size_t y = y0; y < static_cast(y1); y++) + for (size_t x = 0; x < width; x++) { + const size_t i = y * width + x; + if (m[i] != 0) continue; + const float fx = static_cast(x), fy = static_cast(y); + const int ring = static_cast(geometry.TwoTheta_rad(fx, fy) / ring_rad); + const int sector = std::min(SECTORS - 1, static_cast(geometry.Phi_rad(fx, fy) + / static_cast(2.0 * PI) * SECTORS)); + key[i] = ring * SECTORS + sector; + } + }); + for (const int32_t k : key) + if (k >= 0) { + nrings = std::max(nrings, k / SECTORS + 1); + unmasked++; + } + + key_begin.assign(static_cast(nrings) * SECTORS + 1, 0); + for (const int32_t k : key) + if (k >= 0) key_begin[k + 1]++; + for (size_t k = 1; k < key_begin.size(); k++) + key_begin[k] += key_begin[k - 1]; +} + +void HotPixelFinder::AddImage(const int32_t *image, std::vector &scratch) { + const size_t npix = width * height; + const size_t nkeys = static_cast(nrings) * SECTORS; + + // The frame's valid counts laid out by ring and sector. A saturated pixel has no count to add. + scratch.resize(npix); + std::vector count(nkeys, 0); + for (size_t i = 0; i < npix; i++) { + const int32_t k = key[i], v = image[i]; + if (k < 0 || v == INT32_MIN || v == INT32_MAX) continue; + scratch[key_begin[k] + count[k]++] = v; + } + + std::vector sector_level(nkeys, 0); + for (size_t k = 0; k < nkeys; k++) + if (count[k] >= MIN_SECTOR_PIXELS) + sector_level[k] = median_of(scratch.data() + key_begin[k], count[k]); + + // Each ring's sectors packed together - forward into the space the ring owns, so nothing is + // overwritten before it is moved - then its median and its robust spread about that median. + std::vector ring_level(nrings, 0); + std::vector ring_spread(nrings, 0.0f); + std::vector ring_ok(nrings, 0); + for (int r = 0; r < nrings; r++) { + int32_t *ring = scratch.data() + key_begin[r * SECTORS]; + size_t n = 0; + for (int s = 0; s < SECTORS; s++) { + const size_t k = r * SECTORS + s; + std::memmove(ring + n, scratch.data() + key_begin[k], count[k] * sizeof(int32_t)); + n += count[k]; + } + if (n < MIN_RING_PIXELS) continue; + ring_ok[r] = 1; + ring_level[r] = median_of(ring, n); + for (size_t j = 0; j < n; j++) + ring[j] = std::abs(ring[j] - ring_level[r]); + ring_spread[r] = 1.4826f * static_cast(median_of(ring, n)); + } + + std::vector level(nkeys, 0); + std::vector threshold(nkeys, 0.0f); + for (size_t k = 0; k < nkeys; k++) { + const int r = static_cast(k / SECTORS); + level[k] = std::max(ring_level[r], sector_level[k]); + const float noise = std::max(std::sqrt(static_cast(std::max(level[k], 0))), ring_spread[r]); + threshold[k] = static_cast(level[k]) + LIT_NSIGMA * noise + LIT_OFFSET; + } + + // Every sum is an integer, so the result does not depend on the order the frames arrive in. + { + std::lock_guard lock(m); + frames++; + } + const size_t rows_per_band = (height + BANDS - 1) / BANDS; + const size_t first = next_band.fetch_add(1); + for (size_t b = 0; b < BANDS; b++) { + const size_t band = (first + b) % BANDS; + const size_t begin = std::min(npix, band * rows_per_band * width); + const size_t end = std::min(npix, (band + 1) * rows_per_band * width); + std::lock_guard lock(band_mutex[band]); + for (size_t i = begin; i < end; i++) { + const int32_t k = key[i], v = image[i]; + if (k < 0) continue; + if (v == INT32_MIN) { + n_error[i]++; + continue; + } + if (!ring_ok[k / SECTORS]) continue; + n_valid[i]++; + sum_value[i] += v; + sum_level[i] += level[k]; + if (v == INT32_MAX || static_cast(v) > threshold[k]) + n_lit[i]++; + } + } +} + +HotPixelFinder::Result HotPixelFinder::GetMask(double oscillation_deg, double spacing_deg, + size_t nthreads) const { + std::lock_guard lock(m); + Result ret; + ret.frames = frames; + ret.mask.assign(width * height, 0); + const int n = static_cast(frames); + + // The chance rate per ring, from the pixels lit on no more than half of their frames: whatever + // lights those - reflections, zingers, noise above the bound - lights a defect-free pixel too. + std::vector lit(nrings, 0.0), seen(nrings, 0.0); + for (size_t i = 0; i < key.size(); i++) + if (key[i] >= 0 && n_valid[i] > 0 && 2 * n_lit[i] <= n_valid[i]) { + lit[key[i] / SECTORS] += n_lit[i]; + seen[key[i] / SECTORS] += n_valid[i]; + } + std::vector k_chance(nrings, n + 1); + for (int r = 0; r < nrings; r++) + if (seen[r] > 0.0) + k_chance[r] = binomial_bound(n, std::clamp(lit[r] / seen[r], 1e-6, 0.999), + static_cast(unmasked), FAMILY_WISE_RATE); + + // Persistent: lit on more frames than one reflection or chance explains. + const int min_valid = std::max(10, n / 2); + std::vector persistent(width * height, 0); + ParallelChunks(static_cast(height), nthreads, [&](int y0, int y1) { + for (size_t y = y0; y < static_cast(y1); y++) + for (size_t x = 0; x < width; x++) { + const size_t i = y * width + x; + if (key[i] < 0 || n_valid[i] < min_valid || n_lit[i] == 0 || !(spacing_deg > 0.0)) continue; + // One reflection's stay on this pixel, in sampled frames: 1 / |zeta| turns the rocking + // width into rotation, and zeta = |axis . (s1 x s0)| with s0 along z. + const Coord s1 = geometry.LabCoord(static_cast(x), static_cast(y)).Normalize(); + const double zeta = std::max(1e-4, static_cast(std::fabs(axis * (s1 % Coord(0, 0, 1))))); + const double stay = (oscillation_deg + ROCKING_WIDTH_DEG) / zeta; + const double k_bragg = 1.0 + std::ceil(stay / spacing_deg); + const double k = std::min(std::max(k_bragg, k_chance[key[i] / SECTORS]), + n_valid[i]); + persistent[i] = n_lit[i] >= k; + } + }); + + // Masked: a persistent pixel standing alone - on its own or as one of a pair; a larger patch is + // a feature of the scattering, not a defect - whose mean is STRONG_RATIO times its ring's and + // whose excess is above the Poisson bound. A weaker one cannot make an outlier. + const auto persistent_neighbours = [&](size_t x, size_t y) { + int count = 0; + for (size_t yy = (y > 0 ? y - 1 : 0); yy <= std::min(height - 1, y + 1); yy++) + for (size_t xx = (x > 0 ? x - 1 : 0); xx <= std::min(width - 1, x + 1); xx++) + if ((xx != x || yy != y) && persistent[yy * width + xx]) count++; + return count; + }; + ParallelChunks(static_cast(height), nthreads, [&](int y0, int y1) { + for (size_t y = y0; y < static_cast(y1); y++) + for (size_t x = 0; x < width; x++) { + const size_t i = y * width + x; + if (key[i] < 0) continue; + if (2 * n_error[i] > n) { + ret.mask[i] = 2; + continue; + } + if (!persistent[i]) continue; + const int neighbours = persistent_neighbours(x, y); + bool isolated = neighbours == 0; + if (neighbours == 1) + for (size_t yy = (y > 0 ? y - 1 : 0); yy <= std::min(height - 1, y + 1); yy++) + for (size_t xx = (x > 0 ? x - 1 : 0); xx <= std::min(width - 1, x + 1); xx++) + if ((xx != x || yy != y) && persistent[yy * width + xx]) + isolated = persistent_neighbours(xx, yy) == 1; + const double mean_level = static_cast(sum_level[i]) / n_valid[i]; + const double excess = static_cast(sum_value[i] - sum_level[i]) / n_valid[i]; + if (isolated + && static_cast(sum_value[i]) >= STRONG_RATIO * static_cast(sum_level[i]) + && excess >= LIT_NSIGMA * std::sqrt(std::max(mean_level, 0.0)) + LIT_OFFSET) + ret.mask[i] = 1; + } + }); + for (const uint32_t v : ret.mask) { + ret.hot += v == 1; + ret.error += v == 2; + } + return ret; +} diff --git a/rugnux/HotPixels.h b/rugnux/HotPixels.h new file mode 100644 index 000000000..03dfc64e0 --- /dev/null +++ b/rugnux/HotPixels.h @@ -0,0 +1,111 @@ +// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute +// SPDX-License-Identifier: GPL-3.0-only + +#pragma once + +// ============================================================================= +// HotPixelFinder - pixels the pre-scan's own frames show to be defective +// ============================================================================= +// +// A pixel that reads high on frame after frame, whatever the crystal is doing, is not recording +// diffraction. Unmasked, it is integrated as part of whichever reflection's box it falls in, and +// under rotation that is one pixel at one resolution collecting a different reflection on every +// frame that reaches it - a merged intensity hundreds or thousands of times its shell mean, +// supported by one or two observations the merge's outlier test cannot judge. The file's own +// mask misses such pixels on many detectors, and which pixels are hot moves with the threshold +// setting, so they are measured per dataset, on the pre-scan's sample of frames. +// +// On each frame a pixel is LIT when it is Poisson-significantly above the level of its own +// resolution ring - the larger of the median of the 2 px iso-2theta ring and of the ring's +// sixteenth in azimuth, so an ice or powder ring, the polarization dip and a partly shadowed ring +// all set their own level. It is PERSISTENT when it is lit on more of the sampled frames than +// either explanation that is not a defect allows: +// +// * one Bragg reflection: it stays on a pixel for (oscillation + rocking width) / |zeta| of +// rotation, i.e. on at most 1 + ceil(that / frame spacing) of frames sampled that far apart; +// * chance: independent reflections and noise light a pixel of this ring on a fraction q of the +// frames (measured, on the ring's pixels that are not candidates), and the number of lit frames +// that fewer than 0.01 of all the detector's pixels would reach by chance is the binomial bound. +// +// A persistent pixel is masked only if it stands alone (by itself or in a pair - a larger patch is a +// feature of the scattering, not a defect), reads on average at least ten times its ring, and its +// mean excess is above the Poisson bound: a weaker one cannot make an outlier. A pixel holding the +// detector's error value on most frames is masked with it: every frame already treats it as invalid, +// but the static mask did not know. The detector's outermost row and column get no rule of their +// own - a hot pixel there is caught like any other. +// +// None of this holds for a CCD, whose pixels carry a read-out offset and are not Poisson; the caller +// runs it for counting sensors only. +// ============================================================================= + +#include +#include +#include +#include + +#include "../common/DiffractionExperiment.h" +#include "../common/PixelMask.h" + +class HotPixelFinder { +public: + // Sixteen sectors of the ring; the level is the larger of the two medians. + static constexpr int SECTORS = 16; + // Ring width in 2theta: this many pixels where the beam meets the detector, wider further out. + static constexpr float RING_WIDTH_PX = 2.0f; + // A ring needs this many valid pixels to have a level, a sector this many to have one of its own. + static constexpr int MIN_RING_PIXELS = 16; + static constexpr int MIN_SECTOR_PIXELS = 8; + // Lit: above level + LIT_NSIGMA * noise + LIT_OFFSET (noise = the larger of sqrt(level) and the + // ring's robust spread; the offset keeps a pixel in a ring with no background from being lit by + // one or two photons). + static constexpr float LIT_NSIGMA = 3.3f; + static constexpr float LIT_OFFSET = 2.0f; + // How long one reflection can stay on a pixel, degrees of rotation beyond the oscillation: +-3 + // sigma of a rocking curve 2 degrees FWHM, wider than the crystals this is meant for. + static constexpr float ROCKING_WIDTH_DEG = 5.0f; + // Pixels expected to be called persistent by chance on the whole detector. + static constexpr double FAMILY_WISE_RATE = 0.01; + // A persistent pixel is masked only where it reads this many times its ring on average: the + // strength at which the pixels behind the merged outliers were found, and well clear of a pixel + // that is merely a little over-responding. + static constexpr double STRONG_RATIO = 10.0; + + struct Result { + std::vector mask; // non-zero = masked (1 hot, 2 error value), converted geometry + size_t hot = 0; // persistent above the ring + size_t error = 0; // holding the error value on most frames + uint32_t frames = 0; + }; + + HotPixelFinder(const DiffractionExperiment &experiment, const PixelMask &mask, size_t nthreads); + + // One preprocessed frame (INT32_MIN = masked or error value, INT32_MAX = saturated). Thread + // safe; `scratch` is the caller's own, reused across its calls. + void AddImage(const int32_t *image, std::vector &scratch); + + // The mask, from the frames added so far. oscillation_deg is the rotation per image and + // spacing_deg the rotation between two consecutive sampled frames. + [[nodiscard]] Result GetMask(double oscillation_deg, double spacing_deg, size_t nthreads) const; + +private: + const DiffractionGeometry geometry; + const Coord axis; // rotation axis; zero where there is none + const size_t width, height; + int nrings = 0; + + // Ring * SECTORS + sector of every pixel, -1 where the pixel is already masked. + std::vector key; + // Where each ring-sector's pixels start in a scratch buffer laid out by key. + std::vector key_begin; + size_t unmasked = 0; + + // The per-pixel sums are guarded by bands of rows, so workers adding frames at the same time + // meet only when they reach the same band. + static constexpr size_t BANDS = 64; + mutable std::mutex band_mutex[BANDS]; + std::atomic next_band{0}; + mutable std::mutex m; + uint32_t frames = 0; + std::vector n_valid, n_lit, n_error; + std::vector sum_value, sum_level; +}; diff --git a/rugnux/Rugnux.cpp b/rugnux/Rugnux.cpp index c4ce5ed0e..cd419d874 100644 --- a/rugnux/Rugnux.cpp +++ b/rugnux/Rugnux.cpp @@ -7,6 +7,7 @@ #include "WriteModel.h" #include "SpindleCuspLoss.h" #include "SpotWidth.h" +#include "HotPixels.h" #include "DiagnosticOutput.h" #include @@ -820,7 +821,15 @@ void Rugnux::PreScan(int start_image, int images_to_process, int frame_count, Ru && config_.two_pass_rotation && experiment_.IsRotationIndexing(); const bool want_width = config_.adaptive_integration_radius && !spot_width_measured_ && !second_pass_follows; - if (!want_shadow && !want_beam_center && !want_width) + // Defective pixels, for the same reason on the same pass: each pixel is compared against its + // resolution ring. Only where the counts are photons from a counting sensor - a CCD (no sensor + // depth) is read with an offset and is not Poisson - and only under rotation, where a reflection + // moves off a pixel and a defect does not. + const auto goniometer = experiment_.GetGoniometer(); + const bool want_hot = !hot_pixels_measured_ && !second_pass_follows + && experiment_.IsRotationIndexing() && goniometer && goniometer->IsScanning() + && experiment_.GetDetectorSetup().GetSensorThickness_um() > 0.0f; + if (!want_shadow && !want_beam_center && !want_width && !want_hot) return; // The two consumers want different frames and each gets its own set. The shadow is built from @@ -833,7 +842,6 @@ void Rugnux::PreScan(int start_image, int images_to_process, int frame_count, Ru // [0, images_to_process) always picks the very first and the very last image, and those are the // ones a shutter out of step spoils - the last carries under 90 % of the sample's median counts // on 12 of 38 regression sweeps and is essentially unexposed on 5. - const auto goniometer = experiment_.GetGoniometer(); const int margin = std::min(PRESCAN_END_MARGIN_IMAGES, images_to_process / 10); auto shadow_sample = select_equally_spaced_image_ordinals(images_to_process - 2 * margin, frame_count); @@ -1174,6 +1182,8 @@ void Rugnux::PreScan(int start_image, int images_to_process, int frame_count, Ru return; } + // Where the scattered background puts the beam, when the projection exists to say so. + std::optional> ring_centre; if (want_shadow) { // Every pixel is compared against the ring it sits on, so the rings have to be drawn about // the beam. A centre far enough out draws them across the background's own radial fall-off @@ -1189,6 +1199,7 @@ void Rugnux::PreScan(int start_image, int images_to_process, int frame_count, Ru if (const auto ring_center = FindBeamCenterFromBackground(experiment_, pixel_mask_, projection)) { finder.BeamCenter(ring_center->beam_x_pxl, ring_center->beam_y_pxl); + ring_centre = std::make_pair(ring_center->beam_x_pxl, ring_center->beam_y_pxl); logger.Info("Beam stop: comparing each pixel against its ring about the measured " "centre ({:.2f},{:.2f}) +- {:.2f} px, {:.2f} px from the file's", ring_center->beam_x_pxl, ring_center->beam_y_pxl, ring_center->sigma_pxl, @@ -1240,6 +1251,9 @@ void Rugnux::PreScan(int start_image, int images_to_process, int frame_count, Ru // projecting every frame for this alone is the largest per-frame cost of the pre-scan. On the // second pass of a two-pass run the shadow is already in the mask, so this does not run again - // by then the centre has been post-refined and the file's value is no longer what is in it. + if (want_hot) + MaskDefectivePixels(start_image, shadow_sample, ring_centre); + if (want_shadow && config_.beam_center_check) { const auto t0 = std::chrono::steady_clock::now(); BeamCenterFFTResult capture; @@ -1479,6 +1493,61 @@ void Rugnux::PreScan(int start_image, int images_to_process, int frame_count, Ru experiment_.BeamX_pxl(estimate->beam_x_pxl).BeamY_pxl(estimate->beam_y_pxl); } +void Rugnux::MaskDefectivePixels(int start_image, const std::vector &sample, + const std::optional> &ring_centre) { + Logger logger("Rugnux"); + hot_pixels_measured_ = true; + + // The frames are read a second time, because the rings each pixel is compared against have to + // be drawn about the beam, and the centre the file states can be far enough out that a ring + // crosses the background's own radial fall-off - the pixels on its bright side then read high on + // every frame. The centre the beam-stop projection has just measured does not exist until every + // frame of the first read is in. + DiffractionExperiment about = experiment_; + if (ring_centre) + about.BeamX_pxl(ring_centre->first).BeamY_pxl(ring_centre->second); + const size_t nthreads = static_cast(std::max(config_.nthreads, 1)); + HotPixelFinder finder(about, pixel_mask_, nthreads); + + std::atomic next{0}; + std::vector> futures; + const size_t nworkers = std::min(nthreads, std::min(PRESCAN_MAX_WORKERS, sample.size())); + for (size_t t = 0; t < nworkers; t++) + futures.emplace_back(std::async(std::launch::async, [&] { + ImagePreprocessorCPU preprocessor(experiment_, pixel_mask_); + ImagePreprocessorBuffer image(experiment_.GetPixelsNum()); + JFJochReaderRawImage raw; + std::vector buffer; + std::vector scratch; + for (size_t i = next.fetch_add(1); i < sample.size(); i = next.fetch_add(1)) { + const int image_idx = start_image + sample[i] * config_.stride; + try { + if (!reader_.ReadRawImage(image_idx, raw)) continue; + preprocessor.Analyze(image, raw.image.GetUncompressedPtr(buffer), raw.image.GetMode()); + } catch (const std::exception &e) { + if (IsFatalResourceError(e)) throw; + logger.Warning("Defective pixels: failed to read image {}: {}", image_idx, e.what()); + continue; + } + finder.AddImage(image.data(), scratch); + } + })); + for (auto &f : futures) f.get(); + + const auto goniometer = experiment_.GetGoniometer(); + const double oscillation = std::abs(goniometer->GetIncrement_deg()); + const double spacing = sample.size() > 1 + ? oscillation * (sample.back() - sample.front()) / static_cast(sample.size() - 1) + : 0.0; + const auto hot = finder.GetMask(oscillation, spacing, nthreads); + if (hot.frames == 0) + return; + pixel_mask_.LoadHotPixelMask(experiment_, hot.mask); + logger.Info("Defective pixels: {} masked from {} pre-scan frames - {} lit above their ring on more " + "frames than one reflection or chance explains, {} holding the detector's error value", + hot.hot + hot.error, hot.frames, hot.hot, hot.error); +} + void Rugnux::RefineStillsGeometry(int start_image, int end_image, int images_to_process, RugnuxObserver *observer) { Logger logger("Rugnux"); diff --git a/rugnux/Rugnux.h b/rugnux/Rugnux.h index 1ed2bee04..c74278625 100644 --- a/rugnux/Rugnux.h +++ b/rugnux/Rugnux.h @@ -554,6 +554,9 @@ class Rugnux { // The recorded spot width the pre-scan measured (config_.adaptive_integration_radius), kept so the // two-pass rotation run measures it once and both passes integrate at the same radius. bool spot_width_measured_ = false; + // The pixels the pre-scan's own frames show to be defective (HotPixelFinder) are measured once, + // on the pre-scan that also measures the width, and stay in pixel_mask_ for every pass after it. + bool hot_pixels_measured_ = false; // The integration radii in force before the measured spot width widened them, so a widening that // turns out to cost data can be given back exactly rather than to a written-down default. std::optional bragg_before_adaptive_; @@ -600,6 +603,10 @@ class Rugnux { // width that sets the integration radius (config_.adaptive_integration_radius). Any of the three // may be asked for without the others. void PreScan(int start_image, int images_to_process, int frame_count, RugnuxObserver *observer); + // The pre-scan's defective-pixel mask (HotPixelFinder), read on `sample` with the rings drawn + // about `ring_centre` where the background measured one. + void MaskDefectivePixels(int start_image, const std::vector &sample, + const std::optional> &ring_centre); // Powder calibration, second pass: re-integrate the same images into a profile binned with the // geometry the first fit produced, and fit that. Nothing but the binning changes, which is the // point - which pixel went into which (q, phi) bin was decided by the geometry the run started diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index c0e10383c..2992aa624 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -52,6 +52,7 @@ ADD_EXECUTABLE(jfjoch_test JFJochReaderTest.cpp SweepLayoutTest.cpp ShadowFinderTest.cpp + HotPixelFinderTest.cpp ParallelForTest.cpp RugnuxTest.cpp ResultReportTest.cpp diff --git a/tests/HotPixelFinderTest.cpp b/tests/HotPixelFinderTest.cpp new file mode 100644 index 000000000..6fc72fcb1 --- /dev/null +++ b/tests/HotPixelFinderTest.cpp @@ -0,0 +1,65 @@ +// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute +// SPDX-License-Identifier: GPL-3.0-only + +#include + +#include +#include +#include + +#include "../common/DetectorSetup.h" +#include "../common/DiffractionExperiment.h" +#include "../common/PixelMask.h" +#include "../rugnux/HotPixels.h" + +namespace { + constexpr int W = 257, H = 257, C = 128; + constexpr int NFRAMES = 60; + constexpr double OSC_DEG = 0.1, SPACING_DEG = 6.0; // 60 frames spread over a full turn + + constexpr size_t I(int x, int y) { return static_cast(y) * W + x; } +} + +// A Poisson background with a powder ring, and on it four kinds of pixel: one that reads 60 counts +// high on every frame, one only 20 high - persistent, but too weak to make an outlier - one that holds +// the error value on every frame, and one crossed by a genuine reflection. The last sits close to the rotation axis, where one reflection stays on a pixel for a +// long stretch of rotation - here nine consecutive sampled frames, more than the chance bound allows +// but fewer than the one-reflection bound at that zeta. Only the first and the third are masked. +TEST_CASE("HotPixelFinder_PersistentPixelNotBragg", "[HotPixelFinder]") { + DiffractionExperiment x(DetDECTRIS(W, H, "Test detector", "")); + x.IncidentEnergy_keV(WVL_1A_IN_KEV).DetectorDistance_mm(10.0f); + x.BeamX_pxl(static_cast(C)).BeamY_pxl(static_cast(C)); + x.Goniometer(GoniometerAxis("omega", 0.0f, static_cast(OSC_DEG), Coord(1, 0, 0), std::nullopt)); + const PixelMask pixel_mask(x); + HotPixelFinder finder(x, pixel_mask, 4); + + constexpr int HOT_X = 200, HOT_Y = 200, WARM_X = 190, WARM_Y = 60, ERR_X = 60, ERR_Y = 190; + constexpr int BRAGG_X = 40, BRAGG_Y = 115; + std::mt19937 rng(1); + // The powder ring is a smooth radial profile, as a real one is: 45 counts over the background at + // 82 px, 4 px sigma. + std::vector frame(static_cast(W) * H), scratch; + for (int f = 0; f < NFRAMES; f++) { + for (int y = 0; y < H; y++) + for (int x_ = 0; x_ < W; x_++) { + const double r = std::hypot(x_ - C, y - C); + const double mean = 5.0 + 45.0 * std::exp(-0.5 * (r - 82.0) * (r - 82.0) / 16.0); + frame[I(x_, y)] = std::poisson_distribution(mean)(rng); + } + frame[I(HOT_X, HOT_Y)] += 60; + frame[I(WARM_X, WARM_Y)] += 20; + frame[I(ERR_X, ERR_Y)] = INT32_MIN; + if (f >= 20 && f < 29) + frame[I(BRAGG_X, BRAGG_Y)] += 500; + finder.AddImage(frame.data(), scratch); + } + + const auto result = finder.GetMask(OSC_DEG, SPACING_DEG, 4); + CHECK(result.frames == NFRAMES); + CHECK(result.mask[I(HOT_X, HOT_Y)] == 1); // 1 = hot, 2 = error value + CHECK(result.mask[I(ERR_X, ERR_Y)] == 2); + CHECK(result.mask[I(WARM_X, WARM_Y)] == 0); + CHECK(result.mask[I(BRAGG_X, BRAGG_Y)] == 0); + CHECK(result.hot == 1); + CHECK(result.error == 1); +}