diff --git a/common/CorrelationCoefficient.h b/common/CorrelationCoefficient.h index 943a3936a..474d5784c 100644 --- a/common/CorrelationCoefficient.h +++ b/common/CorrelationCoefficient.h @@ -16,5 +16,6 @@ public: // Weighted pair: a plain Pearson when every weight is the same. void Add(double x, double y, double w); [[nodiscard]] double GetCC() const; + [[nodiscard]] int GetN() const { return n_cc; } }; diff --git a/docs/ACKNOWLEDGEMENT.md b/docs/ACKNOWLEDGEMENT.md index 2d33580de..8cd5fc00b 100644 --- a/docs/ACKNOWLEDGEMENT.md +++ b/docs/ACKNOWLEDGEMENT.md @@ -466,6 +466,14 @@ merge reaches the finest resolution, as KAMO takes the data set of the smallest K. Yamashita, K. Hirata and M. Yamamoto, "KAMO: towards automated data processing for microcrystals" (2018), Acta Cryst. D74, 441-449 [doi:10.1107/S2059798318004576](https://doi.org/10.1107/S2059798318004576). +**Anomalous signal indicators** — the half-set anomalous correlation is AIMLESS's CCanom, and the +resolution to which it holds above 0.15 shell by shell is AIMLESS's limit of the anomalous signal; the +halves here keep the two mates of a Bijvoet pair measured together on one side, which the per-observation +deal of the original does not. Measurability — the fraction of the acentric pairs with |I(+)-I(-)| at three +sigma and both hands at I/sigma 3 — is phenix.xtriage's: P. H. Zwart, "Anomalous signal indicators in +protein crystallography" (2005), Acta Cryst. D61, 1437-1448 +[doi:10.1107/S0907444905023589](https://doi.org/10.1107/S0907444905023589). + ### Physical corrections and calibration **Sensor absorption at oblique incidence, and the flight path** — the angle-dependent quantum diff --git a/docs/CPU_DATA_ANALYSIS_INTEGRATION.md b/docs/CPU_DATA_ANALYSIS_INTEGRATION.md index afbb9fbe6..4b50e81f7 100644 --- a/docs/CPU_DATA_ANALYSIS_INTEGRATION.md +++ b/docs/CPU_DATA_ANALYSIS_INTEGRATION.md @@ -398,7 +398,7 @@ The error model is refined as $\sigma_\mathrm{corr}^2 = a\,\sigma^2 + (b\,\langl $a$ and $b$ are **reported in XDS's convention**, which is $\sigma^2 = a(\sigma_0^2 + b I^2)$ with $\mathrm{ISa}=1/\sqrt{ab}$, so the printed pair can be read straight against a `CORRECT.LP`. The internal fit keeps the form above; only the report converts, as $b_\mathrm{XDS} = b^2/a$ (and on stills $c_\mathrm{XDS} = c^2/a$). Note that $a$ is the same in both conventions and that the two ISa expressions are the same number, $1/\sqrt{a\cdot b^2/a} = 1/b$ — so the rotation log prints **two** ISa, the whole-range $1/b$ (XDS's meaning) and the strong-reflection asymptote beside it, which can only ever be the more optimistic of the two. The mmCIF follows the same split: `_reflns.jfjoch_diffrn_ISa` is the whole-range value, directly comparable with a `CORRECT.LP`, and the asymptote is written separately as `_reflns.jfjoch_diffrn_ISa_asymptotic`, with `_reflns.jfjoch_error_model_a` and `_b` alongside so the number can be re-derived. Note that a file written before this change carries the *asymptote* under the plain `ISa` name. A third, unrelated $b$ appears in the space-group search (§13.1); it is fitted with the $\sigma^2$ coefficient held at 1 and its gate constants are calibrated in that convention. -**Anomalous signal-to-noise (SigAno).** The strength of the anomalous signal is reported per shell and overall as $\mathrm{SigAno}=\langle|\Delta I|\rangle / \langle\sigma(\Delta I)\rangle$, where $\Delta I = I(+)-I(-)$ over acentric reflections measured in both Bijvoet hands and $\sigma(\Delta I)=\sqrt{\sigma_+^2+\sigma_-^2}$. It is computed from the **full-multiplicity** inverse-variance $I(+)/I(-)$ split (the same one written to the output), i.e. from all observations rather than a half-set. For pure noise $\mathrm{SigAno}$ approaches the half-normal value $\sqrt{2/\pi}\approx0.8$, and it rises above $1$ once a real anomalous difference is present. A half-set anomalous correlation ($\mathrm{CC}_\mathrm{anom}$) is reported beside it: $\Delta I$ is formed once per half-set and the two are correlated over the acentric pairs where **both** hands split into two non-empty halves, per shell and overall as one correlation rather than a mean of shells. Unlike SigAno it is not a ratio against the error model, so an optimistic $\sigma$ cannot inflate it. It has no floor either: subtracting the two Bijvoet hands cancels the large common intensity that keeps $\mathrm{CC}_{1/2}$ non-negative, so on data with little anomalous signal and about two observations per mate it goes strongly negative. That is a property of the statistic and is reported as measured. It agrees with AIMLESS's `CCanom` and `phenix.merging_statistics`' `cc_anom`; XDS's `Anomal Corr` is a **different quantity and is not comparable with it** — on the same observations it reads two to three times higher in the low shells. $\mathrm{CC}_\mathrm{anom}$ is a rotation-path statistic (the stills merge forms no half-set anomalous difference), and it is reported in the `CCanom` column of the printed merge-statistics table and as `CC_ANOM=` in the results report — not in the mmCIF. SigAno is emitted only when an anomalous split was made, using the standard PDBx items `_reflns.pdbx_absDiff_over_sigma_anomalous` (overall) and `_reflns_shell.pdbx_absDiff_over_sigma_anomalous` (per shell), and appears as the `SigAno` column of the same table. Where either could not be measured at all — a Friedel-merged run that split no Bijvoet pair, a shell too thin to split one in both hands — the table prints `-` and the results report writes no key, which is not the same statement as a value measured to be zero. +**Anomalous signal-to-noise (SigAno).** The strength of the anomalous signal is reported per shell and overall as $\mathrm{SigAno}=\langle|\Delta I|\rangle / \langle\sigma(\Delta I)\rangle$, where $\Delta I = I(+)-I(-)$ over acentric reflections measured in both Bijvoet hands and $\sigma(\Delta I)=\sqrt{\sigma_+^2+\sigma_-^2}$. It is computed from the **full-multiplicity** inverse-variance $I(+)/I(-)$ split (the same one written to the output), i.e. from all observations rather than a half-set. For pure noise $\mathrm{SigAno}$ approaches the half-normal value $\sqrt{2/\pi}\approx0.8$, and it rises above $1$ once a real anomalous difference is present. A half-set anomalous correlation ($\mathrm{CC}_\mathrm{anom}$) is reported beside it: $\Delta I$ is formed once per half-set and the two are correlated over the acentric pairs where **both** hands split into two non-empty halves, per shell and overall as one correlation rather than a mean of shells. Unlike SigAno it is not a ratio against the error model, so an optimistic $\sigma$ cannot inflate it. The halves are not dealt out one observation at a time, as the $\mathrm{CC}_{1/2}$ halves are: the two mates of a Bijvoet pair are often measured **together** — with a symmetry axis along the spindle, the mirror image of a spot across the plane through the beam and the spindle lies on the same image and is of the opposite hand; inverse-beam wedges follow each other — and such a couple shares whatever error the two images have in common (beam, frame scale, absorption), an error as large as the anomalous difference or larger. Dealt out singly, the two mates of a couple land on opposite sides half of the time and the shared error enters the two half-set differences with opposite signs, so $\mathrm{CC}_\mathrm{anom}$ reads strongly **negative** on strong data (tens of percent at $I/\sigma$ of 50 and above, the more negative the stronger the shell) whatever the signal; the pattern was found on the open and in-house rotation sets and reproduced on XDS's own scaled observations of the same crystals. So the observations are coupled, an $I(+)$ with an $I(-)$, the closest in time first, and the couples are dealt out whole, alternately in time order — balanced, and with the shared error cancelling inside each half's own $\Delta I$ (`AssignAnomalousHalves`). It has no floor: subtracting the two Bijvoet hands cancels the large common intensity that keeps $\mathrm{CC}_{1/2}$ non-negative, so on data with little anomalous signal and about two observations per mate it is noisy and may go negative. The definition is AIMLESS's `CCanom` and `phenix.merging_statistics`' `cc_anom`, which deal the observations out singly and so carry the bias above; XDS's `Anomal Corr` is counted over a selected subset of the pairs (its `Nano` column) and reads higher, so it is not comparable either. The number of pairs behind the correlation is reported with it (`CC_ANOM_PAIRS=`), and its significance is read against that. Beside the two, **measurability** (Zwart (2005) Acta Cryst. D61, 1437–1448; `phenix.xtriage`) is the fraction of the acentric pairs measured in both hands with $|\Delta I| \ge 3\sigma(\Delta I)$ and $I \ge 3\sigma$ in each hand (`ANOM_MEASURABILITY=`). The report's summary quotes $\mathrm{CC}_\mathrm{anom}$ shell by shell from the low-resolution end, where an anomalous signal lives, not the overall correlation, which the noise shells dilute — the resolution to which it holds above 0.15 (`ANOMALOUS_SIGNAL_D_MIN=`), or the lowest shell's value against its number of pairs — and decides the Anomalous line on the model-phased anomalous difference map at the model's own anomalous scatterers, which sums the signal over every pair at once and sees a weak one no pair statistic can (the lowest shell's SigAno without a model). $\mathrm{CC}_\mathrm{anom}$ also reproduces a Friedel difference that is systematic rather than anomalous, so by itself it is not a verdict. $\mathrm{CC}_\mathrm{anom}$ is a rotation-path statistic (the stills merge forms no half-set anomalous difference), and it is reported in the `CCanom` column of the printed merge-statistics table and as `CC_ANOM=` in the results report — not in the mmCIF. SigAno is emitted only when an anomalous split was made, using the standard PDBx items `_reflns.pdbx_absDiff_over_sigma_anomalous` (overall) and `_reflns_shell.pdbx_absDiff_over_sigma_anomalous` (per shell), and appears as the `SigAno` column of the same table. Where either could not be measured at all — a Friedel-merged run that split no Bijvoet pair, a shell too thin to split one in both hands — the table prints `-` and the results report writes no key, which is not the same statement as a value measured to be zero. ### 10.6 Rotation datasets: combining partials into fulls (3D integration) diff --git a/docs/RUGNUX_REPORT.md b/docs/RUGNUX_REPORT.md index 3fd0a3d68..4a00351b0 100644 --- a/docs/RUGNUX_REPORT.md +++ b/docs/RUGNUX_REPORT.md @@ -252,7 +252,7 @@ The keys most scripts read, by section; the rest of this page explains the ones | `RESOLUTION_CUT_PLAIN` | Diagnostic, rotation only: the limit the cut would have written from the fit on the standard CC1/2. Nothing is cut at it | | `UNIQUE_REFLECTIONS`, `TOTAL_OBSERVATIONS`, `COMPLETENESS`, `MULTIPLICITY` | Over the written range; completeness in percent | | `I_OVER_SIGMA`, `R_MEAS`, `CC_HALF`, `WILSON_B` | The overall merging statistics; the shell table beside them is in the comment lines. `R_MEAS` (and `R_MERGE`, `R_PIM`) rotation only, `R_SPLIT` stills only | -| `SIGANO`, `CC_ANOM`, `FRIEDELS_LAW` | The anomalous signal, and whether `-A` was given (`FALSE` with it). On rotation data the merge is the same either way, Friedel mates merged, and the `ANOM_*` keys count it per hand on every run; on stills `FALSE` means the hands were merged apart | +| `SIGANO`, `CC_ANOM`, `CC_ANOM_PAIRS`, `ANOM_MEASURABILITY`, `ANOMALOUS_SIGNAL_D_MIN`, `FRIEDELS_LAW` | The anomalous signal: SigAno, the half-set anomalous correlation over the written range with the number of Bijvoet pairs behind it, phenix.xtriage's measurability, the resolution to which `CC_ANOM` holds above 0.15 shell by shell from the low-resolution end (absent where no shell does), and whether `-A` was given (`FALSE` with it). The summary's `Anomalous` line quotes `CC_ANOM` shell by shell from the low-resolution end, not the overall value, and decides on the model-phased anomalous map (or the lowest shell's `SIGANO` without a model). On rotation data the merge is the same either way, Friedel mates merged, and the `ANOM_*` keys count it per hand on every run; on stills `FALSE` means the hands were merged apart | | `ERROR_MODEL_A`, `ERROR_MODEL_B`, `ISA` | The error model in XDS's convention and ISa = 1/sqrt(a·b); `ISA= undetermined` where b is zero within its error, so 1/b would be noise. Rotation only for `ISA` | | `ISA_LOW`, `ISA_HIGH` | Rotation data: the 95% interval of `ISA` from a bootstrap over the reflections (100 replicates, fixed draws). With `ISA= undetermined`, `ISA_LOW` alone is a lower bound: b reaches zero inside its interval, so only ISa ≥ `ISA_LOW` is measured. Both absent where there is no fit to resample (b out of reach of the data, or a on its bound) and on stills, which write no `ISA`. `ISA_ASYMPTOTIC` (`--developer`) is the ISa of the strong-reflection tier alone | | `ERROR_MODEL_C` | Stills only: the partiality term of the stills error model, σ² = a(σ₀² + b·I² + c·((1−p)/p)²·I²) in the same convention. A stills report writes no `ISA` ([below](#the-stills-error-model)), and `ERROR_MODEL_B= undetermined` where b is zero within its error | diff --git a/image_analysis/scale_merge/AnomalousHalves.h b/image_analysis/scale_merge/AnomalousHalves.h new file mode 100644 index 000000000..b25154a59 --- /dev/null +++ b/image_analysis/scale_merge/AnomalousHalves.h @@ -0,0 +1,71 @@ +// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute +// SPDX-License-Identifier: GPL-3.0-only + +#pragma once + +#include +#include +#include +#include + +// One observation of a Bijvoet pair for the half-set split below: when it was measured (its frame), +// and where it sits in the caller's arrays. +struct TimedObservation { + int32_t frame; + int32_t at; +}; + +// The CCanom half-sets of one Bijvoet pair, written to half[at] for every observation given. +// +// The two Bijvoet mates of a reflection are often measured TOGETHER: with a symmetry axis along the +// spindle the mirror image of a spot across the plane through the beam and the spindle is on the same +// image and is of the opposite hand, and inverse-beam wedges follow each other. Such a couple shares +// whatever error the two images have in common - the beam, the frame's scale, absorption - and that +// error is as large as the anomalous difference it is measured beside, or larger. Dealt out one +// observation at a time, as CC1/2's halves are, the two members of a couple land on opposite sides +// half of the time, and the shared error then enters the two half-set differences with opposite +// signs: CCanom reads NEGATIVE on strong data (tens of percent at I/sigma 50 and above), in proportion +// to the shared error and regardless of any anomalous signal. So the observations are first coupled, +// an I(+) with an I(-), the closest in time first, and the couples are dealt out whole, +// alternately in time order - which balances the halves and keeps the shared error inside each +// half's own I(+)-I(-), where it cancels. An observation left without a partner is dealt out the +// same way on its own. The halves are a property of the pair's set of observations, not of the +// order it was walked in. +inline void AssignAnomalousHalves(std::vector plus, std::vector minus, + std::vector &half) { + const auto by_time = [](const TimedObservation &a, const TimedObservation &b) { + return a.frame < b.frame || (a.frame == b.frame && a.at < b.at); + }; + std::sort(plus.begin(), plus.end(), by_time); + std::sort(minus.begin(), minus.end(), by_time); + // A couple, or a single, keyed by when it was measured. + struct Item { TimedObservation first; int32_t partner; }; // partner < 0: on its own + std::vector items; + items.reserve(plus.size() + minus.size()); + // The closest couples first, each observation in one couple at most. + struct Candidate { int32_t gap; size_t p, m; }; + std::vector candidates; + candidates.reserve(plus.size() * minus.size()); + for (size_t p = 0; p < plus.size(); ++p) + for (size_t m = 0; m < minus.size(); ++m) + candidates.push_back({std::abs(plus[p].frame - minus[m].frame), p, m}); + std::sort(candidates.begin(), candidates.end(), [](const Candidate &a, const Candidate &b) { + return a.gap < b.gap || (a.gap == b.gap && (a.p < b.p || (a.p == b.p && a.m < b.m))); + }); + std::vector plus_taken(plus.size(), 0), minus_taken(minus.size(), 0); + for (const auto &c : candidates) { + if (plus_taken[c.p] || minus_taken[c.m]) continue; + plus_taken[c.p] = minus_taken[c.m] = 1; + const bool plus_first = by_time(plus[c.p], minus[c.m]); + items.push_back({plus_first ? plus[c.p] : minus[c.m], plus_first ? minus[c.m].at : plus[c.p].at}); + } + for (size_t p = 0; p < plus.size(); ++p) + if (!plus_taken[p]) items.push_back({plus[p], -1}); + for (size_t m = 0; m < minus.size(); ++m) + if (!minus_taken[m]) items.push_back({minus[m], -1}); + std::sort(items.begin(), items.end(), [&](const Item &a, const Item &b) { return by_time(a.first, b.first); }); + for (size_t r = 0; r < items.size(); ++r) { + half[items[r].first.at] = static_cast(r & 1); + if (items[r].partner >= 0) half[items[r].partner] = static_cast(r & 1); + } +} diff --git a/image_analysis/scale_merge/Merge.cpp b/image_analysis/scale_merge/Merge.cpp index 4936c78a0..10797019a 100644 --- a/image_analysis/scale_merge/Merge.cpp +++ b/image_analysis/scale_merge/Merge.cpp @@ -620,7 +620,7 @@ struct ShellAccum { CorrelationCoefficient cc_split; CorrelationCoefficient cc_anom; double anom_abs_diff = 0.0, anom_sigma = 0.0; - int anom_pairs = 0; + int anom_pairs = 0, anom_measurable = 0; double split_abs_diff = 0.0; double split_sum = 0.0; int split_pairs = 0; @@ -865,6 +865,9 @@ MergeStatistics MergeOnTheFly::MergeStats(const std::vector &m a->anom_abs_diff += std::fabs(plus->I - minus.I); a->anom_sigma += std::hypot(plus->sigma, minus.sigma); a->anom_pairs++; + if (std::fabs(plus->I - minus.I) >= 3.0f * std::hypot(plus->sigma, minus.sigma) + && plus->I >= 3.0f * plus->sigma && minus.I >= 3.0f * minus.sigma) + a->anom_measurable++; } if (std::isfinite(plus->I_split[0]) && std::isfinite(plus->I_split[1]) && std::isfinite(minus.I_split[0]) && std::isfinite(minus.I_split[1])) @@ -921,6 +924,8 @@ MergeStatistics MergeOnTheFly::MergeStats(const std::vector &m if (a.anom_pairs > 0) { ss.abs_diff_over_sigma_anomalous = a.anom_abs_diff / a.anom_sigma; ss.cc_anom = a.cc_anom.GetCC(); + ss.cc_anom_pairs = a.cc_anom.GetN(); + ss.anomalous_measurability = static_cast(a.anom_measurable) / a.anom_pairs; } ss.n_split_pairs = a.split_pairs; if (a.split_pairs == 0) diff --git a/image_analysis/scale_merge/Merge.h b/image_analysis/scale_merge/Merge.h index 65f6a65dd..cbe1e4780 100644 --- a/image_analysis/scale_merge/Merge.h +++ b/image_analysis/scale_merge/Merge.h @@ -68,8 +68,16 @@ struct MergeStatisticsShell { // Unlike SigAno it is not a ratio against the error model, so a mis-estimated sigma cannot move // it. On stills the halves are the frame-whole ones of R_split, so the two differences come from // different crystals. NaN when no reflection has an anomalous split, which is not the same - // statement as zero - zero means measured and absent. + // statement as zero - zero means measured and absent. On rotation the halves of a pair keep its + // Bijvoet mates measured together on one side (AssignAnomalousHalves), so a shared error cannot + // read as a negative correlation. double cc_anom = NAN; + // The pairs cc_anom correlates, which is what its significance is read from. + int cc_anom_pairs = 0; + // Measurability (Zwart (2005) Acta Cryst. D61, 1437-1448; phenix.xtriage): the fraction of the + // acentric pairs measured in both hands with |I(+)-I(-)|/sigma >= 3 and I/sigma >= 3 in each hand. + // NaN where no pair was measured in both hands. + double anomalous_measurability = NAN; // The serial-crystallography pair (stills only, NaN on rotation): every frame's observations go // whole to one half-set, as CrystFEL's partialator deals out crystals, and the two half-set means diff --git a/image_analysis/scale_merge/RotationScaleMerge.cpp b/image_analysis/scale_merge/RotationScaleMerge.cpp index e5e0e8d24..ae6c439b8 100644 --- a/image_analysis/scale_merge/RotationScaleMerge.cpp +++ b/image_analysis/scale_merge/RotationScaleMerge.cpp @@ -27,6 +27,7 @@ #include #include "AndersonMixing.h" +#include "AnomalousHalves.h" #include "HKLKey.h" #include "RfreeFlags.h" #include "FrenchWilson.h" @@ -6794,6 +6795,9 @@ RotationScaleMerge::Result RotationScaleMerge::MergeAndStats(int n_groups, bool std::vector sig_num(n_shells, 0.0), sig_den(n_shells, 0.0); double sig_num_all = 0.0, sig_den_all = 0.0; size_t sig_n = 0; + // Measurability on the same pairs: those with |dI| >= 3 sigma(dI) and each hand at I >= 3 sigma. + std::vector meas_num(n_shells, 0), meas_den(n_shells, 0); + int meas_num_all = 0; // CCanom on the same shells, and over the whole range as one correlation (not a mean of shells). std::vector cc_anom_shell(n_shells); CorrelationCoefficient cc_anom_overall; @@ -6847,11 +6851,10 @@ RotationScaleMerge::Result RotationScaleMerge::MergeAndStats(int n_groups, bool } std::vector anom(pair_hkl.size()); if (own_table) anom_export.reserve(anom.size()); - // The half-sets CCanom needs are balanced within the MATE, not merely within the reflection: - // it correlates one half's I(+)-I(-) against the other's, so each hand separately needs both - // of its halves filled, and a mate left entirely in one half loses the whole pair rather than - // half of it. So the cell here is (pair, hand), where the merge above used the reflection. - // Each observation's cell on its own, so on all threads (the key generator is const). + // The cell here is (pair, hand), where the merge above used the reflection: CCanom + // correlates one half's I(+)-I(-) against the other's, so each hand separately needs both + // of its halves filled. Each observation's cell on its own, so on all threads (the key + // generator is const). std::vector anom_cell(fulls.size(), -1); ParallelChunks(n_full, ThreadsForWork(fulls.size(), nthreads), [&](int lo, int hi) { for (int i = lo; i < hi; ++i) { @@ -6885,18 +6888,22 @@ RotationScaleMerge::Result RotationScaleMerge::MergeAndStats(int n_groups, bool if (pair_start[q + 1] - pair_start[q] > 1) std::sort(out.begin(), out.end()); }; - // The halves of each (pair, hand) cell, from the pair's fulls. + // The halves of each pair, from its fulls of both hands: NOT the per-observation deal of the + // CC1/2 halves, which puts the two mates of a Bijvoet pair measured together on opposite + // sides half of the time and turns their shared error into a negative CCanom on strong + // data - see AssignAnomalousHalves. std::vector anom_half(fulls.size(), 0); ParallelBlocks(n_pair, nthreads, [&](int, int q0, int q1) { - std::vector fulls_of_pair, member; + std::vector fulls_of_pair; + std::vector plus, minus; for (int q = q0; q < q1; ++q) { fulls_of(q, fulls_of_pair); - for (int cell = 2 * q; cell < 2 * q + 2; ++cell) { - member.clear(); - for (const int i : fulls_of_pair) - if (anom_cell[i] == cell) member.push_back(i); - AssignHalvesOfMembers(obs_key, member.data(), static_cast(member.size()), anom_half); + plus.clear(); minus.clear(); + for (const int i : fulls_of_pair) { + if (anom_cell[i] < 0) continue; + ((anom_cell[i] & 1) == 0 ? plus : minus).push_back({fulls[i].frame, i}); } + AssignAnomalousHalves(plus, minus, anom_half); } }, 512); ParallelBlocks(n_pair, nthreads, [&](int, int q0, int q1) { @@ -6993,6 +7000,10 @@ RotationScaleMerge::Result RotationScaleMerge::MergeAndStats(int n_groups, bool const double sig_di = std::sqrt(1.0 / swp + 1.0 / swm); sig_num[*shell] += abs_di; sig_den[*shell] += sig_di; sig_num_all += abs_di; sig_den_all += sig_di; ++sig_n; + meas_den[*shell]++; + if (abs_di >= 3.0 * sig_di && swIp / swp >= 3.0 / std::sqrt(swp) && swIm / swm >= 3.0 / std::sqrt(swm)) { + meas_num[*shell]++; meas_num_all++; + } } // CCanom: the anomalous difference measured twice, once per half, correlated over the // pairs where all four cells were filled - which needs both mates measured at least @@ -7065,6 +7076,8 @@ RotationScaleMerge::Result RotationScaleMerge::MergeAndStats(int n_groups, bool ss.r_pim = urmeas_den[s] > 0.0 ? rpim_num[s] / urmeas_den[s] : NAN; ss.abs_diff_over_sigma_anomalous = sig_den[s] > 0.0 ? sig_num[s] / sig_den[s] : NAN; ss.cc_anom = cc_anom_shell[s].GetCC(); + ss.cc_anom_pairs = cc_anom_shell[s].GetN(); + ss.anomalous_measurability = meas_den[s] > 0 ? static_cast(meas_num[s]) / meas_den[s] : NAN; } auto &overall = out.overall; double sum_ios = 0.0; int n_ios = 0; @@ -7084,6 +7097,8 @@ RotationScaleMerge::Result RotationScaleMerge::MergeAndStats(int n_groups, bool overall.r_pim = urmeas_den_all > 0.0 ? rpim_num_all / urmeas_den_all : NAN; overall.abs_diff_over_sigma_anomalous = sig_den_all > 0.0 ? sig_num_all / sig_den_all : NAN; overall.cc_anom = cc_anom_overall.GetCC(); + overall.cc_anom_pairs = cc_anom_overall.GetN(); + overall.anomalous_measurability = sig_n > 0 ? static_cast(meas_num_all) / sig_n : NAN; // The per-hand presentation of the same merge (see AnomalousMergeStatistics). SigAno and // CCanom are pair quantities and read the same in either table, so they are carried over. @@ -7117,6 +7132,8 @@ RotationScaleMerge::Result RotationScaleMerge::MergeAndStats(int n_groups, bool ho.r_meas = ha_rd > 0.0 ? ha_rn / ha_rd : NAN; ho.abs_diff_over_sigma_anomalous = overall.abs_diff_over_sigma_anomalous; ho.cc_anom = overall.cc_anom; + ho.cc_anom_pairs = overall.cc_anom_pairs; + ho.anomalous_measurability = overall.anomalous_measurability; } if (own_table && std::isfinite(overall.abs_diff_over_sigma_anomalous)) logger->Info("Anomalous signal SigAno = {:.2f} ({} acentric pairs), CCanom = {:.3f} ({} pairs " diff --git a/rugnux/ResultReport.cpp b/rugnux/ResultReport.cpp index 11f016154..71d147723 100644 --- a/rugnux/ResultReport.cpp +++ b/rugnux/ResultReport.cpp @@ -472,6 +472,37 @@ namespace { return o.str(); } + // What CC_anom says shell by shell from the low-resolution end, where an anomalous signal lives + // (the overall value is one correlation over every pair of the written range, most of them in the + // noise shells): the resolution to which it holds above CC_ANOM_SIGNAL - AIMLESS's limit of the + // anomalous signal - and, where no shell reaches that, the lowest shell's value against its own + // number of pairs. Quoted in the summary's Anomalous row; the verdict there is the map's. + struct CCanomEvidence { + double d_min = NAN; // the resolution limit of the signal; NaN where the lowest shell is under it + std::string text; // ", holding above 0.15 to 2.79 A" / ", 0.09 over 1368 pairs in the lowest shell" + }; + + CCanomEvidence CCanomSignalEvidence(const MergeStatistics &ms) { + CCanomEvidence v; + const MergeStatisticsShell *low = nullptr; // the lowest-resolution shell CC_anom was measured on + for (const auto &sh : ms.shells) { + if (!std::isfinite(sh.cc_anom)) { + if (low) break; // a gap in the measured shells ends the run + continue; + } + if (!low) low = &sh; + if (sh.cc_anom > CC_ANOM_SIGNAL) v.d_min = sh.d_min; + else break; + } + if (!low) + return v; + if (std::isfinite(v.d_min)) + v.text = fmt::format(", holding above {:.2f} to {:.2f} A", CC_ANOM_SIGNAL, v.d_min); + else + v.text = fmt::format(", {:.2f} over {} pairs in the lowest shell", low->cc_anom, low->cc_anom_pairs); + return v; + } + // The per-hand (FRIEDEL'S_LAW=FALSE) table, in the columns of the run's own. std::string PerHandShellTable(const AnomalousMergeStatistics &ph) { std::ostringstream o; @@ -1737,8 +1768,17 @@ ReportDocument BuildReportDocument(const std::string &output_prefix, Add(s, KeyReal("CC_HALF_SPLIT", o.cc_half_split, "{:.4f}")); if (std::isfinite(o.abs_diff_over_sigma_anomalous)) Add(s, KeyReal("SIGANO", o.abs_diff_over_sigma_anomalous, "{:.3f}")); - if (std::isfinite(o.cc_anom)) + if (std::isfinite(o.cc_anom)) { Add(s, KeyReal("CC_ANOM", o.cc_anom, "{:.4f}")); + Add(s, KeyInt("CC_ANOM_PAIRS", o.cc_anom_pairs)); + } + if (std::isfinite(o.anomalous_measurability)) + Add(s, KeyReal("ANOM_MEASURABILITY", o.anomalous_measurability, "{:.4f}")); + { + const auto v = CCanomSignalEvidence(ms); + if (std::isfinite(v.d_min)) + Add(s, KeyReal("ANOMALOUS_SIGNAL_D_MIN", v.d_min, "{:.2f}")); + } if (std::isfinite(ms.wilson_b)) Add(s, KeyReal("WILSON_B", ms.wilson_b, "{:.2f}")); if (std::isfinite(ms.wilson_b) && std::isfinite(ms.wilson_b_d_low_A)) @@ -1837,17 +1877,31 @@ ReportDocument BuildReportDocument(const std::string &output_prefix, if (std::isfinite(o.cc_anom)) Add(s, ProseDefaultOnly( " CC_ANOM is the anomalous difference measured twice and correlated between the two\n" - " halves; it is what says whether there is a signal to phase on. A negative value is\n" - " a measurement, not an error. XDS's `Anomal Corr` is NOT this quantity.")); + " halves, over the whole written range; the summary's Anomalous line quotes it shell by\n" + " shell, where the signal is, and decides on the anomalous map. XDS's `Anomal Corr` is\n" + " counted over a selected subset of the pairs and reads higher.")); Add(s, Prose(" CC_ANOM is the anomalous difference measured twice - I(+)-I(-) from one half of the\n" " observations against the same difference from the other half - and correlated over the\n" " acentric pairs where both hands were measured at least twice. It is what says whether\n" " there is an anomalous signal to phase on, and unlike SIGANO it is not a ratio against\n" - " the error model, so an optimistic sigma cannot inflate it. It agrees with AIMLESS's\n" - " CCanom and phenix.merging_statistics' cc_anom. XDS's CORRECT.LP has a column named\n" - " `Anomal Corr` which is NOT this quantity and reads considerably higher at low\n" - " resolution, so the two are not comparable.\n" + " the error model, so an optimistic sigma cannot inflate it. The halves keep the two\n" + " mates of a Bijvoet pair measured together - on one image, with a symmetry axis along\n" + " the spindle, or in inverse-beam wedges - on one side, so the error the two share\n" + " cancels in each half's difference instead of reading as a negative correlation on\n" + " strong data, which it does where the observations are dealt out one by one as\n" + " AIMLESS's CCanom and phenix.merging_statistics' cc_anom deal them. XDS's CORRECT.LP\n" + " column `Anomal Corr` is counted over a selected subset of the pairs (its Nano) and\n" + " reads higher, so the two are not comparable. CC_ANOM_PAIRS is the number of pairs\n" + " behind the overall value; the shell table carries the same correlation per shell, and\n" + " the summary's Anomalous line quotes the low-resolution shells, where an anomalous\n" + " signal lives, not the overall value, which the noise shells dilute - and decides on\n" + " the model-phased anomalous map, which pools every pair and sees what no pair\n" + " statistic can, or on the lowest shell's SIGANO without a model.\n" + " ANOM_MEASURABILITY is phenix.xtriage's measurability, the fraction of the acentric\n" + " pairs measured in both hands with |I(+)-I(-)| at 3 sigma and each hand at I/sigma 3,\n" + " over the written range; ANOMALOUS_SIGNAL_D_MIN is the resolution to which CC_ANOM\n" + " holds above 0.15 shell by shell from the low-resolution end, where there is one.\n" " A negative value is a measurement, not an error: on data with little anomalous signal\n" " and around two observations per Bijvoet mate the statistic is unstable and goes\n" " negative, in this program and in the others alike. Where no pair could be split in\n" @@ -3687,7 +3741,10 @@ ReportDocument BuildReportDocument(const std::string &output_prefix, if (std::isfinite(sigano_low)) stats += fmt::format("SigAno {:.2f} in the lowest shell (0.80 = none)", sigano_low); if (std::isfinite(o.cc_anom)) - stats += fmt::format("{}CC_anom {:.2f}", stats.empty() ? "" : ", ", o.cc_anom); + stats += fmt::format("{}CC_anom {:.2f} over {} pairs{}", stats.empty() ? "" : ", ", o.cc_anom, + o.cc_anom_pairs, CCanomSignalEvidence(result.merge_statistics).text); + if (std::isfinite(o.anomalous_measurability)) + stats += fmt::format(", measurability {:.2f}", o.anomalous_measurability); // With a placed model the anomalous difference map at it decides, in both directions: // it pools every Bijvoet pair coherently, so it reads a signal the per-reflection // statistics cannot, and it reads nothing where a systematic Friedel difference gave diff --git a/rugnux/ResultReport.h b/rugnux/ResultReport.h index 25fe2fab7..3c3df3db9 100644 --- a/rugnux/ResultReport.h +++ b/rugnux/ResultReport.h @@ -80,6 +80,9 @@ inline constexpr double ANOM_MAP_PEAK_SIGNAL = 6.0; // the strongest site or u inline constexpr double ANOM_MAP_PEAK_WEAK = 5.0; inline constexpr double ANOM_SIGANO_SIGNAL = 1.0; // the lowest shell's <|dI|>/ inline constexpr double ANOM_SIGANO_WEAK = 0.9; +// The per-shell CC_anom above which a shell counts as carrying anomalous signal: the signal's resolution +// limit (ANOMALOUS_SIGNAL_D_MIN) is where the shells stop holding it, from the low-resolution end. +inline constexpr double CC_ANOM_SIGNAL = 0.15; // TWINNING_VERDICT: NO_INDICATION, INDICATED, SYMMETRY_SUSPECT, NO_TWIN_LAW or NOT_READABLE, from the merge's // intensity statistics (result.twinning, and the space-group search's merge where one was promoted from). diff --git a/tests/MergeScaleTest.cpp b/tests/MergeScaleTest.cpp index 8c6fa952a..cedebbbd8 100644 --- a/tests/MergeScaleTest.cpp +++ b/tests/MergeScaleTest.cpp @@ -7,6 +7,7 @@ #include #include "../image_analysis/bragg_integration/CalcISigma.h" #include "../image_analysis/scale_merge/ErrorModel.h" +#include "../image_analysis/scale_merge/AnomalousHalves.h" #include "../image_analysis/scale_merge/HKLKey.h" #include "../image_analysis/scale_merge/Merge.h" #include "../image_analysis/scale_merge/ResolutionCutoff.h" @@ -1636,5 +1637,31 @@ TEST_CASE("MergeOnTheFly_StillsAnomalousStatistics") { const auto merged = merge.ExportReflections(); const auto stats = merge.MergeStats(merged, outcomes); CHECK(stats.overall.cc_anom > 0.9); + CHECK(stats.overall.cc_anom_pairs == 60); CHECK(stats.overall.abs_diff_over_sigma_anomalous > 5.0); + CHECK(stats.overall.anomalous_measurability > 0.9); +} + +// The CCanom halves of a Bijvoet pair: each I(+) is coupled with the I(-) measured nearest to it in time, +// a couple is never split, and the couples alternate between the halves in time order. +TEST_CASE("AnomalousHalves_CouplesStayTogetherAndAlternateInTime") { + // Couples at frames (10, 11), (100, 99), (200, 203), (300, 300): indices 0-3 are the I(+), 4-7 their I(-) + // in the same order; the I(-) are handed over out of time order to show the order does not matter. + std::vector half(8, 9); + AssignAnomalousHalves({{10, 0}, {100, 1}, {200, 2}, {300, 3}}, {{300, 7}, {11, 4}, {203, 6}, {99, 5}}, half); + for (int c = 0; c < 4; ++c) + CHECK(half[c] == half[4 + c]); + CHECK(half[0] == 0); CHECK(half[1] == 1); CHECK(half[2] == 0); CHECK(half[3] == 1); +} + +TEST_CASE("AnomalousHalves_AnObservationWithoutAPartnerIsDealtOutOnItsOwn") { + // Three I(+) at 10, 100, 200; one I(-) at 101: it couples with the I(+) at 100, the two lone I(+) + // take the other turns, so the halves are 10 -> 0, (100, 101) -> 1, 200 -> 0. + std::vector half(4, 9); + AssignAnomalousHalves({{10, 0}, {100, 1}, {200, 2}}, {{101, 3}}, half); + CHECK(half[0] == 0); CHECK(half[1] == 1); CHECK(half[3] == 1); CHECK(half[2] == 0); + // One hand only: dealt out alternately, so a hand measured four times still fills both halves. + std::vector one(4, 9); + AssignAnomalousHalves({}, {{5, 0}, {1, 1}, {9, 2}, {3, 3}}, one); + CHECK(one[1] == 0); CHECK(one[3] == 1); CHECK(one[0] == 0); CHECK(one[2] == 1); } diff --git a/tests/RotationScaleMergeSegmentsTest.cpp b/tests/RotationScaleMergeSegmentsTest.cpp index 1a1957398..c61e969f6 100644 --- a/tests/RotationScaleMergeSegmentsTest.cpp +++ b/tests/RotationScaleMergeSegmentsTest.cpp @@ -10,6 +10,8 @@ #include #include +#include + #include "../common/CorrelationCoefficient.h" #include "../common/CUDAWrapper.h" #include "../common/Logger.h" @@ -350,3 +352,71 @@ TEST_CASE("RotationScaleMerge_WeakStretchOfOneCrystalKept", "[RotationScale]") { const auto r = Merge(data, SyntheticExperiment(true), {}); CHECK(r.statistics.sweep_quality.removed_stretches.empty()); } + +// Every frame records its Friedel pairs with both mates together, as a symmetry axis along the spindle +// does, with an anomalous difference of 5% planted and an error of 8% shared by the two mates of each +// couple - what the two spots have in common on real data: the beam, the frame's scale, absorption. +// The shared error is far larger than the signal. Dealt out one observation at a time, it would put the +// two mates on opposite sides half of the time and read as a CCanom well below zero; dealt out by +// couples it cancels inside each half's I(+)-I(-), and the planted difference is what the halves agree on. +TEST_CASE("RotationScaleMerge_CCanomSurvivesAnErrorSharedByTheBijvoetMates", "[RotationScale]") { + std::mt19937 rng(7); + std::vector> hkl; // one representative per Friedel pair + for (int h = -12; h <= 12; ++h) + for (int k = -12; k <= 12; ++k) + for (int l = -12; l <= 12; ++l) { + const std::array m{h, k, l}; + const double d = CELL / std::sqrt(static_cast(h * h + k * k + l * l)); + if ((h || k || l) && d >= 1.6 && m == FriedelKey(h, k, l)) hkl.push_back(m); + } + std::exponential_distribution wilson(1.0); + std::normal_distribution noise(0.0, 1.0); + std::uniform_int_distribution pick(0, hkl.size() - 1); + std::vector I_true(hkl.size()), dano(hkl.size()); + for (size_t i = 0; i < hkl.size(); ++i) { + const auto &m = hkl[i]; + const double s2 = (m[0] * m[0] + m[1] * m[1] + m[2] * m[2]) / (4.0 * CELL * CELL); + I_true[i] = 2000.0 * std::exp(-2.0 * 15.0 * s2) * (0.05 + wilson(rng)); + dano[i] = 0.05 * noise(rng); + } + Synthetic data; + for (int f = 0; f < 60; ++f) { + IntegrationOutcome o; + o.latt = CrystalLattice(UnitCell{static_cast(CELL), static_cast(CELL), + static_cast(CELL), 90, 90, 90}); + for (int j = 0; j < 300; ++j) { + const size_t i = pick(rng); + const auto &m = hkl[i]; + const double shared = 1.0 + 0.08 * noise(rng); + for (const int sign: {1, -1}) { + const double expected = I_true[i] * (1.0 + sign * dano[i]) * shared; + const double sigma = std::sqrt(std::max(expected, 0.0) + 20.0); + Reflection r{}; + r.h = sign * m[0]; r.k = sign * m[1]; r.l = sign * m[2]; + r.image_number = static_cast(f); + r.d = static_cast(CELL / std::sqrt(static_cast(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]))); + r.I = static_cast(expected + sigma * noise(rng)); + r.sigma = static_cast(sigma); + r.var_bkg = static_cast(sigma * sigma - std::max(0.0, static_cast(r.I))); + r.bkg = 20.0f; + r.prescaling_corr = 1.0f; + r.partiality = 1.0f; + r.zeta = 1.0f; + r.image_scale_corr = 1.0f; + r.predicted_x = 500.0f; + r.predicted_y = 500.0f; + o.reflections.push_back(r); + } + } + data.frames.push_back(std::move(o)); + } + const auto r = Merge(data, SyntheticExperiment(false), {}); + for (const auto &sh: r.statistics.shells) + UNSCOPED_INFO(fmt::format("shell d_min {:.2f}: I/sigma {:.1f} SigAno {:.2f} CCanom {:.3f} over {} pairs, " + "measurability {:.2f}", sh.d_min, sh.mean_i_over_sigma, + sh.abs_diff_over_sigma_anomalous, sh.cc_anom, sh.cc_anom_pairs, + sh.anomalous_measurability)); + CHECK(r.statistics.overall.cc_anom_pairs > 1000); + CHECK(r.statistics.overall.cc_anom > 0.5); + CHECK(r.statistics.overall.abs_diff_over_sigma_anomalous > 1.0); +}