Files
leonarski_fandClaude Opus 5.5 5172955cb4 Stills merge: a reflection's resolution is the reference cell's, not the image's
Stills each carry their own cell (and an XFEL pulse its own wavelength), merged while it is within the
indexing tolerance of the reference cell (5 % by default). The merge cut each observation at the
high-resolution limit by the d of the image that measured it, and gave the merged reflection the d of its
first observation, while the completeness counted the possible reflections in the reference cell. A
reflection just past the limit was then merged from whichever image's cell put it inside, and the
outermost shell counted more reflections than it could hold: measured, 204 % and 147 % in the last shell
of a four-run --mode scale merge at multiplicities in the thousands, with a CC1/2 in those shells that
meant nothing. The inner shells read 99-101 % from the same shuffling across shell boundaries.

The merge now takes a reflection's d in the reference cell, where there is one, for the resolution cut, the
d it reports and the shell it is counted in - the cell the possible reflections are counted in - so a
reflection has one d whichever image measured it and no shell can exceed complete. Without a reference
cell nothing changes. New test: images on cells 2 % either side of the reference, every reflection to past
the limit; it fails before (reflections past the limit, shells over 100 %) and passes now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HVeDQrPqZ52Tp6rzzZGxf3
2026-11-23 19:35:29 +01:00

1174 lines
52 KiB
C++

