Rotation scaling: penalised per-frame scale of the fulls; fulls-only partials get flux and partiality
Three defects in the per-frame scaling of sparse (small-molecule, weak) rotation sweeps: 1. The fulls' per-frame scale pooled sparse frames by their RAW full count, but in a high-symmetry group with many systematic absences most usable counts stayed under the minimum, so most frames were never fitted and kept corr = 1 beside pinned, fitted frames (two gauges in one reference). The release step then read the gauge offset (a constant 134x on a cubic Ia-3d small-molecule sweep) as signal and gave each frame exp(kept_f * 4.9) - the e^-5 errors on a quarter of the frames, R1 0.62. A fixed box window also cannot follow a 100x absorption ramp over a few degrees, and frames under the credible floor, exempt from the window, ran away to 1e-7. Now each round fits every frame on its own fulls (no pooling, no minimum), and the scale is a penalised second-difference smoother of log G (Whittaker/Eilers), each frame at the information of its fit, lambda by cross-validation over blocks one rocking curve wide (interleaved single frames leak through shared rocking curves and chose to follow every frame). After convergence the existing ShrinkToRestrained hands back the per-frame deviation its neighbour shares. Pooling and the box window are gone from the fulls loop; the partials loop is unchanged. 2. With partial scaling off (< 50 rocking events per frame) the partials kept the integration-time corr: no incident-flux correction and not the partiality of the ingest-smoothed geometry, because only the partial scaling loop rewrote corr. They now get corr = prescaling_corr / partiality at G = 1 (host, and a device kernel). 3. The flux meter (per-frame mean background) jumped 30x between neighbouring frames of a sparse sweep - on a few reflections it measures which reflections the frame holds. It is read through the same smoother at the precision of each frame's mean. SHELXL R1(>4sig) against the published structures, rc174-cand -> this, on the in-house small-molecule sweeps: cubic Ia-3d 0.615 -> 0.119 (XDS 0.088); four organic sweeps (monoclinic / orthorhombic) 0.0515 -> 0.0459, 0.0451 -> 0.0396, 0.0747 -> 0.0709, 0.0452 -> 0.0413; ISa up to 11.6 -> 31. Raw flux instead of smoothed costs 0.002-0.003 R1 on the first two. A weak, decaying protein sweep on the fulls-only path: ISa 6.7 -> 27.1. CPU and GPU paths agree. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01K5K8jvPPbmCrbqnWkddTuB
This commit is contained in:
1 parent
e72236b08d
commit
495f6a97b3
8 files changed
+427
-191
No files matched your search
@@ -52,10 +52,12 @@ namespace {
|
||||
constexpr double SCALING_TOLERANCE = 1e-3;
|
||||
// The per-frame scale is smoothed over at least this many rocking curves (see Run).
|
||||
constexpr int SMOOTH_G_MIN_ROCKING_EVENTS = 6;
|
||||
|
||||
// ShrinkToRestrained reads two variances off the frames of the sweep; on fewer frames than this
|
||||
// neither of them means anything, and the restraint is kept whole.
|
||||
constexpr size_t MIN_FRAMES_FOR_SHRINKAGE = 20;
|
||||
// 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.
|
||||
@@ -205,7 +207,7 @@ namespace {
|
||||
// the loop shrank every scale by 10-30% per round for thirty rounds under the robust fit and
|
||||
// settled in fourteen under the plain one. With the weights the reference uses, the plain
|
||||
// alternating fit is exact coordinate descent on one objective and cannot climb.
|
||||
double SolveScale(const std::vector<ScaleObs> &obs) {
|
||||
double SolveScale(const std::vector<ScaleObs> &obs, double &info) {
|
||||
double num = 0.0, den = 0.0;
|
||||
for (const auto &o : obs) {
|
||||
const double w2 = o.weight * o.weight;
|
||||
@@ -213,6 +215,7 @@ namespace {
|
||||
den += w2 * o.coeff * o.coeff;
|
||||
}
|
||||
const double G = den > 0.0 ? num / den : NAN;
|
||||
info = den;
|
||||
return std::isfinite(G) ? std::max(0.0, G) : 1.0;
|
||||
}
|
||||
|
||||
@@ -280,28 +283,44 @@ RotationScaleMerge::RotationScaleMerge(const DiffractionExperiment &experiment,
|
||||
// here the fitted G takes back out, because smoothing leaves G its low frequencies. Only the fast part -
|
||||
// the part no smoothed per-frame scale can represent anyway - is taken on trust.
|
||||
//
|
||||
// The mean is over the frame's reflections, whose backgrounds differ with where on the detector they
|
||||
// fall, so on a frame of a handful of reflections it measures which reflections the frame holds as
|
||||
// much as the flux: on a sparse small-molecule sweep it jumped thirtyfold between neighbouring frames.
|
||||
// So the meter is read through the same smoothing as the fulls' scale (SmoothLogScale, lambda by
|
||||
// cross-validation), each frame at the precision of its mean: a frame of thousands of reflections
|
||||
// keeps its own reading, a frame of five is carried by its neighbours.
|
||||
//
|
||||
// Neither half of this costs a pass over the observations of its own: the per-frame mean background is
|
||||
// accumulated by the ingest fill loop, which already reads every reflection, and the division into prescaling_corr
|
||||
// rides on the finiteness pass that follows it.
|
||||
void RotationScaleMerge::MeasureIncidentFlux(const std::vector<double> &mean_bkg) {
|
||||
void RotationScaleMerge::MeasureIncidentFlux(const std::vector<double> &mean_bkg,
|
||||
const std::vector<double> &mean_bkg_info) {
|
||||
frame_flux.assign(n_frames, 1.0);
|
||||
|
||||
// log of the mean at the information on it: n mean^2 / var for n background readings. A frame's
|
||||
// reading is its own measurement, so the frames are left out one at a time (block 1).
|
||||
std::vector<double> y(n_frames, 0.0), J(n_frames, 0.0);
|
||||
for (int f = 0; f < n_frames; ++f)
|
||||
if (std::isfinite(mean_bkg[f]) && mean_bkg[f] > 0.0) {
|
||||
y[f] = std::log(mean_bkg[f]);
|
||||
J[f] = mean_bkg_info[f];
|
||||
}
|
||||
const std::vector<double> x = SmoothLogScale(y, J, ChooseLogScaleSmoothing(y, J, 1));
|
||||
|
||||
// Collected in frame order, serially: it is one value per frame, and the median only depends on
|
||||
// the set, but keeping the order removes the question.
|
||||
std::vector<double> finite;
|
||||
finite.reserve(n_frames);
|
||||
for (int f = 0; f < n_frames; ++f)
|
||||
if (std::isfinite(mean_bkg[f])) finite.push_back(mean_bkg[f]);
|
||||
if (std::isfinite(mean_bkg[f])) finite.push_back(x[f]);
|
||||
if (finite.empty())
|
||||
return;
|
||||
|
||||
// Gauge: the run median. Only the frame-to-frame RATIO matters - a constant factor is degenerate
|
||||
// with the overall scale.
|
||||
const size_t mid = finite.size() / 2;
|
||||
std::nth_element(finite.begin(), finite.begin() + mid, finite.end());
|
||||
const double median = finite[mid];
|
||||
const double median = median_of(finite);
|
||||
for (int f = 0; f < n_frames; ++f)
|
||||
if (std::isfinite(mean_bkg[f])) frame_flux[f] = mean_bkg[f] / median;
|
||||
if (std::isfinite(mean_bkg[f])) frame_flux[f] = std::exp(x[f] - median);
|
||||
}
|
||||
|
||||
void RotationScaleMerge::Ingest() {
|
||||
@@ -340,7 +359,7 @@ void RotationScaleMerge::Ingest() {
|
||||
// The per-frame mean background - the incident-flux meter, see MeasureIncidentFlux - is
|
||||
// accumulated here rather than in a pass of its own. One frame is still summed in its own order,
|
||||
// which is what keeps the mean bit-exact.
|
||||
std::vector<double> mean_bkg(n_frames, NAN);
|
||||
std::vector<double> mean_bkg(n_frames, NAN), mean_bkg_info(n_frames, 0.0);
|
||||
|
||||
// The h range comes out of the same sweep - the sort below buckets by h and needs to know how many
|
||||
// buckets that is - and so does the narrow key of every observation. The fat Obs is NOT built here:
|
||||
@@ -355,19 +374,28 @@ void RotationScaleMerge::Ingest() {
|
||||
const auto cell = partials_out[o].latt.GetUnitCell();
|
||||
frame_cell_ok[o] = cell.is_close(*reference_cell, dist_tol, ang_tol) ? 1 : 0;
|
||||
}
|
||||
double bkg_sum = 0.0;
|
||||
double bkg_sum = 0.0, bkg_sum2 = 0.0;
|
||||
int bkg_n = 0;
|
||||
int lmin = INT_HI, lmax = INT_LO;
|
||||
for (const auto &r : partials_out[o].reflections) {
|
||||
if (std::isfinite(r.bkg) && r.bkg > 0.0f) { bkg_sum += r.bkg; ++bkg_n; }
|
||||
if (std::isfinite(r.bkg) && r.bkg > 0.0f) {
|
||||
bkg_sum += r.bkg;
|
||||
bkg_sum2 += static_cast<double>(r.bkg) * r.bkg;
|
||||
++bkg_n;
|
||||
}
|
||||
lmin = std::min(lmin, r.h);
|
||||
lmax = std::max(lmax, r.h);
|
||||
}
|
||||
if (bkg_n > 0) mean_bkg[o] = bkg_sum / bkg_n;
|
||||
if (bkg_n > 0) {
|
||||
const double mean = bkg_sum / bkg_n;
|
||||
const double var = bkg_sum2 / bkg_n - mean * mean;
|
||||
mean_bkg[o] = mean;
|
||||
if (bkg_n > 1 && var > 0.0) mean_bkg_info[o] = bkg_n * mean * mean / var;
|
||||
}
|
||||
h_lo[o] = lmin; h_hi[o] = lmax;
|
||||
});
|
||||
|
||||
MeasureIncidentFlux(mean_bkg);
|
||||
MeasureIncidentFlux(mean_bkg, mean_bkg_info);
|
||||
|
||||
int h_min = 0, h_max = 0;
|
||||
{
|
||||
@@ -1417,16 +1445,69 @@ void RotationScaleMerge::ReduceScalingGroupMeans(int n_groups, const std::vector
|
||||
});
|
||||
}
|
||||
|
||||
int RotationScaleMerge::PoolHalfWidth(const std::vector<int32_t> &fcount, int f) {
|
||||
const int n = static_cast<int>(fcount.size());
|
||||
int64_t total = fcount[f];
|
||||
int h = 0;
|
||||
while (total < static_cast<int64_t>(MIN_REFLECTIONS) && h < n) {
|
||||
++h;
|
||||
if (f - h >= 0) total += fcount[f - h];
|
||||
if (f + h < n) total += fcount[f + h];
|
||||
std::vector<double> RotationScaleMerge::SmoothLogScale(const std::vector<double> &y, const std::vector<double> &J,
|
||||
double lambda) {
|
||||
// Following Eilers (2003) Anal. Chem. 75, 3631-3636 (Whittaker's smoother).
|
||||
// The normal equations (diag(J) + lambda D2'D2) x = J y, D2 the second-difference operator: a
|
||||
// symmetric band of half-width two, solved by its Cholesky factor in one pass down and one up.
|
||||
// A curve with no second difference (a straight line in log scale) costs nothing, so two frames
|
||||
// with information are enough to make the system definite.
|
||||
const int n = static_cast<int>(y.size());
|
||||
if (std::count_if(J.begin(), J.end(), [](double j) { return j > 0.0; }) < 2)
|
||||
return y;
|
||||
std::vector<double> a0(J), a1(n, 0.0), a2(n, 0.0); // diagonal, first and second off-diagonal
|
||||
for (int i = 0; i + 2 < n; ++i) {
|
||||
a0[i] += lambda; a0[i + 1] += 4.0 * lambda; a0[i + 2] += lambda;
|
||||
a1[i] -= 2.0 * lambda; a1[i + 1] -= 2.0 * lambda;
|
||||
a2[i] += lambda;
|
||||
}
|
||||
return h;
|
||||
std::vector<double> l0(n), l1(n, 0.0), l2(n, 0.0), z(n), x(n);
|
||||
for (int j = 0; j < n; ++j) {
|
||||
const double p1 = j >= 1 ? l1[j - 1] : 0.0, p2 = j >= 2 ? l2[j - 2] : 0.0;
|
||||
l0[j] = std::sqrt(a0[j] - p1 * p1 - p2 * p2);
|
||||
if (j + 1 < n) l1[j] = (a1[j] - (j >= 1 ? l2[j - 1] * l1[j - 1] : 0.0)) / l0[j];
|
||||
if (j + 2 < n) l2[j] = a2[j] / l0[j];
|
||||
}
|
||||
for (int j = 0; j < n; ++j)
|
||||
z[j] = (J[j] * y[j] - (j >= 1 ? l1[j - 1] * z[j - 1] : 0.0) - (j >= 2 ? l2[j - 2] * z[j - 2] : 0.0)) / l0[j];
|
||||
for (int j = n - 1; j >= 0; --j)
|
||||
x[j] = (z[j] - (j + 1 < n ? l1[j] * x[j + 1] : 0.0) - (j + 2 < n ? l2[j] * x[j + 2] : 0.0)) / l0[j];
|
||||
return x;
|
||||
}
|
||||
|
||||
double RotationScaleMerge::ChooseLogScaleSmoothing(const std::vector<double> &y, const std::vector<double> &J,
|
||||
int block) {
|
||||
// Blocks of `block` frames are left out in turn, every fifth block, and predicted from the curve
|
||||
// through the others; the lambda whose curve predicts them best (each frame at its own
|
||||
// information) is the one the data ask for. The grid runs in half decades from a curve that
|
||||
// follows every frame (lambda = J/100: a frame's neighbours barely pull on it) to one that is
|
||||
// straight over hundreds of frames.
|
||||
std::vector<double> positive;
|
||||
for (double j : J)
|
||||
if (j > 0.0) positive.push_back(j);
|
||||
if (positive.size() < 2 * CV_FOLDS)
|
||||
return 0.0;
|
||||
auto fold_of = [&](int f) { return (f / block) % CV_FOLDS; };
|
||||
const double j_typ = median_of(positive);
|
||||
const int n = static_cast<int>(y.size());
|
||||
double best_lambda = 0.0, best_err = INFINITY;
|
||||
for (int k = -4; k <= 20; ++k) {
|
||||
const double lambda = j_typ * std::pow(10.0, 0.5 * k);
|
||||
double err = 0.0;
|
||||
for (int fold = 0; fold < CV_FOLDS; ++fold) {
|
||||
std::vector<double> J_train(J);
|
||||
for (int f = 0; f < n; ++f)
|
||||
if (fold_of(f) == fold) J_train[f] = 0.0;
|
||||
const std::vector<double> x = SmoothLogScale(y, J_train, lambda);
|
||||
for (int f = 0; f < n; ++f)
|
||||
if (fold_of(f) == fold) err += J[f] * (x[f] - y[f]) * (x[f] - y[f]);
|
||||
}
|
||||
if (err < best_err) {
|
||||
best_err = err;
|
||||
best_lambda = lambda;
|
||||
}
|
||||
}
|
||||
return best_lambda;
|
||||
}
|
||||
|
||||
template <class O>
|
||||
@@ -1435,16 +1516,11 @@ void RotationScaleMerge::FitPerFrameG(const std::vector<O> &obs, const std::vect
|
||||
const std::vector<double> &group_mean_in,
|
||||
bool unity, std::vector<double> &g) {
|
||||
std::vector<uint8_t> scaled(fstart.size(), 0);
|
||||
std::vector<double> info(fstart.size(), 0.0);
|
||||
const int n_fr = static_cast<int>(fstart.size());
|
||||
ParallelFor(n_fr, nthreads, [&](int f) {
|
||||
// A full is a whole rocking event filed under one frame, so on a sparse sweep a frame holds a
|
||||
// handful of them - too few to fit a scale on, and the frame was left unscaled, which on such a
|
||||
// sweep was every frame. Those frames are fitted over the nearest frames on either side that
|
||||
// together hold enough; a frame with enough of its own is fitted on its own, as before.
|
||||
const int h = unity && pool_sparse_fulls ? PoolHalfWidth(fcount, f) : 0;
|
||||
std::vector<ScaleObs> so;
|
||||
for (int j = std::max(0, f - h); j <= std::min(n_fr - 1, f + h); ++j)
|
||||
for (int i = fstart[j]; i < fstart[j] + fcount[j]; ++i) {
|
||||
for (int i = fstart[f]; i < fstart[f] + fcount[f]; ++i) {
|
||||
const auto &o = obs[i];
|
||||
if (o.group < 0) continue;
|
||||
if (o.on_ice) continue;
|
||||
@@ -1471,27 +1547,17 @@ void RotationScaleMerge::FitPerFrameG(const std::vector<O> &obs, const std::vect
|
||||
}
|
||||
so.push_back({coeff, static_cast<double>(o.I), SafeInv(o.sigma, 1.0)});
|
||||
}
|
||||
if (so.size() < MIN_REFLECTIONS) return; // leave g[f]/corr untouched (as ScaleOnTheFly does)
|
||||
g[f] = SolveScale(so);
|
||||
// A partial frame needs MIN_REFLECTIONS of its own (corr is left untouched otherwise, as
|
||||
// ScaleOnTheFly does). A full is a whole rocking event filed under one frame, so on a sparse
|
||||
// sweep a frame holds a handful; its fit goes in at the information it has, and the smoothing
|
||||
// in RunFullsScalingLoop decides how far its neighbours carry it.
|
||||
if (so.empty() || (!unity && so.size() < MIN_REFLECTIONS)) return;
|
||||
g[f] = SolveScale(so, info[f]);
|
||||
scaled[f] = 1;
|
||||
});
|
||||
// Remember which frames were fitted this call (so the caller updates corr only there).
|
||||
frame_scaled_scratch = std::move(scaled);
|
||||
}
|
||||
|
||||
void RotationScaleMerge::UpdateCorr(std::vector<Obs> &obs, const std::vector<double> &g,
|
||||
const std::vector<uint8_t> &frame_scaled) const {
|
||||
ParallelChunks(static_cast<int>(obs.size()), nthreads, [&](int lo, int hi) {
|
||||
for (int i = lo; i < hi; ++i) {
|
||||
auto &o = obs[i];
|
||||
if (!frame_scaled[o.frame]) continue;
|
||||
const double denom = static_cast<double>(o.partiality) * g[o.frame]; // B_term = 1 (no B refine)
|
||||
if (std::isfinite(o.prescaling_corr) && std::isfinite(denom) && denom > 0.0)
|
||||
o.corr = static_cast<float>(o.prescaling_corr / denom);
|
||||
else
|
||||
o.corr = NAN;
|
||||
}
|
||||
});
|
||||
frame_info_scratch = std::move(info);
|
||||
}
|
||||
|
||||
void RotationScaleMerge::ShrinkToRestrained(const char *what, const std::vector<double> &g_restrained,
|
||||
@@ -1573,7 +1639,6 @@ void RotationScaleMerge::ShrinkToRestrained(const char *what, const std::vector<
|
||||
|
||||
RotationScaleMerge::ScalingLoopOutcome RotationScaleMerge::RunScalingLoop(
|
||||
const char *what, std::vector<double> &g, const std::vector<int32_t> &frame_obs_count, int window,
|
||||
bool release_restraint,
|
||||
const std::function<void()> &iterate,
|
||||
const std::function<void(const std::vector<uint8_t> &, const std::vector<double> &)> &rescale) {
|
||||
// Alternating least squares on a bilinear model: the reference intensities given the scales, the
|
||||
@@ -1597,14 +1662,9 @@ RotationScaleMerge::ScalingLoopOutcome RotationScaleMerge::RunScalingLoop(
|
||||
// mean, so no frame can lose its vote alone, and what a frame's own observations cannot determine
|
||||
// its neighbourhood's do. The post-loop smoothing is then this same operation and is not repeated.
|
||||
//
|
||||
// The restraint is a prior, though, not a measurement, and on a merge where a frame carries
|
||||
// hundreds of observations the frame's own data outvote it. So a loop that is asked to
|
||||
// (release_restraint) ends with ONE free fit against the settled reference, shrunk frame by
|
||||
// frame toward the restrained scale by how much of the difference is real - see
|
||||
// ShrinkToRestrained. Only the loop over the fulls is asked to: a partial's scale is the
|
||||
// direction the collapse runs in, and handing any of it back re-opens it (measured: ISa 23.8 ->
|
||||
// 22.1 on a 360 deg, 14x merge), while a full is a whole rocking event and cannot enter it. And
|
||||
// only off a loop that settled, since a loop still walking has measured nothing to hand back.
|
||||
// The restraint is never released here: a partial's scale is the direction the collapse runs in,
|
||||
// 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 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
|
||||
@@ -1684,27 +1744,12 @@ RotationScaleMerge::ScalingLoopOutcome RotationScaleMerge::RunScalingLoop(
|
||||
g_prev = g;
|
||||
}
|
||||
frame_scaled_scratch = scaled_any;
|
||||
// Only off a settled loop: the deviation below is a measurement of the frames, and a loop that
|
||||
// walked until it was stopped has not measured them.
|
||||
if (release_restraint && window > 1 && out.converged) {
|
||||
const std::vector<double> g_restrained = g;
|
||||
iterate(); // one free fit against the settled reference
|
||||
for (int f = 0; f < n_frames; ++f)
|
||||
scaled_any[f] |= frame_scaled_scratch[f];
|
||||
const std::vector<double> g_free = g;
|
||||
ShrinkToRestrained(what, g_restrained, scaled_any, frame_obs_count, g);
|
||||
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);
|
||||
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; }
|
||||
ratio[f] = g_free[f];
|
||||
g[f] /= g_ref;
|
||||
ratio[f] /= g[f];
|
||||
}
|
||||
rescale(scaled_any, ratio);
|
||||
frame_scaled_scratch = scaled_any;
|
||||
}
|
||||
out.best_step = best_step;
|
||||
LogScalingOutcome(what, out);
|
||||
return out;
|
||||
}
|
||||
|
||||
void RotationScaleMerge::LogScalingOutcome(const char *what, const ScalingLoopOutcome &out) const {
|
||||
if (out.converged)
|
||||
logger.Info("Per-frame scaling ({}): settled after {} iterations (rms |dlogG| {:.1e})", what,
|
||||
out.iterations, out.step);
|
||||
@@ -1712,12 +1757,121 @@ RotationScaleMerge::ScalingLoopOutcome RotationScaleMerge::RunScalingLoop(
|
||||
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, best_step);
|
||||
out.iterations, out.step, 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);
|
||||
}
|
||||
|
||||
RotationScaleMerge::ScalingLoopOutcome RotationScaleMerge::RunFullsScalingLoop(
|
||||
std::vector<double> &g, std::vector<double> &g_fit, const std::vector<int32_t> &frame_obs_count,
|
||||
const std::function<void()> &fit,
|
||||
const std::function<void(const std::vector<uint8_t> &, const std::vector<double> &)> &rescale) {
|
||||
// A full is a whole rocking event, so its frame's scale is free of the partiality model, and how
|
||||
// smooth that scale is over the rotation is left to the data rather than fixed in advance. Each
|
||||
// round fits every frame on its own fulls against the current reference, and the scale is then
|
||||
// the curve in log G that stays closest to those fits, each at its information, while bending as
|
||||
// little as possible (SmoothLogScale) - with how little chosen by how well the curve predicts
|
||||
// frames it was not fitted to (ChooseLogScaleSmoothing). A frame of hundreds of fulls is then
|
||||
// followed frame by frame, a frame of two or three is carried by its neighbours, a stretch with
|
||||
// none is bridged, and a scale that falls by a hundred over a few degrees - an absorbing crystal
|
||||
// turning edge-on - is followed where a fixed window would average across it.
|
||||
//
|
||||
// In log G about the scale s the fulls stand at, a frame's fit G says y = log s + log(G/s) at
|
||||
// information s^2 sum w^2 c^2 (the fit's information on G, carried to log G at s). A fit at or
|
||||
// below zero - a frame whose fulls hold nothing the reference expects - moves its frame one e-fold
|
||||
// down per round and no further, so that a frame the crystal stopped diffracting on walks toward
|
||||
// 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.
|
||||
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);
|
||||
std::vector<uint8_t> has_fulls(n_frames);
|
||||
for (int f = 0; f < n_frames; ++f) {
|
||||
n_obs[f] = frame_obs_count[f];
|
||||
has_fulls[f] = frame_obs_count[f] > 0 ? 1 : 0;
|
||||
}
|
||||
double best_step = INFINITY, lambda = 0.0;
|
||||
int rounds_since_best = 0;
|
||||
for (int it = 0; it < scaling_iter; ++it) {
|
||||
fit();
|
||||
out.iterations = it + 1;
|
||||
for (int f = 0; f < n_frames; ++f) {
|
||||
const bool fitted = frame_scaled_scratch[f] && frame_info_scratch[f] > 0.0;
|
||||
J[f] = fitted ? frame_info_scratch[f] * g[f] * g[f] : 0.0;
|
||||
y[f] = std::log(g[f]);
|
||||
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));
|
||||
const std::vector<double> x = SmoothLogScale(y, J, lambda);
|
||||
for (int f = 0; f < n_frames; ++f)
|
||||
g_new[f] = std::exp(x[f]);
|
||||
const double g_ref = TypicalFrameScale(g_new, n_obs);
|
||||
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)
|
||||
if (has_fulls[f] && g_new[f] >= g_floor) {
|
||||
const double d = std::log(g_new[f] / g[f]);
|
||||
ss += frame_obs_count[f] * d * d;
|
||||
sw += frame_obs_count[f];
|
||||
}
|
||||
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);
|
||||
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) {
|
||||
out.stalled = true;
|
||||
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) -
|
||||
// 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;
|
||||
}
|
||||
frame_scaled_scratch = has_fulls;
|
||||
out.best_step = best_step;
|
||||
std::vector<double> positive;
|
||||
for (double j : J)
|
||||
if (j > 0.0) positive.push_back(j);
|
||||
if (!positive.empty() && lambda > 0.0)
|
||||
logger.Info("Per-frame scaling (fulls): smoothness chosen by cross-validation over the frames - "
|
||||
"a frame's scale is carried over about {:.0f} frames", std::pow(lambda / median_of(positive), 0.25));
|
||||
LogScalingOutcome("fulls", out);
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -5660,7 +5814,6 @@ RotationScaleMerge::Result RotationScaleMerge::Run(bool for_search, bool full_st
|
||||
rocking_event_frames_at_start = RockingEventFrames(&rocking_events_at_start);
|
||||
const double events_per_frame = n_frames > 0 ? static_cast<double>(rocking_events_at_start) / n_frames : 0.0;
|
||||
const bool scale_partials = events_per_frame >= MIN_EVENTS_PER_FRAME_SCALE_PARTIALS;
|
||||
pool_sparse_fulls = !scale_partials;
|
||||
if (!scale_partials)
|
||||
logger.Info("Per-frame scale from the fulls alone: {:.1f} rocking events per frame, under the {:.0f} "
|
||||
"a partial's scale needs to stay apart from the partiality model", events_per_frame,
|
||||
@@ -5676,7 +5829,7 @@ RotationScaleMerge::Result RotationScaleMerge::Run(bool for_search, bool full_st
|
||||
std::vector<double> g_dev(n_frames);
|
||||
std::vector<uint8_t> scaled_dev(n_frames);
|
||||
partial_loop = RunScalingLoop("partials", g_partial, frame_count, smooth_window,
|
||||
/*release_restraint=*/false, [&] {
|
||||
[&] {
|
||||
gpu_->ScalePartials(1, min_partiality, d_min_limit.has_value());
|
||||
gpu_->GetG(g_dev.data(), scaled_dev.data());
|
||||
for (int f = 0; f < n_frames; ++f)
|
||||
@@ -5689,9 +5842,28 @@ RotationScaleMerge::Result RotationScaleMerge::Run(bool for_search, bool full_st
|
||||
}
|
||||
#endif
|
||||
if (!scale_partials) {
|
||||
// corr as the partial scaling would leave it at G = 1: the deterministic corrections, the
|
||||
// incident flux and the partiality of the smoothed geometry.
|
||||
std::fill(g_partial.begin(), g_partial.end(), 1.0);
|
||||
frame_scaled_scratch.assign(n_frames, 1);
|
||||
partial_loop.converged = true;
|
||||
bool unit_on_gpu = false;
|
||||
#ifdef JFJOCH_USE_CUDA
|
||||
if (gpu_active_) {
|
||||
gpu_->SetUnitPartialScale();
|
||||
unit_on_gpu = true;
|
||||
}
|
||||
#endif
|
||||
if (!unit_on_gpu)
|
||||
ParallelChunks(static_cast<int>(partials.size()), ThreadsForWork(partials.size(), nthreads),
|
||||
[&](int lo, int hi) {
|
||||
for (int i = lo; i < hi; ++i) {
|
||||
Obs &o = partials[i];
|
||||
const double denom = static_cast<double>(o.partiality);
|
||||
o.corr = std::isfinite(o.prescaling_corr) && std::isfinite(denom) && denom > 0.0
|
||||
? static_cast<float>(o.prescaling_corr / denom) : NAN;
|
||||
}
|
||||
});
|
||||
} else if (!scaled_on_gpu) {
|
||||
const PartialLoopKey key{x.GetSpaceGroupOrP1().xhm(), merge_friedel, d_min_limit, d_max_limit,
|
||||
min_partiality, smooth_window, scaling_iter};
|
||||
@@ -5740,7 +5912,7 @@ RotationScaleMerge::Result RotationScaleMerge::Run(bool for_search, bool full_st
|
||||
std::vector<double> g_fitted;
|
||||
std::vector<uint8_t> frame_fitted;
|
||||
partial_loop = RunScalingLoop("partials", g_partial, frame_count, smooth_window,
|
||||
/*release_restraint=*/false, [&] {
|
||||
[&] {
|
||||
ReduceScalingGroupMeans(n_groups, scaling_refs, scaling_corr, partial_mean);
|
||||
FitPerFrameG(scaling_obs, frame_start, frame_count, partial_mean, /*unity=*/false, g_partial);
|
||||
g_fitted = g_partial;
|
||||
@@ -5978,15 +6150,14 @@ RotationScaleMerge::Result RotationScaleMerge::Run(bool for_search, bool full_st
|
||||
|
||||
gpu_->ResetFullsScale();
|
||||
if (static_cast<int>(g_full.size()) != n_frames) g_full.assign(n_frames, 1.0);
|
||||
std::vector<double> g_dev(n_frames);
|
||||
std::vector<double> g_fit(n_frames), info(n_frames);
|
||||
std::vector<uint8_t> scaled_dev(n_frames);
|
||||
fulls_loop = RunScalingLoop("fulls", g_full, f_count, smooth_window,
|
||||
/*release_restraint=*/true, [&] {
|
||||
gpu_->ScaleFulls(1, min_partiality, pool_sparse_fulls);
|
||||
gpu_->GetG(g_dev.data(), scaled_dev.data());
|
||||
for (int f = 0; f < n_frames; ++f)
|
||||
if (scaled_dev[f]) g_full[f] = g_dev[f];
|
||||
fulls_loop = RunFullsScalingLoop(g_full, g_fit, f_count, [&] {
|
||||
gpu_->FitFullsScale(min_partiality);
|
||||
gpu_->GetG(g_fit.data(), scaled_dev.data());
|
||||
gpu_->GetInfo(info.data());
|
||||
frame_scaled_scratch = scaled_dev;
|
||||
frame_info_scratch = info;
|
||||
}, [&](const std::vector<uint8_t> &apply, const std::vector<double> &ratio) {
|
||||
gpu_->SmoothFullsCorr(apply.data(), ratio.data());
|
||||
});
|
||||
@@ -6041,12 +6212,10 @@ RotationScaleMerge::Result RotationScaleMerge::Run(bool for_search, bool full_st
|
||||
|
||||
// --- 4. Scale the fulls (XDS order, Unity model). ---
|
||||
if (scale_fulls && !scaled_fulls_on_gpu) {
|
||||
std::vector<double> full_mean;
|
||||
fulls_loop = RunScalingLoop("fulls", g_full, fulls_frame_count, smooth_window,
|
||||
/*release_restraint=*/true, [&] {
|
||||
std::vector<double> full_mean, g_fit(n_frames);
|
||||
fulls_loop = RunFullsScalingLoop(g_full, g_fit, fulls_frame_count, [&] {
|
||||
ReduceGroupMeans(fulls, n_groups, full_mean);
|
||||
FitPerFrameG(fulls, fulls_frame_start, fulls_frame_count, full_mean, /*unity=*/true, g_full);
|
||||
UpdateCorr(fulls, g_full, frame_scaled_scratch);
|
||||
FitPerFrameG(fulls, fulls_frame_start, fulls_frame_count, full_mean, /*unity=*/true, g_fit);
|
||||
}, [&](const std::vector<uint8_t> &apply, const std::vector<double> &ratio) {
|
||||
for (auto &o : fulls)
|
||||
if (apply[o.frame] && std::isfinite(o.corr))
|
||||
|
||||
Reference in new issue
Block a user