v1.0.0-rc.178 (#88)
Build Packages / Create release (push) Successful in 17s
Build Packages / build:portable:macos-arm64:nocuda (push) Successful in 4m41s
Build Packages / HDF5 consumer tests (DIALS, XDS) (push) Successful in 20m49s
Build Packages / build:portable:windows-x86_64:nocuda (push) Successful in 13m6s
Build Packages / build:portable:windows-x86_64:cuda (push) Successful in 23m44s
Build Packages / build:rugnux:linux-aarch64:cuda (push) Successful in 7m28s
Build Packages / build:portable:linux-x86_64:nocuda (push) Successful in 11m50s
Build Packages / build:portable:linux-x86_64:cuda (push) Successful in 14m9s
Build Packages / build:jfjoch:rocky8:nocuda (push) Successful in 16m25s
Build Packages / build:jfjoch:ubuntu2204:nocuda (push) Successful in 15m42s
Build Packages / build:jfjoch:rocky9:nocuda (push) Successful in 20m50s
Build Packages / build:jfjoch:ubuntu2404:nocuda (push) Successful in 20m36s
Build Packages / build:jfjoch:rocky8:cuda-sls9 (push) Successful in 22m18s
Build Packages / build:jfjoch:rocky9:cuda-sls9 (push) Successful in 23m29s
Build Packages / Generate python client (push) Successful in 30s
Build Packages / Build documentation (push) Successful in 1m10s
Build Packages / build:jfjoch:rocky8:cuda (push) Successful in 21m38s
Build Packages / build:jfjoch:ubuntu2204:cuda (push) Successful in 17m8s
Build Packages / build:jfjoch:rocky9:cuda (push) Successful in 23m10s
Build Packages / build:jfjoch:ubuntu2404:cuda (push) Successful in 19m16s
Build Packages / Unit tests (push) Successful in 2h8m4s
Build Packages / Validation Battery (push) Successful in 40m53s

* Rugnux: Processes serial crystallography data from XFELs - SACLA (MPCCD), PAL-XFEL and European XFEL (CXI), LCLS (XTC) and SwissFEL Alvra (JUNGFRAU with a CrystFEL module geometry) - with several files or Jungfraujoch master files merged in one run (`rugnux *_master.h5`).
* Rugnux: Stills processing takes a known unit cell and space group as a starting point, finds the beam centre (and, with a cell, the detector distance) from the images, detects the saturation level in other facilities' files and refines the placement of individual detector panels.
* Rugnux: The stills report gives R_split and CC1/2 from frame half-sets, comparable with CrystFEL.
* jfjoch_viewer: Opens the same XFEL file formats.
* Validation: A stills battery checks Rugnux against deposited structures from SACLA, PAL-XFEL, LCLS, European XFEL and SwissFEL.
* Rugnux: More reliable convergence of rotation scaling, and live molecular replacement starts as soon as the model is uploaded.
* jfjoch_broker: Initialize clears the previous dataset's bearer tokens, image buffer and live Rugnux status, and a slow CUDA JIT cache is reported at start.

Reviewed-on: #88
Co-authored-by: Filip Leonarski <filip.leonarski@psi.ch>
This commit was merged in pull request #88.
This commit is contained in:
leonarski_f authored and leonarski_f committed 2026-10-21 11:20:01 +02:00
1 parent 7ed32b899f
commit afbe844b20
320 files changed
+8900 -901

No files matched your search

+327 -113
View File
@@ -26,6 +26,7 @@
#include <gemmi/unitcell.hpp>
#include <gemmi/symmetry.hpp>
#include "AndersonMixing.h"
#include "HKLKey.h"
#include "RfreeFlags.h"
#include "FrenchWilson.h"
@@ -58,8 +59,30 @@ namespace {
constexpr double MIN_EVENTS_PER_FRAME_SCALE_PARTIALS = 50.0;
constexpr int64_t MIN_REFLECTIONS_FOR_IMAGE_CC = 20; // below this a frame's CC means nothing
// The per-frame scaling loop has settled when the scales moved less than this between two
// iterations, as the rms of |log(G_new/G_old)| over the frames fitted in both.
constexpr double SCALING_TOLERANCE = 1e-3;
// iterations, as the rms of |log(G_new/G_old)| over the frames fitted in both. Tight enough that the
// merge no longer depends on where a loop stopped: with Anderson mixing a loop gets here in fewer
// rounds than a plain one took to 1e-3.
constexpr double SCALING_TOLERANCE = 1e-5;
// The correction surfaces (ApplyCellSurface) are NOT run to that tolerance: their fit stops once a
// round moves the cell factors by less than this, as the rms of |log| of the update. Their fixed
// point is worse than where this stops them: run to 1e-5 (up to 300 rounds), the detector-frame
// surfaces walked along the resolution direction the gauge projects out - 1.2x -> 8.5x of ramp
// removed on one set, 15 -> 283 rounds - their held-out half-set gain fell (+0.026 -> -0.031 per
// shell on one small-molecule set, -0.28 -> -0.78 on a protein), and ISa fell 37 -> 18, 22.8 -> 19.6,
// 7.4 -> 5.3, 17.0 -> 15.3 and 31.0 -> 18.1 on five of 23 sets, with SHELXL R1 0.0307 -> 0.0328 on
// one. The prior and the gates the surfaces carry were calibrated at this tolerance.
constexpr double SURFACE_TOLERANCE = 1e-3;
// The rounds of history the per-frame scaling loops are accelerated with (AndersonMixing). Their slow
// directions are a few smooth modes over the sweep: measured on a 4nwv-class sweep, 3, 5 and 8 rounds
// take its ten loops in 92, 91 and 90 iterations, against 364 without.
constexpr int SCALING_ANDERSON_DEPTH = 5;
// The loops are accelerated only once their step is below this: Anderson mixing models the map near
// its fixed point, and a loop still further out is as likely to be walking.
constexpr double SCALING_ANDERSON_ONSET = 1e-2;
// A scaling loop has stopped settling when the trend of log(step) over its last this many rounds is
// not falling (StepsStoppedFalling): a steady slow fall is a loop still contracting, a flat or
// rising trend is not.
constexpr int SCALING_STALL_WINDOW = 6;
// The per-frame scale is smoothed over at least this many rocking curves (see Run).
constexpr int SMOOTH_G_MIN_ROCKING_EVENTS = 6;
@@ -69,15 +92,17 @@ namespace {
// Interleaved folds of the cross-validation that sets the smoothness of the fulls' scale.
constexpr int CV_FOLDS = 5;
// A fitted per-frame scale below this fraction of the run's median is not a measurement of anything:
// it would mean the frame received 2% of its neighbours' dose while still producing indexable spots.
// A fitted per-frame scale below this fraction of the run's typical frame (of the median, for the
// fulls - see DropCollapsedScales) is not a measurement of anything: it would mean the frame received
// 2% of its neighbours' dose while still producing indexable spots.
// It matters because the scale enters as 1/G, so a G that collapses toward zero multiplies every
// intensity on that frame without bound - and sigma by the identical factor, which is why no
// sigma-based outlier test can see it. Measured over 12 rotation crystals in the default
// configuration, the smallest LEGITIMATE min(G)/median(G) is 0.070; the case this bound exists for
// sat at 0.0017 (a 546x amplification that put 99% of sum(I^2) into 0.66% of the observations and
// took the merged CC1/2 from 93.7% to 17.2%). 0.02 is 3.5x below anything real and 12x above the
// failure.
// failure. Against the typical frame, over the 252 merged sets of one battery (read off their final
// per-frame scales), the smallest merged frame of a set that drops none sat at 0.036.
constexpr double MIN_CREDIBLE_SCALE_RATIO = 0.02;
// The same quantity, for the P1 merge that feeds the de-novo space-group search only. That merge
@@ -296,6 +321,21 @@ namespace {
std::nth_element(v.begin(), v.begin() + v.size() / 2, v.end());
return v[v.size() / 2];
}
// Whether the steps of a scaling loop have stopped falling: the median of the pairwise slopes of
// log(step) over the last SCALING_STALL_WINDOW rounds (Theil-Sen) is not negative. A median, so that
// one round's jump - the smoothness re-chosen five decades away, on a loop that was falling by a
// quarter a round - does not end a loop that is still contracting.
bool StepsStoppedFalling(const std::vector<double> &steps) {
const int n = SCALING_STALL_WINDOW;
if (static_cast<int>(steps.size()) < n) return false;
const double *s = steps.data() + steps.size() - n;
std::vector<double> slopes;
for (int i = 0; i < n; ++i)
for (int j = i + 1; j < n; ++j)
slopes.push_back(std::log(s[j] / s[i]) / (j - i));
return median_of(slopes) >= 0.0;
}
}
RotationScaleMerge::RotationScaleMerge(const DiffractionExperiment &experiment,
@@ -339,6 +379,86 @@ RotationScaleMerge::RotationScaleMerge(const DiffractionExperiment &experiment,
mosaicity_deg = s.GetDefaultMosaicity();
}
// The frames at either end of a rotation sweep that the beam never reached - a shutter that opened late
// or closed early, a beam that went off - which many sweeps carry. Their reflections are cleared, so
// nothing downstream sees them (the scaling, the merge, the post-refinement, the unmerged file) and the
// sweep reads as ending where the exposure did. Decided per frame, before anything is scaled, and with
// no stretch length: one blank frame at an end is as blank as twenty.
//
// Two things have to hold of such a frame, and each is read off its own integrated reflections.
//
// It recorded no diffraction. The reflections are counted by sign: those standing more than
// BLANK_TAIL_SIGMA above zero and those standing as far below it. Noise puts as many in one tail as in
// the other, however its sigmas are calibrated, so the excess of the upper tail is the diffraction the
// frame recorded, and the two counts are its own Poisson variance. Counted, not averaged: a mean I/sigma
// is carried by the many weak reflections, where a slight bias of the background estimate cancels what
// the few strong ones say - measured, the tail of a crystal leaving the beam read a mean below zero
// while its frames still correlated 0.3 with the merge, and a frame the shutter half exposed read as
// blank as one it never opened on. The frame has no diffraction when its excess is within
// BLANK_TAIL_SIGMA standard errors of zero AND that band lies wholly below the same band around the
// run's typical frame. The first alone would trim every frame of a crystal too weak for one frame to
// show it; the second makes a run that cannot tell a blank frame from a typical one trim nothing.
//
// And there was no beam: its background - the incident flux, see MeasureIncidentFlux - is nearer to none
// than to the run's typical frame. That is what separates a shutter from a crystal that has left the
// beam, which records no diffraction either but still scatters the beam into the background. Those are
// a finding about the crystal, and stay for the sweep ledger to report.
//
// A frame that recorded anything - partly exposed, the tail of a crystal leaving the beam - stays, for
// the scaling and the sweep ledger to judge as they judge any other. Only from the ends inward: a frame
// inside the sweep without beam is news, and is left to the ledger too. A frame with nothing integrated
// on it (missing from disk, not processed) is walked past and not counted.
std::pair<int, int> TrimBlankSweepEnds(std::vector<IntegrationOutcome> &outcomes, size_t nthreads) {
constexpr double BLANK_TAIL_SIGMA = 3.0;
const int n = static_cast<int>(outcomes.size());
std::vector<int64_t> upper(n, 0), lower(n, 0);
std::vector<double> bkg(n, 0.0);
ParallelFor(n, nthreads, [&](int f) {
double bkg_sum = 0.0;
int64_t bkg_n = 0;
for (const auto &r : outcomes[f].reflections) {
if (std::isfinite(r.I) && std::isfinite(r.sigma) && r.sigma > 0.0f) {
upper[f] += r.I > BLANK_TAIL_SIGMA * r.sigma;
lower[f] += r.I < -BLANK_TAIL_SIGMA * r.sigma;
}
if (std::isfinite(r.bkg)) { bkg_sum += r.bkg; ++bkg_n; }
}
if (bkg_n > 0) bkg[f] = bkg_sum / bkg_n;
});
std::vector<double> excess, tails, background;
for (int f = 0; f < n; ++f)
if (!outcomes[f].reflections.empty()) {
excess.push_back(static_cast<double>(upper[f] - lower[f]));
tails.push_back(static_cast<double>(upper[f] + lower[f]));
background.push_back(bkg[f]);
}
if (excess.empty())
return {0, 0};
auto median = [](std::vector<double> &v) {
std::nth_element(v.begin(), v.begin() + v.size() / 2, v.end());
return v[v.size() / 2];
};
const double typical = median(excess);
const double typical_band = BLANK_TAIL_SIGMA * std::sqrt(median(tails));
const double typical_bkg = median(background);
auto blank = [&](int f) {
const double e = static_cast<double>(upper[f] - lower[f]);
const double band = BLANK_TAIL_SIGMA * std::sqrt(static_cast<double>(upper[f] + lower[f]));
return e <= band && e + band < typical - typical_band && bkg[f] < typical_bkg - bkg[f];
};
auto walk = [&](int from, int step) {
int cleared = 0;
for (int f = from; f >= 0 && f < n && (outcomes[f].reflections.empty() || blank(f)); f += step)
if (!outcomes[f].reflections.empty()) {
outcomes[f].reflections.clear();
++cleared;
}
return cleared;
};
const int at_start = walk(0, 1);
return {at_start, walk(n - 1, -1)};
}
// Measure the incident flux per frame from the per-frame mean of the integrator's background estimate,
// so it can be divided out of the scale before anything is fitted.
//
@@ -404,6 +524,11 @@ void RotationScaleMerge::IngestHost() {
resident_ingest = gpu_active_ && !observation_dump;
#endif
data_first = 0;
while (data_first < n_frames && partials_out[data_first].reflections.empty()) ++data_first;
data_last = n_frames - 1;
while (data_last >= 0 && partials_out[data_last].reflections.empty()) --data_last;
frame_cell_ok.assign(n_frames, 1);
g_partial.assign(n_frames, 1.0);
const float dist_tol = x.GetIndexingSettings().GetUnitCellDistTolerance();
@@ -1846,19 +1971,37 @@ RotationScaleMerge::ScalingLoopOutcome RotationScaleMerge::RunScalingLoop(
// and handing any of it back re-opens it (measured: ISa 23.8 -> 22.1 on a 360 deg, 14x merge). The
// fulls, each a whole rocking event, have their own loop (RunFullsScalingLoop).
//
// The iteration converges linearly, and slowly: a round takes 5-15% off the step on most sweeps and
// 2% on the slowest, so a loop stopped on its step stopped several steps' worth short of where it
// was going. Each round's scales are therefore accelerated (AndersonMixing, in log G, each frame at
// its observation count): the plain round's answer corrected by the combination of the last few
// rounds' steps that best cancels this one. That moves no fixed point - only the path to it - and
// it takes the loop to its answer in a quarter of the rounds and closer: on one sweep the merged
// intensities ended 0.02% rms from the converged point, against 0.12% for the plain loop stopped at
// the same tolerance. A frame below the credible floor (below) takes the plain round's scale. A
// loop whose step grows is not contracting - it walks, and acceleration would only walk it faster -
// so from that round on its rounds are plain ones.
//
// The loop stops when the relative scales stop moving - the rms of |log(G_new/G_old)| over the
// frames, each weighted by its observation count and nothing else (a weight that vanishes with G
// is what let a collapsing sweep report itself settled) - or when they stop settling: a step that
// has not fallen below nine tenths of its smallest value for five rounds is a loop on a flat or
// rising valley, and more rounds of it can only walk further. Both leave the frames where they are
// and say so.
// is what let a collapsing sweep report itself settled) - or when they stop settling: steps that
// have not fallen over the last SCALING_STALL_WINDOW rounds, by the median trend of their logarithm,
// are a loop on a flat or rising valley, and more rounds of it can only walk further. A steady slow
// fall is not a stall (a rule of 'not below nine tenths of the best for five rounds' stopped a third
// of the unsettled loops of one battery while they were still falling at 2% a round). However the
// loop stops, it ends on the plain round with the smallest step - on a settled loop that is the
// last round, on any other the state closest to a fixed point it reached, not wherever its walk
// had got to. The step is the residual of the round, F(x) - x at the state the round started from,
// so the test reads the same whether that state was a plain round's or an accelerated one.
ScalingLoopOutcome out;
std::vector<uint8_t> scaled_any(n_frames, 0);
std::vector<double> g_prev(n_frames, 0.0), g_smooth;
std::vector<int64_t> n_obs(n_frames, 0);
std::vector<double> ratio(n_frames, 1.0);
double best_step = INFINITY;
int rounds_since_best = 0;
std::vector<double> steps, g_best;
AndersonMixing anderson(SCALING_ANDERSON_DEPTH);
std::vector<double> log_g_prev(n_frames), log_g(n_frames), weight(n_frames);
for (int it = 0; it < scaling_iter; ++it) {
iterate();
out.iterations = it + 1;
@@ -1867,60 +2010,83 @@ RotationScaleMerge::ScalingLoopOutcome RotationScaleMerge::RunScalingLoop(
// What each frame's corr is multiplied by: the fitted G over the G it ends the round with.
for (int f = 0; f < n_frames; ++f)
ratio[f] = scaled_any[f] && std::isfinite(g[f]) && g[f] > 0.0 ? g[f] : 1.0;
// The credible floor is a fraction of the run's typical frame - the frame the gauge is pinned
// to below, so the floor stands still while the loop runs (see DropCollapsedScales).
for (int f = 0; f < n_frames; ++f)
n_obs[f] = scaled_any[f] && std::isfinite(g[f]) && g[f] > 0.0 ? frame_obs_count[f] : 0;
if (window > 1) {
frame_scaled_scratch = scaled_any;
ComputeSmoothGWindow(g, window, g_smooth);
ComputeSmoothGWindow(g, window, TypicalFrameScale(g, n_obs) * MIN_CREDIBLE_SCALE_RATIO, g_smooth);
for (int f = 0; f < n_frames; ++f)
if (scaled_any[f] && std::isfinite(g_smooth[f]) && g_smooth[f] > 0.0)
g[f] = g_smooth[f];
}
for (int f = 0; f < n_frames; ++f)
n_obs[f] = scaled_any[f] && std::isfinite(g[f]) && g[f] > 0.0 ? frame_obs_count[f] : 0;
const double g_ref = TypicalFrameScale(g, n_obs);
std::vector<uint8_t> usable(n_frames);
for (int f = 0; f < n_frames; ++f) {
if (!scaled_any[f] || !(std::isfinite(g[f]) && g[f] > 0.0)) { ratio[f] = 1.0; continue; }
g[f] /= g_ref;
ratio[f] /= g[f];
usable[f] = scaled_any[f] && std::isfinite(g[f]) && g[f] > 0.0 ? 1 : 0;
n_obs[f] = usable[f] ? frame_obs_count[f] : 0;
}
rescale(scaled_any, ratio);
const double g_ref = TypicalFrameScale(g, n_obs);
for (int f = 0; f < n_frames; ++f)
if (usable[f]) g[f] /= g_ref;
bool stop = false;
if (it > 0) {
// A frame already below the credible floor is not part of the fit's answer: the window
// leaves it out (ComputeSmoothGWindow) and the guard after the loop drops it. Left in the
// step, a single such frame held the rms at 0.18 and the loop was stopped as unsettled after
// 16 rounds; with it left out the same loop settles in 23. On that sweep every loop that
// stopped unsettled was one that went on to drop a frame.
std::vector<double> fitted;
for (int f = 0; f < n_frames; ++f)
if (scaled_any[f] && g[f] > 0.0) fitted.push_back(g[f]);
double g_floor = 0.0;
if (!fitted.empty()) {
std::nth_element(fitted.begin(), fitted.begin() + fitted.size() / 2, fitted.end());
g_floor = fitted[fitted.size() / 2] * MIN_CREDIBLE_SCALE_RATIO;
}
// stopped unsettled was one that went on to drop a frame. The scales are pinned to the
// typical frame by now, so the floor is the ratio itself.
const double g_floor = MIN_CREDIBLE_SCALE_RATIO;
double ss = 0.0, sw = 0.0;
int n = 0;
for (int f = 0; f < n_frames; ++f)
for (int f = 0; f < n_frames; ++f) {
weight[f] = 0.0;
if (scaled_any[f] && g_prev[f] > 0.0 && g[f] > 0.0 && g[f] >= g_floor) {
const double d = std::log(g[f] / g_prev[f]);
log_g_prev[f] = std::log(g_prev[f]);
log_g[f] = std::log(g[f]);
const double d = log_g[f] - log_g_prev[f];
ss += frame_obs_count[f] * d * d;
sw += frame_obs_count[f];
weight[f] = frame_obs_count[f];
++n;
} else {
log_g_prev[f] = log_g[f] = 0.0;
}
}
out.step = sw > 0.0 ? std::sqrt(ss / sw) : 0.0;
logger->Debug("Per-frame scaling ({}): iteration {}, rms |dlogG| {:.2e} over {} frames, "
"gauge {:.4f}", what, it + 1, out.step, n, g_ref);
"gauge {:.4f}, {} restarts{}", what, it + 1, out.step, n, g_ref, anderson.Restarts(),
anderson.Stopped() ? ", plain" : "");
steps.push_back(out.step);
if (out.step < best_step) {
best_step = out.step;
g_best = g;
}
if (out.step < SCALING_TOLERANCE) {
out.converged = true;
break;
}
if (out.step < 0.9 * best_step) {
best_step = out.step;
rounds_since_best = 0;
} else if (++rounds_since_best >= 5) {
stop = true;
} else if (StepsStoppedFalling(steps)) {
out.stalled = true;
break;
stop = true;
}
if (stop || it + 1 == scaling_iter) {
for (int f = 0; f < n_frames; ++f)
if (usable[f]) g[f] = g_best[f];
} else if (out.step < SCALING_ANDERSON_ONSET) {
// The next round starts from the accelerated scales, gauge-pinned again.
const std::vector<double> next = anderson.Next(log_g_prev, log_g, weight);
for (int f = 0; f < n_frames; ++f)
if (weight[f] > 0.0) g[f] *= std::exp(next[f] - log_g[f]);
const double g_ref_next = TypicalFrameScale(g, n_obs);
for (int f = 0; f < n_frames; ++f)
if (usable[f]) g[f] /= g_ref_next;
}
}
for (int f = 0; f < n_frames; ++f)
ratio[f] = usable[f] ? ratio[f] / g[f] : 1.0;
rescale(scaled_any, ratio);
if (stop) break;
g_prev = g;
}
frame_scaled_scratch = scaled_any;
@@ -1935,14 +2101,16 @@ void RotationScaleMerge::LogScalingOutcome(const char *what, const ScalingLoopOu
out.iterations, out.step);
else if (out.stalled)
logger->Warning("Per-frame scaling ({}): stopped after {} iterations - the scales stopped settling "
"(rms |dlogG| {:.1e}, not below {:.1e} for five rounds); more rounds would only walk "
"them, so everything read off this merge is read off an unsettled state", what,
out.iterations, out.step, out.best_step);
"(rms |dlogG| {:.1e}, not falling over the last {} rounds); they are left at the "
"round with the smallest step ({:.1e}), and everything read off this merge is read "
"off an unsettled state", what, out.iterations, out.step, SCALING_STALL_WINDOW,
out.best_step);
else
logger->Warning("Per-frame scaling ({}): NOT settled after the cap of {} iterations - the scales "
"were still moving by rms |dlogG| {:.1e} (tolerance {:.0e}); everything read off "
"this merge is read off an unsettled state", what, out.iterations, out.step,
SCALING_TOLERANCE);
"were still moving by rms |dlogG| {:.1e} (tolerance {:.0e}); they are left at the "
"round with the smallest step ({:.1e}), and everything read off this merge is read "
"off an unsettled state", what, out.iterations, out.step, SCALING_TOLERANCE,
out.best_step);
}
RotationScaleMerge::ScalingLoopOutcome RotationScaleMerge::RunFullsScalingLoop(
@@ -1966,7 +2134,16 @@ RotationScaleMerge::ScalingLoopOutcome RotationScaleMerge::RunFullsScalingLoop(
// zero, where DropCollapsedFullScales finds it, without one round's noise throwing it there.
//
// A frame below the credible floor is left out of the step, as in RunScalingLoop: it walks
// toward zero for as long as the loop runs, which is the answer, not a failure to settle.
// toward zero for as long as the loop runs, which is the answer, not a failure to settle. The
// rounds are accelerated as RunScalingLoop's are, in log G with each frame at its count of fulls;
// the frame below the floor takes the plain round's scale.
//
// The smoothness is chosen afresh each round only while the loop is still far out; once its step is
// within SCALING_ANDERSON_ONSET - the round acceleration starts on - it is kept for every round after.
// A choice made every round makes each round a different map, which has no fixed point to settle on:
// on 149 of the 245 fulls loops that ended unsettled over one battery the choice was still jumping
// 2x or more at the end, one sweep's cycling between two choices 300x apart for as long as the loop
// ran. The acceleration, too, models one map.
ScalingLoopOutcome out;
std::vector<double> y(n_frames), J(n_frames), g_new(n_frames), ratio(n_frames);
std::vector<int64_t> n_obs(n_frames);
@@ -1976,7 +2153,10 @@ RotationScaleMerge::ScalingLoopOutcome RotationScaleMerge::RunFullsScalingLoop(
has_fulls[f] = frame_obs_count[f] > 0 ? 1 : 0;
}
double best_step = INFINITY, lambda = 0.0;
int rounds_since_best = 0;
bool lambda_kept = false;
std::vector<double> steps, g_best;
AndersonMixing anderson(SCALING_ANDERSON_DEPTH);
std::vector<double> log_g(n_frames), log_g_new(n_frames), weight(n_frames);
for (int it = 0; it < scaling_iter; ++it) {
fit();
out.iterations = it + 1;
@@ -1987,7 +2167,8 @@ RotationScaleMerge::ScalingLoopOutcome RotationScaleMerge::RunFullsScalingLoop(
if (fitted)
y[f] += g_fit[f] > 0.0 ? std::max(std::log(g_fit[f] / g[f]), -1.0) : -1.0;
}
lambda = ChooseLogScaleSmoothing(y, J, std::max(1, rocking_event_frames_at_start), nthreads);
if (!lambda_kept)
lambda = ChooseLogScaleSmoothing(y, J, std::max(1, rocking_event_frames_at_start), nthreads);
const std::vector<double> x = SmoothLogScale(y, J, lambda);
for (int f = 0; f < n_frames; ++f)
g_new[f] = std::exp(x[f]);
@@ -1995,54 +2176,77 @@ RotationScaleMerge::ScalingLoopOutcome RotationScaleMerge::RunFullsScalingLoop(
std::vector<double> scales;
for (int f = 0; f < n_frames; ++f) {
g_new[f] /= g_ref;
ratio[f] = g[f] / g_new[f];
if (has_fulls[f]) scales.push_back(g_new[f]);
}
rescale(has_fulls, ratio);
const double g_floor = scales.empty() ? 0.0 : median_of(scales) * MIN_CREDIBLE_SCALE_RATIO;
double ss = 0.0, sw = 0.0;
for (int f = 0; f < n_frames; ++f)
for (int f = 0; f < n_frames; ++f) {
weight[f] = 0.0;
if (has_fulls[f] && g_new[f] >= g_floor) {
const double d = std::log(g_new[f] / g[f]);
log_g[f] = std::log(g[f]);
log_g_new[f] = std::log(g_new[f]);
const double d = log_g_new[f] - log_g[f];
ss += frame_obs_count[f] * d * d;
sw += frame_obs_count[f];
weight[f] = frame_obs_count[f];
} else {
log_g[f] = log_g_new[f] = 0.0;
}
g = g_new;
}
out.step = sw > 0.0 ? std::sqrt(ss / sw) : 0.0;
logger->Debug("Per-frame scaling (fulls): iteration {}, rms |dlogG| {:.2e}, lambda {:.3g}, gauge {:.4f}",
it + 1, out.step, lambda, g_ref);
logger->Debug("Per-frame scaling (fulls): iteration {}, rms |dlogG| {:.2e}, lambda {:.3g}, gauge {:.4f}, "
"{} restarts{}", it + 1, out.step, lambda, g_ref, anderson.Restarts(),
anderson.Stopped() ? ", plain" : "");
if (out.step < SCALING_ANDERSON_ONSET) lambda_kept = true;
// Stopped and ended on the best round as RunScalingLoop's loop is.
steps.push_back(out.step);
if (out.step < best_step) {
best_step = out.step;
g_best = g_new;
}
bool stop = false;
if (out.step < SCALING_TOLERANCE) {
out.converged = true;
break;
}
if (out.step < 0.9 * best_step) {
best_step = out.step;
rounds_since_best = 0;
} else if (++rounds_since_best >= 5) {
stop = true;
} else if (StepsStoppedFalling(steps)) {
out.stalled = true;
break;
stop = true;
}
if (stop || it + 1 == scaling_iter) {
g_new = g_best;
} else if (out.step < SCALING_ANDERSON_ONSET) {
// The next round starts from the accelerated scales, gauge-pinned again.
const std::vector<double> next = anderson.Next(log_g, log_g_new, weight);
for (int f = 0; f < n_frames; ++f)
if (weight[f] > 0.0) g_new[f] *= std::exp(next[f] - log_g_new[f]);
const double g_ref_next = TypicalFrameScale(g_new, n_obs);
for (int f = 0; f < n_frames; ++f) g_new[f] /= g_ref_next;
}
}
// The curve is the part of the scale the frames share over a rocking curve and more; what a
// frame's own fulls say beyond it is handed back by how much of it is real (ShrinkToRestrained) -
// only off a loop that settled, since a loop still walking has measured nothing to hand back.
if (out.converged) {
fit();
std::vector<uint8_t> fitted(n_frames);
for (int f = 0; f < n_frames; ++f)
fitted[f] = frame_scaled_scratch[f] && frame_info_scratch[f] > 0.0 ? 1 : 0;
g_new = g;
ShrinkToRestrained("fulls", g, fitted, frame_obs_count, g_fit);
for (int f = 0; f < n_frames; ++f)
if (fitted[f] && std::isfinite(g_fit[f]) && g_fit[f] > 0.0) g_new[f] = g_fit[f];
const double g_ref = TypicalFrameScale(g_new, n_obs);
for (int f = 0; f < n_frames; ++f) {
g_new[f] /= g_ref;
ratio[f] = g[f] / g_new[f];
}
rescale(has_fulls, ratio);
g = g_new;
if (stop) break;
}
// The curve is the part of the scale the frames share over a rocking curve and more; what a
// frame's own fulls say beyond it is handed back by how much of it is real (ShrinkToRestrained),
// however the loop stopped: what is real is read off the frames themselves, and a hand-back that
// depended on whether the last step crossed the tolerance moved ISa by 0.6 on one sweep.
fit();
std::vector<uint8_t> fitted(n_frames);
for (int f = 0; f < n_frames; ++f)
fitted[f] = frame_scaled_scratch[f] && frame_info_scratch[f] > 0.0 ? 1 : 0;
g_new = g;
ShrinkToRestrained("fulls", g, fitted, frame_obs_count, g_fit);
for (int f = 0; f < n_frames; ++f)
if (fitted[f] && std::isfinite(g_fit[f]) && g_fit[f] > 0.0) g_new[f] = g_fit[f];
const double g_ref = TypicalFrameScale(g_new, n_obs);
for (int f = 0; f < n_frames; ++f) {
g_new[f] /= g_ref;
ratio[f] = g[f] / g_new[f];
}
rescale(has_fulls, ratio);
g = g_new;
frame_scaled_scratch = has_fulls;
out.best_step = best_step;
std::vector<double> positive;
@@ -2533,11 +2737,14 @@ namespace {
// Running median over `window` frames. A median rather than a mean because the real per-frame scale
// moves fast (its median frame-to-frame step in log is ~0.06) and one dead frame inside a good stretch
// must not drag the window down.
std::vector<double> RunningMedian(const std::vector<double> &v, int window) {
// Over the frames [lo, hi] only - the sweep the data span, so that frames trimmed off its ends
// (empty, and reading 0) do not drag down the medians of the frames beside them. Outside the span
// a frame keeps its own value.
std::vector<double> RunningMedian(const std::vector<double> &v, int window, int lo, int hi) {
const int n = static_cast<int>(v.size()), half = window / 2;
std::vector<double> out(n), buf;
for (int i = 0; i < n; ++i) {
buf.assign(v.begin() + std::max(0, i - half), v.begin() + std::min(n, i + half + 1));
std::vector<double> out(v), buf;
for (int i = std::max(0, lo); i <= std::min(n - 1, hi); ++i) {
buf.assign(v.begin() + std::max(lo, i - half), v.begin() + std::min(hi + 1, i + half + 1));
const size_t mid = buf.size() / 2;
std::nth_element(buf.begin(), buf.begin() + mid, buf.end());
out[i] = buf[mid];
@@ -2685,7 +2892,8 @@ void RotationScaleMerge::MeasureSweepQuality(const std::vector<uint8_t> &partial
if (model[f] < model[trough]) trough = f;
if (model[f] > model[peak]) peak = f;
}
const auto qm = RunningMedian(quality, std::max(3, static_cast<int>(std::lround(SWEEP_WINDOW_DEG / osc_deg))));
const auto qm = RunningMedian(quality, std::max(3, static_cast<int>(std::lround(SWEEP_WINDOW_DEG / osc_deg))),
data_first, data_last);
// A modulation is a dimming, not a disappearance: the crystal has to be measurably worse at the
// trough than at the peak, and still delivering data there. A sweep whose trough is simply dead
// is a sweep with a dead arc, and is reported as one.
@@ -2708,10 +2916,10 @@ void RotationScaleMerge::MeasureSweepQuality(const std::vector<uint8_t> &partial
// a stretch interrupted by a few good frames is one event, not two.
const int window = std::max(3, static_cast<int>(std::lround(SWEEP_WINDOW_DEG / osc_deg)));
const int min_len = std::max(1, static_cast<int>(std::lround(SWEEP_MIN_RANGE_DEG / osc_deg)));
const auto sm = RunningMedian(scale, window);
const auto qm = RunningMedian(quality, window);
const auto sm = RunningMedian(scale, window, data_first, data_last);
const auto qm = RunningMedian(quality, window, data_first, data_last);
std::vector<std::pair<int, int>> found;
for (int f = 0; f < n_frames; ++f) {
for (int f = data_first; f <= data_last; ++f) {
if (!(sm[f] < SWEEP_SCALE_FRACTION && qm[f] < SWEEP_CC_FRACTION)) continue;
if (!found.empty() && f - found.back().second - 1 <= min_len) found.back().second = f;
else found.emplace_back(f, f);
@@ -3199,8 +3407,8 @@ void RotationScaleMerge::MeasureBatchDeltaCCHalf(int n_groups) {
// nothing on its own. A frame at the run's typical scale AND at its typical agreement is a frame
// nothing measured here says anything is wrong with.
const int sweep_window = std::max(3, static_cast<int>(std::lround(SWEEP_WINDOW_DEG / osc_deg)));
const auto scale_median = RunningMedian(sweep_scale, sweep_window);
const auto cc_median = RunningMedian(sweep_cc, sweep_window);
const auto scale_median = RunningMedian(sweep_scale, sweep_window, data_first, data_last);
const auto cc_median = RunningMedian(sweep_cc, sweep_window, data_first, data_last);
auto normal_frame = [&](int f) {
return scale_median[f] >= SWEEP_SCALE_FRACTION && cc_median[f] >= SWEEP_CC_FRACTION;
};
@@ -3290,6 +3498,11 @@ void RotationScaleMerge::MeasureBatchDeltaCCHalf(int n_groups) {
spent[worst] = 1; // nothing here any other channel can see; look elsewhere
continue;
}
// A stretch that stops short of an end of the sweep by less than one rocking event takes the rest
// of it, where those frames read as the stretch does: so few frames are below what this statistic
// can judge on their own, and left in they are the one piece of the defect nothing looks at again.
if (data_last - f1 < min_frames && corroborated(f1 + 1, data_last)) f1 = std::max(f1, data_last);
if (f0 - data_first < min_frames && corroborated(data_first, f0 - 1)) f0 = std::min(f0, data_first);
int n_new = 0;
for (int f = f0; f <= f1; ++f) n_new += frame_rejected[f] ? 0 : 1;
if (n_rejected + n_new > max_rejected) {
@@ -3998,8 +4211,8 @@ void RotationScaleMerge::ApplyCellSurface(const std::vector<int32_t> &cell, int
// Fit the per-cell factor over the subset {frame&1 == parity} (parity < 0 = all fulls), alternating
// rounds against that subset's own reference (a prior pull to 1, then gauge-fixed within each
// resolution shell where resolution_gauge, which also holds the overall scale) until the factors settle - the same
// tolerance as the per-frame scales, on the rms |log| of the round's update - or n_iter rounds
// resolution shell where resolution_gauge, which also holds the overall scale) until the factors settle -
// SURFACE_TOLERANCE on the rms |log| of the round's update - or n_iter rounds
// have been spent. Returns the per-cell factor.
int rounds_used = 0;
bool settled = false;
@@ -4138,7 +4351,7 @@ void RotationScaleMerge::ApplyCellSurface(const std::vector<int32_t> &cell, int
}
A[c] = next;
}
if (n_step > 0 && std::sqrt(step2 / n_step) < SCALING_TOLERANCE) {
if (n_step > 0 && std::sqrt(step2 / n_step) < SURFACE_TOLERANCE) {
settled = true;
break;
}
@@ -4235,7 +4448,7 @@ void RotationScaleMerge::ApplyCellSurface(const std::vector<int32_t> &cell, int
rounds_used, gauge_ramp, n_clamped, ncell);
}
void RotationScaleMerge::ComputeSmoothGWindow(const std::vector<double> &g, int window,
void RotationScaleMerge::ComputeSmoothGWindow(const std::vector<double> &g, int window, double g_floor,
std::vector<double> &g_smooth) const {
const int n = static_cast<int>(g.size());
const int half = window / 2;
@@ -4249,19 +4462,8 @@ void RotationScaleMerge::ComputeSmoothGWindow(const std::vector<double> &g, int
// stays NAN, which the caller reads as "leave this frame alone"), so what reaches
// DropCollapsedScales is the scale the fit actually produced.
//
// The floor is the guard's, read the same way: MIN_CREDIBLE_SCALE_RATIO of the MEDIAN fitted
// scale, not of the precision-weighted typical frame - see DropCollapsedScales for why the median.
std::vector<double> fitted;
fitted.reserve(n);
for (int f = 0; f < n; ++f)
if (frame_scaled_scratch[f] && std::isfinite(g[f]) && g[f] > 0.0)
fitted.push_back(g[f]);
if (fitted.empty())
return;
const size_t mid = fitted.size() / 2;
std::nth_element(fitted.begin(), fitted.begin() + mid, fitted.end());
const double g_floor = fitted[mid] * MIN_CREDIBLE_SCALE_RATIO;
// The floor is the guard's, read the same way: MIN_CREDIBLE_SCALE_RATIO of the run's typical frame,
// passed in by the loop.
// Each frame's logarithm once, not once per window it falls in.
std::vector<double> log_g(n, 0.0);
std::vector<uint8_t> credible(n, 0);
@@ -4284,7 +4486,7 @@ void RotationScaleMerge::ComputeSmoothGWindow(const std::vector<double> &g, int
}
}
// Drop the observations of any frame whose scale fitted far below the run's median, reporting the
// Drop the observations of any frame whose scale fitted far below the run's typical frame, reporting the
// per-frame factor the caller has to apply to its corr (1 where nothing changed, 0 where the frame is
// dropped). Returns false when there was nothing to drop.
//
@@ -4306,11 +4508,19 @@ bool RotationScaleMerge::DropCollapsedScales(const std::vector<uint8_t> &fitted_
apply.assign(n, 0);
ratio.assign(n, 1.0);
// Against the MEDIAN frame, not the precision-weighted typical frame the sweep ledger reads: a
// frame that collapsed toward zero and was not quite dropped has its intensities amplified by
// 1/G, the fulls built from them are re-fitted with a scale of that size, and a cubic mean is then
// theirs - measured on a sweep 60% out of the beam, the fulls' precision-weighted typical scale
// sat on such frames and the floor dropped three quarters of every live frame's fulls.
// Against the run's typical frame (TypicalFrameScale), the frame the scaling loop pins its gauge to,
// not against the median frame. On a sweep that spent most of its turn out of the beam the median is
// itself a dead frame, and it walks: the dead frames' scales slide toward zero round after round
// (an empty frame's scale has no fixed point above zero), the median and the floor slide with them,
// and the frames on the floor cross it, re-enter the smoothing window at their neighbours' scale and
// cross it again - so the loop never settled, and which frames were merged depended on the round it
// stopped on. Measured on a lysozyme sweep two thirds out of the beam, where the median frame sat at
// a sixth of the typical one: the floor fell 2.4x in one loop, and the same loop ended by two
// stopping rules merged R_meas 287% and 685%; with the floor on the typical frame it merges 81%,
// CC1/2 0.93 -> 0.97, model R-free 0.330 -> 0.327. Where most of the sweep diffracts the
// median and the typical frame are the same frame and nothing changes. The fulls keep the median
// (DropCollapsedFullScales): their scales are not gauge-pinned, and amplified fulls of a frame that
// was not quite dropped pull a cubic mean up onto themselves.
std::vector<double> fitted;
fitted.reserve(n);
for (int f = 0; f < n; ++f)
@@ -4321,7 +4531,11 @@ bool RotationScaleMerge::DropCollapsedScales(const std::vector<uint8_t> &fitted_
const size_t mid = fitted.size() / 2;
std::nth_element(fitted.begin(), fitted.begin() + mid, fitted.end());
const double g_typ = fitted[mid];
const double g_median = fitted[mid];
std::vector<int64_t> n_obs(n, 0);
for (int f = 0; f < n; ++f)
if (fitted_mask[f] && std::isfinite(g[f]) && g[f] > 0.0) n_obs[f] = frame_count[f];
const double g_typ = TypicalFrameScale(g, n_obs);
const double g_floor = g_typ * MIN_CREDIBLE_SCALE_RATIO;
int n_dropped = 0;
@@ -4332,12 +4546,12 @@ bool RotationScaleMerge::DropCollapsedScales(const std::vector<uint8_t> &fitted_
apply[f] = 1;
ratio[f] = 0.0; // zero corr = out of the combine, the merge and the error model
worst = std::max(worst, g_typ / g[f]);
g[f] = g_typ; // keep the median in g so this frame cannot drag a smoothing window
g[f] = g_median; // keep the median in g so this frame cannot drag a smoothing window
++n_dropped;
}
if (n_dropped > 0)
logger->Warning("Dropped {} frame(s) whose scale came out more than {:.0f}x below the run median "
"(worst {:.0f}x) - a scale that small says the frame holds no diffraction, and "
logger->Warning("Dropped {} frame(s) whose scale came out more than {:.0f}x below the run's typical "
"frame (worst {:.0f}x) - a scale that small says the frame holds no diffraction, and "
"using it would amplify the frame's intensities, and its sigmas with them, "
"by the same factor",
n_dropped, 1.0 / MIN_CREDIBLE_SCALE_RATIO, worst);