Merge branch 'pp50-reg' into rc175

This commit is contained in:
leonarski_f committed 2026-10-08 07:59:33 +02:00
commit ebc008ad94
8 files changed
+171 -47

No files matched your search

+33 -1
View File
@@ -106,6 +106,7 @@ HotPixelFinder::HotPixelFinder(const DiffractionExperiment &experiment, const Pi
key_frames.assign(static_cast<size_t>(nrings) * SECTORS, 0);
key_level_sum.assign(static_cast<size_t>(nrings) * SECTORS, 0);
key_local_level_sum.assign(static_cast<size_t>(nrings) * SECTORS, 0);
key_begin.assign(static_cast<size_t>(nrings) * SECTORS + 1, 0);
for (size_t i = 0; i < width * height; i++)
if (key[i] >= 0) key_begin[key[i] + 1]++;
@@ -176,9 +177,15 @@ void HotPixelFinder::AddImage(const int32_t *image, std::vector<int32_t> &scratc
ring_spread[r] = 1.4826f * static_cast<float>(median_of(ring, n));
}
// The level a pixel is judged dark against is its own sector's - the ring's where the sector has
// too few pixels for one.
std::vector<int32_t> local_level(nkeys);
for (size_t k = 0; k < nkeys; k++)
local_level[k] = count[k] >= MIN_SECTOR_PIXELS ? sector_level[k] : ring_level[k / SECTORS];
std::vector<int32_t> level;
std::vector<float> threshold;
AddLevels(sector_level, ring_level, ring_spread, ring_ok, level, threshold);
AddLevels(sector_level, ring_level, ring_spread, ring_ok, local_level, level, threshold);
const size_t rows_per_band = (height + BANDS - 1) / BANDS;
const size_t first = next_band.fetch_add(1);
@@ -208,6 +215,7 @@ void HotPixelFinder::AddImage(const int32_t *image, std::vector<int32_t> &scratc
void HotPixelFinder::AddLevels(const std::vector<int32_t> &sector_level, const std::vector<int32_t> &ring_level,
const std::vector<float> &ring_spread, const std::vector<char> &ring_ok,
const std::vector<int32_t> &local_level,
std::vector<int32_t> &level, std::vector<float> &threshold) {
const size_t nkeys = static_cast<size_t>(nrings) * SECTORS;
level.assign(nkeys, 0);
@@ -228,6 +236,7 @@ void HotPixelFinder::AddLevels(const std::vector<int32_t> &sector_level, const s
if (ring_ok[k / SECTORS]) {
key_frames[k]++;
key_level_sum[k] += level[k];
key_local_level_sum[k] += local_level[k];
}
}
@@ -297,14 +306,19 @@ HotPixelFinder::Result HotPixelFinder::GetMask(double oscillation_deg, double sp
// Persistent: lit on more frames than one reflection or chance explains.
const int min_valid = std::max(10, n / 2);
// Whether the pixel's own sums are on the host. A sum of zero reads as dark, so a pixel whose sums
// stayed on the device must not be judged by the dead rule.
std::vector<uint8_t> sums_known(width * height, 1);
#ifdef JFJOCH_USE_CUDA
// With a GPU the per-pixel sums stay there. Only the pixels that can be masked come back - those the
// tests below could pass (see GetCandidates) - into the host arrays, which are zero everywhere else,
// so the tests below run on them unchanged.
if (gpu) {
const auto c = gpu->GetCandidates(frames, min_valid, spacing_deg > 0.0, k_chance);
std::fill(sums_known.begin(), sums_known.end(), 0);
for (size_t j = 0; j < c.index.size(); j++) {
const size_t i = c.index[j];
sums_known[i] = 1;
n_lit[i] = c.n_lit[j];
n_error[i] = c.n_error[j];
n_error_ring_ok[i] = c.n_error_ring_ok[j];
@@ -314,6 +328,7 @@ HotPixelFinder::Result HotPixelFinder::GetMask(double oscillation_deg, double sp
for (size_t k = 0; k < key_frames.size(); k++) {
key_frames[k] = static_cast<uint16_t>(c.key_frames[k]);
key_level_sum[k] = c.key_level_sum[k];
key_local_level_sum[k] = c.key_local_level_sum[k];
}
}
#endif
@@ -351,6 +366,22 @@ HotPixelFinder::Result HotPixelFinder::GetMask(double oscillation_deg, double sp
ret.mask[i] = 2;
continue;
}
// Dead: the mirror of hot. A pixel reading at most half of its own sector's level, by
// more than the bound a hot pixel's excess has to clear, is not recording the light that
// reaches it, and every reflection whose disk covers it is integrated short by that
// deficit on every frame - a dead row along a detector edge merged reflections there
// to large negative intensities. Nothing that is not a defect keeps a pixel dark on
// frame after frame: a reflection only adds counts. A pixel that also held the error
// value on some frames is left to the rule above.
if (sums_known[i] && n_error[i] == 0 && n_valid(i) >= min_valid
&& 2 * sum_value[i] <= key_local_level_sum[key[i]]) {
const double mean_local = static_cast<double>(key_local_level_sum[key[i]]) / n_valid(i);
const double deficit = mean_local - static_cast<double>(sum_value[i]) / n_valid(i);
if (deficit >= LIT_NSIGMA * std::sqrt(mean_local) + LIT_OFFSET) {
ret.mask[i] = 3;
continue;
}
}
if (!persistent[i]) continue;
const double mean_level = static_cast<double>(sum_level(i)) / n_valid(i);
const double excess = static_cast<double>(sum_value[i] - sum_level(i)) / n_valid(i);
@@ -362,6 +393,7 @@ HotPixelFinder::Result HotPixelFinder::GetMask(double oscillation_deg, double sp
for (const uint32_t v : ret.mask) {
ret.hot += v == 1;
ret.error += v == 2;
ret.dead += v == 3;
}
return ret;
}
+16 -5
View File
@@ -32,11 +32,16 @@
// patch lit through the whole sweep is stationary in the lab, so it is not a reflection of the
// rotating crystal, and a reflection crossing it reads the patch. 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.
// but the static mask did not know.
//
// 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.
// A DEAD pixel is the mirror of a hot one: it reads on average at most half of its own sector's level,
// and its mean deficit is above the bound a hot pixel's excess has to clear. Nothing but a defect keeps
// a pixel dark on frame after frame - a reflection only adds counts - and every reflection whose disk
// covers it is integrated short by the deficit. The detector's outermost row and column get no rule of
// their own - a dead edge row, or a hot pixel there, is caught like any other.
//
// A CCD is read with an offset and is not Poisson, but neither test needs it to be: a dead CCD pixel
// reads its offset, far below a ring with any background on it, and a hot one ten times its ring.
// =============================================================================
#include <atomic>
@@ -78,9 +83,10 @@ public:
static constexpr int MAX_SAMPLED_FRAMES = UINT16_MAX;
struct Result {
std::vector<uint32_t> mask; // non-zero = masked (1 hot, 2 error value), converted geometry
std::vector<uint32_t> mask; // non-zero = masked (1 hot, 2 error value, 3 dead), converted geometry
size_t hot = 0; // persistent above the ring
size_t error = 0; // holding the error value on most frames
size_t dead = 0; // reading at most half of its sector's level
uint32_t frames = 0;
};
@@ -134,6 +140,10 @@ private:
// memory traffic per frame.
std::vector<uint16_t> key_frames;
std::vector<int64_t> key_level_sum;
// The same sum for the level a pixel is judged DARK against: its own sector's median, the ring's
// where the sector has too few pixels. Every pixel of a key has the same, so it needs no per-pixel
// correction - a pixel with error frames is not judged dark.
std::vector<int64_t> key_local_level_sum;
std::unique_ptr<uint16_t[]> n_error_ring_ok;
std::unique_ptr<int64_t[]> error_level_sum;
#ifdef JFJOCH_USE_CUDA
@@ -144,6 +154,7 @@ private:
// share of the per-key sums. The device does the same in HotPixelsGPU.cu, with the same roundings.
void AddLevels(const std::vector<int32_t> &sector_level, const std::vector<int32_t> &ring_level,
const std::vector<float> &ring_spread, const std::vector<char> &ring_ok,
const std::vector<int32_t> &local_level,
std::vector<int32_t> &level, std::vector<float> &threshold);
[[nodiscard]] int n_valid(size_t i) const { return key_frames[key[i]] - n_error_ring_ok[i]; }
[[nodiscard]] int64_t sum_level(size_t i) const { return key_level_sum[key[i]] - error_level_sum[i]; }
+23 -9
View File
@@ -154,7 +154,8 @@ __global__ void levels_kernel(size_t nkeys, int sectors, HotPixelLevelRules rule
const int32_t *__restrict__ sector_median, const int32_t *__restrict__ ring_median,
const int32_t *__restrict__ ring_mad, int32_t *__restrict__ level,
float *__restrict__ threshold, char *__restrict__ ring_ok,
uint32_t *__restrict__ key_frames, int64_t *__restrict__ key_level_sum) {
uint32_t *__restrict__ key_frames, int64_t *__restrict__ key_level_sum,
int64_t *__restrict__ key_local_level_sum) {
const size_t k = blockIdx.x * static_cast<size_t>(blockDim.x) + threadIdx.x;
if (k >= nkeys) return;
const size_t r = k / sectors;
@@ -164,7 +165,9 @@ __global__ void levels_kernel(size_t nkeys, int sectors, HotPixelLevelRules rule
const bool ok = n >= static_cast<uint32_t>(rules.min_ring_pixels);
const int32_t ring_level = ok ? ring_median[r] : 0;
const float ring_spread = ok ? 1.4826f * static_cast<float>(ring_mad[r]) : 0.0f;
const int32_t sector_level = count[k] >= static_cast<uint32_t>(rules.min_sector_pixels) ? sector_median[k] : 0;
const bool sector_ok = count[k] >= static_cast<uint32_t>(rules.min_sector_pixels);
const int32_t sector_level = sector_ok ? sector_median[k] : 0;
const int32_t local_level = sector_ok ? sector_median[k] : ring_level;
const int32_t lv = max(ring_level, sector_level);
const float root = sqrtf(static_cast<float>(max(lv, 0)));
const float noise = root < ring_spread ? ring_spread : root;
@@ -176,6 +179,8 @@ __global__ void levels_kernel(size_t nkeys, int sectors, HotPixelLevelRules rule
atomicAdd(&key_frames[k], 1u);
atomicAdd(reinterpret_cast<unsigned long long *>(&key_level_sum[k]),
static_cast<unsigned long long>(static_cast<int64_t>(lv)));
atomicAdd(reinterpret_cast<unsigned long long *>(&key_local_level_sum[k]),
static_cast<unsigned long long>(static_cast<int64_t>(local_level)));
}
}
@@ -200,7 +205,8 @@ __global__ void chance_kernel(size_t npixels, int sectors, const int32_t *__rest
__global__ void candidate_kernel(size_t npixels, int sectors, uint32_t frames, int min_valid, bool spacing_ok,
const int32_t *__restrict__ key, const uint32_t *__restrict__ key_frames,
const uint16_t *__restrict__ n_lit, const uint16_t *__restrict__ n_error,
const uint16_t *__restrict__ n_error_ring_ok, const int *__restrict__ k_chance,
const uint16_t *__restrict__ n_error_ring_ok, const int64_t *__restrict__ sum_value,
const int64_t *__restrict__ key_local_level_sum, const int *__restrict__ k_chance,
uint32_t *__restrict__ count, uint32_t *__restrict__ out) {
const size_t i = blockIdx.x * static_cast<size_t>(blockDim.x) + threadIdx.x;
if (i >= npixels || key[i] < 0) return;
@@ -209,7 +215,9 @@ __global__ void candidate_kernel(size_t npixels, int sectors, uint32_t frames, i
const int lit = n_lit[i];
const bool persistent = spacing_ok && nv >= min_valid && lit > 0
&& lit >= min(max(2, k_chance[key[i] / sectors]), nv);
if (!error && !persistent) return;
// Can be dead (HotPixelFinder::GetMask): at most half of its sector's level, no error frames.
const bool dark = n_error[i] == 0 && nv >= min_valid && 2 * sum_value[i] <= key_local_level_sum[key[i]];
if (!error && !persistent && !dark) return;
const uint32_t slot = atomicAdd(count, 1u);
if (out) out[slot] = static_cast<uint32_t>(i);
}
@@ -244,7 +252,8 @@ HotPixelFinderGPU::HotPixelFinderGPU(const int32_t *host_key, size_t npixels,
key_begin(host_key_begin.size(), ALLOC),
n_lit(npixels, ALLOC), n_error(npixels, ALLOC), n_error_ring_ok(npixels, ALLOC),
sum_value(npixels, ALLOC), error_level_sum(npixels, ALLOC),
key_frames(std::max<size_t>(nkeys, 1), ALLOC), key_level_sum(std::max<size_t>(nkeys, 1), ALLOC) {
key_frames(std::max<size_t>(nkeys, 1), ALLOC), key_level_sum(std::max<size_t>(nkeys, 1), ALLOC),
key_local_level_sum(std::max<size_t>(nkeys, 1), ALLOC) {
cuda_err(cudaEventCreateWithFlags(&last_accumulate, cudaEventDisableTiming));
CudaStream stream;
cuda_err(cudaMemcpyAsync(key, host_key, npixels * sizeof(int32_t), cudaMemcpyHostToDevice, stream));
@@ -257,6 +266,7 @@ HotPixelFinderGPU::HotPixelFinderGPU(const int32_t *host_key, size_t npixels,
cuda_err(cudaMemsetAsync(error_level_sum, 0, npixels * sizeof(int64_t), stream));
cuda_err(cudaMemsetAsync(key_frames, 0, std::max<size_t>(nkeys, 1) * sizeof(uint32_t), stream));
cuda_err(cudaMemsetAsync(key_level_sum, 0, std::max<size_t>(nkeys, 1) * sizeof(int64_t), stream));
cuda_err(cudaMemsetAsync(key_local_level_sum, 0, std::max<size_t>(nkeys, 1) * sizeof(int64_t), stream));
// The unmasked pixels grouped by key: a stable sort of the pixel indices by key, so each key's
// pixels stay in pixel order. A masked pixel's key, -1, is the largest as unsigned and sorts last.
@@ -303,7 +313,7 @@ void HotPixelFinderGPU::Add(const int32_t *device_image, Frame &frame) {
cuda_err(cudaGetLastError());
levels_kernel<<<static_cast<unsigned>((nkeys + THREADS - 1) / THREADS), THREADS, 0, stream>>>(
nkeys, sectors, rules, frame.count, frame.sector_median, frame.ring_median, frame.ring_mad,
frame.level, frame.threshold, frame.ring_ok, key_frames, key_level_sum);
frame.level, frame.threshold, frame.ring_ok, key_frames, key_level_sum, key_local_level_sum);
cuda_err(cudaGetLastError());
std::lock_guard lock(accumulate_mutex);
@@ -344,7 +354,8 @@ HotPixelFinderGPU::Candidates HotPixelFinderGPU::GetCandidates(uint32_t frames,
stream));
cuda_err(cudaMemsetAsync(d_count, 0, sizeof(uint32_t), stream));
candidate_kernel<<<blocks, THREADS, 0, stream>>>(npixels, sectors, frames, min_valid, spacing_ok, key, key_frames,
n_lit, n_error, n_error_ring_ok, d_k_chance, d_count, nullptr);
n_lit, n_error, n_error_ring_ok, sum_value, key_local_level_sum,
d_k_chance, d_count, nullptr);
cuda_err(cudaGetLastError());
uint32_t n = 0;
cuda_err(cudaMemcpyAsync(&n, d_count, sizeof(uint32_t), cudaMemcpyDeviceToHost, stream));
@@ -353,11 +364,14 @@ HotPixelFinderGPU::Candidates HotPixelFinderGPU::GetCandidates(uint32_t frames,
Candidates c;
c.key_frames.resize(nkeys);
c.key_level_sum.resize(nkeys);
c.key_local_level_sum.resize(nkeys);
if (nkeys > 0) {
cuda_err(cudaMemcpyAsync(c.key_frames.data(), key_frames, nkeys * sizeof(uint32_t), cudaMemcpyDeviceToHost,
stream));
cuda_err(cudaMemcpyAsync(c.key_level_sum.data(), key_level_sum, nkeys * sizeof(int64_t),
cudaMemcpyDeviceToHost, stream));
cuda_err(cudaMemcpyAsync(c.key_local_level_sum.data(), key_local_level_sum, nkeys * sizeof(int64_t),
cudaMemcpyDeviceToHost, stream));
}
if (n > 0) {
CudaDevicePtr<uint32_t> index(n, ALLOC);
@@ -365,8 +379,8 @@ HotPixelFinderGPU::Candidates HotPixelFinderGPU::GetCandidates(uint32_t frames,
CudaDevicePtr<int64_t> g_sum(n, ALLOC), g_error_level(n, ALLOC);
cuda_err(cudaMemsetAsync(d_count, 0, sizeof(uint32_t), stream));
candidate_kernel<<<blocks, THREADS, 0, stream>>>(npixels, sectors, frames, min_valid, spacing_ok, key,
key_frames, n_lit, n_error, n_error_ring_ok, d_k_chance,
d_count, index);
key_frames, n_lit, n_error, n_error_ring_ok, sum_value,
key_local_level_sum, d_k_chance, d_count, index);
cuda_err(cudaGetLastError());
const unsigned gb = (n + THREADS - 1) / THREADS;
gather_kernel<<<gb, THREADS, 0, stream>>>(n, index, n_lit.get(), g_lit.get());
+6 -4
View File
@@ -42,7 +42,7 @@ class HotPixelFinderGPU {
CudaDevicePtr<uint16_t> n_lit, n_error, n_error_ring_ok;
CudaDevicePtr<int64_t> sum_value, error_level_sum;
CudaDevicePtr<uint32_t> key_frames;
CudaDevicePtr<int64_t> key_level_sum;
CudaDevicePtr<int64_t> key_level_sum, key_local_level_sum;
// Each pixel's sums are plain read-modify-writes, so the frames add to them one after another:
// every accumulation waits on the device for the one before it (an event, not the host).
@@ -82,16 +82,18 @@ public:
// valid frames, summed (HotPixelFinder::GetMask's chance rate). Waits for every frame added.
void ChanceCounts(std::vector<int64_t> &lit, std::vector<int64_t> &seen);
// The pixels that can be masked: those holding the error value on more than half of `frames`, and,
// The pixels that can be masked: those holding the error value on more than half of `frames`;
// where spacing_ok, those lit on at least min(max(2, k_chance[ring]), valid frames) of at least
// min_valid valid frames - a persistent pixel is lit on at least that many, because one reflection
// explains at least two. For each, its index and per-pixel sums; and every key's sums.
// explains at least two; and those with no error frame, at least min_valid valid frames and a sum
// at most half of their sector's level sum, which a dead pixel has. For each, its index and
// per-pixel sums; and every key's sums.
struct Candidates {
std::vector<uint32_t> index;
std::vector<uint16_t> n_lit, n_error, n_error_ring_ok;
std::vector<int64_t> sum_value, error_level_sum;
std::vector<uint32_t> key_frames;
std::vector<int64_t> key_level_sum;
std::vector<int64_t> key_level_sum, key_local_level_sum;
};
Candidates GetCandidates(uint32_t frames, int min_valid, bool spacing_ok, const std::vector<int> &k_chance);
};
+41 -17
View File
@@ -4,6 +4,7 @@
#include "ResolutionCutoff.h"
#include <algorithm>
#include <array>
#include <cmath>
#include <limits>
@@ -15,6 +16,7 @@ namespace {
constexpr int N_FIT_BINS = 25;
constexpr int MIN_BIN_COUNT = 10;
constexpr int MIN_FIT_BINS = 5; // need at least this many usable bins for a fit
constexpr int MAX_CC_GROUPS = 7; // a bin's CC1/2 is the median over this many groups (odd)
constexpr int EXTEND_BINS_PAST_FALLOFF = 2; // bins kept beyond the first sub-target bin
constexpr double SHELLS_FOR_EXTENSION = 10.0; // "+1 shell" = one 10-shell width in s (report-independent)
@@ -80,12 +82,13 @@ ResolutionCutoffResult ComputeCCHalfLogisticCutoff(const std::vector<MergedRefle
// reflections are still merged, still written, still counted in the shell table.
//
// s = 1/d^2 range over the merged reflections that carry a half-set pair.
auto usable = [](const MergedReflection &m) {
return !m.on_ice_ring && m.d > 0.0f && std::isfinite(m.I_half[0]) && std::isfinite(m.I_half[1]);
};
double s_lo = std::numeric_limits<double>::max(), s_hi = 0.0;
double d_data_min = std::numeric_limits<double>::max();
for (const auto &m : merged) {
if (m.on_ice_ring)
continue;
if (!(m.d > 0.0f) || !std::isfinite(m.I_half[0]) || !std::isfinite(m.I_half[1]))
if (!usable(m))
continue;
const double s = 1.0 / (static_cast<double>(m.d) * m.d);
s_lo = std::min(s_lo, s);
@@ -99,28 +102,49 @@ ResolutionCutoffResult ComputeCCHalfLogisticCutoff(const std::vector<MergedRefle
// Bin CC1/2 against s (equal width in s, matching the reporting shells which are equal in 1/d^2).
const double bin_w = (s_hi - s_lo) / N_FIT_BINS;
std::vector<CorrelationCoefficient> bin_cc(N_FIT_BINS);
std::vector<int> bin_n(N_FIT_BINS, 0);
for (const auto &m : merged) {
if (m.on_ice_ring)
continue;
if (!(m.d > 0.0f) || !std::isfinite(m.I_half[0]) || !std::isfinite(m.I_half[1]))
continue;
auto bin_of = [&](const MergedReflection &m) {
const double s = 1.0 / (static_cast<double>(m.d) * m.d);
int b = static_cast<int>((s - s_lo) / bin_w);
b = std::clamp(b, 0, N_FIT_BINS - 1);
bin_cc[b].Add(m.I_half[0], m.I_half[1], m.cc_weight);
++bin_n[b];
return std::clamp(static_cast<int>((s - s_lo) / bin_w), 0, N_FIT_BINS - 1);
};
std::vector<int> bin_n(N_FIT_BINS, 0);
for (const auto &m : merged)
if (usable(m)) ++bin_n[bin_of(m)];
// A bin's CC1/2 is the median of the Pearson CC1/2 of a few groups its reflections are dealt into by
// their indices, not one Pearson over the whole bin. A Pearson CC has no bound on
// what one pair can do to it: in a weak shell a single reflection with a huge intensity in both
// halves - an artefact the halves reproduce, or one observation with a sigma fifty times the shell's
// - carries nearly all of the covariance and reads the shell at CC1/2 0.98 where the rest of it is
// noise, and the cut runs on through it. Here such a reflection takes one group with it, and the
// median does not follow. On a shell without one, every group estimates the same CC1/2 and the
// median is the Pearson value. Groups of fewer than MIN_BIN_COUNT reflections are not formed: a bin
// too small for three groups is one group, the plain Pearson CC1/2.
std::vector<int> bin_groups(N_FIT_BINS);
for (int b = 0; b < N_FIT_BINS; ++b) {
const int g = std::min(MAX_CC_GROUPS, std::max(1, bin_n[b] / MIN_BIN_COUNT));
bin_groups[b] = g % 2 == 1 ? g : g - 1;
}
std::vector<std::array<CorrelationCoefficient, MAX_CC_GROUPS>> group_cc(N_FIT_BINS);
for (const auto &m : merged) {
if (!usable(m)) continue;
const int b = bin_of(m);
const uint32_t hash = static_cast<uint32_t>(m.h) * 73856093u ^ static_cast<uint32_t>(m.k) * 19349663u
^ static_cast<uint32_t>(m.l) * 83492791u;
group_cc[b][hash % bin_groups[b]].Add(m.I_half[0], m.I_half[1], m.cc_weight);
}
// Usable bins (enough counts), in ascending-s order, with their bin-centre s.
std::vector<double> s_bin, cc_bin;
for (int b = 0; b < N_FIT_BINS; ++b) {
if (bin_n[b] < MIN_BIN_COUNT) continue;
const double cc = bin_cc[b].GetCC();
if (!std::isfinite(cc)) continue;
std::vector<double> cc;
for (int g = 0; g < bin_groups[b]; ++g)
if (std::isfinite(group_cc[b][g].GetCC()))
cc.push_back(group_cc[b][g].GetCC());
if (cc.empty()) continue;
std::nth_element(cc.begin(), cc.begin() + cc.size() / 2, cc.end());
s_bin.push_back(s_lo + (b + 0.5) * bin_w);
cc_bin.push_back(cc);
cc_bin.push_back(cc[cc.size() / 2]);
}
if (static_cast<int>(s_bin.size()) < MIN_FIT_BINS) {
result.note = "too few usable CC1/2 bins";
+6 -8
View File
@@ -163,13 +163,10 @@ void Rugnux::PreScan(int start_image, int images_to_process, int frame_count, Ru
// radius the first one measured rather than re-reading the frames.
const bool want_width = config_.adaptive_integration_radius && !spot_width_measured_;
// 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.
// resolution ring. 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_
&& experiment_.IsRotationIndexing() && goniometer && goniometer->IsScanning()
&& experiment_.GetDetectorSetup().GetSensorThickness_um() > 0.0f;
&& experiment_.IsRotationIndexing() && goniometer && goniometer->IsScanning();
if (!want_shadow && !want_width && !want_hot)
return;
@@ -916,8 +913,9 @@ void Rugnux::MaskDefectivePixels(int start_image, const std::vector<int> &sample
if (hot.frames == 0)
return;
pixel_mask_.LoadHotPixelMask(experiment_, hot.mask);
const size_t masked = hot.hot + hot.error + hot.dead;
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);
Note(fmt::format("{} defective pixel{} masked", hot.hot + hot.error, hot.hot + hot.error == 1 ? "" : "s"));
"frames than one reflection or chance explains, {} holding the detector's error value, {} dead",
masked, hot.frames, hot.hot, hot.error, hot.dead);
Note(fmt::format("{} defective pixel{} masked", masked, masked == 1 ? "" : "s"));
}
+22 -3
View File
@@ -27,6 +27,8 @@ namespace {
// 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 - and
// a 3x3 patch reading high on every frame, which is stationary in the lab and so no reflection either.
// Three dark pixels besides: one dead on the powder ring, which is masked, one on the ring reading 70%
// of it, and one dead on the 5-count background, whose deficit is too small to make an outlier.
TEST_CASE("HotPixelFinder_PersistentPixelNotBragg", "[HotPixelFinder]") {
DiffractionExperiment x(DetDECTRIS(W, H, "Test detector", ""));
x.IncidentEnergy_keV(WVL_1A_IN_KEV).DetectorDistance_mm(10.0f);
@@ -38,6 +40,7 @@ TEST_CASE("HotPixelFinder_PersistentPixelNotBragg", "[HotPixelFinder]") {
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;
constexpr int PATCH_X = 150, PATCH_Y = 225;
constexpr int DEAD_X = C + 82, DEAD_Y = C, DIM_X = C, DIM_Y = C + 82, DEAD_BKG_X = 20, DEAD_BKG_Y = 20;
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.
@@ -57,28 +60,36 @@ TEST_CASE("HotPixelFinder_PersistentPixelNotBragg", "[HotPixelFinder]") {
frame[I(PATCH_X + dx, PATCH_Y + dy)] += 60;
if (f >= 20 && f < 29)
frame[I(BRAGG_X, BRAGG_Y)] += 500;
frame[I(DEAD_X, DEAD_Y)] = 0;
frame[I(DIM_X, DIM_Y)] = static_cast<int32_t>(0.7 * frame[I(DIM_X, DIM_Y)]);
frame[I(DEAD_BKG_X, DEAD_BKG_Y)] = 0;
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(HOT_X, HOT_Y)] == 1); // 1 = hot, 2 = error value, 3 = dead
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);
for (int dy = -1; dy <= 1; dy++)
for (int dx = -1; dx <= 1; dx++)
CHECK(result.mask[I(PATCH_X + dx, PATCH_Y + dy)] == 1);
CHECK(result.mask[I(DEAD_X, DEAD_Y)] == 3);
CHECK(result.mask[I(DIM_X, DIM_Y)] == 0);
CHECK(result.mask[I(DEAD_BKG_X, DEAD_BKG_Y)] == 0);
CHECK(result.hot == 10);
CHECK(result.error == 1);
CHECK(result.dead == 1);
}
#ifdef JFJOCH_USE_CUDA
// The device path against the host one, on frames that take every branch of both: a background bright
// enough on one annulus that the host reads its rings' statistics off the exact selection rather than
// its histogram, negative counts, saturated and error pixels scattered at random, masked pixels, and a
// few hundred planted pixels whose excess and persistence straddle every threshold, so that a level or
// a threshold one count off would move some of them across. The masks must be identical.
// few hundred planted pixels whose excess and persistence straddle every threshold, and as many read at
// fractions of their counts that straddle the dead rule's, so that a level or a threshold one count off
// would move some of them across. The masks must be identical.
TEST_CASE("HotPixelFinder_DeviceMatchesHost", "[HotPixelFinder]") {
if (get_gpu_count() == 0) {
WARN("No CUDA GPU present. Skipping HotPixelFinder_DeviceMatchesHost");
@@ -104,6 +115,9 @@ TEST_CASE("HotPixelFinder_DeviceMatchesHost", "[HotPixelFinder]") {
std::vector<Planted> planted;
for (int p = 0; p < 300; p++)
planted.push_back({I(coord(rng), coord(rng)), 5 + p / 3, 0.2 + 0.8 * (p % 7) / 6.0});
std::vector<std::pair<size_t, double>> dark;
for (int p = 0; p < 300; p++)
dark.push_back({I(coord(rng), coord(rng)), 0.3 + 0.3 * (p % 13) / 12.0});
std::vector<int32_t> image(static_cast<size_t>(W) * H), scratch;
std::uniform_real_distribution<double> u(0.0, 1.0);
@@ -122,6 +136,9 @@ TEST_CASE("HotPixelFinder_DeviceMatchesHost", "[HotPixelFinder]") {
for (const auto &p : planted)
if (u(rng) < p.rate && image[p.i] != INT32_MIN && image[p.i] != INT32_MAX)
image[p.i] += p.excess;
for (const auto &[i, fraction] : dark)
if (image[i] != INT32_MIN && image[i] != INT32_MAX)
image[i] = static_cast<int32_t>(fraction * image[i]);
for (size_t i = 0; i < image.size(); i++)
if (pixel_mask.GetMask()[i] != 0)
image[i] = INT32_MIN; // as the preprocessor leaves a masked pixel
@@ -137,6 +154,8 @@ TEST_CASE("HotPixelFinder_DeviceMatchesHost", "[HotPixelFinder]") {
const auto expected = host.GetMask(OSC_DEG, SPACING_DEG, 4);
const auto result = device.GetMask(OSC_DEG, SPACING_DEG, 4);
CHECK(expected.hot > 10);
CHECK(expected.dead > 3);
CHECK(result.dead == expected.dead);
CHECK(result.frames == expected.frames);
CHECK(result.hot == expected.hot);
CHECK(result.error == expected.error);
+24
View File
@@ -316,6 +316,7 @@ namespace {
std::normal_distribution<double> g(0.0, sigma);
for (int j = 0; j < n; ++j) {
MergedReflection m;
m.h = static_cast<int32_t>(v.size()); // every reflection its own index
m.d = static_cast<float>(1.0 / std::sqrt(s_from + (j + 0.5) * (s_to - s_from) / n));
const double a = g(rng), b = g(rng);
m.I_half[0] = static_cast<float>(a);
@@ -345,6 +346,29 @@ TEST_CASE("ResolutionCutoff_CleanFallOff") {
CHECK(*rc.d_cut == Catch::Approx(1.92).margin(0.15));
}
// Past the fall-off, a few single reflections read hundreds of times the shell's noise in both halves -
// an artefact the half-sets reproduce. Each carries nearly all of its shell's covariance, so a Pearson
// CC1/2 reads those shells as signal and the cut runs on through them; one reflection per shell must not
// decide where the signal stops.
TEST_CASE("ResolutionCutoff_SingleReflectionsDoNotHoldTheCutOpen") {
Logger logger("test");
std::mt19937 rng(12345);
std::vector<MergedReflection> merged;
AddBand(merged, rng, 0.01, 0.25, 480, true);
AddBand(merged, rng, 0.25, 0.51, 520, false);
for (const double s : {0.26, 0.28, 0.30, 0.32}) {
MergedReflection m;
m.h = static_cast<int32_t>(merged.size());
m.d = static_cast<float>(1.0 / std::sqrt(s));
m.I_half[0] = m.I_half[1] = 300.0f;
merged.push_back(m);
}
const auto rc = ComputeCCHalfLogisticCutoff(merged, 0.30, logger);
REQUIRE(rc.d_fit);
CHECK(*rc.d_fit == Catch::Approx(2.0).margin(0.15));
}
// A sweep with a long stretch where the crystal barely diffracted: the reflections measured only there
// are noise scaled up by 1/G, sigmas with them, and there are many of them at every resolution. Counted
// by the information they carry they must not hide where the well-measured reflections stop.