// SPDX-FileCopyrightText: 2025 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
// SPDX-License-Identifier: GPL-3.0-only
#include "Merge.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include <map>
#include <span>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <spdlog/fmt/fmt.h>
#include <gemmi/reciproc.hpp>
#include "../../common/CorrelationCoefficient.h"
#include "../../common/ResolutionShells.h"
#include "../../common/Definitions.h"
#include "../../common/ParallelFor.h"
#include "HKLKey.h"
#include "RfreeFlags.h"
#include "FrenchWilson.h"
#include "OutlierBand.h"
#include "ErrorModel.h"
namespace {
// Which half-set an observation prefers: a splitmix64 bit-mix of the image's stable index, so the
// preference is a function of image identity rather than a draw from a shared RNG. The preference
// is overridden where it would unbalance a reflection's two halves (see AddImage), which makes the
// half a reflection's observations end up in depend on the order AddImage sees them in - image
// order, every caller being a serial loop over the images.
int HalfForImage(int64_t image_id) {
uint64_t z = static_cast<uint64_t>(image_id) + 0x9e3779b97f4a7c15ULL;
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL;
z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL;
z = z ^ (z >> 31);
return static_cast<int>(z & 1ULL);
}
// Calls reduce(i, out) for the images in parallel, a block of them at a time, and then consume(i, out)
// for each image of the block in image order - the order that every floating-point sum, every
// half-set choice and every hash-map insertion of the merge depends on. The result is therefore the
// serial loop's, bit for bit, at any thread count.
template <typename T, typename Reduce, typename Consume>
void ReduceImagesInOrder(size_t n_images, size_t nthreads, Reduce reduce, Consume consume) {
constexpr size_t BLOCK_IMAGES = 4096;
std::vector<std::vector<T>> out(std::min(BLOCK_IMAGES, n_images));
for (size_t first = 0; first < n_images; first += BLOCK_IMAGES) {
const int n = static_cast<int>(std::min(BLOCK_IMAGES, n_images - first));
ParallelChunks(n, nthreads, [&](int lo, int hi) {
for (int j = lo; j < hi; ++j) {
out[j].clear();
reduce(first + j, out[j]);
}
});
for (int j = 0; j < n; ++j)
consume(first + j, out[j]);
}
}
}
MergeOnTheFly::MergeOnTheFly(const DiffractionExperiment &x)
: space_group(x.GetSpaceGroupOrP1()),
scaling_settings(x.GetScalingSettings()),
indexing_settings(x.GetIndexingSettings()),
high_resolution_limit(scaling_settings.GetHighResolutionLimit_A()),
// A min-image-CC of 0 (the default) means "no limit": leave the optional
// empty so the per-image CC cut is inactive. Otherwise a 0.0 threshold
// would silently drop every image with a non-positive per-image CC.
image_cc_limit(scaling_settings.GetMinCCForImage() > 0.0
? std::optional<double>(scaling_settings.GetMinCCForImage())
: std::nullopt),
min_partiality(scaling_settings.GetMinPartiality()),
existence_min_partiality(std::min(min_partiality, EXISTENCE_MIN_PARTIALITY)),
capture_coeff(scaling_settings.GetCaptureUncertaintyCoeff()),
generator(scaling_settings.GetMergeFriedel(), space_group),
reject_outliers(scaling_settings.GetOutlierRejectNsigma() > 0.0),
reject_nsigma(scaling_settings.GetOutlierRejectNsigma()) {
}
MergeOnTheFly &MergeOnTheFly::ReferenceCell(const std::optional<UnitCell> &cell) {
reference_cell = cell;
reference_reciprocal.reset();
if (cell) {
const CrystalLattice lattice(*cell);
reference_reciprocal = {lattice.Astar(), lattice.Bstar(), lattice.Cstar()};
}
return *this;
}
float MergeOnTheFly::Resolution(const Reflection &r) const {
if (!reference_reciprocal)
return r.d;
const auto &[astar, bstar, cstar] = *reference_reciprocal;
const float q = (static_cast<float>(r.h) * astar + static_cast<float>(r.k) * bstar
+ static_cast<float>(r.l) * cstar).Length();
return q > 0.0f ? 1.0f / q : NAN;
}
bool MergeOnTheFly::Accept(const Reflection &r, std::optional<double> d_min_limit,
std::optional<double> d_max_limit) const {
if (!AcceptReflection(r, std::nullopt, std::nullopt))
return false;
const float d = Resolution(r);
return std::isfinite(d) && !(d_min_limit && d < *d_min_limit) && !(d_max_limit && d > *d_max_limit);
}
size_t MergeOnTheFly::Contributions(const IntegrationOutcome &outcome, std::vector<Contribution> &out) const {
size_t rejected = 0;
for (const auto &r: outcome.reflections) {
if (generator.IsSystematicallyAbsent(r))
continue;
if (r.image_scale_corr <= 0.0 || !std::isfinite(r.image_scale_corr))
continue;
if (!Accept(r, high_resolution_limit, std::nullopt))
continue;
if (exclude_ice_rings && r.on_ice_ring)
continue;
if (BelowMergeFloor(r.partiality))
continue;
auto hkl = generator(r);
auto hkl_key = hkl.pack();
const auto [I_corr, w] = Weigh(r, hkl_key);
if (w == 0.0)
continue;
// Robust outlier rejection: drop this observation if it sits outside the band about the
// reflection's median that the error model allows (OutlierBand.h). Needs the active error model
// so sigma_corr reflects the real scatter (else the threshold is the bare counting sigma and
// would cull good partials).
if (reject_outliers && error_model_active) {
const auto mit = reject_median_I.find(hkl_key);
if (mit != reject_median_I.end()) {
const double I_b = error_model_mean_I.at(hkl_key);
if (OutsideOutlierBand(I_corr, mit->second, reject_nsigma, 1.0 / w, I_b,
error_model_b * I_b, reject_up, reject_down)) {
++rejected;
continue;
}
}
}
out.push_back(Contribution{
.key = hkl_key,
.h = hkl.plus ? hkl.h : -hkl.h,
.k = hkl.plus ? hkl.k : -hkl.k,
.l = hkl.plus ? hkl.l : -hkl.l,
.w = w,
.wI = w * I_corr,
.d = Resolution(r),
.on_ice_ring = r.on_ice_ring,
.exists = r.partiality >= existence_min_partiality,
.far_tail = r.partiality < FAR_TAIL_PARTIALITY
});
}
return rejected;
}
// The tests of Contributions and Mask, each on its own rather than up to the first that fails.
std::vector<std::vector<ObservationVerdict>> MergeOnTheFly::Verdicts(const std::vector<IntegrationOutcome> &outcomes) const {
std::vector<std::vector<ObservationVerdict>> out(outcomes.size());
for (size_t i = 0; i < outcomes.size(); ++i) {
const uint32_t image_flags = Mask(outcomes[i]) ? OBS_IMAGE_MASKED : 0;
for (const auto &r: outcomes[i].reflections) {
ObservationVerdict v{.flags = image_flags};
if (generator.IsSystematicallyAbsent(r))
v.flags |= OBS_ABSENT;
const bool scaled = r.image_scale_corr > 0.0 && std::isfinite(r.image_scale_corr);
if (!scaled)
v.flags |= OBS_NO_SCALE;
if (!Accept(r, high_resolution_limit, std::nullopt))
v.flags |= OBS_RESOLUTION;
if (exclude_ice_rings && r.on_ice_ring)
v.flags |= OBS_ICE_EXCLUDED;
if (BelowMergeFloor(r.partiality))
v.flags |= OBS_LOW_PARTIALITY;
const uint64_t hkl_key = generator(r).pack();
const auto [I_corr, w] = scaled ? Weigh(r, hkl_key) : Weighted{};
if (w == 0.0) {
if (scaled)
v.flags |= OBS_BAD_VALUE;
out[i].push_back(v);
continue;
}
v.sigma = static_cast<float>(std::sqrt(1.0 / w));
if (reject_outliers && error_model_active) {
const auto mit = reject_median_I.find(hkl_key);
const auto bit = error_model_mean_I.find(hkl_key);
if (mit != reject_median_I.end() && bit != error_model_mean_I.end()
&& OutsideOutlierBand(I_corr, mit->second, reject_nsigma, 1.0 / w,
bit->second, error_model_b * bit->second, reject_up, reject_down))
v.flags |= OBS_OUTLIER;
}
out[i].push_back(v);
}
}
return out;
}
void MergeOnTheFly::Accumulate(const std::vector<Contribution> &contributions, int64_t image_id) {
const int prefer = HalfForImage(image_id);
for (const auto &c: contributions) {
auto it = accumulator.find(c.key);
if (it == accumulator.end())
it = accumulator.emplace(c.key, MergeAccum{.h = c.h, .k = c.k, .l = c.l}).first;
it->second.sum_wI += c.wI;
it->second.sum_w += c.w;
// CC1/2 correlates the two half-set means, so a reflection whose observations all land in one
// half has no second mean and drops out of the statistic entirely. Taking the image's own
// preference only while it keeps the two counts within one of each other splits every
// reflection floor(n/2) against ceil(n/2), which is the split cctbx and XDS use.
const int half = it->second.n_half[prefer] > it->second.n_half[1 - prefer]
? 1 - prefer : prefer;
it->second.sum_wI_half[half] += c.wI;
it->second.sum_w_half[half] += c.w;
it->second.n_half[half]++;
it->second.sum_wI_split[prefer] += c.wI;
it->second.sum_w_split[prefer] += c.w;
if (c.exists) {
it->second.exists = true;
it->second.exists_half[half] = true;
it->second.exists_split[prefer] = true;
}
if (c.far_tail)
++far_tail_count;
if (c.on_ice_ring)
it->second.on_ice_ring = true;
if (!std::isfinite(it->second.d) && std::isfinite(c.d) && c.d > 0.0f)
it->second.d = c.d;
}
}
void MergeOnTheFly::AddImage(const IntegrationOutcome &outcome, int64_t image_id) {
std::unique_lock ul(merged_mutex);
if (Mask(outcome))
return;
std::vector<Contribution> contributions;
reject_count += Contributions(outcome, contributions);
Accumulate(contributions, image_id);
}
void MergeOnTheFly::AddImages(const std::vector<IntegrationOutcome> &outcomes) {
std::unique_lock ul(merged_mutex);
std::vector<size_t> rejected(outcomes.size(), 0);
images_merged.assign(outcomes.size(), 0);
ReduceImagesInOrder<Contribution>(
outcomes.size(), nthreads,
[&](size_t i, std::vector<Contribution> &out) {
if (!Mask(outcomes[i]))
rejected[i] = Contributions(outcomes[i], out);
},
[&](size_t i, const std::vector<Contribution> &out) {
reject_count += rejected[i];
images_merged[i] = !out.empty();
Accumulate(out, static_cast<int64_t>(i));
});
}
double MergeOnTheFly::CountingVariance(double sigma_corr, float image_scale_corr, float var_bkg, float partiality,
double I_mean) const {
// A weak observation's sigma^2 = a background/read part plus a Poisson signal part proportional to its
// OWN intensity; weighting the merge by 1/sigma^2 with that per-observation sigma biases the
// inverse-variance mean low at <1 photon (an up-fluctuated observation gets a larger sigma and is
// over-downweighted, so the weighted mean drifts below <I>). Rebuild the signal part at the reflection's
// EXPECTED intensity <I> instead - the background part plus corr*<I> - so the weight no longer
// correlates with the observation's own fluctuation. This mirrors the rotation combine in
// RotationScaleMerge::process_rawrun. A negative mean has no Poisson signal, hence max(0, <I>).
double v = sigma_corr * sigma_corr;
if (scaling_settings.GetExpectedVarianceMerge()) {
const double base = static_cast<double>(image_scale_corr) * image_scale_corr * var_bkg
+ static_cast<double>(image_scale_corr) * std::max(0.0, I_mean);
if (base > 0.0)
v = base;
}
const double capture = capture_coeff * (1.0 - std::min(1.0f, partiality)) * std::max(0.0, I_mean);
return v + capture * capture;
}
double MergeOnTheFly::PartialityTerm(float partiality) {
const double q = (1.0 - std::min(1.0f, partiality)) / partiality;
return q * q;
}
double MergeOnTheFly::CorrectedVariance(double I_corr, double sigma_corr, float image_scale_corr,
float var_bkg, float partiality,
uint64_t hkl_key) const {
if (!error_model_active)
return sigma_corr * sigma_corr;
// The systematic terms use the reflection's mean (constant over its observations), falling back to
// this observation only if the mean is unknown: using the per-observation I_i instead would
// over-weight down-fluctuated points.
const auto it = error_model_mean_I.find(hkl_key);
const double I_mean = (it != error_model_mean_I.end()) ? it->second : I_corr;
const double v = error_model_a * CountingVariance(sigma_corr, image_scale_corr, var_bkg, partiality, I_mean)
+ (error_model_b * error_model_b + error_model_c2 * PartialityTerm(partiality)) * I_mean * I_mean;
return (v > 0.0) ? v : sigma_corr * sigma_corr;
}
MergeOnTheFly::Weighted MergeOnTheFly::Weigh(const Reflection &r, uint64_t hkl_key) const {
const double I_corr = static_cast<double>(r.I) * r.image_scale_corr;
const double sigma_corr = static_cast<double>(r.sigma) * r.image_scale_corr;
if (!std::isfinite(I_corr) || !std::isfinite(sigma_corr) || sigma_corr <= 0.0)
return {};
const double w = 1.0 / CorrectedVariance(I_corr, sigma_corr, r.image_scale_corr, r.var_bkg, r.partiality, hkl_key);
if (!std::isfinite(w) || !(w > 0.0))
return {};
return {I_corr, w};
}
void MergeOnTheFly::RefineErrorModel(const std::vector<IntegrationOutcome> &outcomes) {
// Reset to identity up front: every early return below then leaves the model inactive (CorrectedVariance
// returns sigma unchanged) rather than keeping a stale model from a previous call.
error_model_active = false;
error_model_a = 1.0;
error_model_b = 0.0;
error_model_c2 = 0.0;
error_model_chi2 = 0.0;
error_model_b_resolved = true;
error_model_mean_I.clear();
reject_median_I.clear();
reject_up = 0.0;
reject_down = 0.0;
reject_count = 0;
// --- 1. Collect accepted, scaled observations grouped by symmetry-equivalent hkl, applying the filters
// AddImage uses, down to the existence partiality.
struct Obs { float I, sigma, corr, var_bkg, p; };
struct KeyedObs { uint64_t key; Obs obs; };
std::vector<KeyedObs> all; // in image order
ReduceImagesInOrder<KeyedObs>(
outcomes.size(), nthreads,
[&](size_t i, std::vector<KeyedObs> &out) {
if (Mask(outcomes[i]))
return;
for (const auto &r: outcomes[i].reflections) {
if (generator.IsSystematicallyAbsent(r))
continue;
if (r.image_scale_corr <= 0.0 || !std::isfinite(r.image_scale_corr))
continue;
if (!Accept(r, high_resolution_limit, std::nullopt))
continue;
if (exclude_ice_rings && r.on_ice_ring)
continue;
if (r.partiality < existence_min_partiality)
continue;
const float I_corr = r.I * r.image_scale_corr;
const float sigma_corr = r.sigma * r.image_scale_corr;
if (!std::isfinite(I_corr) || !std::isfinite(sigma_corr) || sigma_corr <= 0.0f)
continue;
out.push_back({generator(r).pack(), {I_corr, sigma_corr, r.image_scale_corr, r.var_bkg, r.partiality}});
}
},
[&](size_t, const std::vector<KeyedObs> &out) {
all.insert(all.end(), out.begin(), out.end());
});
// The observations of each reflection side by side, in key order and within a reflection in image
// order - a sort on (key, place), a total order, so the same on any number of workers. Every sum
// below runs over them in that fixed order.
struct KeyPlace { uint64_t key; size_t place; };
std::vector<KeyPlace> order(all.size());
const size_t obs_threads = ThreadsForWork(all.size(), nthreads);
ParallelChunks(static_cast<int>(all.size()), obs_threads, [&](int lo, int hi) {
for (int i = lo; i < hi; ++i)
order[i] = {all[i].key, static_cast<size_t>(i)};
});
ParallelSort(order.begin(), order.end(), nthreads, [](const KeyPlace &x, const KeyPlace &y) {
return x.key < y.key || (x.key == y.key && x.place < y.place);
});
std::vector<Obs> flat(all.size());
ParallelChunks(static_cast<int>(all.size()), obs_threads, [&](int lo, int hi) {
for (int i = lo; i < hi; ++i)
flat[i] = all[order[i].place].obs;
});
all = {};
std::vector<uint64_t> keys;
std::vector<size_t> start; // reflection k is flat[start[k] .. start[k + 1])
for (size_t i = 0; i < order.size(); ++i)
if (i == 0 || order[i].key != order[i - 1].key) {
keys.push_back(order[i].key);
start.push_back(i);
}
start.push_back(order.size());
order = {};
const auto group = [&](int k) { return std::span<const Obs>(flat.data() + start[k], start[k + 1] - start[k]); };
const int n_keys = static_cast<int>(keys.size());
const size_t key_threads = ThreadsForWork(keys.size(), nthreads, 1024);
// --- 2. The starting mean of each reflection (counting-sigma weights) and, where there are three
// observations for it to stand on, the median - the robust centre of the outlier test.
std::vector<double> mean(n_keys);
std::vector<float> median(n_keys, NAN);
ParallelChunks(n_keys, key_threads, [&](int lo, int hi) {
for (int k = lo; k < hi; ++k) {
const auto obs = group(k);
double sum_w = 0.0, sum_wI = 0.0;
for (const auto &o: obs) {
const double w = 1.0 / (static_cast<double>(o.sigma) * o.sigma);
sum_w += w;
sum_wI += w * o.I;
}
mean[k] = sum_wI / sum_w;
if (reject_outliers && obs.size() >= 3) {
std::vector<float> iv;
iv.reserve(obs.size());
for (const auto &o: obs)
iv.push_back(o.I);
std::nth_element(iv.begin(), iv.begin() + iv.size() / 2, iv.end());
median[k] = iv[iv.size() / 2];
}
}
});
for (int k = 0; k < n_keys; ++k)
if (!std::isnan(median[k]))
reject_median_I[keys[k]] = median[k];
// --- 3. Fit the model (ErrorModel.h, FitStillsErrorModel) on the scatter about the reflection means,
// the counting variance rebuilt at the mean, and refit with the means the fitted model weights:
// the means and the model each depend on the other, and a single pass leaves the weights of
// the strong reflections at the counting-sigma means the fit started from. Measured on serial
// and rotation-as-serial sets, a few rounds raise the anomalous signal of the merge; they have
// settled after four, most often already after two or three: a round that leaves the model where
// the previous one put it (to 1e-3) would only reproduce the same means, and ends the iteration.
// Those rounds only carry the means to where the model settles, so they fit every stride-th
// observation (some four million of them); one last round fits them all and makes the final means.
// Each observation's sample goes to its own slot, so the pool is in key order whatever the number
// of workers; the slots left empty (single observations, the leverage cut) are dropped after.
constexpr int ROUNDS = 4;
const size_t stride = std::max<size_t>(1, flat.size() >> 22);
bool last_round = false;
std::vector<StillsErrorModelSample> samples;
StillsErrorModelFit fit;
double a = 1.0, b2 = 0.0, c2 = 0.0;
if (error_model_start) {
a = (*error_model_start)[0]; b2 = (*error_model_start)[1]; c2 = (*error_model_start)[2];
fit.a = a; fit.b2 = b2; fit.c2 = c2;
}
auto variance = [&](const Obs &o, double m) {
return a * CountingVariance(o.sigma, o.corr, o.var_bkg, o.p, m) + (b2 + c2 * PartialityTerm(o.p)) * m * m;
};
for (int round = 0; ; ++round) {
const size_t step = last_round ? 1 : stride;
samples.assign((flat.size() + step - 1) / step, StillsErrorModelSample{NAN, NAN, NAN, NAN});
ParallelChunks(n_keys, key_threads, [&](int lo, int hi) {
std::vector<double> var;
for (int k = lo; k < hi; ++k) {
const auto obs = group(k);
if (obs.size() < 2)
continue;
const double m = mean[k];
// The residual from the weighted mean has E[(I_i - <I>)^2] = var_i (1 - h_i), h_i = w_i / sum_w
// its leverage, with the weights of the model that made the mean.
var.resize(obs.size());
double sum_w = 0.0;
for (size_t j = 0; j < obs.size(); ++j) {
var[j] = variance(obs[j], m);
sum_w += 1.0 / var[j];
}
for (size_t j = 0; j < obs.size(); ++j) {
if ((start[k] + j) % step != 0)
continue;
const auto &o = obs[j];
const double factor = 1.0 - 1.0 / (var[j] * sum_w);
if (factor < 0.05)
continue;
const double resid = static_cast<double>(o.I) - m;
samples[(start[k] + j) / step] = {CountingVariance(o.sigma, o.corr, o.var_bkg, o.p, m), m * m,
PartialityTerm(o.p) * m * m, resid * resid / factor};
}
}
});
samples.erase(std::remove_if(samples.begin(), samples.end(),
[](const StillsErrorModelSample &x) { return std::isnan(x.dev2); }),
samples.end());
const StillsErrorModelFit last = fit;
fit = FitStillsErrorModel(samples, nthreads, last); // each round starts from the last one's model
if (!fit.active)
return; // too little multiplicity to fit -> leave identity
a = fit.a; b2 = fit.b2; c2 = fit.c2;
const auto close = [](double x, double y) { return std::fabs(x - y) <= 1e-3 * std::fabs(y); };
const bool settled = round > 0 && close(a, last.a) && close(b2, last.b2) && close(c2, last.c2);
// The new means leave out what the merge's outlier test will leave out (the band of OutlierBand.h
// about the median, as Contributions draws it): the systematic terms of every variance scale with the
// mean, so a mean that took in the outliers - observations of the innermost reflections that carry a
// beam-stop flare the frame's scale does not, read at 10-30x the median on weak frames - widens the
// band by as much as it is off, keeps the outliers it should drop, and weights them like the rest.
const double band = reject_nsigma * std::sqrt(b2);
ParallelChunks(n_keys, key_threads, [&](int lo, int hi) {
for (int k = lo; k < hi; ++k) {
double sum_w = 0.0, sum_wI = 0.0;
for (const auto &o: group(k)) {
const double v = variance(o, mean[k]);
if (reject_outliers && !std::isnan(median[k])
&& OutsideOutlierBand(o.I, median[k], reject_nsigma, v, mean[k], std::sqrt(b2) * mean[k],
band, band))
continue;
const double w = 1.0 / v;
sum_w += w;
sum_wI += w * o.I;
}
mean[k] = sum_wI / sum_w;
}
});
if (last_round || ((settled || round + 1 == ROUNDS) && step == 1))
break;
// From an earlier merge's model, one round on the sample carries the means to it.
last_round = settled || round + 1 == ROUNDS || error_model_start.has_value();
}
for (int k = 0; k < n_keys; ++k)
error_model_mean_I[keys[k]] = static_cast<float>(mean[k]);
error_model_a = a;
error_model_b = std::sqrt(b2);
error_model_c2 = c2;
error_model_b_resolved = fit.b_resolved;
error_model_active = true;
// A still's observations of one reflection spread by their partiality and per-crystal scale, not by a
// multiplicative factor about the median: many read near zero, so a band drawn from the spread of
// ln(I / median) would let through even a powder grain or a neighbour's spot at hundreds of sigma.
// The band is the plain one of n sigma about the median.
reject_up = reject_nsigma * error_model_b;
reject_down = reject_nsigma * error_model_b;
// Achieved goodness of fit: the median of dev2 / var over the samples, which is chi^2(1)-distributed
// (median 0.4549) when the sigmas are right; normalised so that honest sigmas report 1.0.
std::vector<double> chi2;
chi2.reserve(samples.size());
for (const auto &x: samples)
chi2.push_back(x.dev2 / (a * x.s2 + b2 * x.I2 + c2 * x.P2));
if (!chi2.empty()) {
std::nth_element(chi2.begin(), chi2.begin() + chi2.size() / 2, chi2.end());
error_model_chi2 = chi2[chi2.size() / 2] / ERROR_MODEL_CHI2_1_MEDIAN;
}
}
bool MergeOnTheFly::Mask(const IntegrationOutcome &outcome) const {
if (reference_cell) {
auto cell = outcome.latt.GetUnitCell();
if (!cell.is_close(*reference_cell,
indexing_settings.GetUnitCellDistTolerance(),
indexing_settings.GetUnitCellAngleTolerance_deg()))
return true;
}
if (filter_by_image_cc && image_cc_limit) {
if (!outcome.image_scale_cc
|| std::isnan(outcome.image_scale_cc.value())
|| outcome.image_scale_cc.value() < image_cc_limit.value())
return true;
}
return false;
}
std::vector<MergedReflection> MergeOnTheFly::ExportIntensities() {
std::unique_lock ul(merged_mutex);
std::vector<MergedReflection> out;
std::vector<std::pair<uint64_t, const MergeAccum *>> by_key;
by_key.reserve(accumulator.size());
for (const auto &[key, accum]: accumulator)
by_key.emplace_back(key, &accum);
std::sort(by_key.begin(), by_key.end(),
[](const auto &a, const auto &b) { return a.first < b.first; });
out.reserve(accumulator.size());
for (const auto &[key, accum_ptr]: by_key) {
const MergeAccum &accum = *accum_ptr;
if (accum.sum_w <= 0.0 || !accum.exists)
continue;
MergedReflection mr{
.h = accum.h,
.k = accum.k,
.l = accum.l,
.I = static_cast<float>(accum.sum_wI / accum.sum_w),
.sigma = static_cast<float>(1.0 / std::sqrt(accum.sum_w)),
.I_half = {NAN, NAN},
.sigma_half = {NAN, NAN},
.d = accum.d,
.on_ice_ring = accum.on_ice_ring,
.n_obs = static_cast<int32_t>(accum.n_half[0] + accum.n_half[1])
};
if (accum.exists_half[0] && accum.exists_half[1]) {
for (int i = 0; i < 2; ++i) {
mr.I_half[i] = static_cast<float>(accum.sum_wI_half[i] / accum.sum_w_half[i]);
mr.sigma_half[i] = static_cast<float>(1.0 / std::sqrt(accum.sum_w_half[i]));
}
}
for (int i = 0; i < 2; ++i)
if (accum.exists_split[i])
mr.I_split[i] = static_cast<float>(accum.sum_wI_split[i] / accum.sum_w_split[i]);
if (!std::isfinite(accum.d) || accum.d <= 0.0f)
continue;
out.emplace_back(mr);
}
return out;
}
std::vector<MergedReflection> MergeOnTheFly::ExportReflections() {
auto out = ExportIntensities();
AssignRfreeFlags(out, space_group, scaling_settings.GetRfreeFraction(), 500, reference_cell, nthreads);
FrenchWilsonOptions fw_opts;
fw_opts.num_threads = static_cast<int>(nthreads); // the same amplitudes at any worker count
ApplyFrenchWilson(out, space_group, fw_opts);
return out;
}
std::vector<MergedReflection> MergeAll(const DiffractionExperiment &x,
const std::vector<IntegrationOutcome> &integration_outcome,
size_t nthreads,
const std::optional<UnitCell> &reference_cell) {
MergeOnTheFly merge(x);
merge.Threads(nthreads).ReferenceCell(reference_cell).AddImages(integration_outcome);
return merge.ExportIntensities();
}
struct ShellAccum {
int total_obs = 0;
int unique = 0;
int possible = 0;
double sum_i_over_sigma = 0.0;
int n_i_over_sigma = 0;
CorrelationCoefficient cc_half;
CorrelationCoefficient cc_ref;
CorrelationCoefficient cc_split;
CorrelationCoefficient cc_anom;
double anom_abs_diff = 0.0, anom_sigma = 0.0;
int anom_pairs = 0, anom_measurable = 0;
double split_abs_diff = 0.0;
double split_sum = 0.0;
int split_pairs = 0;
};
std::pair<double, size_t> ImageReferenceCC(std::span<const Reflection> reflections,
const std::map<HKLKey, double> &reference,
const HKLKeyGenerator &generator,
std::optional<double> d_min_limit,
std::optional<double> d_max_limit,
double min_partiality) {
constexpr size_t MIN_REFLECTIONS = 20;
double sum_x = 0.0;
double sum_y = 0.0;
double sum_x2 = 0.0;
double sum_y2 = 0.0;
double sum_xy = 0.0;
size_t n = 0;
for (const auto &r: reflections) {
if (r.on_ice_ring)
continue;
if (!AcceptReflection(r, d_min_limit, d_max_limit))
continue;
if (r.partiality < min_partiality)
continue;
if (!std::isfinite(r.I) || !std::isfinite(r.image_scale_corr) || r.image_scale_corr <= 0.0f)
continue;
if (!std::isfinite(r.sigma) || r.sigma <= 0.0f)
continue;
const auto it = reference.find(generator(r));
if (it == reference.end())
continue;
const double image_i = static_cast<double>(r.I) * static_cast<double>(r.image_scale_corr);
const double ref_i = it->second;
if (!std::isfinite(image_i) || !std::isfinite(ref_i))
continue;
sum_x += image_i;
sum_y += ref_i;
sum_x2 += image_i * image_i;
sum_y2 += ref_i * ref_i;
sum_xy += image_i * ref_i;
++n;
}
if (n < MIN_REFLECTIONS)
return {NAN, n};
const double nd = static_cast<double>(n);
const double cov = sum_xy - sum_x * sum_y / nd;
const double var_x = sum_x2 - sum_x * sum_x / nd;
const double var_y = sum_y2 - sum_y * sum_y / nd;
if (!(var_x > 0.0 && var_y > 0.0))
return {NAN, n};
return {cov / std::sqrt(var_x * var_y), n};
}
void CalcPossibleReflections(const gemmi::SpaceGroup &sg,
const UnitCell &cell,
double d_min,
double d_max,
const ResolutionShells &shells,
std::vector<ShellAccum> &acc,
bool merge_friedel) {
gemmi::UnitCell gemmi_cell = cell;
// Generate unique reflections
std::vector<gemmi::Miller> possible_hkls = gemmi::make_miller_vector(gemmi_cell, &sg, d_min, d_max, true);
const gemmi::GroupOps gops = sg.operations();
CrystalLattice lattice(cell);
const auto astar = lattice.Astar();
const auto bstar = lattice.Bstar();
const auto cstar = lattice.Cstar();
for (const auto &hkl: possible_hkls) {
const auto q = hkl[0] * astar + hkl[1] * bstar + hkl[2] * cstar;
const auto qlen = q.Length();
if (qlen < 1e-6)
continue;
const auto d = 1.0 / qlen;
const auto shell = shells.GetShell(d);
if (!shell.has_value())
continue;
const int s = *shell;
if (s >= 0 && s < acc.size())
// Anomalous (no Friedel merge): an acentric reflection has two unique members (I+ and I-),
// a centric one only one — match how unique_reflections is counted, so completeness stays
// <=100% instead of approaching 200%.
acc[s].possible += (merge_friedel || gops.is_reflection_centric(hkl)) ? 1 : 2;
}
}
MergeStatistics MergeOnTheFly::MergeStats(const std::vector<MergedReflection> &merged,
const std::vector<IntegrationOutcome > &integration_outcome,
const std::vector<MergedReflection> &reference,
std::optional<double> d_min_override,
std::optional<ReportResolutionRange> declared_range) {
const int n_shells = scaling_settings.GetReportShellCount();
auto d_min_limit_A = d_min_override.has_value()
? d_min_override : scaling_settings.GetHighResolutionLimit_A();
// The low-resolution limit bounds the scale fit, not the merge (ScalingSettings), so the statistics
// run to the coarsest reflection unless a range is declared.
std::optional<double> d_max_limit_A;
if (declared_range) {
d_min_limit_A = declared_range->d_min;
d_max_limit_A = std::isfinite(declared_range->d_max)
? std::optional<double>(declared_range->d_max) : std::nullopt;
}
std::unordered_map<uint64_t, float> reference_intensities;
if (!reference.empty()) {
reference_intensities.reserve(reference.size());
for (const auto &r: reference) {
if (!std::isfinite(r.I))
continue;
const auto hkl = generator(r);
reference_intensities[hkl.pack()] = r.I;
}
}
float d_min = std::numeric_limits<float>::max();
float d_max = 0.0f;
for (const auto &m: merged) {
if (!std::isfinite(m.d) || m.d <= 0.0f)
continue;
if (d_min_limit_A && m.d < d_min_limit_A)
continue;
if (d_max_limit_A && m.d > d_max_limit_A)
continue;
d_min = std::min(d_min, m.d);
d_max = std::max(d_max, m.d);
}
// A declared range is a grid whether or not anything landed in it.
if (!(d_min < d_max && d_min > 0.0f) && !declared_range)
throw JFJochException(JFJochExceptionCategory::InputParameterInvalid,
"MergeStats: Error in resolution calculation");
// Completeness is a claim about how much of a defined set was measured, so the set has to be
// defined by something other than what was measured. The shell grid - and with it the
// denominator, which shares its bounds so nothing is enumerated outside a shell - runs to the
// low resolution the run DECLARES, not to the coarsest reflection that happened to survive the
// beam stop, a detector mask and the limit itself: what those ate now counts as missing, which
// is what it is. An undeclared low limit is the whole sphere, i.e. 1/d^2 down to 0, and an
// infinite d_max is how that is spelled. The high end stays the finest d reached anywhere -
// that is the resolution the run reports, and the full sphere down to it already shows
// anisotropic loss.
const float d_min_pad = declared_range ? static_cast<float>(declared_range->d_min)
: d_min * 0.999f; // GetShell rejects d <= d_min; the finest reflection needs the room
const float d_max_declared = d_max_limit_A ? static_cast<float>(*d_max_limit_A)
: std::numeric_limits<float>::infinity();
// The innermost shell is labelled by the bound it reaches, except when that bound is infinite
// and the coarsest reflection measured is the only finite thing to say.
const float d_max_label = std::isfinite(d_max_declared) ? d_max_declared : d_max;
ResolutionShells shells(d_min_pad, d_max_declared, n_shells);
const auto shell_mean_1_d2 = shells.GetShellMeanOneOverResSq();
const auto shell_min_res = shells.GetShellMinRes();
std::vector<ShellAccum> acc(n_shells);
if (reference_cell.has_value())
CalcPossibleReflections(space_group, reference_cell.value(),
d_min_pad, d_max_declared, shells, acc, scaling_settings.GetMergeFriedel());
CorrelationCoefficient cc_half_overall;
CorrelationCoefficient cc_ref_overall;
ShellAccum split_overall;
for (const auto &m: merged) {
const auto shell = shells.GetShell(m.d);
if (!shell.has_value())
continue;
const int s = *shell;
if (s >= 0 && s < n_shells) {
if (std::isfinite(m.I) && std::isfinite(m.sigma) && m.sigma > 0.0) {
acc[s].unique++;
acc[s].sum_i_over_sigma += m.I / m.sigma;
++acc[s].n_i_over_sigma;
if (!reference_intensities.empty()) {
const auto hkl = generator(m);
const auto ref_it = reference_intensities.find(hkl.pack());
if (ref_it != reference_intensities.end() && std::isfinite(ref_it->second)) {
acc[s].cc_ref.Add(m.I, ref_it->second);
cc_ref_overall.Add(m.I, ref_it->second);
}
}
if (std::isfinite(m.I_half[0]) && std::isfinite(m.I_half[1])) {
acc[s].cc_half.Add(m.I_half[0], m.I_half[1]);
cc_half_overall.Add(m.I_half[0], m.I_half[1]);
}
if (std::isfinite(m.I_split[0]) && std::isfinite(m.I_split[1])) {
for (auto *a: {&acc[s], &split_overall}) {
a->cc_split.Add(m.I_split[0], m.I_split[1]);
a->split_abs_diff += std::fabs(m.I_split[0] - m.I_split[1]);
a->split_sum += 0.5 * (m.I_split[0] + m.I_split[1]);
a->split_pairs++;
}
}
}
}
}
// Anomalous statistics where the merge keeps the Friedel hands apart: an I(-) is stored at the negated
// index of its I(+). CC_anom between the frame-whole half-sets (I_split), so the two differences come
// from different crystals; SigAno against the merged sigmas. Acentric reflections only.
if (!scaling_settings.GetMergeFriedel()) {
std::map<std::tuple<int, int, int>, const MergedReflection *> by_index;
for (const auto &m: merged)
by_index[{m.h, m.k, m.l}] = &m;
const auto &ops = space_group.operations();
for (const auto &[hkl, plus]: by_index) {
const auto it = by_index.find({-plus->h, -plus->k, -plus->l});
if (it == by_index.end() || hkl <= it->first) // each pair once
continue;
const MergedReflection &minus = *it->second;
if (ops.is_reflection_centric({plus->h, plus->k, plus->l}))
continue;
const auto shell = shells.GetShell(plus->d);
if (!shell.has_value() || *shell < 0 || *shell >= n_shells)
continue;
for (auto *a: {&acc[*shell], &split_overall}) {
if (std::isfinite(plus->I) && std::isfinite(minus.I) && plus->sigma > 0.0f && minus.sigma > 0.0f) {
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]))
a->cc_anom.Add(plus->I_split[0] - minus.I_split[0], plus->I_split[1] - minus.I_split[1]);
}
}
}
// The observations are counted again, now only those of the reflections that are reported. No
// R_merge / R_meas / R_pim: they are rotation statistics, and on partials scaled to full equivalents
// they read hundreds of percent and mean nothing. R_split (below) is the serial one.
std::unordered_set<uint64_t> reported;
reported.reserve(merged.size());
for (const auto &m: merged)
if (std::isfinite(m.I))
reported.insert(generator(m).pack());
struct ShellObs { int shell; bool merged; };
ReduceImagesInOrder<ShellObs>(
integration_outcome.size(), nthreads,
[&](size_t i, std::vector<ShellObs> &out) {
if (Mask(integration_outcome[i]))
return;
for (const auto &r: integration_outcome[i].reflections) {
if (generator.IsSystematicallyAbsent(r))
continue;
if (r.image_scale_corr <= 0.0 || !std::isfinite(r.image_scale_corr))
continue;
if (!Accept(r, d_min_limit_A, d_max_limit_A))
continue;
if (BelowMergeFloor(r.partiality))
continue;
const auto key = generator(r).pack();
const auto [I_corr, w] = Weigh(r, key);
if (w == 0.0)
continue;
const auto shell = shells.GetShell(Resolution(r));
if (!shell.has_value())
continue;
const int s = *shell;
if (s >= 0 && s < n_shells)
out.push_back({s, reported.contains(key)});
}
},
[&](size_t, const std::vector<ShellObs> &out) {
for (const auto &o: out)
if (o.merged) // the observations of a reflection that is not reported are not counted
acc[o.shell].total_obs++;
});
// R_split as White et al. (2012) J. Appl. Cryst. 45, 335-341 define it (CrystFEL's compare_hkl).
auto set_split = [](const ShellAccum &a, MergeStatisticsShell &ss) {
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<double>(a.anom_measurable) / a.anom_pairs;
}
ss.n_split_pairs = a.split_pairs;
if (a.split_pairs == 0)
return;
ss.cc_half_split = a.cc_split.GetCC();
if (a.split_sum > 0.0)
ss.r_split = a.split_abs_diff / a.split_sum / std::sqrt(2.0);
};
MergeStatistics out;
out.stills = true;
out.shells.resize(n_shells);
out.n_observations_rejected = reject_count;
for (int s = 0; s < n_shells; ++s) {
const auto &sa = acc[s];
auto &ss = out.shells[s];
ss.mean_one_over_d2 = shell_mean_1_d2[s];
ss.d_min = shell_min_res[s];
ss.d_max = s == 0 ? d_max_label : shell_min_res[s - 1];
ss.total_observations = sa.total_obs;
ss.unique_reflections = sa.unique;
ss.possible_unique_reflections = sa.possible;
ss.mean_i_over_sigma = sa.n_i_over_sigma > 0
? sa.sum_i_over_sigma / sa.n_i_over_sigma
: 0.0;
ss.cc_half = sa.cc_half.GetCC();
ss.cc_half_internal = ss.cc_half; // stills weight nothing
ss.cc_ref = sa.cc_ref.GetCC();
set_split(sa, ss);
}
auto &overall = out.overall;
overall.d_min = d_min < d_max ? d_min : 0.0f; // 0: nothing landed in a declared range
overall.d_max = d_max;
int all_possible = 0;
int all_unique = 0;
double sum_i_over_sigma = 0.0;
int n_i_over_sigma = 0;
for (const auto &sa: acc) {
overall.total_observations += sa.total_obs;
all_unique += sa.unique;
all_possible += sa.possible;
sum_i_over_sigma += sa.sum_i_over_sigma;
n_i_over_sigma += sa.n_i_over_sigma;
}
overall.possible_unique_reflections = all_possible;
overall.unique_reflections = all_unique;
overall.mean_i_over_sigma = n_i_over_sigma > 0 ? sum_i_over_sigma / n_i_over_sigma : 0.0;
overall.cc_half = cc_half_overall.GetCC();
overall.cc_half_internal = overall.cc_half;
overall.cc_ref = cc_ref_overall.GetCC();
set_split(split_overall, overall);
return out;
}
const char *SweepQualityReasonCode(SweepQualityReason reason) {
switch (reason) {
case SweepQualityReason::NoDiffraction: return "no_diffraction";
case SweepQualityReason::CrystalOutOfBeam: return "crystal_out_of_beam";
case SweepQualityReason::WeakDiffraction: return "weak_diffraction";
case SweepQualityReason::LossOfCentring: return "loss_of_centring";
case SweepQualityReason::RadiationDamage: return "radiation_damage";
case SweepQualityReason::InconsistentWithMerge: return "inconsistent_with_merge";
}
return "unknown";
}
const char *SweepQualityReasonText(SweepQualityReason reason) {
switch (reason) {
case SweepQualityReason::NoDiffraction: return "no diffraction";
case SweepQualityReason::CrystalOutOfBeam: return "out of beam";
case SweepQualityReason::WeakDiffraction: return "weak diffraction";
case SweepQualityReason::LossOfCentring: return "loss of centring";
case SweepQualityReason::RadiationDamage: return "radiation damage";
case SweepQualityReason::InconsistentWithMerge: return "inconsistent with the merge";
}
return "unknown";
}
bool WeightedRmeasTerms(double sum_v_absdev, double sum_v_I, double sum_v, double sum_v2,
double &num, double &den) {
if (!(sum_v > 0.0) || !(sum_v2 > 0.0))
return false;
const double n_eff = sum_v * sum_v / sum_v2;
if (!(n_eff > 1.0))
return false;
const double scale = n_eff / sum_v;
num = std::sqrt(n_eff / (n_eff - 1.0)) * scale * sum_v_absdev;
den = scale * sum_v_I;
return true;
}
const char *FrameDispositionCode(FrameDisposition disposition) {
switch (disposition) {
case FrameDisposition::Merged: return "merged";
case FrameDisposition::Downgraded: return "downgraded";
case FrameDisposition::Rejected: return "rejected";
}
return "unknown";
}
namespace {
// A quantity a run did not measure prints as a dash, not as "nan": CCref has nothing to compare
// against unless a reference was given, CCanom needs both Bijvoet mates split in two, and a thin
// shell can be short of the reflections either of them needs. A dash is what XDS and AIMLESS put
// in the same place, and it does not read as a measured value the way "nan" does. A measured
// value always prints, including a negative one - a negative CCanom is a result, not a gap.
std::string Measured(double value, const char *suffix = "", int decimals = 1) {
return std::isfinite(value) ? fmt::format("{:.{}f}{}", value, decimals, suffix)
: std::string("-");
}
}
std::string ShellTableRow(const MergeStatisticsShell &in, bool r_factors) {
// NaN, not 0.0, where the denominator is empty: Measured() below turns that into a dash, and a
// printed 0.0% reads as a measured total failure rather than as a quantity nobody could form.
double completeness = in.possible_unique_reflections > 0
? static_cast<double>(in.unique_reflections) / in.possible_unique_reflections * 100.0 : NAN;
double multiplicity = in.unique_reflections > 0
? static_cast<double>(in.total_observations) / in.unique_reflections : NAN;
std::string out = fmt::format("{:8d} {:8d} {:8d} {:>8s} {:>7s} {:>8s} ",
in.total_observations,
in.unique_reflections,
in.possible_unique_reflections,
Measured(completeness, "%"),
Measured(multiplicity),
Measured(in.mean_i_over_sigma));
if (r_factors)
out += fmt::format("{:>8s} {:>8s} {:>8s} ",
Measured(in.r_merge*100.0, "%"),
Measured(in.r_meas*100.0, "%"),
Measured(in.r_pim*100.0, "%"));
out += fmt::format("{:>8s} {:>8s} {:>8s} {:>8s} {:>8s}",
Measured(in.cc_half*100.0, "%"),
Measured(CCStar(in.cc_half)*100.0, "%"),
Measured(in.cc_ref*100.0, "%"),
Measured(in.cc_anom*100.0, "%"),
Measured(in.abs_diff_over_sigma_anomalous, "", 2));
return out;
}
std::ostream &operator<<(std::ostream &output, const MergeStatisticsShell &in) {
return output << ShellTableRow(in, true);
}
std::string ShellTableHeader(bool r_factors) {
return fmt::format(" {:>8s} {:>8s} {:>8s} {:>8s} {:>8s} {:>7s} {:>8s} ",
"d_min", "N_obs", "N_uniq", "N_possib", "Compl", "Mult", "<I/sig>")
+ (r_factors ? fmt::format("{:>8s} {:>8s} {:>8s} ", "R_merge", "R_meas", "R_pim") : std::string())
+ fmt::format("{:>8s} {:>8s} {:>8s} {:>8s} {:>8s}", "CC1/2", "CC*", "CCref", "CCanom", "SigAno");
}
std::string ShellTableRule(bool r_factors) {
const std::string dash8(8, '-');
std::string rule = fmt::format(" {0} {0} {0} {0} {0} {1} {0}", dash8, std::string(7, '-'));
for (int i = 0; i < (r_factors ? 8 : 5); ++i)
rule += " " + dash8;
return rule;
}
std::string SerialShellTable(const MergeStatistics &in) {
if (in.overall.n_split_pairs == 0)
return "";
std::string o = "\n Serial statistics: every frame whole in one half-set (as CrystFEL's partialator splits by crystal)\n";
o += fmt::format(" {:>8s} {:>8s} {:>8s} {:>8s} {:>8s}\n", "d_min", "N_pairs", "CC1/2", "CC*", "R_split");
o += fmt::format(" {:->8s} {:->8s} {:->8s} {:->8s} {:->8s}\n", "", "", "", "", "");
auto row = [](const MergeStatisticsShell &sh) {
return fmt::format("{:8d} {:>8s} {:>8s} {:>8s}\n", sh.n_split_pairs,
Measured(sh.cc_half_split * 100.0, "%"),
Measured(CCStar(sh.cc_half_split) * 100.0, "%"),
Measured(sh.r_split * 100.0, "%"));
};
for (const auto &sh: in.shells)
if (sh.n_split_pairs > 0)
o += fmt::format(" {:8.2f} ", sh.d_min) + row(sh);
o += fmt::format(" {:->8s} {:->8s} {:->8s} {:->8s} {:->8s}\n", "", "", "", "", "");
o += fmt::format(" {:>8s} ", "Overall") + row(in.overall);
return o;
}
std::ostream &operator<<(std::ostream &output, const MergeStatistics &in) {
// A stills merge has no R_merge / R_meas / R_pim columns: see MergeOnTheFly::MergeStats.
const bool r_factors = !in.stills;
output << std::endl;
output << ShellTableHeader(r_factors) << std::endl;
output << ShellTableRule(r_factors) << std::endl;
for (const auto &sh: in.shells) {
if (sh.unique_reflections == 0)
continue;
output << fmt::format(" {:8.2f} ", sh.d_min);
output << ShellTableRow(sh, r_factors);
output << std::endl;
}
output << ShellTableRule(r_factors) << std::endl;
output << fmt::format(" {:>8s} ", "Overall");
output << ShellTableRow(in.overall, r_factors);
output << std::endl;
output << SerialShellTable(in);
if (std::isfinite(in.wilson_b) && in.wilson_b > 0.0)
output << fmt::format(" Wilson B-factor estimate: {:.2f} A^2 (correlation {:.3f}, fitted over {:.2f}-{:.2f} A)",
in.wilson_b, in.wilson_b_correlation, in.wilson_b_d_low_A, in.wilson_b_d_high_A)
<< std::endl;
if (std::isfinite(in.radiation_damage_delta_b))
output << fmt::format(" Radiation damage: relative B-factor change over run = {:+.2f} A^2 "
"(first->last, {} batches)",
in.radiation_damage_delta_b, in.radiation_damage_b_batch.size()) << std::endl;
output << std::endl;
return output;
}