Files
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

725 lines
33 KiB
C++

// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
// SPDX-License-Identifier: GPL-3.0-only
#include "ReferenceFreeReindex.h"
#include <algorithm>
#include <array>
#include <cstdint>
#include <functional>
#include <map>
#include <numeric>
#include <numbers>
#include <random>
#include <unordered_map>
#include "HKLKey.h"
#include "ReindexAmbiguity.h"
#include "../../common/CrystalLattice.h"
#include "../../common/ParallelFor.h"
namespace {
constexpr size_t MIN_REFLECTIONS = 20;
constexpr int RESOLUTION_BINS = 20;
constexpr int RESTARTS = 4;
constexpr int MAX_SWEEPS = 100;
constexpr int MAX_ROUNDS = 20;
constexpr int EM_ITERATIONS = 100;
constexpr double DECIDED_SIGMA = 3.0;
using CellFeatures = std::array<double, 6>;
// A cell's shape, as CellMetric compares it: the log of each length less their mean, and each angle's
// distance from 90 degrees (rad).
CellFeatures Features(const UnitCell &u) {
const double la = std::log(u.a), lb = std::log(u.b), lc = std::log(u.c);
const double mean = (la + lb + lc) / 3.0;
const auto fold = [](double deg) { return std::fabs(deg - 90.0) * std::numbers::pi / 180.0; };
return {la - mean, lb - mean, lc - mean, fold(u.alpha), fold(u.beta), fold(u.gamma)};
}
// Which of a crystal's cell parameters its refinement measured: an angle held at 90 or 120 degrees was not.
std::array<bool, 6> Measured(const UnitCell &u) {
const auto free = [](double deg) { return std::fabs(deg - 90.0) > 1e-3 && std::fabs(deg - 120.0) > 1e-3; };
return {true, true, true, free(u.alpha), free(u.beta), free(u.gamma)};
}
// A cell to the last digit printed, to find the cells several crystals share.
std::array<int64_t, 6> CellKey(const UnitCell &u) {
const auto r = [](double v) { return static_cast<int64_t>(std::llround(v * 1e4)); };
return {r(u.a), r(u.b), r(u.c), r(u.alpha), r(u.beta), r(u.gamma)};
}
// The cell a crystal truly in indexing g has as indexed: the run's after the inverse of g.
std::vector<CellFeatures> Predictions(const UnitCell &cell, const std::vector<gemmi::Op> &indexings) {
std::vector<CellFeatures> out;
for (const auto &op : indexings)
out.push_back(Features(ReindexLattice(CrystalLattice(cell), op.inverse()).GetUnitCell()));
return out;
}
double Median(std::vector<double> v) {
if (v.empty())
return NAN;
std::nth_element(v.begin(), v.begin() + v.size() / 2, v.end());
return v[v.size() / 2];
}
size_t ArgMax(const std::vector<double> &v) {
return std::max_element(v.begin(), v.end()) - v.begin();
}
// Per operator, the median over the crystals whose cell says anything of how much better it fits as
// indexed than after the operator.
std::vector<double> MetricLogOdds(const std::vector<std::vector<double>> &ll, size_t K) {
std::vector<double> out;
for (size_t g = 1; g < K; ++g) {
std::vector<double> v;
for (const auto &l : ll)
if (l.size() == K && std::any_of(l.begin(), l.end(), [](double x) { return x != 0.0; }))
v.push_back(l[0] - l[g]);
out.push_back(v.empty() ? 0.0 : Median(v));
}
return out;
}
// A consistent answer relabelled as a whole by one of the indexings is as consistent: take the one
// the crystals' cells favour together (metric: per entry of choice, the log-likelihood of each indexing,
// or empty) - and where they say nothing, the one that leaves the most crystals where they are. Two
// indexings are the same for the merge when they send a general reflection to the same reflection of
// the asymmetric unit. Returns, for each indexing g, the indexing a crystal in g is in after that
// relabel. choice: each crystal's indexing.
std::vector<int> GlobalRelabel(const std::vector<gemmi::Op> &indexings, const std::vector<int> &choice,
const gemmi::SpaceGroup &sg, const std::vector<std::vector<double>> &metric) {
const HKLKeyGenerator key_gen(/*merge_friedel=*/true, sg);
const int K = static_cast<int>(indexings.size());
const std::array<int, 3> general{2, 5, 11};
const auto same = [&](const gemmi::Op::Miller &a, const gemmi::Op::Miller &b) {
return key_gen(a[0], a[1], a[2]) == key_gen(b[0], b[1], b[2]);
};
// becomes[h][c]: a crystal in c after the overall relabel h
std::vector<std::vector<int>> becomes(K, std::vector<int>(K));
for (int h = 0; h < K; ++h)
for (int c = 0; c < K; ++c) {
becomes[h][c] = c;
const auto composed = indexings[h].apply_to_hkl(indexings[c].apply_to_hkl(general));
for (int g = 0; g < K; ++g)
if (same(composed, indexings[g].apply_to_hkl(general))) {
becomes[h][c] = g;
break;
}
}
int global = 0;
double global_ll = -INFINITY;
size_t global_kept = 0;
for (int h = 0; h < K; ++h) {
// Only an indexing that keeps the merge's symmetry-equivalent reflections together relabels a merge
// as a whole. Where the crystal's Laue group is not normal in the lattice's (a monoclinic crystal on
// a pseudo-tetragonal lattice, say), some do not - one that puts the two-fold on another axis - and
// taken as one they would split crystals that differ by a symmetry of the crystal into different
// indexings, scrambling a consistent answer.
const auto relabelled = indexings[h].apply_to_hkl(general);
bool keeps_symmetry = true;
for (const auto &op : sg.operations().sym_ops)
keeps_symmetry = keeps_symmetry
&& same(indexings[h].apply_to_hkl(op.apply_to_hkl(general)), relabelled);
if (!keeps_symmetry)
continue;
double ll = 0;
size_t kept = 0;
for (size_t i = 0; i < choice.size(); ++i) {
const int g = becomes[h][choice[i]];
kept += g == 0;
if (!metric.empty() && metric[i].size() == static_cast<size_t>(K))
ll += metric[i][g];
}
if (ll > global_ll || (ll == global_ll && kept > global_kept)) {
global_ll = ll;
global_kept = kept;
global = h;
}
}
return becomes[global];
}
}
std::vector<double> CellMetric::LogLikelihood(const CrystalLattice &latt, const std::vector<gemmi::Op> &ops) const {
std::vector<gemmi::Op> indexings{gemmi::Op::identity()};
indexings.insert(indexings.end(), ops.begin(), ops.end());
std::vector<double> ll(indexings.size(), 0.0);
const UnitCell u = latt.GetUnitCell();
if (priors.contains(CellKey(u)))
return ll;
const CellFeatures x = Features(u);
const auto measured = Measured(u);
const auto prediction = Predictions(cell, indexings);
for (size_t g = 0; g < indexings.size(); ++g)
for (int j = 0; j < 6; ++j)
if (measured[j] && variance[j] > 0) {
const double r = x[j] - prediction[g][j];
ll[g] -= r * r / (2.0 * variance[j]);
}
return ll;
}
CellMetric FitCellMetric(const std::vector<IntegrationOutcome> &outcomes, const UnitCell &cell,
const std::vector<gemmi::Op> &ops) {
std::vector<gemmi::Op> indexings{gemmi::Op::identity()};
indexings.insert(indexings.end(), ops.begin(), ops.end());
const size_t K = indexings.size();
CellMetric m;
m.cell = cell;
std::map<std::array<int64_t, 6>, int> seen;
for (const auto &o : outcomes)
if (!o.reflections.empty())
++seen[CellKey(o.latt.GetUnitCell())];
for (const auto &[key, n] : seen)
if (n > 1)
m.priors.insert(key);
const auto prediction = Predictions(cell, indexings);
std::vector<CellFeatures> x;
std::vector<std::array<bool, 6>> measured;
for (const auto &o : outcomes) {
if (o.reflections.empty())
continue;
const UnitCell u = o.latt.GetUnitCell();
if (m.priors.contains(CellKey(u)))
continue;
x.push_back(Features(u));
measured.push_back(Measured(u));
}
m.crystals = x.size();
if (x.empty())
return m;
// Expectation-maximisation: each crystal in each indexing with the weight its cell gives it, the scatter
// the weighted residuals have; from all indexings equally weighted.
std::vector<double> w(x.size() * K, 1.0 / static_cast<double>(K));
for (int iter = 0; iter < EM_ITERATIONS; ++iter) {
std::array<double, 6> sum{}, count{};
for (size_t f = 0; f < x.size(); ++f)
for (int j = 0; j < 6; ++j)
if (measured[f][j]) {
count[j] += 1.0;
for (size_t g = 0; g < K; ++g) {
const double r = x[f][j] - prediction[g][j];
sum[j] += w[f * K + g] * r * r;
}
}
for (int j = 0; j < 6; ++j)
m.variance[j] = count[j] > 0 ? sum[j] / count[j] : 0.0;
for (size_t f = 0; f < x.size(); ++f) {
std::vector<double> ll(K, 0.0);
for (size_t g = 0; g < K; ++g)
for (int j = 0; j < 6; ++j)
if (measured[f][j] && m.variance[j] > 0) {
const double r = x[f][j] - prediction[g][j];
ll[g] -= r * r / (2.0 * m.variance[j]);
}
const double top = *std::max_element(ll.begin(), ll.end());
double total = 0;
for (size_t g = 0; g < K; ++g)
total += w[f * K + g] = std::exp(ll[g] - top);
for (size_t g = 0; g < K; ++g)
w[f * K + g] /= total;
}
}
return m;
}
double IntensityLogLikelihood(double cc, double n, double weight) {
if (!std::isfinite(cc) || n <= 3)
return 0.0;
return (n - 3.0) * weight * std::atanh(std::clamp(cc, -0.999, 0.999));
}
ReferenceFreeReindexResult ResolveIndexingAmbiguity(std::vector<IntegrationOutcome> &outcomes,
const DiffractionExperiment &x, const UnitCell &cell,
const std::vector<gemmi::Op> &all_ops,
const std::vector<MergedReflection> &reference, size_t nthreads) {
ReferenceFreeReindexResult out;
out.choice.assign(outcomes.size(), -1);
if (all_ops.empty())
return out;
const auto &s = x.GetScalingSettings();
const gemmi::SpaceGroup &sg = x.GetSpaceGroupOrP1();
std::vector<gemmi::Op> indexings{gemmi::Op::identity()};
indexings.insert(indexings.end(), all_ops.begin(), all_ops.end());
const int K = static_cast<int>(indexings.size());
out.model.metric = FitCellMetric(outcomes, cell, all_ops);
const auto accept = [&](const Reflection &r) {
return !r.on_ice_ring && AcceptReflection(r, s.GetHighResolutionLimit_A(), s.GetLowResolutionLimit_A())
&& r.partiality >= s.GetMinPartiality() && r.partiality > 0.0f
&& std::isfinite(r.I) && std::isfinite(r.sigma) && r.sigma > 0.0f;
};
const auto corrected = [](const Reflection &r) {
return static_cast<double>(r.I) * (r.prescaling_corr * r.qe_corr * r.flight_corr) / r.partiality;
};
// The crystals are compared on the square root of the intensity, its sign kept. Intensities follow
// the Wilson distribution, whose long tail lets a few very strong reflections dominate every product
// of two crystals: then the strongest crystals settle among themselves, and a group of them can hold
// one another in the wrong indexing however much the weaker majority disagrees. Amplitudes have no
// such tail.
const auto amplitude = [&](const Reflection &r) {
const double i = corrected(r);
return std::copysign(std::sqrt(std::fabs(i)), i);
};
const auto amplitude_sigma = [&](const Reflection &r) {
const double sigma = r.sigma * (r.prescaling_corr * r.qe_corr * r.flight_corr) / r.partiality;
return sigma / (2.0 * std::sqrt(std::fabs(corrected(r)) + sigma));
};
// What each image has to offer: how many reflections, how fine, and how far its indices reach in
// any of the indexings (which sizes the index table below).
const int n_out = static_cast<int>(outcomes.size());
std::vector<size_t> count(n_out, 0);
std::vector<std::array<int, 3>> reach(n_out, {0, 0, 0});
std::vector<double> s3_max(n_out, 0.0);
ParallelFor(n_out, nthreads, [&](int o) {
for (const auto &r : outcomes[o].reflections) {
if (!accept(r))
continue;
++count[o];
s3_max[o] = std::max(s3_max[o], 1.0 / (static_cast<double>(r.d) * r.d * r.d));
for (const auto &op : indexings) {
const auto h = op.apply_to_hkl({{r.h, r.k, r.l}});
for (int i = 0; i < 3; ++i)
reach[o][i] = std::max(reach[o][i], std::abs(h[i]));
}
}
});
// The crystals: images with enough reflections, in image order.
std::vector<int> crystal_outcome;
std::vector<size_t> begin{0};
std::array<int, 3> bound{0, 0, 0};
double s3_top = 0.0;
for (int o = 0; o < n_out; ++o) {
if (count[o] < MIN_REFLECTIONS)
continue;
crystal_outcome.push_back(o);
begin.push_back(begin.back() + count[o]);
for (int i = 0; i < 3; ++i)
bound[i] = std::max(bound[i], reach[o][i]);
s3_top = std::max(s3_top, s3_max[o]);
}
const int N = static_cast<int>(crystal_outcome.size());
if (N < 2)
return out;
// What each crystal's own cell says of each indexing (CellMetric).
std::vector<std::vector<double>> metric(N);
ParallelFor(N, nthreads, [&](int c) {
metric[c] = out.model.metric.LogLikelihood(outcomes[crystal_outcome[c]].latt, all_ops);
});
out.metric_log_odds = MetricLogOdds(metric, K);
out.crystals = N;
// ... and its CC with the reference in each indexing, as a log-likelihood weighted by how far the right
// indexing stands out in the run (IntensityLogLikelihood): the best indexing against the mean of the
// others.
std::vector<std::vector<double>> by_reference(N);
if (!reference.empty()) {
const ReindexAmbiguityResolver resolver(x, reference);
std::vector<ReindexAmbiguityResolver::Scored> scored(N);
ParallelFor(N, nthreads, [&](int c) { scored[c] = resolver.Scores(outcomes[crystal_outcome[c]].reflections, all_ops); });
std::vector<double> z_best, z_rest;
for (const auto &sc : scored) {
std::vector<double> zs;
for (const double r : sc.cc)
if (std::isfinite(r))
zs.push_back(std::atanh(std::clamp(r, -0.999, 0.999)));
if (zs.size() < 2)
continue;
std::sort(zs.begin(), zs.end(), std::greater<>());
z_best.push_back(zs[0]);
z_rest.push_back(std::accumulate(zs.begin() + 1, zs.end(), 0.0) / static_cast<double>(zs.size() - 1));
}
const double weight = std::max(0.0, Median(z_best) - Median(z_rest));
// An indexing the reference cannot score counts as the crystal's worst scored one; a crystal it cannot
// score at all gets nothing from it.
for (int c = 0; c < N; ++c) {
std::vector<double> ll(K, INFINITY);
for (int g = 0; g < K; ++g)
if (std::isfinite(scored[c].cc[g]))
ll[g] = IntensityLogLikelihood(scored[c].cc[g], static_cast<double>(scored[c].n), weight);
const double worst = *std::min_element(ll.begin(), ll.end());
if (!std::isfinite(worst))
continue;
for (double &v : ll)
v = std::isfinite(v) ? v : worst;
by_reference[c] = ll;
}
}
// What chooses the run's indexing as a whole: the cells and the reference. A crystal itself is decided by
// its agreement with all the other crystals and its cell, not by the reference: a reference - a model's
// intensities most of all - reads a weak crystal less clearly than the merge of all the others does,
// and its CC shares the crystal's own noise with that agreement, so the two are not independent.
// Measured on a pseudo-tetragonal P21 serial run against model truth: 97% of the crystals right with
// the reference weighed in crystal by crystal, 99.5% with the reference fixing the indexing as a whole.
std::vector<std::vector<double>> evidence = metric;
for (int c = 0; c < N; ++c)
for (int g = 0; g < K && !by_reference[c].empty(); ++g)
evidence[c][g] += by_reference[c][g];
const size_t nnz = begin.back();
// The mean and spread of the amplitudes in shells of equal reciprocal volume over the whole run, so
// that a crystal's amplitudes are compared after the fall-off with resolution, which every indexing
// shares, is out. Past the resolution the run reaches, a shell holds only noise and its mean may be
// zero or negative, so a shell is put on its mean and spread rather than divided by its mean.
const auto bin_of = [&](const Reflection &r) {
const double s3 = 1.0 / (static_cast<double>(r.d) * r.d * r.d);
return std::min(RESOLUTION_BINS - 1, static_cast<int>(RESOLUTION_BINS * s3 / s3_top));
};
std::vector<std::array<double, 3 * RESOLUTION_BINS>> bin_part(N);
ParallelFor(N, nthreads, [&](int c) {
auto &b = bin_part[c];
b.fill(0.0);
for (const auto &r : outcomes[crystal_outcome[c]].reflections)
if (accept(r)) {
const double a = amplitude(r);
b[bin_of(r)] += 1.0;
b[RESOLUTION_BINS + bin_of(r)] += a;
b[2 * RESOLUTION_BINS + bin_of(r)] += a * a;
}
});
std::array<double, RESOLUTION_BINS> bin_mean{}, bin_sd{};
{
std::array<double, 3 * RESOLUTION_BINS> total{};
for (const auto &b : bin_part) // in crystal order: the same sum at any thread count
for (int i = 0; i < 3 * RESOLUTION_BINS; ++i)
total[i] += b[i];
for (int i = 0; i < RESOLUTION_BINS; ++i) {
const double n = total[i];
bin_mean[i] = n > 0 ? total[RESOLUTION_BINS + i] / n : 0.0;
const double var = n > 0 ? total[2 * RESOLUTION_BINS + i] / n - bin_mean[i] * bin_mean[i] : 0.0;
bin_sd[i] = var > 0 ? std::sqrt(var) : 1.0;
}
}
// Every index any indexing can produce, mapped to a dense number of its reflection in the
// asymmetric unit (Friedel mates together: the anomalous difference would only add noise here).
const HKLKeyGenerator key_gen(/*merge_friedel=*/true, sg);
const int dh = 2 * bound[0] + 1, dk = 2 * bound[1] + 1, dl = 2 * bound[2] + 1;
const auto entry = [&](int h, int k, int l) {
return (static_cast<size_t>(h + bound[0]) * dk + (k + bound[1])) * dl + (l + bound[2]);
};
std::vector<uint64_t> table_key(static_cast<size_t>(dh) * dk * dl);
ParallelFor(dh, nthreads, [&](int ih) {
for (int k = -bound[1]; k <= bound[1]; ++k)
for (int l = -bound[2]; l <= bound[2]; ++l)
table_key[entry(ih - bound[0], k, l)] = key_gen(ih - bound[0], k, l).pack();
});
std::vector<int32_t> table(table_key.size());
int32_t n_keys = 0;
{
std::unordered_map<uint64_t, int32_t> dense;
for (size_t i = 0; i < table_key.size(); ++i) {
const auto [it, inserted] = dense.try_emplace(table_key[i], n_keys);
n_keys += inserted;
table[i] = it->second;
}
}
table_key = {};
// Each crystal's amplitudes, put on the shell's mean and spread and standardised within the crystal
// (the unknown scale and offset of an image drop out), and where each lands in every indexing. Each is
// weighted by how much of it is signal: a standardised amplitude has unit variance, of which its
// measurement error takes (sigma / sd)^2, so a weak or barely recorded reflection counts for little.
std::vector<float> z(nnz);
std::vector<std::vector<int32_t>> key(K, std::vector<int32_t>(nnz));
ParallelFor(N, nthreads, [&](int c) {
std::vector<double> err;
size_t j = begin[c];
double sum = 0, sum2 = 0;
for (const auto &r : outcomes[crystal_outcome[c]].reflections) {
if (!accept(r))
continue;
const double v = (amplitude(r) - bin_mean[bin_of(r)]) / bin_sd[bin_of(r)];
z[j] = static_cast<float>(v);
err.push_back(amplitude_sigma(r) / bin_sd[bin_of(r)]);
sum += v;
sum2 += v * v;
for (int g = 0; g < K; ++g) {
const auto h = indexings[g].apply_to_hkl({{r.h, r.k, r.l}});
key[g][j] = table[entry(h[0], h[1], h[2])];
}
++j;
}
const double n = static_cast<double>(begin[c + 1] - begin[c]);
const double mean = sum / n;
const double sd = std::sqrt(std::max(0.0, sum2 / n - mean * mean));
for (size_t i = begin[c]; i < begin[c + 1]; ++i) {
const double e = err[i - begin[c]] / sd;
z[i] = sd > 0 ? static_cast<float>((z[i] - mean) / sd / (1.0 + e * e)) : 0.0f;
}
});
table = {};
// Following Brehm & Diederichs (2014) Acta Cryst. D70, 101-109: each crystal in turn takes the
// indexing in which it agrees best with all the others, until none changes. Agreement is the sum
// over all pairs of crystals of the products of their standardised amplitudes on common
// reflections, which is the dot product of a crystal with the sum of all the others - so a pass over
// the crystals costs one pass over the reflections, not one per pair of crystals. The sum of all
// pairs only ever grows, so it ends; a few starts are made and the one that ends highest is kept.
std::vector<double> M(n_keys);
const auto add = [&](int c, int g, double sign) {
for (size_t i = begin[c]; i < begin[c + 1]; ++i)
M[key[g][i]] += sign * z[i];
};
const auto dot = [&](int c, int g) {
double d = 0;
for (size_t i = begin[c]; i < begin[c + 1]; ++i)
d += z[i] * M[key[g][i]];
return d;
};
std::vector<int> best_choice;
double best_objective = -1.0;
for (int restart = 0; restart < RESTARTS; ++restart) {
std::vector<int> choice(N, 0);
std::mt19937 rng(restart);
if (restart > 0)
for (int c = 0; c < N; ++c) {
choice[c] = static_cast<int>(rng() % K);
}
std::fill(M.begin(), M.end(), 0.0);
for (int c = 0; c < N; ++c)
add(c, choice[c], 1.0);
int sweeps = 0;
// Run until a pass moves no more than one crystal in a thousand: what still moves then are crystals
// too weak to be decided either way.
for (int changed = N; changed > N / 1000 && sweeps < MAX_SWEEPS; ++sweeps) {
changed = 0;
for (int c = 0; c < N; ++c) {
add(c, choice[c], -1.0);
int best = choice[c];
double best_dot = dot(c, best);
for (int g = 0; g < K; ++g) {
if (g == choice[c])
continue;
const double d = dot(c, g);
if (d > best_dot) {
best_dot = d;
best = g;
}
}
changed += best != choice[c];
choice[c] = best;
add(c, best, 1.0);
}
}
double objective = 0;
for (double m : M)
objective += m * m;
if (objective > best_objective) {
best_objective = objective;
best_choice = choice;
out.sweeps = sweeps;
}
}
// Each crystal's CC with the mean of all the other crystals in every indexing, and on how many reflections.
std::vector<double> cc(static_cast<size_t>(N) * K), n_used(static_cast<size_t>(N) * K);
std::vector<double> C(n_keys);
const auto correlate = [&] {
std::fill(M.begin(), M.end(), 0.0);
std::fill(C.begin(), C.end(), 0.0);
for (int c = 0; c < N; ++c)
for (size_t i = begin[c]; i < begin[c + 1]; ++i) {
M[key[best_choice[c]][i]] += z[i];
C[key[best_choice[c]][i]] += 1.0;
}
ParallelFor(N, nthreads, [&](int c) {
for (int g = 0; g < K; ++g) {
double sx = 0, sy = 0, sxx = 0, syy = 0, sxy = 0, n = 0;
for (size_t i = begin[c]; i < begin[c + 1]; ++i) {
const int32_t k = key[g][i];
const double own = g == best_choice[c] ? 1.0 : 0.0;
const double cnt = C[k] - own;
if (cnt <= 0)
continue;
const double xv = z[i], yv = (M[k] - own * z[i]) / cnt;
sx += xv; sy += yv; sxx += xv * xv; syy += yv * yv; sxy += xv * yv; n += 1;
}
const double vx = sxx - sx * sx / n, vy = syy - sy * sy / n;
const bool ok = n > 3 && vx > 0 && vy > 0;
cc[c * K + g] = ok ? std::clamp((sxy - sx * sy / n) / std::sqrt(vx * vy), -0.999, 0.999) : NAN;
n_used[c * K + g] = ok ? n : 0.0;
}
});
};
// The best other indexing of each crystal, -1 where there is none to compare with.
const auto other_of = [&](int c) {
int other = -1;
for (int g = 0; g < K; ++g)
if (g != best_choice[c] && std::isfinite(cc[c * K + g]) && (other < 0 || cc[c * K + g] > cc[c * K + other]))
other = g;
return other;
};
// The intensities alone leave the run's indexing as a whole open: the reference and the cells choose it.
{
const std::vector<int> becomes = GlobalRelabel(indexings, best_choice, sg, evidence);
for (int &g : best_choice)
g = becomes[g];
}
// Each crystal into the indexing its intensities and its cell together favour, against the mean of all
// the others as they stand, until (almost) none moves. The weight of the intensities is the run's own
// separation of the chosen indexing from the others (IntensityLogLikelihood).
for (int round = 0; round < MAX_ROUNDS; ++round) {
correlate();
// A wrong indexing's z is the mean over the other indexings, not the best of them: the best of many
// noisy CCs reads high, and on weak crystals would weigh the intensities down to nothing.
std::vector<double> z_chosen, z_other;
for (int c = 0; c < N; ++c) {
if (!std::isfinite(cc[c * K + best_choice[c]]))
continue;
double sum = 0, n = 0;
for (int g = 0; g < K; ++g)
if (g != best_choice[c] && std::isfinite(cc[c * K + g])) {
sum += std::atanh(cc[c * K + g]);
n += 1;
}
if (n > 0) {
z_chosen.push_back(std::atanh(cc[c * K + best_choice[c]]));
z_other.push_back(sum / n);
}
}
out.model.intensity_weight = std::max(0.0, Median(z_chosen) - Median(z_other));
// Crystal by crystal, as the sweep above, so that every decision is made against the others as they
// now stand: taken out of the sums, its CC with the mean of the others in each indexing, and back in.
int changed = 0;
out.cell_moved = 0;
for (int c = 0; c < N; ++c) {
for (size_t i = begin[c]; i < begin[c + 1]; ++i) {
M[key[best_choice[c]][i]] -= z[i];
C[key[best_choice[c]][i]] -= 1.0;
}
// An indexing with no reflection in common with the others cannot be told and never wins; where
// there is none, the crystal stays.
std::vector<double> intensity(K, -INFINITY), both(K, -INFINITY);
for (int g = 0; g < K; ++g) {
double sx = 0, sy = 0, sxx = 0, syy = 0, sxy = 0, n = 0;
for (size_t i = begin[c]; i < begin[c + 1]; ++i) {
const int32_t k = key[g][i];
if (C[k] <= 0)
continue;
const double xv = z[i], yv = M[k] / C[k];
sx += xv; sy += yv; sxx += xv * xv; syy += yv * yv; sxy += xv * yv; n += 1;
}
const double vx = sxx - sx * sx / n, vy = syy - sy * sy / n;
if (n > 3 && vx > 0 && vy > 0) {
const double r = (sxy - sx * sy / n) / std::sqrt(vx * vy);
intensity[g] = IntensityLogLikelihood(r, n, out.model.intensity_weight);
both[g] = intensity[g] + metric[c][g];
}
}
const size_t b = ArgMax(both);
if (std::isfinite(both[b])) {
changed += static_cast<int>(b) != best_choice[c];
out.cell_moved += b != ArgMax(intensity);
best_choice[c] = static_cast<int>(b);
}
for (size_t i = begin[c]; i < begin[c + 1]; ++i) {
M[key[best_choice[c]][i]] += z[i];
C[key[best_choice[c]][i]] += 1.0;
}
}
if (changed <= N / 1000)
break;
}
correlate();
// How clearly each crystal is decided by its intensities: its CC with the mean of all the other crystals,
// in the chosen indexing and in the best other one, and the difference of the two in sigma (Fisher's z;
// each CC on n reflections has an error of 1/sqrt(n - 3), and the two are nearly independent).
std::vector<double> sig, ccc, cco;
for (int c = 0; c < N; ++c) {
const int g0 = best_choice[c], other = other_of(c);
if (other < 0 || !std::isfinite(cc[c * K + g0]))
continue;
ccc.push_back(cc[c * K + g0]);
cco.push_back(cc[c * K + other]);
sig.push_back((std::atanh(cc[c * K + g0]) - std::atanh(cc[c * K + other]))
* std::sqrt((std::min(n_used[c * K + g0], n_used[c * K + other]) - 3.0) / 2.0));
}
out.median_sigma = Median(sig);
out.cc_chosen = Median(ccc);
out.cc_other = Median(cco);
if (!sig.empty())
out.decided_fraction = static_cast<double>(std::count_if(sig.begin(), sig.end(), [](double v) {
return v > DECIDED_SIGMA; })) / static_cast<double>(sig.size());
for (int c = 0; c < N; ++c) {
const int final_g = best_choice[c];
out.choice[crystal_outcome[c]] = final_g;
if (!by_reference[c].empty())
out.reference_overruled += final_g != static_cast<int>(ArgMax(by_reference[c]));
if (final_g == 0)
continue;
++out.reindexed;
auto &o = outcomes[crystal_outcome[c]];
ReindexImage(o.reflections, o.latt, indexings[final_g]);
}
return out;
}
int ReindexOnReference(IntegrationOutcome &outcome, const ReindexAmbiguityResolver &resolver,
const std::vector<gemmi::Op> &ops, const AmbiguityModel &model) {
if (ops.empty() || outcome.reflections.empty())
return 0;
const auto scored = resolver.Scores(outcome.reflections);
const std::vector<double> metric = model.metric.LogLikelihood(outcome.latt, ops);
// As indexed unless another indexing is favoured.
size_t best = 0;
double best_ll = -INFINITY;
for (size_t g = 0; g <= ops.size(); ++g) {
if (!std::isfinite(scored.cc[g])) // cannot be told, so never wins
continue;
const double ll = IntensityLogLikelihood(scored.cc[g], static_cast<double>(scored.n), model.intensity_weight)
+ metric[g];
if (ll > best_ll) {
best_ll = ll;
best = g;
}
}
if (best != 0)
ReindexImage(outcome.reflections, outcome.latt, ops[best - 1]);
return static_cast<int>(best);
}
size_t RelabelRunIndexing(std::vector<IntegrationOutcome> &outcomes, std::vector<int> &choice,
const DiffractionExperiment &x, const std::vector<gemmi::Op> &ops,
const CellMetric &metric) {
if (ops.empty())
return 0;
std::vector<gemmi::Op> indexings{gemmi::Op::identity()};
indexings.insert(indexings.end(), ops.begin(), ops.end());
// Each crystal's cell, read as indexed: the lattice is now in choice[o], so it goes back first.
std::vector<int> taking_part;
std::vector<std::vector<double>> ll;
for (size_t o = 0; o < outcomes.size(); ++o)
if (choice[o] >= 0 && !outcomes[o].reflections.empty()) {
taking_part.push_back(choice[o]);
ll.push_back(metric.LogLikelihood(ReindexLattice(outcomes[o].latt, indexings[choice[o]].inverse()), ops));
}
const std::vector<int> becomes = GlobalRelabel(indexings, taking_part, x.GetSpaceGroupOrP1(), ll);
size_t moved = 0;
for (size_t o = 0; o < outcomes.size(); ++o) {
if (choice[o] < 0 || becomes[choice[o]] == choice[o])
continue;
auto &out = outcomes[o];
ReindexImage(out.reflections, out.latt, indexings[choice[o]].inverse());
choice[o] = becomes[choice[o]];
ReindexImage(out.reflections, out.latt, indexings[choice[o]]);
++moved;
}
return moved;
}