Merge: Wilson outlier test

The median outlier test needs three observations, so a reflection measured
once or twice (one good observation and one artefact, the usual case after
Friedel merging) was never tested, and where there were more, a precise-looking
artefact (a hot pixel, thousands of counts) could outweigh mates from weak
frames and become the weighted median itself.

Every observation of the written merge is now also judged against Wilson
statistics beyond 4 A: E^2 = I / (epsilon <I/epsilon>_shell), centric and
acentric laws, a bound set by alpha = 0.01 expected false rejections per
dataset (ln(2N/alpha); twice that for centrics), the lower confidence limit
I - z*sigma (own sigma, z from the same budget) required to exceed it, shells
whose <I> is not established at that significance not judged, and the bound
widened by the dataset's measured tail scale (peaks over threshold on the
well-measured shells; 1 for a Wilson crystal, larger under tNCS/anisotropy).
An improbable singleton is rejected; one with company only when most of its
reflection's other observations are probable and it disagrees with them. The
reflection is the group, or the Friedel pair under -A. Search merges are not
tested (epsilon is 1 in P1, and the screw rows are the reflections a wrong
epsilon would call improbable). The flags are handed to the device merge as
pre-rejections, so CPU and GPU agree.

Report: OBSERVATIONS_REJECTED_WILSON= (part of OBSERVATIONS_REJECTED=), and the
developer report lists each rejected observation (hkl, d, E^2, image, x, y).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01D1G8gJVAy6gp1K5Dz3NE5C
This commit is contained in:
leonarski_fandClaude Opus 5.5 committed 2026-09-24 07:26:42 +02:00
1 parent cab91e2663
commit 257686c6fd
12 files changed
+484 -22

No files matched your search

