Files
Jungfraujoch/image_analysis/scale_merge/ReindexAmbiguity.cpp
T
leonarski_f 511be0c366
Build Packages / build:rpm (rocky8) (push) Successful in 24m0s
Build Packages / Unit tests (push) Skipped
Build Packages / build:windows:nocuda (push) Successful in 16m54s
Build Packages / build:windows:cuda (push) Successful in 19m25s
Build Packages / build:viewer-tgz:cpu (push) Successful in 14m44s
Build Packages / build:viewer-tgz:cuda (push) Successful in 16m3s
Build Packages / build:rugnux-tgz (x86_64) (push) Successful in 13m15s
Build Packages / build:rugnux:windows (push) Successful in 10m45s
Build Packages / build:rugnux:aarch64 (cross) (push) Successful in 9m34s
Build Packages / build:rpm (rocky8_nocuda) (push) Successful in 19m7s
Build Packages / build:rpm (rocky9_nocuda) (push) Successful in 18m9s
Build Packages / build:rpm (ubuntu2204_nocuda) (push) Successful in 24m48s
Build Packages / build:rpm (ubuntu2404_nocuda) (push) Successful in 18m13s
Build Packages / build:rpm (rocky8_sls9) (push) Successful in 24m51s
Build Packages / build:rpm (rocky9_sls9) (push) Successful in 22m58s
Build Packages / build:rpm (rocky9) (push) Successful in 21m23s
Build Packages / Generate python client (push) Successful in 1m2s
Build Packages / Build documentation (push) Successful in 1m23s
Build Packages / Create release (push) Skipped
Build Packages / XDS test (durin plugin) (push) Successful in 9m45s
Build Packages / XDS test (neggia plugin) (push) Successful in 10m19s
Build Packages / XDS test (JFJoch plugin) (push) Successful in 11m10s
Build Packages / build:rpm (ubuntu2204) (push) Successful in 22m15s
Build Packages / build:rpm (ubuntu2404) (push) Successful in 17m37s
Build Packages / DIALS test (push) Successful in 17m16s
v1.0.0-rc.165 (#75)
* `rugnux --model` adopts the model's space group as a label where the data were merged in its enantiomorph, instead of reindexing the reflections - which swapped I(+) with I(-).
* `rugnux --model` warns, naming the atom, when the anomalous density at the model's atoms comes out inverted, which means the data and the model are in opposite hands.
* `rugnux --model` writes an anomalous difference map (`<prefix>_anom.ccp4`) when the merge kept the Bijvoet split, and names the ten model atoms it peaks highest on as `ANOMALOUS_SITE_01`..`_10`.
* `MEAN_ATOM_DENSITY_SIGMA` is read from the map by cubic rather than linear interpolation and comes out around a tenth higher; it is no longer comparable with the figure earlier versions printed.
* `rugnux --model` reads an mmCIF coordinate file as well as a PDB one, gzipped or not, taking the format from the file's content rather than its name.
* A model `rugnux --model` cannot use is reported as a `WARNING:` line in the results report instead of only in the log.
* The rugnux results report has a `10. MODEL VALIDATION` section when `--model` was given; `REPORT_VERSION` is 4, `WARNINGS` moves to section 11 and no existing key changed.
* The rugnux results report records how the run was invoked, what it cost and what it ran on: `COMMAND_LINE=`, `WALL_TIME=` and `GPU_COUNT=` / `GPU=`.
* rugnux says which GPUs it can see before it starts processing.
* `rugnux --export-unmerged` also writes `<prefix>_unmerged.mtz` on a `--no-merge` run, and is ignored on a run with no output prefix instead of writing a file called `_unmerged.mtz`.
* `/start` asks the writer whether the run can be written before the detector is armed, so a run whose master file already exists, or whose output directory cannot be created, is refused up front with the writer's own message. This needs the TCP image stream or the built-in HDF5 writer; the ZeroMQ stream is unchanged.
* A calibration that fails goes to `Error` carrying the reason instead of `Inactive`, so `/wait_till_done` and `/wait_until_running` report it; a cancelled calibration still goes to `Inactive`.
* `/wait_till_done` answers 500 with the message when a collection ended in an error. A cancelled collection and a collection that only triggered a warning still answer 200.
* A pending start failure is discarded by `/cancel` and `/deactivate`, as it already was by `/start` and `/initialize`.
* `/scan_result` no longer reports the previous run's images after a collection that failed to start, or after `/deactivate`.
* The TCP image stream protocol version is 4. `jfjoch_writer` and `jfjoch_broker` have to be of the same release, as before.

Reviewed-on: #75
2026-08-27 22:16:54 +02:00

218 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 "ReindexAmbiguity.h"
#include <cmath>
#include <unordered_map>
#include <utility>
#include "gemmi/twin.hpp"
#include "HKLKey.h"
namespace {
constexpr size_t MIN_REFLECTIONS = 20;
struct BestReindex {
gemmi::Op op = gemmi::Op::identity();
bool is_identity = true;
double score = 0.0;
double identity_score = 0.0;
};
// Among identity (the baseline, scored `identity_score`) and `ops`, return the operator with the
// highest `score_op(op)`. A non-finite score never wins (too little overlap to decide). Shared by the
// stills per-image resolver and the rotation post-merge ChooseReindex.
BestReindex PickBestReindex(double identity_score, const std::vector<gemmi::Op> &ops,
const std::function<double(const gemmi::Op &)> &score_op) {
BestReindex best;
best.identity_score = identity_score;
best.score = identity_score;
for (const auto &op : ops) {
const double sc = score_op(op);
if (std::isfinite(sc) && (!std::isfinite(best.score) || sc > best.score)) {
best.score = sc;
best.op = op;
best.is_identity = false;
}
}
return best;
}
}
std::vector<gemmi::Op> ReindexAmbiguityOperators(const UnitCell &cell, int space_group_number,
double max_obliquity_deg) {
const gemmi::SpaceGroup *sg = gemmi::find_spacegroup_by_number(space_group_number);
if (sg == nullptr)
return {};
return gemmi::find_twin_laws(static_cast<gemmi::UnitCell>(cell), sg, max_obliquity_deg,
/*all_ops=*/false);
}
std::vector<MergedReflection> ReindexReflections(const std::vector<MergedReflection> &merged,
const gemmi::Op &op) {
std::vector<MergedReflection> out = merged;
for (auto &r : out) {
const gemmi::Op::Miller h = op.apply_to_hkl({{static_cast<int>(r.h),
static_cast<int>(r.k),
static_cast<int>(r.l)}});
r.h = h[0];
r.k = h[1];
r.l = h[2];
}
return out;
}
std::vector<MergedReflection> ReindexMergedIntoAsu(const std::vector<MergedReflection> &merged,
const gemmi::Op &op, int space_group_number,
bool merge_friedel) {
const gemmi::SpaceGroup *sg = gemmi::find_spacegroup_by_number(space_group_number);
if (sg == nullptr)
return merged;
// merge_friedel=false so the generator reports which side of the Friedel pair the ASU index was
// reached from; that sign is what the two hands have to follow.
const HKLKeyGenerator key_gen(/*merge_friedel=*/false, *sg);
std::vector<MergedReflection> out = merged;
for (auto &r : out) {
const gemmi::Op::Miller h = op.apply_to_hkl({{r.h, r.k, r.l}});
const HKLKey key = key_gen(h[0], h[1], h[2]);
// The hands follow a CHANGE of hand, not the hand the new index happens to land on. An
// anomalous merge stores the minus mate at -hkl_asu (Merge.cpp), so a row can already be on
// the minus side before the operator is applied, while I_plus/I_minus are attached in the
// plus convention on both mates alike (RotationScaleMerge.cpp keys the lookup at plus=true).
// Since the operator is rotation-type, op(-x) == -op(x), and the minus mate's key.plus is
// therefore the negation of the plus mate's - testing key.plus alone swaps exactly the rows
// that must not move, and leaves the ones that must. With merge_friedel every row is stored
// at the ASU representative, so was_plus is always true and this reduces to the old test.
const bool was_plus = key_gen(r.h, r.k, r.l).plus;
if (was_plus != key.plus) {
std::swap(r.I_plus, r.I_minus);
std::swap(r.sigma_plus, r.sigma_minus);
std::swap(r.F_plus, r.F_minus);
std::swap(r.sigmaF_plus, r.sigmaF_minus);
}
const bool at_asu_index = merge_friedel || key.plus;
r.h = at_asu_index ? key.h : -key.h;
r.k = at_asu_index ? key.k : -key.k;
r.l = at_asu_index ? key.l : -key.l;
}
return out;
}
ReindexChoice ChooseReindex(const std::vector<MergedReflection> &merged,
const UnitCell &cell, int space_group_number,
const std::function<double(const std::vector<MergedReflection> &)> &score,
double max_obliquity_deg) {
const auto ops = ReindexAmbiguityOperators(cell, space_group_number, max_obliquity_deg);
const BestReindex best = PickBestReindex(
score(merged), ops,
[&](const gemmi::Op &op) { return score(ReindexReflections(merged, op)); });
ReindexChoice choice;
choice.op = best.op;
choice.is_identity = best.is_identity;
choice.score = best.score;
choice.identity_score = best.identity_score;
choice.n_candidates = 1 + static_cast<int>(ops.size());
return choice;
}
double ReferenceIntensityCC(const std::vector<MergedReflection> &merged,
const std::vector<MergedReflection> &reference,
int space_group_number) {
const gemmi::SpaceGroup *sg = gemmi::find_spacegroup_by_number(space_group_number);
if (sg == nullptr)
return 0.0;
const HKLKeyGenerator key(/*merge_friedel=*/true, *sg);
std::unordered_map<uint64_t, double> ref;
ref.reserve(reference.size());
for (const auto &r : reference)
if (std::isfinite(r.I))
ref[key(r).pack()] = r.I;
double sx = 0, sy = 0, sxx = 0, syy = 0, sxy = 0;
int n = 0;
for (const auto &m : merged) {
if (!std::isfinite(m.I))
continue;
const auto it = ref.find(key(m).pack());
if (it == ref.end())
continue;
const double x = m.I, y = it->second;
sx += x; sy += y; sxx += x * x; syy += y * y; sxy += x * y;
++n;
}
if (n < 10)
return 0.0;
const double cov = n * sxy - sx * sy;
const double vx = n * sxx - sx * sx;
const double vy = n * syy - sy * sy;
return (vx > 0 && vy > 0) ? cov / std::sqrt(vx * vy) : 0.0;
}
ReindexAmbiguityResolver::ReindexAmbiguityResolver(const DiffractionExperiment &x,
const std::vector<MergedReflection> &reference)
: s(x.GetScalingSettings()),
hkl_key_generator(s.GetMergeFriedel(), x.GetSpaceGroupNumber().value_or(1)) {
for (const auto &r : reference)
reference_data[hkl_key_generator(r)] = r.I;
if (x.GetUnitCell().has_value() && x.GetSpaceGroupNumber().has_value())
ops = ReindexAmbiguityOperators(*x.GetUnitCell(), static_cast<int>(*x.GetSpaceGroupNumber()));
}
bool ReindexAmbiguityResolver::Accept(const Reflection &r) const {
if (r.on_ice_ring) // ice-contaminated intensity would bias the correlation; keep it out
return false;
return AcceptReflection(r, s.GetHighResolutionLimit_A(), s.GetLowResolutionLimit_A());
}
double ReindexAmbiguityResolver::ReferenceCC(const std::vector<Reflection> &reflections,
const gemmi::Op &op) const {
double sx = 0, sy = 0, sxx = 0, syy = 0, sxy = 0;
size_t n = 0;
for (const auto &r : reflections) {
if (!Accept(r) || r.partiality < s.GetMinPartiality())
continue;
if (!std::isfinite(r.I) || !std::isfinite(r.sigma) || r.sigma <= 0.0f || r.partiality <= 0.0f)
continue;
const gemmi::Op::Miller h = op.apply_to_hkl({{r.h, r.k, r.l}});
const auto it = reference_data.find(hkl_key_generator(h[0], h[1], h[2]));
if (it == reference_data.end())
continue;
const double x = static_cast<double>(r.I) * r.rlp / r.partiality;
const double y = it->second;
if (!std::isfinite(x) || !std::isfinite(y))
continue;
sx += x; sy += y; sxx += x * x; syy += y * y; sxy += x * y;
++n;
}
if (n < MIN_REFLECTIONS)
return NAN;
const double nd = static_cast<double>(n);
const double cov = sxy - sx * sy / nd;
const double vx = sxx - sx * sx / nd;
const double vy = syy - sy * sy / nd;
return (vx > 0 && vy > 0) ? cov / std::sqrt(vx * vy) : NAN;
}
// Serial stills index each crystal in one of the merohedrally-equivalent hands at random; pick, for this
// image alone, the reindexing whose intensities correlate best with the external reference and apply it.
void ReindexAmbiguityResolver::Resolve(std::vector<Reflection> &reflections) const {
if (ops.empty())
return;
const BestReindex best = PickBestReindex(
ReferenceCC(reflections, gemmi::Op::identity()), ops,
[&](const gemmi::Op &op) { return ReferenceCC(reflections, op); });
if (best.is_identity)
return;
for (auto &r : reflections) {
const gemmi::Op::Miller h = best.op.apply_to_hkl({{r.h, r.k, r.l}});
r.h = h[0]; r.k = h[1]; r.l = h[2];
}
}