// SPDX-FileCopyrightText: 2025 Filip Leonarski, Paul Scherrer Institute // SPDX-License-Identifier: GPL-3.0-only #include "Merge.h" #include #include #include #include #include #include #include #include #include #include #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(image_id) + 0x9e3779b97f4a7c15ULL; z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL; z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL; z = z ^ (z >> 31); return static_cast(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 void ReduceImagesInOrder(size_t n_images, size_t nthreads, Reduce reduce, Consume consume) { constexpr size_t BLOCK_IMAGES = 4096; std::vector> out(std::min(BLOCK_IMAGES, n_images)); for (size_t first = 0; first < n_images; first += BLOCK_IMAGES) { const int n = static_cast(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(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 &cell) { reference_cell = cell; return *this; } size_t MergeOnTheFly::Contributions(const IntegrationOutcome &outcome, std::vector &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 (!AcceptReflection(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 = r.d, .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> MergeOnTheFly::Verdicts(const std::vector &outcomes) const { std::vector> 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 (!AcceptReflection(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(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 &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 contributions; reject_count += Contributions(outcome, contributions); Accumulate(contributions, image_id); } void MergeOnTheFly::AddImages(const std::vector &outcomes) { std::unique_lock ul(merged_mutex); std::vector rejected(outcomes.size(), 0); ReduceImagesInOrder( outcomes.size(), nthreads, [&](size_t i, std::vector &out) { if (!Mask(outcomes[i])) rejected[i] = Contributions(outcomes[i], out); }, [&](size_t i, const std::vector &out) { reject_count += rejected[i]; Accumulate(out, static_cast(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 ). Rebuild the signal part at the reflection's // EXPECTED intensity instead - the background part plus corr* - 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, ). double v = sigma_corr * sigma_corr; if (scaling_settings.GetExpectedVarianceMerge()) { const double base = static_cast(image_scale_corr) * image_scale_corr * var_bkg + static_cast(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(r.I) * r.image_scale_corr; const double sigma_corr = static_cast(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 &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 all; // in image order ReduceImagesInOrder( outcomes.size(), nthreads, [&](size_t i, std::vector &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 (!AcceptReflection(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 &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 order(all.size()); const size_t obs_threads = ThreadsForWork(all.size(), nthreads); ParallelChunks(static_cast(all.size()), obs_threads, [&](int lo, int hi) { for (int i = lo; i < hi; ++i) order[i] = {all[i].key, static_cast(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 flat(all.size()); ParallelChunks(static_cast(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 keys; std::vector 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(flat.data() + start[k], start[k + 1] - start[k]); }; const int n_keys = static_cast(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 mean(n_keys); std::vector 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(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 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(1, flat.size() >> 22); bool last_round = false; std::vector 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 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 - )^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(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(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 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 MergeOnTheFly::ExportIntensities() { std::unique_lock ul(merged_mutex); std::vector out; std::vector> 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(accum.sum_wI / accum.sum_w), .sigma = static_cast(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 }; if (accum.exists_half[0] && accum.exists_half[1]) { for (int i = 0; i < 2; ++i) { mr.I_half[i] = static_cast(accum.sum_wI_half[i] / accum.sum_w_half[i]); mr.sigma_half[i] = static_cast(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(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 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(nthreads); // the same amplitudes at any worker count ApplyFrenchWilson(out, space_group, fw_opts); return out; } std::vector MergeAll(const DiffractionExperiment &x, const std::vector &integration_outcome, size_t nthreads, const std::optional &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; double split_abs_diff = 0.0; double split_sum = 0.0; int split_pairs = 0; }; std::pair ImageReferenceCC(std::span reflections, const std::map &reference, const HKLKeyGenerator &generator, std::optional d_min_limit, std::optional 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(r.I) * static_cast(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(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 &acc, bool merge_friedel) { gemmi::UnitCell gemmi_cell = cell; // Generate unique reflections std::vector 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 &merged, const std::vector &integration_outcome, const std::vector &reference, std::optional d_min_override, std::optional 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 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(declared_range->d_max) : std::nullopt; } std::unordered_map 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::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(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(*d_max_limit_A) : std::numeric_limits::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 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, 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::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 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( integration_outcome.size(), nthreads, [&](size_t i, std::vector &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 (!AcceptReflection(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(r.d); 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 &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.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(in.unique_reflections) / in.possible_unique_reflections * 100.0 : NAN; double multiplicity = in.unique_reflections > 0 ? static_cast(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", "") + (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; }