Files
Jungfraujoch/image_analysis/scale_merge/SublatticeRelabel.cpp
leonarski_f 7f2ebd8209
Build Packages / Build documentation (push) Successful in 46s
Build Packages / Create release (push) Successful in 8s
Build Packages / build:portable:macos-arm64:nocuda (push) Successful in 5m25s
Build Packages / build:rugnux:linux-aarch64:cuda (push) Successful in 9m46s
Build Packages / build:portable:linux-x86_64:nocuda (push) Successful in 13m25s
Build Packages / build:portable:linux-x86_64:cuda (push) Successful in 16m41s
Build Packages / build:portable:windows-x86_64:nocuda (push) Successful in 23m46s
Build Packages / HDF5 consumer tests (DIALS, XDS) (push) Successful in 25m37s
Build Packages / build:jfjoch:rocky8:nocuda (push) Successful in 24m31s
Build Packages / build:portable:windows-x86_64:cuda (push) Successful in 28m9s
Build Packages / build:jfjoch:ubuntu2204:nocuda (push) Successful in 20m47s
Build Packages / build:jfjoch:rocky9:nocuda (push) Successful in 26m21s
Build Packages / build:jfjoch:ubuntu2404:nocuda (push) Successful in 27m36s
Build Packages / Generate python client (push) Successful in 31s
Build Packages / build:jfjoch:rocky8:cuda-sls9 (push) Successful in 29m27s
Build Packages / build:jfjoch:rocky9:cuda-sls9 (push) Successful in 31m46s
Build Packages / build:jfjoch:ubuntu2204:cuda (push) Successful in 25m22s
Build Packages / build:jfjoch:rocky8:cuda (push) Successful in 30m36s
Build Packages / build:jfjoch:rocky9:cuda (push) Successful in 31m49s
Build Packages / build:jfjoch:ubuntu2404:cuda (push) Successful in 23m57s
Build Packages / Unit tests (push) Successful in 1h47m52s
Build Packages / Validation Battery (push) Successful in 44m55s
v1.0.0-rc.184 (#95)
* Rugnux: Rotation processing recovers most of the speed lost since 1.0.0-rc.180; live processing in jfjoch_broker finishes sooner.
* Rugnux: More reliable rotation processing and indexing, including small molecules and supercells.
* Rugnux: More robust serial data and model refinement; molecular replacement handles multi-chain models.
* jfjoch_broker (experimental): Live serial processing keeps the detector geometry fixed for the whole run.
* jfjoch_broker: Pixel sum without an FPGA, a mask bit for inactive pixels, and several stability fixes.
* jfjoch_broker: Rotation indexing and quick integration moved to rugnux live mode; their API settings are deprecated and ignored.
* jfjoch_broker, Rugnux: Azimuthal integration can use logarithmic (log10) Q bins or a given number of bins, set from the API, the web interface and the Rugnux command line.
* jfjoch_viewer: Build and display fixes; the README is rewritten.

Reviewed-on: #95
Co-authored-by: Filip Leonarski <filip.leonarski@psi.ch>
2026-11-10 22:06:51 +01:00

260 lines
13 KiB
C++

// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
// SPDX-License-Identifier: GPL-3.0-only
#include "SublatticeRelabel.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include "../indexing/AnalyzeIndexing.h"
namespace {
// Largest coefficient tried: a reference axis up to four frame axes long, which covers the 2x, 3x
// and 4x axis multiples a few-spot frame gets indexed in.
constexpr int MAX_COEFFICIENT = 4;
// Largest volume ratio frame / reference accepted: the frame's lattice a 2x, 3x or 4x supercell (or
// the reference itself in another setting). A denser lattice holds near-fits of almost any cell.
constexpr int MAX_INDEX = 4;
float AngleDeg(const Coord &u, const Coord &v) {
const float c = (u * v) / (u.Length() * v.Length());
return std::acos(std::clamp(c, -1.0f, 1.0f)) * (180.0f / 3.14159265f);
}
int Det(const std::array<std::array<int, 3>, 3> &m) {
return m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1])
- m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
+ m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]);
}
}
std::vector<std::array<std::array<int, 3>, 3>> FindSublatticeBases(const CrystalLattice &frame,
const UnitCell &reference,
const IndexingSettings &settings) {
const CrystalLattice ref(reference);
const Coord ref_star[3] = {ref.Astar(), ref.Bstar(), ref.Cstar()};
const Coord frame_star[3] = {frame.Astar(), frame.Bstar(), frame.Cstar()};
const float dist_tol = settings.GetUnitCellDistTolerance();
const float angle_tol = settings.GetUnitCellAngleTolerance_deg();
// The frame's reciprocal lattice vectors as long as each reference axis.
struct Candidate { std::array<int, 3> n; Coord v; };
std::vector<Candidate> axis[3];
for (int i = -MAX_COEFFICIENT; i <= MAX_COEFFICIENT; ++i)
for (int j = -MAX_COEFFICIENT; j <= MAX_COEFFICIENT; ++j)
for (int k = -MAX_COEFFICIENT; k <= MAX_COEFFICIENT; ++k) {
const Coord v = frame_star[0] * i + frame_star[1] * j + frame_star[2] * k;
for (int a = 0; a < 3; ++a)
if (std::fabs(v.Length() - ref_star[a].Length()) <= dist_tol * ref_star[a].Length())
axis[a].push_back({{i, j, k}, v});
}
const float ref_angle[3] = {AngleDeg(ref_star[1], ref_star[2]), AngleDeg(ref_star[0], ref_star[2]),
AngleDeg(ref_star[0], ref_star[1])};
std::vector<std::array<std::array<int, 3>, 3>> bases;
for (const auto &a: axis[0])
for (const auto &b: axis[1]) {
if (std::fabs(AngleDeg(a.v, b.v) - ref_angle[2]) > angle_tol)
continue;
for (const auto &c: axis[2]) {
if (std::fabs(AngleDeg(b.v, c.v) - ref_angle[0]) > angle_tol
|| std::fabs(AngleDeg(a.v, c.v) - ref_angle[1]) > angle_tol)
continue;
const std::array<std::array<int, 3>, 3> m = {a.n, b.n, c.n};
if (Det(m) > 0 && Det(m) <= MAX_INDEX)
bases.push_back(m);
}
}
return bases;
}
namespace {
// The reference basis in this frame's orientation: the reciprocal axes are rows of M times the
// frame's, and the real axes their reciprocal.
CrystalLattice OnBasis(const CrystalLattice &frame, const std::array<std::array<int, 3>, 3> &M) {
const Coord fs[3] = {frame.Astar(), frame.Bstar(), frame.Cstar()};
Coord rs[3];
for (int i = 0; i < 3; ++i)
rs[i] = fs[0] * M[i][0] + fs[1] * M[i][1] + fs[2] * M[i][2];
const float v_star = rs[0] * (rs[1] % rs[2]);
return {(rs[1] % rs[2]) / v_star, (rs[2] % rs[0]) / v_star, (rs[0] % rs[1]) / v_star};
}
// The frame's reflections at nodes of the lattice M picks out, re-indexed on it: a frame index h'
// is h = h' M^-1 = h' adj(M) / det(M) there, a node only where all three are integers.
ReflectionVector NodesOf(const ReflectionVector &reflections, const std::array<std::array<int, 3>, 3> &M,
float d_min) {
const int det = Det(M);
int adj[3][3];
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j) {
const int r0 = (j + 1) % 3, r1 = (j + 2) % 3, c0 = (i + 1) % 3, c1 = (i + 2) % 3;
adj[i][j] = M[r0][c0] * M[r1][c1] - M[r0][c1] * M[r1][c0];
}
ReflectionVector nodes;
for (const auto &r: reflections) {
const int hp[3] = {r.h, r.k, r.l};
int h[3];
bool node = true;
for (int j = 0; j < 3; ++j) {
const int s = hp[0] * adj[0][j] + hp[1] * adj[1][j] + hp[2] * adj[2][j];
node = node && s % det == 0;
h[j] = s / det;
}
if (!node || !(r.d >= d_min))
continue;
Reflection relabelled = r;
relabelled.h = h[0];
relabelled.k = h[1];
relabelled.l = h[2];
nodes.push_back(relabelled);
}
return nodes;
}
double MeanISigma(const ReflectionVector &reflections) {
double sum = 0.0;
size_t n = 0;
for (const auto &r: reflections)
if (std::isfinite(r.I) && r.sigma > 0.0f) {
sum += r.I / r.sigma;
++n;
}
return n > 0 ? sum / static_cast<double>(n) : -std::numeric_limits<double>::infinity();
}
}
SublatticeRelabelResult RelabelOnSublattice(std::vector<IntegrationOutcome> &outcomes,
const UnitCell &reference,
const IndexingSettings &settings) {
const auto on_reference = [&](const IntegrationOutcome &o) {
return o.latt.GetUnitCell().is_close(reference, settings.GetUnitCellDistTolerance(),
settings.GetUnitCellAngleTolerance_deg());
};
// A frame indexed in the wrong lattice was also predicted to the wrong resolution - its limit read
// off spots that were mostly noise - so its reflections are kept only as fine as the frames already
// on the reference cell reach.
float d_min = std::numeric_limits<float>::infinity();
for (const auto &o: outcomes)
if (on_reference(o))
for (const auto &r: o.reflections)
if (std::isfinite(r.d) && r.d > 0.0f)
d_min = std::min(d_min, r.d);
SublatticeRelabelResult result;
double all_i_sigma = 0.0, kept_i_sigma = 0.0;
for (auto &o: outcomes) {
if (o.reflections.empty() || on_reference(o))
continue;
// A lattice can hold the reference in more than one way - a supercell whose metric is nearly
// symmetric fits it along either of two axes - and only the true one has signal at its nodes:
// the reflections between them are empty. So the bases are told apart by the data.
std::optional<std::array<std::array<int, 3>, 3>> best;
ReflectionVector best_nodes;
double best_signal = 0.0;
for (const auto &m: FindSublatticeBases(o.latt, reference, settings)) {
auto nodes = NodesOf(o.reflections, m, d_min);
const double signal = MeanISigma(nodes);
if (!best || signal > best_signal) {
best = m;
best_nodes = std::move(nodes);
best_signal = signal;
}
}
if (!best)
continue;
result.reflections_dropped += o.reflections.size() - best_nodes.size();
result.reflections_kept += best_nodes.size();
for (const auto &r: o.reflections)
if (std::isfinite(r.I) && r.sigma > 0.0f)
all_i_sigma += r.I / r.sigma;
for (const auto &r: best_nodes)
if (std::isfinite(r.I) && r.sigma > 0.0f)
kept_i_sigma += r.I / r.sigma;
o.reflections = std::move(best_nodes);
o.latt = OnBasis(o.latt, *best);
++result.frames;
}
if (result.reflections_kept > 0)
result.kept_i_sigma = kept_i_sigma / static_cast<double>(result.reflections_kept);
if (result.reflections_dropped > 0)
result.dropped_i_sigma = (all_i_sigma - kept_i_sigma) / static_cast<double>(result.reflections_dropped);
return result;
}
std::optional<UnitCell> CellOnReference(const UnitCell &cell, const UnitCell &reference,
const IndexingSettings &settings) {
auto bases = FindSublatticeBases(CrystalLattice(cell), reference, settings);
if (bases.empty())
return {};
// The reference in another setting (index 1) before any axis multiple of it.
std::sort(bases.begin(), bases.end(), [](const auto &x, const auto &y) { return Det(x) < Det(y); });
return OnBasis(CrystalLattice(cell), bases.front()).GetUnitCell();
}
UnitCell SubLatticeCell(const UnitCell &cell, const std::array<int, 3> &translation, int index) {
const CrystalLattice standing(cell);
const Coord A = standing.Vec0(), B = standing.Vec1(), C = standing.Vec2();
const auto [u, v, w] = translation;
const Coord t = (A * static_cast<float>(u) + B * static_cast<float>(v) + C * static_cast<float>(w))
/ static_cast<float>(index);
const CrystalLattice sub = w ? CrystalLattice(A, B, t) : v ? CrystalLattice(A, t, C) : CrystalLattice(t, B, C);
return sub.NiggliReduce().GetUnitCell();
}
// A frame's cell can be a supercell of the crystal's that indexes every spot the crystal's cell does, its extra
// nodes empty: the centred conventional cell a pseudo-symmetric metric suggests (a monoclinic cell whose a and
// c are nearly equal reads as C-centred orthorhombic, twice its volume), or face diagonals - a+b and a-b - the
// FFT returned as rows. Where most frames get it, the frames vote for it. Every sub-lattice of a small prime
// index p is the standing lattice with one translation t = (u a + v b + w c) / p added, and its reciprocal
// lattice keeps the nodes with h u + k v + l w a multiple of p: the spots on the others are what the
// sub-lattice would lose. As in the rotation first pass (SubLatticeHypothesis), the candidate is the one that
// loses fewest, and it is adopted where those are no more than the spots off the lattice put there by chance:
// a real superstructure keeps its cell, because the nodes it adds hold reflections.
SubLatticeTest TestSubLattices(const std::vector<const FrameSpotIndices *> &frames, float indexing_tolerance) {
constexpr std::array<int, 4> PRIMES = {2, 3, 5, 7};
SubLatticeTest best;
int64_t off_lattice = 0;
for (const auto *f : frames) {
best.spots += static_cast<int64_t>(f->hkl.size());
off_lattice += f->off_lattice;
}
for (const int p : PRIMES)
for (int u = 0; u < p; u++)
for (int v = 0; v < p; v++)
for (int w = 0; w < p; w++) {
// Each line through the origin once: its last non-zero component 1.
if ((w ? w : v ? v : u) != 1)
continue;
int64_t dropped = 0;
for (const auto *f : frames)
for (const auto &q : f->hkl)
if ((q[0] * u + q[1] * v + q[2] * w) % p != 0)
dropped++;
if (best.index != 0 && dropped >= best.dropped)
continue;
best.index = p;
best.translation = {u, v, w};
best.dropped = dropped;
}
if (best.index == 0)
return best;
// A spot off the crystal's lattice lands within the indexing tolerance of a node - a sphere of that
// radius in fractional indices - with probability 4/3 pi tol^3, and on a dropped node (p-1)/p of the
// time.
const double tol = indexing_tolerance;
best.chance = static_cast<double>(off_lattice) * (4.0 / 3.0) * 3.14159265358979 * tol * tol * tol
* (best.index - 1) / best.index;
// And on too few spots, no more than chance is also what nodes as full as the kept ones could give: those
// would hold (p-1)/p of the spots, binomially, and the count has to be well short of that.
const double q = static_cast<double>(best.index - 1) / best.index;
const double full = static_cast<double>(best.spots) * q;
const double dropped = static_cast<double>(best.dropped);
best.adopt = dropped - best.chance <= SPOT_BUDGET_SIGNIFICANCE_Z * std::sqrt(std::max(1.0, best.chance))
&& full - dropped > SPOT_BUDGET_SIGNIFICANCE_Z * std::sqrt(full * (1.0 - q));
return best;
}