Files
Jungfraujoch/image_analysis/indexing/SpindleBlindFraction.cpp
T
leonarski_f a39fd29f77
Build Packages / XDS test (JFJoch plugin) (push) Successful in 11m4s
Build Packages / Unit tests (push) Skipped
Build Packages / build:windows:nocuda (push) Successful in 17m46s
Build Packages / build:windows:cuda (push) Successful in 20m20s
Build Packages / build:viewer-tgz:cpu (push) Successful in 15m56s
Build Packages / build:viewer-tgz:cuda (push) Successful in 17m57s
Build Packages / build:rugnux-tgz (x86_64) (push) Successful in 14m10s
Build Packages / build:rugnux:windows (push) Successful in 11m12s
Build Packages / build:rugnux:aarch64 (cross) (push) Successful in 7m14s
Build Packages / build:rpm (rocky8_nocuda) (push) Successful in 22m13s
Build Packages / build:rpm (rocky9_nocuda) (push) Successful in 19m17s
Build Packages / build:rpm (ubuntu2204_nocuda) (push) Successful in 21m21s
Build Packages / build:rpm (ubuntu2404_nocuda) (push) Successful in 17m26s
Build Packages / build:rpm (rocky8_sls9) (push) Successful in 23m56s
Build Packages / build:rpm (rocky9_sls9) (push) Successful in 20m48s
Build Packages / build:rpm (rocky8) (push) Successful in 23m43s
Build Packages / build:rpm (rocky9) (push) Successful in 20m38s
Build Packages / build:rpm (ubuntu2204) (push) Successful in 24m57s
Build Packages / build:rpm (ubuntu2404) (push) Successful in 20m58s
Build Packages / XDS test (durin plugin) (push) Successful in 10m43s
Build Packages / Generate python client (push) Successful in 47s
Build Packages / Build documentation (push) Successful in 1m5s
Build Packages / Create release (push) Skipped
Build Packages / XDS test (neggia plugin) (push) Successful in 8m57s
Build Packages / DIALS test (push) Successful in 18m40s
v1.0.0-rc.167 (#77)
* `rugnux --model` reports CC(model, data) - the correlation of the merged intensities with the placed, scaled model - by resolution shell, on the same shells as CC1/2, with the reflection count and a significance for each.
* `rugnux --model` fits the model's scale, anisotropic B and bulk-solvent parameters on the working reflections only, so the R-free it reports is measured against a model no free reflection helped scale.
* The bulk-solvent parameters of `rugnux --model` are searched over their physically meaningful range instead of being fitted without bounds, so a model is never scaled with a solvent term that has silently switched itself off.
* The rigid-body placement of `rugnux --model` uses the same bounded bulk solvent as the reported fit, so a model is no longer placed against a target carrying a solvent term with no physical meaning.
* `rugnux --model` puts the model into the data's own description of the lattice before placing it, so a model whose cell is written on other axes - I-centred where the run indexed C-centred, a different unique axis, a permuted orthorhombic cell - is placed rather than scored where it was read; `MODEL_CHANGE_OF_BASIS=` and `MODEL_SETTING_AS_READ=` report it when it happens.
* The rugnux results report opens with a summary - `VERDICT=` (`OK`, `WARNINGS`, `UNUSABLE`, `FAILED`), `VERDICT_TEXT=`, `PATHOLOGY_FLAGS=` with one closed-vocabulary code per condition that warned, and the `WARNING:` lines, which used to close the file - and the sections after it are renumbered 1-5 with no gaps.
* `rugnux --developer` writes the full results report - the pipeline-internal keys and the long explanations the default report now leaves out - and `--finalist-ledger` adds the evidence for every space group the search considered, not only the one it adopted.
* The results report warns when the merged data carry no usable signal and when too little of reciprocal space was measured inside the fitted resolution, and omits `FITTED_RESOLUTION` where the CC1/2 curve it is fitted on never falls off.
* rugnux detects translational pseudo-symmetry and reports it under the `PSEUDO_TRANSLATION` flag as `TNCS_DETECTED=` and the `TNCS_*` keys - a translation the merged data are exactly invariant under is reported as `UNDECLARED_LATTICE_TRANSLATION=` under `LATTICE_TRANSLATION` instead - and a detected pseudo-translation can no longer buy a false screw axis in the space-group search or hide a twin from the L-test (`L_TEST_VS_TNCS=`).
* The space-group search determines glide planes from zonal systematic absences, so a non-Sohncke space group such as P 2_1/c or Pbca is named where the run previously stopped at its Sohncke subgroup; `SOHNCKE_SPACE_GROUP=` carries the best Sohncke group beside it on every run that searched, and a centre of symmetry is never claimed.
* Where the cell metric carries more rotational symmetry than the Bravais class the indexer named, the extra rotations are put to the intensities and the space-group search is asked again on the metric's own cell - adopted only where the intensities confirm the higher symmetry - so a lattice that is nearly but not exactly hexagonal, or whose reduction landed in a sub-cell, still reaches its true point group.
* Systematic-absence calls rest on the evidence rather than on counts: a screw axis whose absent class the data show extinct is no longer refused because a handful of reflections in it read as present, and `SPACE_GROUP_ALTERNATIVES=` no longer drops a candidate that differs only on a zone the sweep never measured.
* A reference correlation measured on too few reflections is refused instead of scored zero, so a run given a reference MTZ is no longer reindexed on an operator that mapped almost everything outside the reference's coverage.
* A frame counts as indexed from 6 spots on its lattice rather than 9, so a weakly diffracting crystal whose frames cannot carry 9 is no longer refused the lattice it fits; `--min-indexed-spots` overrides it.
* `-C` accepts a known cell in any equivalent description - conventional or primitive, centred or not - instead of only the reduced primitive form, so a centred cell given the way it is published no longer makes the run report that it found no lattice.
* Each reflection is corrected for the sensor's quantum efficiency at the angle it meets the detector (attenuation lengths from the NIST tables, which also fixes the spot-width parallax term on CdTe) and for the attenuation of the flight path between the sample and its pixel; `--flight-path air|helium|vacuum` declares the medium - default air, since no file states it - and the report says what was assumed and what it was worth. The unmerged MTZ records the factors in new `QE` and `FLIGHT` columns beside `LP`, so raw counts are `I / LP * QE * FLIGHT`, and `_process.h5` in new optional `qe` and `flight` datasets.
* Rotation geometry post-refinement fits the crystal and the detector at once, against the observed spot positions and the observed rocking angles together, so the refined distance depends far less on how wrong the file's distance was.
* A coarsely sliced sweep integrates correctly: partials are joined into one rocking event by angle rather than by frame count, so two crossings of the Ewald sphere are no longer summed into one full, and at 0.5 degrees per image or coarser the per-frame geometry refinement accepts a spot whose miss the exposure's own rotation accounts for.
* `rugnux --mode scale` reports the detector tilt and direct beam of the geometry it re-scaled at, instead of zeros that read as a flat detector, and no longer warns that no image was indexed on a run whose lattice came from its input file.
* Every rotation run that determined a space group and merged reports what the mounting cost: `SPINDLE_LOST_UNIQUE_FRACTION=` is the fraction (0-1) of unique reflections the mounting made unmeasurable under the measured point group, also written to the master as `/entry/MX/spindleLostUniqueFraction` and what the mounting warning fires on; `SPINDLE_SYMMETRY_AXIS_ANGLE_DEG=` / `SPINDLE_SYMMETRY_AXIS_ORDER=` describe the mounting in the `--developer` report.
* Stills and grid scans carry a per-image `spindle_blind_fraction` - how much of a rotation sweep's blind cone this orientation would make unrecoverable, 0.5 and above calling for a second orientation - through the CBOR stream, HDF5 (`/entry/MX/spindleBlindFraction`), the plot and scan-result APIs, and the viewer and frontend plots; an absent value means the frame could not be assessed and is not a 0.
* The results report's `REPORT_VERSION` is 7.

Reviewed-on: #77
Co-authored-by: Filip Leonarski <filip.leonarski@psi.ch>
2026-09-09 07:25:13 +02:00

182 lines
9.2 KiB
C++

// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
// SPDX-License-Identifier: GPL-3.0-only
#include <algorithm>
#include <cmath>
#include "SpindleBlindFraction.h"
#include "../../common/JFJochMath.h" // PI - M_PI is not standard, and MSVC does not define it
namespace {
// Only rows short enough to be a plausible symmetry axis count. The cut is relative to the
// crystal's own shortest row, not an absolute length, so it works the same for a 40 A cell and
// a 200 A one: measured over 107 solved cells, 2.5 x the shortest row covers 88% of all
// symmetry axes and 98% of crystals' shortest one.
constexpr float MAX_ROW_LENGTH_RATIO = 2.5f;
// The reference length is taken over the strong rows only. A long-cell still makes the pass
// invent short spurious rows - measured at 0.4-0.6 of the true row's peak - and taking the
// reference over every row would let one of those shrink the window until the real aligned row
// fell outside it, turning a severe orientation into a reported zero.
constexpr float MIN_MAGNITUDE_RATIO = 0.5f;
// Where the search grid can no longer resolve the crystal's rows, the pass stops returning them
// and starts returning short spurious ones instead, and the shortlist becomes internally
// inconsistent: its strong rows are many times longer than its shortest entry. Measured on the
// stills of 22 solved crystals - 22 independent mounts, so 22 is the sample size, not the
// several hundred frames they contributed - the ratio never exceeded 2.34 and was 1.00 at the
// median; on a
// synthetic still whose cell is past the grid's reach it runs 4-13. Past this the score would be
// reporting a cone it cannot see into, so it reports nothing instead.
constexpr float MAX_REFERENCE_LENGTH_RATIO = 3.0f;
}
float SpindleThetaMax_deg(float wavelength_A, float d_min_A) {
if (wavelength_A <= 0 || d_min_A <= 0)
return 0;
const float sin_theta = std::min(1.0f, wavelength_A / (2.0f * d_min_A));
return static_cast<float>(std::asin(sin_theta) * 180.0 / PI);
}
float BlindConeSelfOverlap(float x) {
if (x >= 1.0f)
return 0.0f;
if (x <= 0.0f)
return 1.0f;
return static_cast<float>(2.0 / PI) *
(std::acos(x) - x * std::sqrt(1.0f - x * x));
}
std::optional<SpindleSeverity> SpindleBlindFraction(const std::vector<Coord> &rows,
const std::vector<float> &magnitudes,
const Coord &spindle,
float theta_max_deg) {
if (rows.empty() || rows.size() != magnitudes.size() || theta_max_deg <= 0)
return {};
const float axis_length = spindle.Length();
if (axis_length < 1e-6f)
return {};
const Coord axis = spindle.Normalize();
float max_magnitude = 0;
for (const auto &m : magnitudes)
max_magnitude = std::max(max_magnitude, m);
float reference_length = 0;
for (size_t i = 0; i < rows.size(); i++)
if (magnitudes[i] >= MIN_MAGNITUDE_RATIO * max_magnitude) {
const float l = rows[i].Length();
if (reference_length == 0 || l < reference_length)
reference_length = l;
}
if (reference_length == 0)
return {};
float shortest_length = reference_length;
for (const auto &r : rows)
shortest_length = std::min(shortest_length, r.Length());
if (reference_length > MAX_REFERENCE_LENGTH_RATIO * shortest_length)
return {};
std::vector<size_t> eligible;
for (size_t i = 0; i < rows.size(); i++) {
const float length = rows[i].Length();
if (length <= 0 || length > MAX_ROW_LENGTH_RATIO * reference_length)
continue;
if (magnitudes[i] < MIN_MAGNITUDE_RATIO * max_magnitude)
continue;
eligible.push_back(i);
}
SpindleSeverity ret;
bool scored = false;
const auto consider = [&](const Coord &direction, float row_length_A) {
const float len = direction.Length();
const float cos_beta = std::min(1.0f, std::fabs(direction * axis) / len);
const float beta_deg = static_cast<float>(std::acos(cos_beta) * 180.0 / PI);
// A direction PERPENDICULAR to the spindle is as damaging as one along it, and far more
// common: a lone 2-fold about it carries the blind cone onto the cone's opposite lobe, which
// the same sweep leaves equally unmeasured. That is Friedel's rescue, which is no rescue -
// the cone is double-sided. (An axis of order >= 3 there DOES repair the cone - measured
// unrepaired fraction 0.000 for orders 3, 4 and 6 against 1.000 for order 2 - but a still
// cannot know the order, and the lone diad is the worst case this bound assumes.) Both ends
// of the range are the bad case and the safe zone lies between them, so the miss-angle is
// folded about 45 deg. Checked against a Monte-Carlo of the true spherical overlap the
// folded form is within 0.006 to theta_max = 20 deg and 0.024 to 45 deg; unfolded it is
// wrong by a full 1.0 at beta = 90 deg, reporting the worst case as the best.
const float fold_deg = std::min(beta_deg, 90.0f - beta_deg);
const float score = BlindConeSelfOverlap(fold_deg / theta_max_deg);
if (!scored || score > ret.score) {
ret.score = score;
ret.row_length_A = row_length_A;
ret.miss_angle_deg = beta_deg;
scored = true;
}
};
for (const auto i : eligible)
consider(rows[i], rows[i].Length());
// A lone 2-fold on an axis LONGER than the length window is invisible above - not among the
// shortlist's rows, and excluded by the window even when it is - but its direction is still
// recoverable: the normal to two direct-lattice rows is itself a reciprocal-lattice row, and a
// symmetry axis is parallel in the direct and reciprocal bases, so for a monoclinic cell
// cross(a, c) IS the unique-axis direction whatever the length of b. Score the normals of the
// strong in-window row pairs alongside the rows themselves; measured on a synthetic lone-diad
// crystal with a 300 A unique axis, the fraction of severe mounts reported severe at the 0.5
// trigger rises from 0.60 to 1.00 and the engagement rate on harmless mounts of that class
// does not move. The guard only rejects a numerically degenerate normal; the shortlist already
// keeps its rows 5 deg apart.
for (size_t a = 0; a < eligible.size(); a++)
for (size_t b = a + 1; b < eligible.size(); b++) {
const Coord n = rows[eligible[a]] % rows[eligible[b]];
if (n.Length() > 1e-4f * rows[eligible[a]].Length() * rows[eligible[b]].Length())
consider(n, 0.0f); // 0 = a direction inferred from a pair, not a measured row
}
return ret;
}
std::optional<SpindleSeverity> SpindleBlindFractionFromLattice(const CrystalLattice &lattice,
const Coord &spindle,
float theta_max_deg) {
// Candidate rows: the direct lattice's shortest few distinct directions, drawn from the index
// box up to +/-2 - the range in which the symmetry axes of a reduced or conventional basis
// lie. The count matches what the FFT shortlist resolves in practice (four or five distinct
// rows - see FilterFFTResults), so the bound is taken over comparable evidence on either path.
// That parity is load-bearing: a worst case over every enumerable direction saturates towards
// "always engage" - measured on a generic triclinic cell it fires on 100% of harmless mounts,
// against 74% for this selection at theta_max = 15 deg - and an always-firing trigger decides
// nothing. The diad-detection rate stays 1.00 on the monoclinic classes either way, because a
// dropped axis row is recovered by the pair normals exactly as an invisible one is.
std::vector<Coord> all;
all.reserve(62);
for (int u = 0; u <= 2; u++)
for (int v = (u == 0) ? 0 : -2; v <= 2; v++)
for (int w = (u == 0 && v == 0) ? 1 : -2; w <= 2; w++)
all.push_back(lattice.Vec0() * static_cast<float>(u)
+ lattice.Vec1() * static_cast<float>(v)
+ lattice.Vec2() * static_cast<float>(w));
std::sort(all.begin(), all.end(),
[](const Coord &a, const Coord &b) { return a.Length() < b.Length(); });
constexpr size_t MAX_LATTICE_ROWS = 6;
const float cos_5_deg = std::cos(5.0f * static_cast<float>(PI) / 180.0f);
std::vector<Coord> rows;
for (const auto &r : all) {
if (rows.size() >= MAX_LATTICE_ROWS
|| r.Length() > MAX_ROW_LENGTH_RATIO * all.front().Length())
break;
bool distinct = true;
for (const auto &k : rows)
if (std::fabs(r * k) / (r.Length() * k.Length()) > cos_5_deg) {
distinct = false;
break;
}
if (distinct)
rows.push_back(r);
}
const std::vector<float> magnitudes(rows.size(), 1.0f);
return SpindleBlindFraction(rows, magnitudes, spindle, theta_max_deg);
}