+8
View File
@@ -186,6 +186,14 @@ package: algorithms and new approaches for multi-crystal scaling" (2020), Acta C
G. Winter, D. G. Waterman et al., "Robust background modelling in DIALS" (2016), J. Appl. Cryst. 49,
1912-1921 [doi:10.1107/S1600576716013595](https://doi.org/10.1107/S1600576716013595).
**Wilson outlier test** — judging an observation that has no symmetry mates against the acentric and
centric intensity distributions of its resolution shell, with the symmetry enhancement factor, is
Wilson's statistics; rejecting only observations that are also significant, and keeping a reflection
whose observations are all large, follows AIMLESS's EMAX test. A. J. C. Wilson, "The probability
distribution of X-ray intensities" (1949), Acta Cryst. 2, 318-321 (DOI not verified, so omitted);
P. Evans, "Scaling and assessment of data quality" (2006), Acta Cryst. D62, 72-82
[doi:10.1107/S0907444905036693](https://doi.org/10.1107/S0907444905036693).
**Diffraction anisotropy** — the description of the overall fall-off by a single anisotropic
displacement tensor, its symmetry constraints, and the fact that only its deviatoric part is
determined (the isotropic part being degenerate with the overall scale) are Sheriff and Hendrickson's.
+2
View File
@@ -64,6 +64,8 @@ Beside them, on rotation data, the run reports **twin-immune zone evidence** for
Merging applies an optional per-observation median-based $N\sigma$ cut (`--reject-outliers`, default 6σ for `rot3d`, off otherwise). The same $N\sigma$ cut is fed back into the error model: after an initial $a,b$ fit the parameters are re-fit once on the reflections that survive rejection (dropping any whose squared deviation exceeds $N^2\,[a\,\sigma^2 + (b\,\langle I\rangle)^2]$), so the calibrated errors describe the reflections that actually enter the merge rather than the pre-rejection pool.
The median needs three observations, so a reflection measured once or twice — typically one good observation and one artefact (a hot pixel, a zinger) after Friedel merging — is never tested by it, and an artefact that looks precise (thousands of counts, a small relative $\sigma$) can outweigh mates from weak frames and become the median itself. Every observation of the written merge is therefore also judged by **Wilson statistics**. Beyond 4 Å its $E^2 = I/(\varepsilon\,\langle I/\varepsilon\rangle_\mathrm{shell})$ is compared with a bound set by a budget of $\alpha = 0.01$ expected false rejections per dataset: with $N$ observations tested, $\ln(2N/\alpha)$ for acentrics and twice that for centrics, and the observation's lower confidence limit $I - z\sigma$ (with its own $\sigma$, and $z$ from the same budget) must exceed it, so noise in weak shells does not trigger it; a shell whose $\langle I\rangle$ is not itself established at that significance is not judged. The bound is widened by the tail scale of the dataset's own intensity distribution, measured on its well-measured observations (1 for a Wilson crystal; larger under a pseudo-translation or anisotropy). An improbable singleton is dropped; an improbable observation with company only when most of the reflection's other observations are probable and it disagrees with their mean beyond the errors — several large observations confirm each other. The count is `OBSERVATIONS_REJECTED_WILSON=` in the report (included in `OBSERVATIONS_REJECTED=`), and the developer report lists each observation with its image and detector position.
### 13.4 Automatic resolution cutoff
By default the reported/written high-resolution limit is trimmed where $\mathrm{CC}_{1/2}$ falls off: a logistic is fitted to $\mathrm{CC}_{1/2}(s)$, and the limit is set **one reported-shell width past** the point where the fit crosses 0.30 — deliberately "one shell too far", so weak-but-real data below the crossing are kept rather than discarded. The extension is measured over the range that is actually kept, not the full measured range, so a detector reaching far past where the crystal diffracts cannot inflate it. `--scaling-high-resolution` overrides the limit and `--resolution-cutoff off` disables it.
+3 -1
View File
@@ -26,7 +26,9 @@ ADD_LIBRARY(JFJochScaleMerge
TranslationalNCS.cpp
TranslationalNCS.h
ScalingResult.h
ScalingResult.cpp)
ScalingResult.cpp
WilsonOutliers.cpp
WilsonOutliers.h)
TARGET_LINK_LIBRARIES(JFJochScaleMerge Ceres::ceres Eigen3::Eigen JFJochCommon fftw3f)
IF (JFJOCH_CUDA_AVAILABLE)
+12
View File
@@ -139,6 +139,16 @@ struct AnomalousMergeStatistics {
bool measured = false;
};
// An observation the Wilson outlier test removed from the merge (see WilsonOutliers.h): its own
// indices, its normalised intensity, and where it was recorded, so a recurring detector position shows.
struct WilsonRejectedObservation {
int32_t h = 0, k = 0, l = 0;
float d = NAN;
float e2 = NAN;
float image = NAN; // fractional image number
float x = NAN, y = NAN; // predicted detector position (pixels)
};
struct MergeStatistics {
std::vector<MergeStatisticsShell> shells;
MergeStatisticsShell overall;
@@ -163,6 +173,8 @@ struct MergeStatistics {
// BETTER by every number it reports, so the count has to be visible or the failure is silent.
// Zero when rejection is off.
size_t n_observations_rejected = 0;
// The part of those the Wilson test removed (see WilsonOutliers.h), each listed, in the written range.
std::vector<WilsonRejectedObservation> wilson_rejected;
double radiation_damage_delta_b = NAN;
std::vector<float> radiation_damage_b_batch;
double radiation_damage_batch_deg = 0.0;
@@ -23,6 +23,7 @@
#include "RfreeFlags.h"
#include "FrenchWilson.h"
#include "ResolutionCutoff.h"
#include "WilsonOutliers.h"
#include "../../common/CorrelationCoefficient.h"
#include "../../common/CrystalLattice.h"
#include "../../common/Definitions.h"
@@ -4202,6 +4203,8 @@ RotationScaleMerge::Result RotationScaleMerge::MergeAndStats(int n_groups, bool
fit_ab(kept);
}
};
// Friedel pair of each group when the hands are merged separately (-A); filled with the medians below.
std::vector<int32_t> pair_of_group;
{
std::vector<int32_t> cnt(n_groups, 0); // per-group usable count (both paths; feeds reject-median)
bool did_gpu = false;
@@ -4291,7 +4294,6 @@ RotationScaleMerge::Result RotationScaleMerge::MergeAndStats(int n_groups, bool
// the merge and took a whole CC1/2 bin, and the cut with it, from 0.80 to 0.18. A hand with
// three of its own keeps its own median, as before. Median set g is group g's own; median
// set n_groups + p is Friedel pair p's, filled only where a hand of p needs it.
std::vector<int32_t> pair_of_group;
std::vector<uint8_t> pair_needed;
if (!merge_friedel) {
const HKLKeyGenerator anom_keygen(/*merge_friedel=*/false, x.GetSpaceGroupOrP1());
@@ -4361,9 +4363,9 @@ RotationScaleMerge::Result RotationScaleMerge::MergeAndStats(int n_groups, bool
fit_error_model(samples);
}
auto corrected_sigma = [&](const Obs &o, float I_corr, float sigma_corr) -> float {
// The full's sigma under the error model, with the variance evaluated at intensity I_for_b.
auto model_sigma = [&](const Obs &o, double I_for_b, float sigma_corr) -> float {
if (!error_model_active) return sigma_corr;
const double I_for_b = std::isfinite(em_mean[o.group]) ? em_mean[o.group] : I_corr;
// A full's own sigma carries its own Poisson fluctuation: a full that came out low has a
// smaller sigma, so 1/sigma^2 weights it up and the merged mean drifts below <I>. Rebuild the
// variance at the reflection's EXPECTED intensity - var_bkg + var_per_I*<I>, the linear model
@@ -4378,6 +4380,9 @@ RotationScaleMerge::Result RotationScaleMerge::MergeAndStats(int n_groups, bool
+ (error_model_b * I_for_b) * (error_model_b * I_for_b);
return v > 0.0 ? static_cast<float>(std::sqrt(v)) : sigma_corr;
};
auto corrected_sigma = [&](const Obs &o, float I_corr, float sigma_corr) -> float {
return model_sigma(o, std::isfinite(em_mean[o.group]) ? em_mean[o.group] : I_corr, sigma_corr);
};
// ---- What the pooled outlier test's tolerance gains from the shell's own Bijvoet variance. ----
// An observation of one hand sits dI/2 from the pooled pair's mean, so its share of the pair's
// anomalous variance is dI^2/4 and the cut becomes n * sqrt(sigma^2 + v_anom). That is the plain
@@ -4480,6 +4485,33 @@ RotationScaleMerge::Result RotationScaleMerge::MergeAndStats(int n_groups, bool
std::vector<double> merged_I;
size_t reject_count = 0;
std::vector<uint8_t> rejected_obs; // per-full outlier-rejected flag (both paths)
// ---- The Wilson test (WilsonOutliers.h): every observation against the intensity distribution of
// its shell, beside the median test. It reaches what the median cannot - a reflection measured
// once or twice, and an artefact that outweighs its mates and becomes the median - and its
// reflection is the group, or with the hands merged separately the Friedel pair, which is
// what the median pools too. On the written merges only: the
// search merges run in P1 and its subgroups, where an axial reflection has epsilon 1 and the
// rows the screw-axis test reads are the ones a wrong epsilon would call improbable. ----
const bool wilson_test = reject_outliers && !for_search;
std::vector<float> group_epsilon;
std::vector<uint8_t> group_centric;
if (wilson_test) {
const gemmi::GroupOps gops = x.GetSpaceGroupOrP1().operations();
group_epsilon.resize(n_groups);
group_centric.resize(n_groups);
ParallelChunks(n_groups, ThreadsForWork(n_groups, nthreads), [&](int lo, int hi) {
for (int g = lo; g < hi; ++g) {
const gemmi::Op::Miller hkl{group_h[g], group_k[g], group_l[g]};
group_epsilon[g] = static_cast<float>(std::max(1, gops.epsilon_factor_without_centering(hkl)));
group_centric[g] = gops.is_reflection_centric(hkl) ? 1 : 0;
}
});
}
// Expected false rejections per dataset.
constexpr double WILSON_ALPHA = 0.01;
WilsonOutlierResult wilson;
std::vector<int32_t> wilson_full; // the full behind each Wilson observation
auto run_merge = [&]() {
// The device path's unpack below writes every field of every group - MergeAccumKernel fills the
// empty ones too - so there this only has to be the right size. The host path accumulates into
@@ -4494,6 +4526,24 @@ RotationScaleMerge::Result RotationScaleMerge::MergeAndStats(int n_groups, bool
merged_I.assign(n_groups, NAN);
reject_count = 0;
rejected_obs.assign(fulls.size(), 0);
if (wilson_test) {
// Each observation with its OWN sigma, the error model evaluated at its own intensity: the
// reflection's mean, which the merge weights use, is exactly what an artefact inflates.
std::vector<WilsonObservation> wobs;
wilson_full.clear();
for (int i = 0; i < n_full; ++i) {
const int g = mf.group[i];
if (g < 0) continue;
const Obs &o = fulls[i];
const float I_corr = o.I * o.corr;
wobs.push_back({I_corr, model_sigma(o, I_corr, o.sigma * o.corr), o.d, group_epsilon[g],
group_centric[g] != 0, merge_friedel ? g : pair_of_group[g]});
wilson_full.push_back(i);
}
wilson = WilsonOutliers(wobs, WILSON_ALPHA);
for (size_t j = 0; j < wobs.size(); ++j)
if (wilson.rejected[j]) rejected_obs[wilson_full[j]] = 1;
}
bool did_gpu_acc = false;
#ifdef JFJOCH_USE_CUDA
if (use_gpu_merge) {
@@ -4539,6 +4589,10 @@ RotationScaleMerge::Result RotationScaleMerge::MergeAndStats(int n_groups, bool
if (!did_gpu_acc)
for (const auto &o : fulls) {
if (!usable_merge(o)) continue;
if (rejected_obs[&o - fulls.data()]) { // by the Wilson test above
++reject_count;
continue;
}
const float I_corr = o.I * o.corr;
float sigma_corr = o.sigma * o.corr;
sigma_corr = corrected_sigma(o, I_corr, sigma_corr);
@@ -4769,6 +4823,10 @@ RotationScaleMerge::Result RotationScaleMerge::MergeAndStats(int n_groups, bool
if (reject_count > 0)
logger.Info("Merge outlier rejection: dropped {} observations", reject_count);
if (wilson_test && wilson.n_tested > 0)
logger.Info("Wilson outlier test: {} observations tested, "
"tail scale {:.2f}, bound E^2 > {:.1f} (acentric), {} rejected", wilson.n_tested,
wilson.tail_scale, wilson.bound, wilson.n_rejected);
// ---- Statistics (report_shell_count shells): completeness, multiplicity, <I/sigma>, R_meas, CC1/2,
// SigAno and CCanom, over a shell grid. A lambda because the same merged reflections are
// binned a second time, over the reference range, when --report-resolution asked for that
@@ -5180,6 +5238,12 @@ RotationScaleMerge::Result RotationScaleMerge::MergeAndStats(int n_groups, bool
// Radiation-damage monitor (measured before any correction by MeasureRadiationDamageB): carry the
// first->last relative-B change and the per-batch curve into the reported statistics / mmCIF.
out.n_observations_rejected = reject_count;
for (size_t j = 0; j < wilson.rejected.size(); ++j) {
if (!wilson.rejected[j]) continue;
const Obs &o = fulls[wilson_full[j]];
if (effective_d_min && o.d < *effective_d_min) continue;
out.wilson_rejected.push_back({o.h, o.k, o.l, o.d, wilson.e2[j], o.image_number, o.px, o.py});
}
out.radiation_damage_delta_b = rad_damage_delta_b;
out.radiation_damage_b_batch = rad_damage_b_batch;
out.radiation_damage_batch_deg = rad_damage_batch_deg;
@@ -528,6 +528,18 @@ namespace {
}
}
// The full's sigma under the error model with its variance at intensity I_for_b - the host model_sigma.
// At the reflection's expected intensity the merge weight cannot know this full's own fluctuation.
__device__ __forceinline__ float ModelSigma(int i, const MergeParams &p, double I_for_b, float sigma_raw) {
const double bi = p.error_model_b * I_for_b;
const double c = p.corr[i];
double a_var = double(sigma_raw) * sigma_raw;
const double base = c * c * p.var_bkg[i] + c * p.var_per_I[i] * Dmax(0.0, I_for_b);
if (base > 0.0) a_var = base;
const double v = p.error_model_a * a_var + bi * bi;
return v > 0.0 ? float(sqrt(v)) : sigma_raw;
}
// One thread per group: the merge accumulators (inv-var sums + deterministic half-sets), with the
// error-model-corrected sigma. Mirrors MergeAndStats' merge loop (reject path stays on the host).
__global__ void MergeAccumKernel(MergeParams p) {
@@ -541,20 +553,12 @@ namespace {
for (int q = lo; q < hi; ++q) {
const int i = p.gperm[q];
if (!MergeUsable(i, p)) continue;
if (p.rejected_obs[i]) { ++rejected; continue; } // by the host's Wilson test
const float I_corr = p.I[i] * p.corr[i];
float sigma_corr = p.sigma[i] * p.corr[i];
if (p.error_model_active) {
const double I_for_b = isfinite(p.em_mean[g]) ? p.em_mean[g] : double(I_corr);
const double bi = p.error_model_b * I_for_b;
// The full's variance rebuilt at the reflection's expected intensity, so the merge
// weight cannot know this full's own fluctuation (see the host corrected_sigma).
const double c = p.corr[i];
double a_var = double(sigma_corr) * sigma_corr;
const double base = c * c * p.var_bkg[i] + c * p.var_per_I[i] * Dmax(0.0, I_for_b);
if (base > 0.0) a_var = base;
const double v = p.error_model_a * a_var + bi * bi;
if (v > 0.0) sigma_corr = float(sqrt(v));
}
const float sigma_raw = p.sigma[i] * p.corr[i];
const float sigma_corr = p.error_model_active
? ModelSigma(i, p, isfinite(p.em_mean[g]) ? p.em_mean[g] : double(I_corr), sigma_raw)
: sigma_raw;
if (p.reject_outliers && p.error_model_active && isfinite(rmed)) {
const double tol = p.reject_nsigma * sqrt(double(sigma_corr) * sigma_corr + v_add);
if (fabs(double(I_corr) - rmed) > tol) {
@@ -934,9 +938,7 @@ void RotationScaleMergeGPU::MergeAccum(double error_model_a, double error_model_
d.a_nh0 = CudaDevicePtr<int32_t>(std::max(1, ng)); d.a_nh1 = CudaDevicePtr<int32_t>(std::max(1, ng));
d.a_d = CudaDevicePtr<double>(std::max(1, ng)); d.a_rejected = CudaDevicePtr<int32_t>(std::max(1, ng));
d.a_on_ice = CudaDevicePtr<uint8_t>(std::max(1, ng));
d.m_rejected = CudaDevicePtr<uint8_t>(std::max(1, d.n_fulls));
CudaCheck(cudaMemset(d.m_rejected.get(), 0, size_t(std::max(1, d.n_fulls)) * sizeof(uint8_t)),
"zero m_rejected");
Upload(d.m_rejected, rejected_obs, d.n_fulls);
Upload(d.reject_median, reject_median, ng);
if (reject_var_add && ng > 0) Upload(d.reject_var_add, reject_var_add, ng);
else d.reject_var_add = CudaDevicePtr<float>();
@@ -95,8 +95,9 @@ public:
// from a/b). `half` is the per-full CC1/2 half-set (length n_fulls) assigned on the host, so this
// kernel and the host merge loop cannot disagree about it.
// The per-group results stay on the device for MergeAccumRange to download; reject_median is
// uploaded (NAN where none). rejected_obs is the per-full flag (length n_fulls): the host needs it
// for the reductions it still does itself, above all the anomalous I(+)/I(-) split.
// uploaded (NAN where none). rejected_obs is the per-full flag (length n_fulls): on entry the
// observations the host already rejected (the Wilson test), on return those plus the median test's;
// the host needs it for the reductions it still does itself, above all the anomalous I(+)/I(-) split.
// frame_cc_factor (length n_frames) is each frame's (G_ref/G)^2 floored at 1; swh_typ0/1 are the
// half-set weights multiplied by it. Requires MergeEmSamples first (em_mean resident).
// reject_var_add (n_groups) widens the pooled cut by the shell's own measured Bijvoet
@@ -0,0 +1,168 @@
// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
// SPDX-License-Identifier: GPL-3.0-only
#include "WilsonOutliers.h"
#include <algorithm>
#include <cmath>
#include <numeric>
WilsonOutlierResult WilsonOutliers(const std::vector<WilsonObservation> &obs, double alpha) {
WilsonOutlierResult out;
out.rejected.assign(obs.size(), 0);
out.e2.assign(obs.size(), NAN);
std::vector<size_t> idx;
for (size_t i = 0; i < obs.size(); ++i) {
const auto &o = obs[i];
if (o.unit >= 0 && o.d > 0.0f && o.d < WILSON_OUTLIER_D_MAX && std::isfinite(o.I)
&& o.sigma > 0.0f && std::isfinite(o.sigma))
idx.push_back(i);
}
if (idx.empty())
return out;
// alpha / N per observation, half of it to each tail. Wilson's acentric law is P(E^2 > t) = exp(-t)
// and the centric one P(E^2 > t) = erfc(sqrt(t/2)) <= exp(-t/2), so t and 2t; the Gaussian tail is
// P(> z sigma) <= exp(-z^2/2) / 2. Both bounds are the conservative side of the exact quantile.
// Following Wilson (1949) Acta Cryst. 2, 318-321; the significance guard as in Aimless, Evans (2006)
// Acta Cryst. D62, 72-82.
const double p = alpha / (2.0 * static_cast<double>(idx.size()));
const double t = std::log(1.0 / p);
const double z = std::sqrt(2.0 * std::log(1.0 / (2.0 * p)));
// <I/epsilon> in shells of equal observation count, low to high resolution. Two thousand observations
// put the shell mean at 2% (an exponential's sd equals its mean); narrow shells keep the fall-off
// across one from reading as spread.
constexpr size_t OBS_PER_SHELL = 2000;
std::sort(idx.begin(), idx.end(), [&](size_t a, size_t b) {
return obs[a].d != obs[b].d ? obs[a].d > obs[b].d : a < b;
});
const size_t n_shells = std::max<size_t>(1, idx.size() / OBS_PER_SHELL);
const auto shell_of = [&](size_t j) { return j * n_shells / idx.size(); };
const auto lower_e2 = [&](const WilsonObservation &o, double mu) {
return (o.I - z * o.sigma) / (o.epsilon * mu);
};
const auto wilson_bound = [&](const WilsonObservation &o) { return o.centric ? 2.0 * t : t; };
// A shell is judged only where its mean is itself established at the same significance: with no
// measured <I>, nothing in the shell can be called improbable against it.
std::vector<double> mu(n_shells, 0.0);
std::vector<uint8_t> shell_valid(n_shells, 0);
{
std::vector<double> sum(n_shells, 0.0);
std::vector<size_t> cnt(n_shells, 0);
for (size_t j = 0; j < idx.size(); ++j) {
sum[shell_of(j)] += obs[idx[j]].I / obs[idx[j]].epsilon;
++cnt[shell_of(j)];
}
// Once more without the observations the plain Wilson bound already calls improbable: a single
// artefact thousands of times <I> would otherwise raise the mean of its own shell several-fold
// and hide the smaller artefacts sharing it.
std::vector<double> sum_kept(n_shells, 0.0), sum2_kept(n_shells, 0.0);
std::vector<size_t> cnt_kept(n_shells, 0);
for (size_t j = 0; j < idx.size(); ++j) {
const auto &o = obs[idx[j]];
const size_t s = shell_of(j);
if (sum[s] > 0.0 && lower_e2(o, sum[s] / cnt[s]) > wilson_bound(o))
continue;
const double x = o.I / o.epsilon;
sum_kept[s] += x; sum2_kept[s] += x * x; ++cnt_kept[s];
}
for (size_t s = 0; s < n_shells; ++s) {
if (cnt_kept[s] < 2) continue;
const double n = static_cast<double>(cnt_kept[s]);
mu[s] = sum_kept[s] / n;
const double var = std::max(0.0, (sum2_kept[s] - n * mu[s] * mu[s]) / (n - 1.0));
shell_valid[s] = mu[s] > 0.0 && mu[s] > z * std::sqrt(var / n);
}
}
// The tail's scale, peaks over threshold: above any threshold an exponential's excess is the same
// exponential, so the median excess of the acentric observations over a common threshold u is
// k ln 2. u is where Wilson leaves a hundred acentric observations above it. Only shells whose
// typical observation is significant at u take part: where sigma is comparable to u <I>, what
// exceeds u is the noise tail, and it would read as a heavy intensity tail.
size_t n_acentric = 0;
for (size_t j = 0; j < idx.size(); ++j)
if (!obs[idx[j]].centric && shell_valid[shell_of(j)]) ++n_acentric;
const double u = std::max(0.0, std::log(static_cast<double>(n_acentric) / 100.0));
std::vector<uint8_t> shell_measures_tail(n_shells, 0);
{
std::vector<std::vector<double>> noise(n_shells); // sigma / (epsilon <I/epsilon>)
for (size_t j = 0; j < idx.size(); ++j) {
const auto &o = obs[idx[j]];
if (shell_valid[shell_of(j)]) noise[shell_of(j)].push_back(o.sigma / (o.epsilon * mu[shell_of(j)]));
}
for (size_t s = 0; s < n_shells; ++s) {
auto &v = noise[s];
if (v.empty()) continue;
const size_t mid = v.size() / 2;
std::nth_element(v.begin(), v.begin() + mid, v.end());
shell_measures_tail[s] = z * v[mid] <= u;
}
}
std::vector<double> excess;
for (size_t j = 0; j < idx.size(); ++j) {
const auto &o = obs[idx[j]];
if (o.centric || !shell_measures_tail[shell_of(j)]) continue;
const double e2 = o.I / (o.epsilon * mu[shell_of(j)]);
if (e2 > u) excess.push_back(e2 - u);
}
if (!excess.empty()) {
const size_t mid = excess.size() / 2;
std::nth_element(excess.begin(), excess.begin() + mid, excess.end());
out.tail_scale = std::max(1.0, excess[mid] / std::log(2.0));
}
out.bound = out.tail_scale * t;
// Which observations are improbable, and the observations of each reflection (in valid shells).
std::vector<uint8_t> improbable(obs.size(), 0);
std::vector<size_t> tested;
for (size_t j = 0; j < idx.size(); ++j) {
const size_t i = idx[j];
if (!shell_valid[shell_of(j)]) continue;
const auto &o = obs[i];
const double m = mu[shell_of(j)];
out.e2[i] = static_cast<float>(o.I / (o.epsilon * m));
improbable[i] = lower_e2(o, m) > out.tail_scale * wilson_bound(o);
tested.push_back(i);
}
out.n_tested = tested.size();
std::sort(tested.begin(), tested.end(), [&](size_t a, size_t b) {
return obs[a].unit != obs[b].unit ? obs[a].unit < obs[b].unit : a < b;
});
// An improbable observation measured once is rejected. One with company is rejected when most of
// its reflection's other observations are probable and it disagrees with their mean beyond the
// errors - for a pair, the other member. Where most are large, the reflection is (Aimless's "keep
// if most observations are large").
for (size_t lo = 0; lo < tested.size();) {
size_t hi = lo;
while (hi < tested.size() && obs[tested[hi]].unit == obs[tested[lo]].unit) ++hi;
for (size_t q = lo; q < hi; ++q) {
const size_t i = tested[q];
if (!improbable[i]) continue;
size_t n_probable = 0;
double sw = 0.0, swI = 0.0;
for (size_t r = lo; r < hi; ++r) {
const auto &o = obs[tested[r]];
if (r == q || improbable[tested[r]]) continue;
const double w = 1.0 / (static_cast<double>(o.sigma) * o.sigma);
sw += w; swI += w * o.I;
++n_probable;
}
const size_t n_others = hi - lo - 1;
bool reject = n_others == 0;
if (2 * n_probable > n_others) {
const auto &o = obs[i];
reject = std::fabs(o.I - swI / sw) > z * std::sqrt(static_cast<double>(o.sigma) * o.sigma + 1.0 / sw);
}
if (reject) {
out.rejected[i] = 1;
++out.n_rejected;
}
}
lo = hi;
}
return out;
}
@@ -0,0 +1,60 @@
// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <cstddef>
#include <cstdint>
#include <vector>
// An outlier test that judges an observation against the intensity DISTRIBUTION rather than against its
// symmetry mates. The median test in the merge needs three observations of a reflection, so a
// singleton is never tested and a PAIR - one good observation and one artefact, the usual case after
// Friedel merging - is never tested either; and where there are three or more, an artefact that looks
// precise (a hot pixel reads thousands of counts with a small relative sigma) can outweigh mates from
// weak frames and become the weighted median itself. Wilson statistics say how large a genuine
// intensity can plausibly be in its resolution shell, given the symmetry enhancement factor epsilon
// and whether the reflection is centric - independent of the other observations.
//
// The bound is set by the number of false rejections the dataset can afford, alpha, not tuned: with N
// observations tested, each may be falsely called improbable with probability alpha / N. That budget
// is split between the two ways a genuine observation can land high - a true intensity far up the
// Wilson tail, and a measurement error far up its Gaussian tail - so an observation is improbable only
// when even its lower confidence bound I - z*sigma lies beyond the Wilson bound. That is what keeps weak
// shells, where noise alone reaches many times <I>, from misfiring, with no separate I/sigma threshold;
// and a shell whose own <I> is not established at that significance is not judged at all.
//
// Real crystals are not all Wilson crystals - tNCS modulates <I> class by class, anisotropy does
// direction by direction - and every such departure makes the distribution a MIXTURE of exponentials,
// whose tail is heavier than Wilson's (never lighter). The tail's scale is therefore measured on the
// dataset's own well-measured observations and the bound widened by it: a Wilson crystal measures 1
// and is tested at Wilson's bound.
//
// Improbable is not yet rejected. An improbable observation measured once is rejected; one with
// company only when most of its reflection's other observations are probable and it disagrees with
// them beyond the errors. Several large observations of one reflection confirm each other and are
// kept, which is how a genuinely strong reflection survives.
struct WilsonObservation {
float I; // scaled intensity
float sigma; // its own standard uncertainty, at its own intensity
float d; // resolution (A)
float epsilon; // symmetry enhancement factor of the reflection (without centring)
bool centric;
int32_t unit; // the reflection the observation measures; < 0 = not part of the test
};
struct WilsonOutlierResult {
std::vector<uint8_t> rejected; // per observation
std::vector<float> e2; // I / (epsilon <I/epsilon>_shell); NaN outside the tested range
double tail_scale = 1.0; // the measured tail scale (1 = Wilson)
double bound = 0.0; // acentric bound on E^2 of the lower confidence limit; centric 2x
size_t n_tested = 0; // observations in shells with an established <I>, beyond 4 A
size_t n_rejected = 0;
};
// Wilson statistics hold where the scattering of the unit cell is effectively random - beyond about
// 4 A. At lower resolution the solvent and the secondary structure make the distribution a mixture of
// its own.
constexpr float WILSON_OUTLIER_D_MAX = 4.0f;
WilsonOutlierResult WilsonOutliers(const std::vector<WilsonObservation> &obs, double alpha);
+17
View File
@@ -770,6 +770,23 @@ ReportDocument BuildReportDocument(const std::string &output_prefix,
// Outlier rejection drops observations from the merge AND from R_meas and the CC1/2
// half-sets, so a run that rejects too much scores BETTER on every other number here.
Add(s, KeyInt("OBSERVATIONS_REJECTED", ms.n_observations_rejected));
// The part of those removed as improbable under Wilson statistics (an observation with no
// symmetry mates to be judged against, or out-voting them); each is listed in the developer
// report.
Add(s, KeyInt("OBSERVATIONS_REJECTED_WILSON", static_cast<int64_t>(ms.wilson_rejected.size())));
if (!ms.wilson_rejected.empty()) {
std::string list = " Observations rejected by the Wilson test:\n"
" h k l d E^2 image x y\n";
constexpr size_t MAX_ROWS = 100;
for (size_t i = 0; i < std::min(ms.wilson_rejected.size(), MAX_ROWS); ++i) {
const auto &w = ms.wilson_rejected[i];
list += fmt::format(" {:6d} {:4d} {:4d} {:6.3f} {:7.1f} {:8.1f} {:8.1f} {:8.1f}\n",
w.h, w.k, w.l, w.d, w.e2, w.image, w.x, w.y);
}
if (ms.wilson_rejected.size() > MAX_ROWS)
list += fmt::format(" ... and {} more\n", ms.wilson_rejected.size() - MAX_ROWS);
Add(s, Prose(list, true));
}
// One rule for every quantity: a run that did not measure it writes NO key, rather than
// the word "nan" or a zero that reads as a measured absence.
if (o.possible_unique_reflections > 0)
+1
View File
@@ -107,6 +107,7 @@ ADD_EXECUTABLE(jfjoch_test
TranslationalNCSTest.cpp
RfreeFlagsTest.cpp
FrenchWilsonTest.cpp
WilsonOutliersTest.cpp
ReindexAmbiguityTest.cpp
LoadReferenceMtzFreeFlagsTest.cpp
WriteReflectionsTest.cpp
+125
View File
@@ -0,0 +1,125 @@
// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
// SPDX-License-Identifier: GPL-3.0-only
#include <catch2/catch_all.hpp>
#include <cmath>
#include <random>
#include <vector>
#include "../image_analysis/scale_merge/WilsonOutliers.h"
namespace {
// Acentric Wilson intensities of mean `mean` between 3.9 and 2.0 A, measured `per_unit` times each
// with Poisson-like noise of variance I + bkg_var.
std::vector<WilsonObservation> WilsonPopulation(int n_units, int per_unit, double mean, double bkg_var,
uint32_t seed) {
std::mt19937 rng(seed);
std::exponential_distribution<double> wilson(1.0 / mean);
std::normal_distribution<double> gauss(0.0, 1.0);
std::vector<WilsonObservation> v;
for (int u = 0; u < n_units; ++u) {
const double I_true = wilson(rng);
const float d = 3.9f - 1.9f * static_cast<float>(u) / n_units;
for (int m = 0; m < per_unit; ++m) {
const double sigma = std::sqrt(I_true + bkg_var);
v.push_back({static_cast<float>(I_true + sigma * gauss(rng)), static_cast<float>(sigma), d,
1.0f, false, u});
}
}
return v;
}
}
TEST_CASE("WilsonOutliers: the artefact member of a discordant pair is dropped", "[wilson_outliers]") {
auto obs = WilsonPopulation(10000, 2, 1000.0, 100.0, 1);
// A pair of one ordinary observation and one two hundred times the shell mean.
const int32_t unit = 10000;
obs.push_back({800.0f, 30.0f, 2.5f, 1.0f, false, unit});
obs.push_back({200000.0f, 450.0f, 2.5f, 1.0f, false, unit});
const auto r = WilsonOutliers(obs, 0.01);
CHECK(r.n_tested == obs.size());
CHECK(r.tail_scale == Catch::Approx(1.0).margin(0.2));
CHECK(r.rejected[obs.size() - 1] == 1);
CHECK(r.rejected[obs.size() - 2] == 0);
CHECK(r.n_rejected == 1);
}
TEST_CASE("WilsonOutliers: two large observations of one reflection confirm each other", "[wilson_outliers]") {
auto obs = WilsonPopulation(10000, 2, 1000.0, 100.0, 2);
const int32_t unit = 10000;
obs.push_back({60000.0f, 300.0f, 2.5f, 1.0f, false, unit});
obs.push_back({61000.0f, 300.0f, 2.5f, 1.0f, false, unit});
const auto r = WilsonOutliers(obs, 0.01);
CHECK(r.n_rejected == 0);
}
TEST_CASE("WilsonOutliers: the symmetry enhancement factor keeps an axial reflection", "[wilson_outliers]") {
auto obs = WilsonPopulation(10000, 2, 1000.0, 100.0, 3);
// Measured once, 12x <I/epsilon> at epsilon 4: 48x the shell mean, but only E^2 = 12.
obs.push_back({48000.0f, 250.0f, 2.5f, 4.0f, false, 10000});
auto r = WilsonOutliers(obs, 0.01);
CHECK(r.rejected.back() == 0);
CHECK(r.e2.back() == Catch::Approx(12.0).epsilon(0.1));
CHECK(r.n_rejected == 0);
// The same observation on a general reflection is improbable.
obs.back().epsilon = 1.0f;
r = WilsonOutliers(obs, 0.01);
CHECK(r.rejected.back() == 1);
}
TEST_CASE("WilsonOutliers: a weak shell does not misfire", "[wilson_outliers]") {
// <I> = 20 under a background of sd 100: noise alone reaches twenty times <I>, while the shell mean
// is still established.
const auto obs = WilsonPopulation(20000, 1, 20.0, 10000.0, 4);
const auto r = WilsonOutliers(obs, 0.01);
CHECK(r.n_tested == obs.size());
CHECK(r.n_rejected == 0);
}
TEST_CASE("WilsonOutliers: an artefact among several mates is dropped", "[wilson_outliers]") {
auto obs = WilsonPopulation(5000, 4, 1000.0, 100.0, 5);
// One precise-looking artefact beside three ordinary mates: the mates out-vote it.
obs[0].I = 500000.0f;
obs[0].sigma = 700.0f;
const auto r = WilsonOutliers(obs, 0.01);
CHECK(r.n_tested == obs.size());
CHECK(r.rejected[0] == 1);
CHECK(r.n_rejected == 1);
}
TEST_CASE("WilsonOutliers: a reflection whose observations are mostly large is kept", "[wilson_outliers]") {
auto obs = WilsonPopulation(5000, 3, 1000.0, 100.0, 8);
// Two of three observations large, the third low (a partial that caught little, say).
obs[0].I = 60000.0f; obs[0].sigma = 300.0f;
obs[1].I = 62000.0f; obs[1].sigma = 300.0f;
obs[2].I = 500.0f; obs[2].sigma = 30.0f;
const auto r = WilsonOutliers(obs, 0.01);
CHECK(r.n_rejected == 0);
}
TEST_CASE("WilsonOutliers: a shell without a measured mean is not judged", "[wilson_outliers]") {
// Pure noise: <I> = 0 within its error, so nothing can be improbable against it.
auto obs = WilsonPopulation(10000, 1, 1e-6, 10000.0, 9);
obs[0].I = 5000.0f; obs[0].sigma = 100.0f;
const auto r = WilsonOutliers(obs, 0.01);
CHECK(r.n_tested == 0);
CHECK(r.n_rejected == 0);
}
TEST_CASE("WilsonOutliers: a heavier-tailed population widens the bound", "[wilson_outliers]") {
// Half the reflections at twice the mean, half at a tenth - the intensity classes of a strong
// pseudo-translation. Wilson's single exponential would call the top of the strong class improbable.
auto strong = WilsonPopulation(10000, 1, 2000.0, 100.0, 6);
const auto weak = WilsonPopulation(10000, 1, 100.0, 100.0, 7);
for (auto o : weak) {
o.unit += 10000;
strong.push_back(o);
}
const auto r = WilsonOutliers(strong, 0.01);
CHECK(r.tail_scale > 1.5);
CHECK(r.n_rejected == 0);
}