diff --git a/rugnux/Rugnux.cpp b/rugnux/Rugnux.cpp index 945ec8fed..79ad0f48a 100644 --- a/rugnux/Rugnux.cpp +++ b/rugnux/Rugnux.cpp @@ -476,7 +476,7 @@ void Rugnux::CollectSpeculativeProbe() { speculative_probe_.reset(); } -std::vector Rugnux::ExperimentKey() const { +std::vector Rugnux::ExperimentKey(bool rotation_angles) const { std::vector k{experiment_.GetBeamX_pxl(), experiment_.GetBeamY_pxl(), experiment_.GetDetectorDistance_mm(), experiment_.GetPoniRot1_rad(), experiment_.GetPoniRot2_rad(), experiment_.GetWavelength_A(), @@ -484,8 +484,10 @@ std::vector Rugnux::ExperimentKey() const { if (const auto g = experiment_.GetGoniometer()) { const Coord a = g->GetAxis(); const auto helical = g->GetHelicalStep().value_or(Coord(-1, -1, -1)); - k.insert(k.end(), {1.0, a.x, a.y, a.z, g->GetStart_deg(), g->GetIncrement_deg(), g->GetWedge_deg(), - g->GetScreeningWedge().value_or(-1.0f), helical.x, helical.y, helical.z}); + k.insert(k.end(), {1.0, a.x, a.y, a.z, helical.x, helical.y, helical.z}); + if (rotation_angles) + k.insert(k.end(), {g->GetStart_deg(), g->GetIncrement_deg(), g->GetWedge_deg(), + g->GetScreeningWedge().value_or(-1.0f)}); } else k.push_back(0.0); if (const auto uc = experiment_.GetUnitCell()) @@ -511,7 +513,10 @@ std::vector Rugnux::ExperimentKey() const { } std::vector Rugnux::SpotFindingKey(const AzimuthalIntegrationMapping &mapping) const { - std::vector k = ExperimentKey(); + // Without the rotation angles: a frame's spots are found the same under any of them, and the angle + // each spot carries is stamped again where a list is taken from the store (prefetch_spots). The + // probes of the rotation-scale walk differ only there, so they find the spots of a frame once. + std::vector k = ExperimentKey(/*rotation_angles=*/false); const auto &f = config_.spot_finding; k.insert(k.end(), {static_cast(f.enable), f.low_resolution_limit.value_or(-1.0f), f.cutoff_spot_count_low_res, f.high_res_gap_Q_recipA.value_or(-1.0f), @@ -858,6 +863,9 @@ ProcessResult Rugnux::RunPipeline(RugnuxObserver *observer, bool write_output, b if (FirstPassRotationIndexing(p)) return result; } + // The rotation-scale walk beside this pass starts once its frames are indexed (see RunAllPasses). + if (rotation_scale_check_) + rotation_scale_check_->Set(rotation_scale_check_->output_indexed); // Whether the lattice this pass integrates on has an index-2 superstructure. Nothing before // integration can ask it: every count the lattice decisions use is dominated by the sub-lattice's diff --git a/rugnux/Rugnux.h b/rugnux/Rugnux.h index d9c261f95..eff26a3e7 100644 --- a/rugnux/Rugnux.h +++ b/rugnux/Rugnux.h @@ -5,6 +5,7 @@ #include #include +#include #include #include #include @@ -595,9 +596,13 @@ class Rugnux { // side (see RunAllPasses), so cancelling the run cancels those too. class CancelFlag { std::shared_ptr> flag = std::make_shared>(false); + // The run's flag, on a copy whose work can be called off by itself (Own). + std::shared_ptr> run; public: - operator bool() const { return flag->load(); } + operator bool() const { return flag->load() || (run && run->load()); } CancelFlag &operator=(bool v) { flag->store(v); return *this; } + // A flag of its own that cancelling the run still sets. + CancelFlag Own() const { CancelFlag f; f.run = flag; return f; } }; CancelFlag cancelled_; @@ -802,8 +807,9 @@ class Rugnux { void StartSpeculativeGeometryProbe(std::shared_ptr run, const std::array &geometry); void CollectSpeculativeProbe(); [[nodiscard]] std::vector FirstPassInputKey() const; - // The part of FirstPassInputKey that is the experiment and the spot-finding settings. - [[nodiscard]] std::vector ExperimentKey() const; + // The part of FirstPassInputKey that is the experiment and the spot-finding settings; without the + // goniometer's angles where rotation_angles is false (SpotFindingKey). + [[nodiscard]] std::vector ExperimentKey(bool rotation_angles = true) const; // The file's detector distance, from before the first pass of the rotation two-pass: a pass whose // distance is still this one asks the post-refinement to test "the header distance is right" // (PostRefineSettings::distance_at_header); a pass that has walked off it does not. @@ -860,6 +866,57 @@ class Rugnux { // Every pass of the run, returning the canonical one. Run() wraps this to time the whole thing. ProcessResult RunAllPasses(RugnuxObserver *observer); + // The rotation-scale walk of the rotation two-pass and the refined passes after it run side by side + // (see RunAllPasses): the walk on the run, the refined passes on a copy of it, at the stored angles. + // What the two share. + struct RotationScaleCheck { + std::mutex m; + std::condition_variable cv; + bool output_indexed = false; // the output pass has indexed: the walk can start + bool output_ended = false; // the refined passes have returned + bool called_off = false; // the walk has called them off + bool done = false; // the walk has ended + bool overturns = false; // the refined passes did not start where the walk leaves the run + int passes = 0; // the probe passes the walk ran + std::string text; // its trail, for the pass decision + void Set(bool &flag) { + { std::lock_guard lock(m); flag = true; } + cv.notify_all(); + } + void Wait(const bool &flag) { + std::unique_lock lock(m); + cv.wait(lock, [&] { return flag; }); + } + // Whether the refined passes are to be thrown away, once the walk has ended or called them off. + bool Overturns() { + std::unique_lock lock(m); + cv.wait(lock, [&] { return done || called_off; }); + return overturns || called_off; + } + }; + // Set on the copy that runs the refined passes beside the walk. + std::shared_ptr rotation_scale_check_; + // The walk's part of the canonical pass's record: the probe passes it ran and its trail. + struct RotationScaleOutcome { + int passes = 0; + std::string text; + }; + // What the refined passes start from. + struct RefinedPassStart { + std::string base_prefix; + std::optional gonio_snapshot; + std::array header_geometry{}; + RotationScaleOutcome scale_walk; // where the walk has ended before they start + }; + // The refined passes of the rotation two-pass, from the second pass on. Empty where they ran beside + // the rotation-scale walk and it overturned them. + std::optional RefinedPasses(RugnuxObserver *observer, ProcessResult pass1, + const RefinedPassStart &start); + // The rotation-scale walk, run on the run while the refined passes run on a copy of it; `check` is + // what the two share, and output_cancel calls the copy off. + RotationScaleWalk WalkRotationScaleBeside(const ProcessResult &pass1, RotationScaleCheck &check, + CancelFlag output_cancel); + public: Rugnux(JFJochReader &reader, DiffractionExperiment experiment, PixelMask pixel_mask, ProcessConfig config); diff --git a/rugnux/RugnuxFirstPass.cpp b/rugnux/RugnuxFirstPass.cpp index 7d1048a31..3cbd61e8b 100644 --- a/rugnux/RugnuxFirstPass.cpp +++ b/rugnux/RugnuxFirstPass.cpp @@ -105,6 +105,15 @@ namespace { return true; } + // The spindle angle each spot of a list carries, stamped as DiffractionSpot::Export stamps it. It + // is the only part of a frame's spot list that depends on the goniometer, so a list found under + // other angles (see SpotFindingKey) is stamped again for the angles in hand. + void StampSpotAngles(std::vector &spots, const DiffractionGeometry &geometry) { + const auto rotation = geometry.GetRotation(); + for (auto &s : spots) + s.phi = rotation ? rotation->GetAngle_deg(s.image) + rotation->GetWedge_deg() / 2.0f : 0.0f; + } + // === Is the larger of two integer-related cells real, or a spurious axis multiple? === // // The validation-FRAME count cannot answer it: a spurious multiple indexes every frame its true @@ -294,7 +303,7 @@ bool Rugnux::FirstPassRotationIndexing(PipelineLocals &p) { double prefetch_time_s = 0.0; const auto prefetch_spots = [&](const std::vector &ordinals) { // What an earlier pass already found under the same key (first_pass_spots_) is taken from - // there. + // there, at this pass's angles. const std::vector key = SpotFindingKey(*spot_mapping); std::map> kept; { @@ -305,6 +314,9 @@ bool Rugnux::FirstPassRotationIndexing(PipelineLocals &p) { if (const auto it = spots.find(ordinal); it != spots.end()) kept.emplace(ordinal, it->second); } + const DiffractionGeometry spot_geometry = experiment_.GetDiffractionGeometry(); + for (auto &[ordinal, spots] : kept) + StampSpotAngles(spots, spot_geometry); std::vector wanted; for (const int ordinal : ordinals) if (!spot_cache.contains(ordinal)) { diff --git a/rugnux/RugnuxPasses.cpp b/rugnux/RugnuxPasses.cpp index 2bcd46a4c..ad420551e 100644 --- a/rugnux/RugnuxPasses.cpp +++ b/rugnux/RugnuxPasses.cpp @@ -532,9 +532,7 @@ ProcessResult Rugnux::RunAllPasses(RugnuxObserver *observer) { experiment_.BeamX_pxl(g[0]).BeamY_pxl(g[1]).DetectorDistance_mm(g[2]) .PoniRot1_rad(g[3]).PoniRot2_rad(g[4]); } - // The probe passes below and the lattice arms after them exist ONLY to measure - see there - so - // the count of passes the run made has to include them even though they write nothing. - int arm_passes = 0; + RefinedPassStart start{base_prefix, gonio_snapshot, header_geometry, {}}; // The goniometer rotation scale: the angles in the file are the commanded ones, so a stage that // turned at the wrong rate is a geometry error like any other - but one pass 1's fit reads only @@ -546,96 +544,49 @@ ProcessResult Rugnux::RunAllPasses(RugnuxObserver *observer) { // post-refinement has measured - and they leave nothing behind: the experiment, the geometry // the second pass is to run at and pass 1's mosaicity (a width in degrees fitted against the // stored angles) are put back when the walk ends. - std::string rotation_scale_walk; + // + // The walk runs BESIDE the output pass, not before it. It adopts a scale other than the stored + // one only rarely, so the refined passes start at once at the stored angles, on a copy of the + // run as the walk finds it, while the walk runs on the run itself. Where the walk adopts a + // scale, or leaves the run changed behind it, the copy's passes are thrown away and run again on + // the run itself - which the walk has then left exactly where the sequential walk would have. + // The walk starts once the output pass has indexed: its probe at the stored angles is that same + // first pass, which it then finds done, and its probe at the fit finds no frame's spots again + // (SpotFindingKey). The output pass waits for the walk only where it would act on the answer - + // before it writes - and a refit, which integrates and only follows a move off the stored + // angles, first calls the output pass off and waits for it to end, so two integrations never + // share the card. if (!cancelled_ && gonio_snapshot && pass1.post_refine && !config_.rotation_scale) { - step("Rotation-scale check"); - const DiffractionExperiment before_walk = experiment_; - const auto geometry_before_walk = prepass_detector_geometry_; - const auto mosaicity_before_walk = prepass_mosaicity_; - // A probe pass at scale k, run on r - this run, or a copy of it (see below). - const auto probe_on = [&](Rugnux &r, RugnuxObserver *obs, float k, bool index_only) { - r.experiment_ = before_walk; - r.experiment_.Goniometer(ScaleRotation(*before_walk.GetGoniometer(), k)); - r.prepass_rotation_scale_ = k; - r.prepass_mosaicity_.clear(); - r.indexing_probe_only_ = index_only; - r.postrefine_probe_ = r.postrefine_probe_only_ = !index_only; - ProcessResult res; - try { - res = r.RunPipeline(obs, /*write_output=*/false, /*geometry_prepass=*/false); - } catch (const std::exception &e) { - if (IsFatalResourceError(e)) throw; - // Angles under which nothing indexes have scored nothing, which is what an empty - // result reads as. - logger.Info("Rotation scale {:.5f}: the probe pass did not complete ({})", k, e.what()); - } - r.indexing_probe_only_ = r.postrefine_probe_ = r.postrefine_probe_only_ = false; - return res; - }; - const auto probe = [&](float k, bool index_only) { - ++arm_passes; - return probe_on(*this, observer, k, index_only); - }; - // The walk always indexes at the stored angles first and at the pass-1 fit next (see - // WalkRotationScale). Both are known now and each is its own pass, so the one at the fit - // runs at the same time, on a copy of the run as it stands before either. What a probe - // leaves behind for the next pass - the spot-finding settings a first-pass ladder rung - // adopts; the experiment is put back by the probe itself - is checked when the fit's turn - // comes: if the probe at the stored angles changed it, the copy started from a state the - // sequential walk would not have, and the probe is run again here. - const float first_fit = static_cast(pass1.post_refine->rotation_scale); - std::shared_ptr fit_copy; - std::future at_fit; - const SpotFindingSettings walk_start_spot_finding = config_.spot_finding; - if (first_fit != 1.0f && !cancelled_) { - fit_copy = std::make_shared(*this); - at_fit = std::async(std::launch::async, [&probe_on, fit_copy, first_fit] { - return probe_on(*fit_copy, nullptr, first_fit, true); - }); + const auto check = std::make_shared(); + const auto output = std::make_shared(*this); + output->rotation_scale_check_ = check; + output->cancelled_ = cancelled_.Own(); + CancelFlag output_cancel = output->cancelled_; + std::future walk_done = std::async(std::launch::async, [&] { + return WalkRotationScaleBeside(pass1, *check, output_cancel); + }); + + std::optional result; + std::exception_ptr output_error; + try { + result = output->RefinedPasses(observer, pass1, start); + } catch (...) { + output_error = std::current_exception(); } - const auto index_at = [&](float k) { - if (at_fit.valid() && k == first_fit) { - ProcessResult r = at_fit.get(); - const bool same_start = - config_.spot_finding.high_resolution_limit == walk_start_spot_finding.high_resolution_limit - && config_.spot_finding.measured_ring_q_recipA == walk_start_spot_finding.measured_ring_q_recipA; - if (same_start) { - ++arm_passes; - config_.spot_finding = fit_copy->config_.spot_finding; - for (const auto &m : fit_copy->first_pass_memo_) - AddFirstPassMemo(m); - return r.validation_evidence; - } - } - return probe(k, true).validation_evidence; - }; - const auto refit_at = [&](float k) -> std::optional { - const ProcessResult r = probe(k, false); - if (!r.post_refine) - return std::nullopt; - logger.Info("Rotation scale {:.5f}: the post-refinement there fits {:.5f} on top of it, " - "held-out residual {:.3e}", k, r.post_refine->rotation_scale, - r.post_refine->held_out_before); - return r.post_refine->rotation_scale; - }; - constexpr int MAX_ROTATION_SCALE_ROUNDS = 8; - const RotationScaleWalk walk = WalkRotationScale(pass1.post_refine->rotation_scale, index_at, - refit_at, MAX_ROTATION_SCALE_ROUNDS); - experiment_ = before_walk; - prepass_detector_geometry_ = geometry_before_walk; - prepass_mosaicity_ = mosaicity_before_walk; - prepass_rotation_scale_.reset(); - if (!walk.trail.empty()) { - rotation_scale_walk = fmt::format( - "goniometer rotation scale walked from the pass-1 fit {:.5f}, validation spots on " - "the lattice beyond chance by scale: {} - {}", pass1.post_refine->rotation_scale, - walk.trail, walk.scale == 1.0f ? "the stored angles stand" - : fmt::format("{:.5f} adopted", walk.scale)); - logger.Info("Two-pass: {}", rotation_scale_walk); + check->Set(check->output_indexed); + check->Set(check->output_ended); + const RotationScaleWalk walk = walk_done.get(); + if (!check->overturns) { + if (output_error) + std::rethrow_exception(output_error); + return *result; } - note(walk.scale == 1.0f ? std::string("the stored rotation angles stand") - : fmt::format("rotation scale {:.5f} adopted", walk.scale)); + + // Overturned: the refined passes run again, on the run itself. + start.scale_walk = {check->passes, check->text}; if (walk.scale != 1.0f) { + step("Rotation-scale check"); + note(fmt::format("rotation scale {:.5f} adopted", walk.scale)); prepass_rotation_scale_ = walk.scale; pass1.post_refine->rotation_scale = walk.scale; pass1.post_refine->rotation_scale_suspect = true; @@ -644,599 +595,746 @@ ProcessResult Rugnux::RunAllPasses(RugnuxObserver *observer) { "integrates at the corrected angles; the fault is in the hardware and should " "be fixed there", walk.scale, 100.0 * (walk.scale - 1.0), walk.scale > 1.0f ? "further" : "less far"); - } + } else + logger.Info("Two-pass: the rotation-scale walk changed the spot finding the refined passes " + "start from, so they run again after it"); } - - // ... and apply the adopted scale, on the same measure-then-re-integrate footing as the geometry. - if (prepass_rotation_scale_ && gonio_snapshot) { - experiment_.Goniometer(ScaleRotation(*experiment_.GetGoniometer(), *prepass_rotation_scale_)); - // The pre-pass mosaicity is a width in degrees fitted against the angles the second pass has - // just stopped using, and the override can only ever raise the second pass's own estimate (it - // takes the larger of the two). Carrying it over would hold the second pass at the rocking - // width the uncorrected angles produced - the correction half-applied. Drop it and let the - // second pass fit its own. - prepass_mosaicity_.clear(); - logger.Info("Two-pass: goniometer rotation scale {:.5f} will drive the second integration pass " - "(oscillation {:.4f} -> {:.4f} deg per image)", *prepass_rotation_scale_, - gonio_snapshot->GetIncrement_deg(), - gonio_snapshot->GetIncrement_deg() * *prepass_rotation_scale_); - } - // The integration radius the pre-scan measured from the crystal's own spot width, applied now - // that the geometry is fitted. The pre-pass ran at the radius the run started with (see - // bragg_adaptive_), so everything pass 2 consumes from it - the post-refined distance and beam, - // the space group, the smoothed mosaicity - is what the fixed radius produces, and the widened - // disk changes only the intensities of the canonical pass. - if (bragg_adaptive_) { - experiment_.ImportBraggIntegrationSettings(*bragg_adaptive_); - logger.Info("Two-pass: the canonical pass integrates at the measured spot width, " - "r1={:.1f} r2={:.1f} r3={:.2f}", bragg_adaptive_->GetR1(), - bragg_adaptive_->GetR2(), bragg_adaptive_->GetR3()); - } - - // Let every refined pass from here on ask the quality guard's question of itself, so one that - // is going to be thrown away can skip the report and the files it would have superseded. - quality_guard_pass1_ = pass1; - config_.output_prefix = base_prefix; // the refined pass is the canonical result (no _02 suffix) - // The canonical pass measures the post-refinement again where the pre-pass moved the geometry - // (it applies nothing), so that the walk below has something to decide on. - postrefine_probe_ = prepass_detector_geometry_.has_value(); - - const auto current_geometry = [&] { - return std::array{experiment_.GetBeamX_pxl(), experiment_.GetBeamY_pxl(), - experiment_.GetDetectorDistance_mm(), - experiment_.GetPoniRot1_rad(), experiment_.GetPoniRot2_rad()}; - }; - const auto set_geometry = [&](const std::array &g) { - experiment_.BeamX_pxl(g[0]).BeamY_pxl(g[1]).DetectorDistance_mm(g[2]) - .PoniRot1_rad(g[3]).PoniRot2_rad(g[4]); - }; - - // The metric symmetry, asked of the spots rather than of the tolerance that admitted it. The - // Bravais class is chosen by a walk that reads two axes as EQUAL when they agree to a fixed - // relative tolerance, and the class carrying that equality is then imposed everywhere below: - // the cell is refined with a = b, reflections are predicted from it and integrated at the - // predicted positions. On a small cell the tolerance is far wider than the positions resolve - - // a 5.8 A axis pair 2.4 % apart is read as tetragonal, and the mean the constraint substitutes - // mispredicts the outermost reflections by a good ten pixels against an integration disc of - // four - so a genuinely orthorhombic crystal is integrated as tetragonal and every decision - // downstream, up to the space group, is read off the wreckage. - // - // So the equality is measured rather than assumed. The indexer already refines the same - // candidate a second time with nothing held, and pass 1 reports how far that free refinement - // leaves the two axes apart (lattice_length_split). A relative split of eps displaces a - // reflection at radius r by eps/2 * r pixels, so the question "do these data resolve it" has - // an answer in the units the integration works in: where that displacement at the far corner - // of the detector stays inside the integration disc, imposing the equality moves nothing out - // of its own box and the higher symmetry is kept with no pass run. Where it does not, both - // hypotheses are run - the promoted class, and the class the same walk carries when it is - // granted no length equality at all - and whichever REALISES the lower held-out residual on a - // re-integrated, re-indexed pass is kept, the - // promoted class on a tie, because it is the one that asserts more. Both arms are probe-only - // passes (postrefine_probe_only_): the residual is all the comparison reads and it is in hand - // before the scaling engine is built, so neither arm pays for a merge, a space-group search or - // a set of correction surfaces, and only the class that wins is ever run as a canonical pass. - std::string lattice_arm; // the arm decision, for the pass decision text - // - // An ANGLE promotion is the same question: the walk holds a monoclinic or orthorhombic angle at - // 90 when the unrefined cell puts it within LATTICE_SEARCH_ANGLE_TOLERANCE_DEG of it, and an - // angle error of delta displaces a reflection at radius r by up to delta/2 * r pixels. Its - // demoted arm is the indexer's free refinement itself; the space group, and with it any - // lower class the data do carry, is then found from the intensities as for any triclinic - // indexing. Measured: a monoclinic crystal whose beta sits 1.4 deg from 90 indexed every - // validation frame as primitive orthorhombic, so the per-frame guard never fired. - const bool length_arm = pass1.lattice_length_split.has_value(); - const bool angle_arm = !length_arm && pass1.lattice_angle_departure_deg.has_value(); - if (!cancelled_ && (length_arm || angle_arm) && pass1.rotation_lattice_type) { - const double split = length_arm ? *pass1.lattice_length_split - : *pass1.lattice_angle_departure_deg * PI / 180.0; - const double dx = std::max(experiment_.GetBeamX_pxl(), - static_cast(experiment_.GetXPixelsNum()) - experiment_.GetBeamX_pxl()); - const double dy = std::max(experiment_.GetBeamY_pxl(), - static_cast(experiment_.GetYPixelsNum()) - experiment_.GetBeamY_pxl()); - const double r_corner_px = std::hypot(dx, dy); - const double miss_px = 0.5 * split * r_corner_px; - const double disc_px = experiment_.GetBraggIntegrationSettings().GetR1(); - if (miss_px > disc_px) { - if (length_arm) - logger.Info("Metric symmetry: {} was promoted on a = b, but the free refinement leaves " - "the two axes {:.2f} % apart - {:.1f} px of misprediction at the far corner " - "against an integration disc of {:.1f} px. Both classes are re-integrated " - "and judged on the held-out residual each realises", - gemmi::crystal_system_str(pass1.rotation_lattice_type->crystal_system), - 100.0 * split, miss_px, disc_px); - else - logger.Info("Metric symmetry: {} holds its angles at 90 deg, but the free refinement " - "leaves one {:.2f} deg from it - {:.1f} px of misprediction at the far " - "corner against an integration disc of {:.1f} px. Both classes are " - "re-integrated and judged on the held-out residual each realises", - gemmi::crystal_system_str(pass1.rotation_lattice_type->crystal_system), - *pass1.lattice_angle_departure_deg, miss_px, disc_px); - step("Metric-symmetry check"); - note(fmt::format("{} re-integrated with and without its {} equality", - gemmi::crystal_system_str(pass1.rotation_lattice_type->crystal_system), - length_arm ? "a = b" : "90 deg angle")); - // The arms are compared on the post-refinement's held-out residual, so they have to - // measure one: a canonical pass only does where the pre-pass moved the geometry. - const bool probe_was = postrefine_probe_; - postrefine_probe_ = true; - postrefine_probe_only_ = true; - const auto promoted_arm = RunPipeline(observer, /*write_output=*/false, /*geometry_prepass=*/false); - ++arm_passes; - IndexingSettings demoted_settings = experiment_.GetIndexingSettings(); - demoted_settings.LatticeClassDemoted(length_arm); - experiment_.ImportIndexingSettings(demoted_settings); - lattice_angles_demoted_ = angle_arm; - const auto demoted_arm = RunPipeline(observer, /*write_output=*/false, /*geometry_prepass=*/false); - ++arm_passes; - postrefine_probe_only_ = false; - postrefine_probe_ = probe_was; - const double realised_promoted = promoted_arm.post_refine ? promoted_arm.post_refine->held_out_before : NAN; - const double realised_demoted = demoted_arm.post_refine ? demoted_arm.post_refine->held_out_before : NAN; - const auto class_text = [](const ProcessResult &r) { - return r.rotation_lattice_type - ? fmt::format("{}-centred {}", r.rotation_lattice_type->centering, - gemmi::crystal_system_str(r.rotation_lattice_type->crystal_system)) - : std::string("no lattice"); - }; - if (!cancelled_ && promoted_arm.post_refine && demoted_arm.post_refine - && HeldOutResidualFell(*promoted_arm.post_refine, *demoted_arm.post_refine)) { - logger.Warning("Metric symmetry: re-integrated as {} the held-out residual is {:.3e} " - "against {:.3e} as {} - the equality is not this crystal's, and the " - "run goes on without it", class_text(demoted_arm), realised_demoted, - realised_promoted, class_text(promoted_arm)); - note(fmt::format("the equality dropped: {} fits better", class_text(demoted_arm))); - lattice_arm = fmt::format( - "the metric symmetry was promoted to {} on {} the free refinement leaves " - "{:.2f} {}; re-integrated as {} the held-out residual is {:.3e} against " - "{:.3e}, so the equality was dropped", class_text(promoted_arm), - length_arm ? "axes" : "an angle", length_arm ? 100.0 * split : split * 180.0 / PI, - length_arm ? "% apart" : "deg from 90", - class_text(demoted_arm), realised_demoted, realised_promoted); - } else if (!cancelled_) { - note(fmt::format("the metric symmetry stands: {}", class_text(promoted_arm))); - IndexingSettings promoted_settings = experiment_.GetIndexingSettings(); - promoted_settings.LatticeClassDemoted(false); - experiment_.ImportIndexingSettings(promoted_settings); - lattice_angles_demoted_ = false; - // An arm that indexed nothing, or post-refined nothing, measures no residual. The - // metric symmetry stands either way - that is the arm whose absence of evidence is - // not evidence against it - but the run must not report a comparison it could not - // make: written as a number, a missing residual came out as "realised a held-out - // residual of nan against 1.234e-03, so the metric symmetry stands". - const bool compared = std::isfinite(realised_promoted) && std::isfinite(realised_demoted); - if (compared) { - logger.Info("Metric symmetry: re-integrated as {} the held-out residual is {:.3e}, " - "which {} does not beat ({:.3e}) - the higher symmetry stands", - class_text(promoted_arm), realised_promoted, class_text(demoted_arm), - realised_demoted); - lattice_arm = fmt::format( - "{} was run as well and realised a held-out residual of {:.3e} against {:.3e} " - "as {}, so the metric symmetry stands", class_text(demoted_arm), - realised_demoted, realised_promoted, class_text(promoted_arm)); - } else { - const char *which = !std::isfinite(realised_demoted) && !std::isfinite(realised_promoted) - ? "neither arm measured a held-out residual" - : !std::isfinite(realised_demoted) - ? "the demoted arm measured no held-out residual" - : "the promoted arm measured no held-out residual"; - logger.Info("Metric symmetry: {}, so the two could not be compared - the higher " - "symmetry stands", which); - lattice_arm = fmt::format( - "{} was run as well, but {}, so the two could not be compared and the " - "metric symmetry stands untested", class_text(demoted_arm), which); - } - } - } else { - logger.Info("Metric symmetry: {} - the free refinement departs from it by {:.2f} {}, " - "{:.1f} px at the far corner, inside the integration disc of {:.1f} px, so " - "these data do not resolve the difference", - gemmi::crystal_system_str(pass1.rotation_lattice_type->crystal_system), - length_arm ? 100.0 * split : split * 180.0 / PI, length_arm ? "%" : "deg", - miss_px, disc_px); - } - } - - logger.Info("Rotation two-pass geometry post-refinement: second pass (refined geometry, canonical) -> {}_*", - base_prefix); - speculate_geometry_probe_ = true; // a walk that follows starts with an indexing probe - rerun_if_starved_ = true; - auto pass2 = RunPipeline(observer, /*write_output=*/true, /*geometry_prepass=*/false); - rerun_if_starved_ = false; - speculate_geometry_probe_ = false; - - // Walk the geometry to the fit's fixed point. The post-refinement is fitted to reflections - // integrated at the very geometry it is correcting, so one fit reaches only as far as those - // reflections see: on a header whose distance is several percent long, the pre-pass absorbs the - // error into an inflated cell, and from that self-consistent pair the fit finds a fraction of it - // and stops. The canonical pass has just re-integrated and re-indexed at what it committed, so - // asking the same fit there is the next step of the same walk - and that re-indexing is also the - // RATIFICATION the old size bound stood in for: a second lattice does not index better at a - // geometry it did not come from, a wrong header does, and a pass that lost the crystal is thrown - // out by the quality guard below, which returns the run to the header geometry. - // - // What starts the walk outright is a move of more than one step: that is the fit saying the - // geometry is somewhere else entirely rather than a fraction of a percent away. A smaller move - // has to be preferred by the validation frames first (below), so a run whose fit settles beside - // the geometry in hand costs two indexing probes and no pass. Once the run IS walking - // it keeps walking because the steps do not get smaller in proportion to what is left: measured - // on a header 3.9 % long, the first round took a third of the error and each of the next took a - // third of the rest. - // - // But a round is kept only for what it REALISES, not for what the fit predicts: the held-out - // residual of the pass re-integrated and re-indexed at the new geometry has to fall below the - // best round's by more than the cross-validation noise of the two (HeldOutResidualFell). With - // the walk allowed twelve rounds, every round's fit predicted a gain the re-integration did not - // show - the realised residual stayed flat, or passed a minimum and rose again, while the - // distance crept on along the distance/cell-scale degeneracy - so "the fit still commits" never - // ended a walk, and the cap decided where on the drift the run stopped. A round that does not - // pay ends the walk and the run goes back to the best round it reached. So does a fit whose - // committed cell the re-indexing pushes back the same way twice running (ReindexPushesCellBack): - // the fit keeps asking for a cell the indexer at the fit's own geometry does not return, and - // nothing ratifies it. A walk still paying when the rounds run out keeps its best round - the - // last - and says it did not converge; the quality guard below judges it against the header - // pass as it judges every refined pass. - // - // The residual is not the only thing a round realises. It is the mean over every reflection, - // measured by centroids taken inside a disc centred on the prediction - so they follow the - // prediction part of the way - and dominated by the low-resolution reflections, where a distance - // and the cell scale that compensates it move every spot alike. What does see such an error is - // the re-indexing: the share of the validation spots that land on the lattice, which the - // high-resolution spots lose first. Measured on a crystal whose canonical pass ran 0.6 % long, - // the round at the fit's distance put 70.4 % of the validation spots on the lattice against - // 58.1 %, while reading the residual only 0.74 of its noise lower - and the run the residual - // stopped kept the long distance and lost 0.05 A of resolution. So a round is kept when EITHER - // realises a gain beyond its noise: the residual (HeldOutResidualFell), or the validation - // frames (ValidationEvidencePrefers). - // - // And a move of less than one step no longer settles the geometry by being small: it is asked - // of the validation frames too, but cheaply first - an indexing probe at the fit's geometry - // against one at the geometry in hand, each scoring the lattice and stopping there - and only a - // move the probes prefer pays for a re-integrated round. A move of a step or more is run as a - // round directly, as it always was, and so is every round of the walk it starts. - const auto on_lattice_pct = [](const ValidationSpotEvidence &e) { - return 100.0 * static_cast(e.on_lattice - e.by_chance) - / static_cast(std::max(1, e.spots)); - }; - // An indexing probe at a geometry: the validation evidence of the lattice indexed there, and - // nothing else - the pass stops once the lattice is scored, and the experiment is put back. - const auto index_at_geometry = [&](const std::array &g) { - const DiffractionExperiment before_probe = experiment_; - const bool probe_was = postrefine_probe_; - set_geometry(g); - CollectSpeculativeProbe(); - indexing_probe_only_ = true; - postrefine_probe_ = false; - ProcessResult r; - try { - r = RunPipeline(observer, /*write_output=*/false, /*geometry_prepass=*/false); - } catch (const std::exception &e) { - if (IsFatalResourceError(e)) throw; - logger.Info("Two-pass: the indexing probe at distance {:.3f} mm did not complete ({})", - g[2], e.what()); - } - indexing_probe_only_ = false; - postrefine_probe_ = probe_was; - experiment_ = before_probe; - ++arm_passes; - return r.validation_evidence; - }; - constexpr int MAX_GEOMETRY_ROUNDS = 8; - int geometry_rounds = 0; // passes run at a geometry the walk moved to - int walk_passes = 0; // every pass the walk ran, the return to its best round included - int best_round = 0; - std::array best_geometry = current_geometry(); - PostRefineResult best_fit; // the fit measured in the best round's pass: its realised residual - int last_pushback = 0; - bool geometry_not_converged = false; - std::string walk_stop; // why the walk ended, where anything but the fit settling ended it - std::string walk_rounds; // distance / realised residual per round, for the pass decision - if (pass2.post_refine) { - best_fit = *pass2.post_refine; - walk_rounds = fmt::format("{:.3f} mm / {:.3e} / {:.1f}%", best_geometry[2], best_fit.held_out_before, - on_lattice_pct(pass2.validation_evidence)); - } - ValidationSpotEvidence best_evidence = pass2.validation_evidence; - std::optional probe_at_best; // the indexing probe at best_geometry, once run - bool large_walk = false; // a round of this walk was started by a move of a step or more - // What the last round started from: a pass can leave the run changed behind it (a spot budget - // it shortened, an axis sign it flipped), so a round is written - // from here, not from where its own probe left the run. - DiffractionExperiment last_round_start = experiment_; - bool walk_shown = false; - while (!cancelled_ && prepass_detector_geometry_ - && pass2.post_refine && pass2.post_refine->detector_refined) { - if (!walk_shown) { - step("Geometry check"); - walk_shown = true; - } - if (geometry_rounds == MAX_GEOMETRY_ROUNDS) { - geometry_not_converged = true; - walk_stop = fmt::format("the fit still moved the geometry after {} rounds, every one of " - "which lowered the realised residual", MAX_GEOMETRY_ROUNDS); - logger.Warning("Two-pass: {} - the walk did not converge; the run keeps its last round " - "and the quality guard judges it against the header pass", walk_stop); - break; - } - const PostRefineResult fit = *pass2.post_refine; - const std::array g = *prepass_detector_geometry_; - large_walk = large_walk || fit.large_move; - if (!large_walk) { - if (!probe_at_best) - probe_at_best = index_at_geometry(best_geometry); - const ValidationSpotEvidence probe_at_fit = index_at_geometry(g); - const bool prefers = ValidationEvidencePrefers(*probe_at_best, probe_at_fit); - logger.Info("Two-pass: the post-refinement moves the geometry by less than a step (distance " - "{:.3f} -> {:.3f} mm, beam {:.2f},{:.2f} -> {:.2f},{:.2f} px); indexing probes put " - "{:.1f}% of the validation spots on the lattice beyond chance there against {:.1f}% " - "at the geometry in hand - {}", fit.distance_before_mm, fit.distance_after_mm, - fit.beam_x_before_px, fit.beam_y_before_px, fit.beam_x_after_px, fit.beam_y_after_px, - on_lattice_pct(probe_at_fit), on_lattice_pct(*probe_at_best), - prefers ? "worth a round" : "the geometry in hand stands"); - if (!prefers) - break; - probe_at_best = probe_at_fit; - } - logger.Info("Two-pass: the post-refinement at the adopted geometry still moves it " - "(distance {:.3f} -> {:.3f} mm) - re-integrating and re-indexing at what it " - "asks for (round {} of at most {})", fit.distance_before_mm, - fit.distance_after_mm, geometry_rounds + 1, MAX_GEOMETRY_ROUNDS); - set_geometry(g); - last_round_start = experiment_; - // A round is a probe pass: the walk reads only its fit and its validation evidence, both in - // hand before the merge, so the files are written once, below, at the round the walk keeps. - speculate_geometry_probe_ = !large_walk; - postrefine_probe_only_ = true; - pass2 = RunPipeline(observer, /*write_output=*/false, /*geometry_prepass=*/false); - postrefine_probe_only_ = false; - speculate_geometry_probe_ = false; - ++geometry_rounds; - ++walk_passes; - const double realised = pass2.post_refine ? pass2.post_refine->held_out_before : NAN; - walk_rounds += fmt::format(", {:.3f} mm / {:.3e} / {:.1f}%", g[2], realised, - on_lattice_pct(pass2.validation_evidence)); - const bool residual_fell = pass2.post_refine && HeldOutResidualFell(best_fit, *pass2.post_refine); - const bool evidence_prefers = ValidationEvidencePrefers(best_evidence, pass2.validation_evidence); - if (!pass2.post_refine || !(residual_fell || evidence_prefers)) { - walk_stop = fmt::format( - "round {} lowered neither the realised held-out residual by more than its noise " - "({:.3e} against {:.3e}, standard errors {:.1e} and {:.1e}) nor the share of " - "validation spots off the lattice ({:.1f}% on it beyond chance against {:.1f}%)", - geometry_rounds, realised, best_fit.held_out_before, - pass2.post_refine ? pass2.post_refine->held_out_before_se : NAN, - best_fit.held_out_before_se, on_lattice_pct(pass2.validation_evidence), - on_lattice_pct(best_evidence)); - logger.Info("Two-pass: {}", walk_stop); - break; - } - best_round = geometry_rounds; - best_geometry = g; - best_fit = *pass2.post_refine; - best_evidence = pass2.validation_evidence; - const int pushback = ReindexPushesCellBack(fit, *pass2.post_refine); - if (pushback != 0 && pushback == last_pushback) { - walk_stop = fmt::format( - "re-indexing pushed the cell length {} back against the fit for the second " - "round running, so nothing ratifies the cell the fit asks for", - "abc"[std::abs(pushback) - 1]); - logger.Info("Two-pass: {} - the walk stops at round {}", walk_stop, geometry_rounds); - break; - } - last_pushback = pushback; - } - postrefine_probe_ = false; - if (walk_shown) - note(geometry_rounds == 0 ? std::string("the geometry in hand stands") - : fmt::format("geometry walked {} round{}, round {} kept: distance {:.2f} mm{}", geometry_rounds, - geometry_rounds == 1 ? "" : "s", best_round, best_geometry[2], - best_round > 0 ? " - the files are written again there" : "")); - // The rounds wrote nothing, so the round the walk kept is run again to write the canonical files. - if (!cancelled_ && geometry_rounds > 0) { - if (best_round == geometry_rounds) { - logger.Info("Two-pass: writing round {} of the geometry walk (distance {:.3f} mm)", - best_round, best_geometry[2]); - experiment_ = last_round_start; - } else { - logger.Info("Two-pass: going back to round {} of the geometry walk (distance {:.3f} mm), " - "the last one that lowered the realised residual", best_round, best_geometry[2]); - set_geometry(best_geometry); - } - rerun_if_starved_ = true; - pass2 = RunPipeline(observer, /*write_output=*/true, /*geometry_prepass=*/false); - rerun_if_starved_ = false; - ++walk_passes; - } - - // The post-refinement is measured by pass 1 and consumed by pass 2, so carry it onto whichever - // result is returned - it is a result of the run, not of the pass that happened to fit it. Where - // the walk took rounds they are ONE geometry decision, so what the report names is where the - // geometry started and where the run left it, not the first step of the way there. - if (best_round > 0 && pass1.post_refine) { - pass1.post_refine->beam_x_after_px = best_geometry[0]; - pass1.post_refine->beam_y_after_px = best_geometry[1]; - pass1.post_refine->distance_after_mm = best_geometry[2]; - // A first pass that held the header distance and a walk that then left it: the run's - // decision is the walk's. - pass1.post_refine->distance_held = false; - } - pass2.post_refine = pass1.post_refine; - pass2.pass_number = 2 + arm_passes + walk_passes; - pass2.pass_count = 2 + arm_passes + walk_passes; - if (geometry_rounds > 0) - pass2.pass_decision = fmt::format( - "post-refined geometry walked {} round{} and kept round {}, detector distance {:.3f} mm " - "against the header's {:.3f}: {}; distance / realised held-out residual / validation spots on the lattice beyond chance by round: {}", - geometry_rounds, geometry_rounds == 1 ? "" : "s", best_round, best_geometry[2], - pass1.post_refine ? pass1.post_refine->distance_before_mm : 0.0, - walk_stop.empty() ? "the fit at the kept geometry commits no further move" : walk_stop, - walk_rounds); - - // r2 = r1 + 2 is also the inner edge of the background ring, so widening the signal disk pushes - // that ring out into the neighbours; a reflection whose ring is left with five or fewer clean - // pixels has no background and is dropped whole. On a pattern dense enough in three dimensions - // at once that costs a quarter of the observations - and NOTHING available before integrating - // predicts it: the crystal it happens to has a mid-table predicted spot spacing, wider than - // crystals that survive r1 = 12. What does measure it is the integrator counting its own drops. - // The pass that integrates at the widened radius is now the canonical one, so the measurement - // and the remedy are both here: re-run it at the radius that keeps the data, the same remedy the - // two guards below use and, like them, a pass only on a crystal that was going to be wrong. - // Asked of every pass that can end the run - the two guards below re-run at whatever radius is - // in hand, and a starved refined pass has written nothing (see the superseded flag in - // RunPipeline) - so each is followed by it. After the first re-run the radius is the fixed one - // and this never fires again. - const auto rerun_if_starved = [&](ProcessResult &pass, const std::string decision) { - if (cancelled_ || !bragg_adaptive_ || !bkg_starved_fraction_ - || *bkg_starved_fraction_ <= spot_width::BKG_STARVED_MAX_FRACTION) - return; - logger.Info("Two-pass: at the widened integration radius r1={:.1f} the neighbouring " - "reflections left {:.2f}% of the predicted reflections without a background " - "ring (bound {:.2f}%), so this pass is re-run at r1={:.1f} r2={:.1f} r3={:.2f}", - bragg_adaptive_->GetR1(), 100.0 * *bkg_starved_fraction_, - 100.0 * spot_width::BKG_STARVED_MAX_FRACTION, - bragg_before_adaptive_->GetR1(), bragg_before_adaptive_->GetR2(), - bragg_before_adaptive_->GetR3()); - const double starved = *bkg_starved_fraction_; - const float wide_r1 = bragg_adaptive_->GetR1(); - const int passes = pass.pass_count + 1; - experiment_.ImportBraggIntegrationSettings(*bragg_before_adaptive_); - bragg_adaptive_.reset(); - note(fmt::format("{:.1f}% of the background rings starved: the pass runs again at r1 {:.1f} px", - 100.0 * starved, bragg_before_adaptive_->GetR1())); - pass = RunPipeline(observer, /*write_output=*/true, /*geometry_prepass=*/false); - pass.post_refine = pass1.post_refine; - pass.pass_number = passes; - pass.pass_count = passes; - pass.pass_decision = fmt::format( - "{}, re-run at the fixed integration radius: at r1={:.1f} neighbouring reflections " - "left {:.2f}% of the predicted reflections without a background ring", decision, wide_r1, - 100.0 * starved); - }; - rerun_if_starved(pass2, "post-refined geometry adopted"); - - // Supercell-collapse guard for the second pass. The de-novo lattice search can be BISTABLE on a - // periodically-modulated dataset: the tiny post-refine geometry move tips it out of the true-cell - // basin onto a spurious SUPERCELL (a large multiple of pass-1's cell volume), and the space group - // reused from pass-1 is then stamped onto that wrong-shaped cell - catastrophic. Pass 1 (header - // geometry, un-perturbed) found the correct lattice, so re-run the second pass with pass-1's FULL - // indexing result forced (its refined lattice + orientation + rotation axis + geometry - not just the - // cell, which loses the per-frame orientation and integrates worse): the re-run then matches de-novo - // quality but at the refined geometry. Only fires when pass 2 is markedly LARGER than pass 1 - a - // genuine de-novo demotion to a smaller primitive (the pseudo-symmetry case the second pass re-indexes - // de novo to catch) has pass2 <= pass1 and is left untouched. - if (!cancelled_ && prepass_result_ && pass1.consensus_cell && pass2.consensus_cell) { - // PRIMITIVE volumes, like the two guards in RunPipeline: a centred conventional cell is an - // exact integer multiple of its primitive one (C/I 2x, R 3x, F 4x), so two settings of the - // SAME lattice differ by that factor and comparing the conventional cells reads a mere - // change of setting as a supercell - which then forces pass 1's setting and, with it, its - // lower symmetry. Measured: every dataset this guard fired on was at an exact centring - // multiplicity, one of them an F-centred lattice held down to P1 at 3.99x. - const auto primitive_volume = [](const UnitCell &cell, std::optional centering) { - return std::abs(CrystalLattice(cell).ToPrimitive(centering.value_or('P')).CalcVolume()); - }; - const double v1 = primitive_volume(*pass1.consensus_cell, pass1.consensus_centering); - const double v2 = primitive_volume(*pass2.consensus_cell, pass2.consensus_centering); - if (v1 > 0.0 && v2 > 1.5 * v1) { - logger.Info("Two-pass: second-pass primitive cell volume {:.0f} A^3 is {:.2f}x pass-1's " - "({:.0f} A^3) - a spurious supercell; re-running the second pass with " - "pass-1's result forced", - v2, v2 / v1, v1); - note("a spurious supercell: the pass runs again on the pre-pass lattice"); - force_rotation_result_ = *prepass_result_; - // Pass 1's result carries pass 1's goniometer, and the per-image path takes its angles - // from there - forcing it whole would put the uncorrected angles back and silently undo - // the rotation scale for the re-run. - if (prepass_rotation_scale_ && force_rotation_result_->axis) - force_rotation_result_->axis = - ScaleRotation(*force_rotation_result_->axis, *prepass_rotation_scale_); - rerun_if_starved_ = true; - pass2 = RunPipeline(observer, /*write_output=*/true, /*geometry_prepass=*/false); - rerun_if_starved_ = false; - pass2.post_refine = pass1.post_refine; - pass2.pass_number = 3; - pass2.pass_count = 3; - pass2.pass_decision = fmt::format( - "post-refined geometry adopted, re-run with pass-1's lattice forced: the de-novo " - "primitive cell volume {:.0f} A^3 was {:.2f}x pass-1's ({:.0f} A^3), a spurious " - "supercell", v2, v2 / v1, v1); - // Still forced: the re-run at the fixed radius is the same pass. - rerun_if_starved(pass2, pass2.pass_decision); - force_rotation_result_.reset(); - } - } - // The refined pass is normally the better answer, which is why it is the canonical output - - // but it is not guaranteed to be, and the guard that decides is RefinedPassIsWorse above. It - // has already been asked once, inside the pass itself, which is how a pass that is about to be - // thrown away knows not to write a report; this is where the answer is acted on. - if (!cancelled_ && pass1.has_merge_statistics && pass2.has_merge_statistics) { - logger.Info("Two-pass quality guard: the refined pass holds {} reflections at I/sigma >= 2 and " - "{} at <= -2 of {} in a {:.0f} A^3 primitive cell, the header-geometry pass {} and {} " - "of {} in {:.0f} A^3; low-order axial {} against {}", - pass2.search_merge_strong_reflections, pass2.search_merge_negative_reflections, - pass2.search_merge_reflections, PrimitiveCellVolume(pass2), - pass1.search_merge_strong_reflections, pass1.search_merge_negative_reflections, - pass1.search_merge_reflections, PrimitiveCellVolume(pass1), - pass2.search_merge_axial_reflections, pass1.search_merge_axial_reflections); - const std::string worse = RefinedPassIsWorse(pass1, pass2); - if (!worse.empty()) { - logger.Warning("Two-pass: the refined pass is worse than the header-geometry pass ({}) " - "- going back to the header geometry. The refined geometry did not help " - "this crystal.", worse); - // The refined pass has already written the canonical files, so re-run at the header - // geometry to replace them - the same remedy the supercell collapse above uses, and it - // only costs a pass on a crystal that was going to be wrong otherwise. - experiment_.BeamX_pxl(header_geometry[0]).BeamY_pxl(header_geometry[1]) - .DetectorDistance_mm(header_geometry[2]) - .PoniRot1_rad(header_geometry[3]).PoniRot2_rad(header_geometry[4]); - if (prepass_rotation_scale_ && gonio_snapshot) { - // The header rotation angles with it - but not the axis DIRECTION, which is not - // part of the geometry being reverted and may have been corrected by the sign - // rescue (see the restore before pass 2). - GoniometerAxis restored = *gonio_snapshot; - if (const auto current = experiment_.GetGoniometer()) - restored.Axis(current->GetAxis()); - experiment_.Goniometer(restored); - prepass_rotation_scale_.reset(); - pass1.post_refine->rotation_scale_suspect = false; - } - config_.output_prefix = base_prefix; - // This pass is the answer whatever it measures - the guard has had its one chance - - // so it must not conclude from its own search merge that it is going to be re-run. - quality_guard_pass1_.reset(); - // What the guard preferred is pass 1 - its lattice, orientation and axis at this very - // geometry - so that is what is re-integrated, not a fresh de-novo index. A de-novo - // re-index here is a new hypothesis nobody judged: measured, at the same centre where - // pass 1 indexed 56/60 validation frames it found 5/60, took the opposite axis sign and - // shipped a merge with R_meas in the hundreds of percent. - if (prepass_result_) - force_rotation_result_ = *prepass_result_; - rerun_if_starved_ = true; - note("the refined geometry is worse: the pass runs again at the header geometry"); - auto redo = RunPipeline(observer, /*write_output=*/true, /*geometry_prepass=*/false); - rerun_if_starved_ = false; - redo.post_refine = pass1.post_refine; - redo.pass_number = pass2.pass_count + 1; - redo.pass_count = pass2.pass_count + 1; - redo.pass_decision = fmt::format( - "header geometry re-adopted: the post-refined pass was worse ({})", worse); - // Still forced: the re-run at the fixed radius is the same pass. - rerun_if_starved(redo, redo.pass_decision); - force_rotation_result_.reset(); - return redo; - } - if (pass2.pass_decision.empty()) - pass2.pass_decision = fmt::format( - "post-refined geometry adopted ({}, {})", SearchMergeCompletenessText(pass1, pass2), - SignalText(pass1, pass2)); - } - if (pass2.pass_decision.empty()) - pass2.pass_decision = (prepass_detector_geometry_ || prepass_rotation_scale_) - ? "post-refined geometry adopted" - : "the post-refinement committed no geometry change, so this pass reproduces the first"; - if (!lattice_arm.empty()) - pass2.pass_decision = lattice_arm + "; " + pass2.pass_decision; - if (!rotation_scale_walk.empty()) - pass2.pass_decision = rotation_scale_walk + "; " + pass2.pass_decision; - pass2.geometry_not_converged = geometry_not_converged; - return pass2; + return *RefinedPasses(observer, std::move(pass1), start); } return RunPipeline(observer, /*write_output=*/true, /*geometry_prepass=*/false); } + +// The rotation-scale walk of RunAllPasses, run beside the refined passes on a copy of the run (`check` +// is what the two share): it starts once their first pass has indexed, calls them off (output_cancel) +// before a refit, and says at its end whether they started where it leaves the run. +RotationScaleWalk Rugnux::WalkRotationScaleBeside(const ProcessResult &pass1, RotationScaleCheck &check, + CancelFlag output_cancel) { + Logger logger("Rugnux"); + const auto call_output_off = [&] { + output_cancel = true; + check.Set(check.called_off); + }; + try { + check.Wait(check.output_indexed); + const DiffractionExperiment before_walk = experiment_; + const auto geometry_before_walk = prepass_detector_geometry_; + const auto mosaicity_before_walk = prepass_mosaicity_; + int probe_passes = 0; + // A probe pass at scale k, run on r - this run, or a copy of it (see below). + const auto probe_on = [&](Rugnux &r, float k, bool index_only) { + r.experiment_ = before_walk; + r.experiment_.Goniometer(ScaleRotation(*before_walk.GetGoniometer(), k)); + r.prepass_rotation_scale_ = k; + r.prepass_mosaicity_.clear(); + r.indexing_probe_only_ = index_only; + r.postrefine_probe_ = r.postrefine_probe_only_ = !index_only; + ProcessResult res; + try { + res = r.RunPipeline(nullptr, /*write_output=*/false, /*geometry_prepass=*/false); + } catch (const std::exception &e) { + if (IsFatalResourceError(e)) throw; + // Angles under which nothing indexes have scored nothing, which is what an + // empty result reads as. + logger.Info("Rotation scale {:.5f}: the probe pass did not complete ({})", k, e.what()); + } + r.indexing_probe_only_ = r.postrefine_probe_ = r.postrefine_probe_only_ = false; + return res; + }; + const auto probe = [&](float k, bool index_only) { + ++probe_passes; + return probe_on(*this, k, index_only); + }; + // The walk always indexes at the stored angles first and at the pass-1 fit next (see + // WalkRotationScale). Both are known now and each is its own pass, so the one at the fit + // runs at the same time, on a copy of the run as it stands before either. What a probe + // leaves behind for the next pass - the spot-finding settings a first-pass ladder rung + // adopts; the experiment is put back by the probe itself - is checked when the fit's turn + // comes: if the probe at the stored angles changed it, the copy started from a state the + // sequential walk would not have, and the probe is run again here. The same check, at the + // end, says whether the refined passes beside the walk started where it leaves the run. + const float first_fit = static_cast(pass1.post_refine->rotation_scale); + std::shared_ptr fit_copy; + std::future at_fit; + const SpotFindingSettings walk_start_spot_finding = config_.spot_finding; + if (first_fit != 1.0f && !cancelled_) { + fit_copy = std::make_shared(*this); + at_fit = std::async(std::launch::async, [&probe_on, fit_copy, first_fit] { + return probe_on(*fit_copy, first_fit, true); + }); + } + const auto same_spot_finding = [&] { + return config_.spot_finding.high_resolution_limit == walk_start_spot_finding.high_resolution_limit + && config_.spot_finding.measured_ring_q_recipA == walk_start_spot_finding.measured_ring_q_recipA; + }; + const auto index_at = [&](float k) { + if (at_fit.valid() && k == first_fit) { + ProcessResult r = at_fit.get(); + if (same_spot_finding()) { + ++probe_passes; + config_.spot_finding = fit_copy->config_.spot_finding; + for (const auto &m : fit_copy->first_pass_memo_) + AddFirstPassMemo(m); + return r.validation_evidence; + } + } + return probe(k, true).validation_evidence; + }; + // A refit integrates, and comes only once the walk has left the stored angles, so the + // refined passes beside it are thrown away anyway: call them off and let them end first. + const auto refit_at = [&](float k) -> std::optional { + call_output_off(); + check.Wait(check.output_ended); + const ProcessResult r = probe(k, false); + if (!r.post_refine) + return std::nullopt; + logger.Info("Rotation scale {:.5f}: the post-refinement there fits {:.5f} on top of it, " + "held-out residual {:.3e}", k, r.post_refine->rotation_scale, + r.post_refine->held_out_before); + return r.post_refine->rotation_scale; + }; + constexpr int MAX_ROTATION_SCALE_ROUNDS = 8; + const RotationScaleWalk walk = WalkRotationScale(pass1.post_refine->rotation_scale, index_at, + refit_at, MAX_ROTATION_SCALE_ROUNDS); + experiment_ = before_walk; + prepass_detector_geometry_ = geometry_before_walk; + prepass_mosaicity_ = mosaicity_before_walk; + prepass_rotation_scale_.reset(); + std::string text; + if (!walk.trail.empty()) { + text = fmt::format( + "goniometer rotation scale walked from the pass-1 fit {:.5f}, validation spots on " + "the lattice beyond chance by scale: {} - {}", pass1.post_refine->rotation_scale, + walk.trail, walk.scale == 1.0f ? "the stored angles stand" + : fmt::format("{:.5f} adopted", walk.scale)); + logger.Info("Two-pass: {}", text); + } + { + std::lock_guard lock(check.m); + check.overturns = check.called_off || walk.scale != 1.0f || !same_spot_finding(); + check.passes = probe_passes; + check.text = text; + check.done = true; + } + check.cv.notify_all(); + return walk; + } catch (...) { + // The run fails as it would have without the output pass beside it; that pass must + // not wait for an answer that is not coming. + call_output_off(); + check.Set(check.done); + throw; + } +} + +// The refined passes of the rotation two-pass, from the second pass on: everything after the +// rotation-scale walk (see RunAllPasses). Empty where they ran beside the walk and it overturned them. +std::optional Rugnux::RefinedPasses(RugnuxObserver *observer, ProcessResult pass1, + const RefinedPassStart &start) { + Logger logger("Rugnux"); + const auto step = [observer](const std::string &title) { if (observer) observer->OnStep(title); }; + const auto note = [observer](const std::string &text) { if (observer) observer->OnNote(text); }; + const std::string &base_prefix = start.base_prefix; + const auto &gonio_snapshot = start.gonio_snapshot; + const auto &header_geometry = start.header_geometry; + RotationScaleOutcome scale_walk = start.scale_walk; + // The probe passes below and the lattice arms after them exist ONLY to measure - see there - so + // the count of passes the run made has to include them even though they write nothing. + int arm_passes = 0; + + // ... and apply the adopted scale, on the same measure-then-re-integrate footing as the geometry. + if (prepass_rotation_scale_ && gonio_snapshot) { + experiment_.Goniometer(ScaleRotation(*experiment_.GetGoniometer(), *prepass_rotation_scale_)); + // The pre-pass mosaicity is a width in degrees fitted against the angles the second pass has + // just stopped using, and the override can only ever raise the second pass's own estimate (it + // takes the larger of the two). Carrying it over would hold the second pass at the rocking + // width the uncorrected angles produced - the correction half-applied. Drop it and let the + // second pass fit its own. + prepass_mosaicity_.clear(); + logger.Info("Two-pass: goniometer rotation scale {:.5f} will drive the second integration pass " + "(oscillation {:.4f} -> {:.4f} deg per image)", *prepass_rotation_scale_, + gonio_snapshot->GetIncrement_deg(), + gonio_snapshot->GetIncrement_deg() * *prepass_rotation_scale_); + } + // The integration radius the pre-scan measured from the crystal's own spot width, applied now + // that the geometry is fitted. The pre-pass ran at the radius the run started with (see + // bragg_adaptive_), so everything pass 2 consumes from it - the post-refined distance and beam, + // the space group, the smoothed mosaicity - is what the fixed radius produces, and the widened + // disk changes only the intensities of the canonical pass. + if (bragg_adaptive_) { + experiment_.ImportBraggIntegrationSettings(*bragg_adaptive_); + logger.Info("Two-pass: the canonical pass integrates at the measured spot width, " + "r1={:.1f} r2={:.1f} r3={:.2f}", bragg_adaptive_->GetR1(), + bragg_adaptive_->GetR2(), bragg_adaptive_->GetR3()); + } + + // Let every refined pass from here on ask the quality guard's question of itself, so one that + // is going to be thrown away can skip the report and the files it would have superseded. + quality_guard_pass1_ = pass1; + config_.output_prefix = base_prefix; // the refined pass is the canonical result (no _02 suffix) + // The canonical pass measures the post-refinement again where the pre-pass moved the geometry + // (it applies nothing), so that the walk below has something to decide on. + postrefine_probe_ = prepass_detector_geometry_.has_value(); + + const auto current_geometry = [&] { + return std::array{experiment_.GetBeamX_pxl(), experiment_.GetBeamY_pxl(), + experiment_.GetDetectorDistance_mm(), + experiment_.GetPoniRot1_rad(), experiment_.GetPoniRot2_rad()}; + }; + const auto set_geometry = [&](const std::array &g) { + experiment_.BeamX_pxl(g[0]).BeamY_pxl(g[1]).DetectorDistance_mm(g[2]) + .PoniRot1_rad(g[3]).PoniRot2_rad(g[4]); + }; + + // The metric symmetry, asked of the spots rather than of the tolerance that admitted it. The + // Bravais class is chosen by a walk that reads two axes as EQUAL when they agree to a fixed + // relative tolerance, and the class carrying that equality is then imposed everywhere below: + // the cell is refined with a = b, reflections are predicted from it and integrated at the + // predicted positions. On a small cell the tolerance is far wider than the positions resolve - + // a 5.8 A axis pair 2.4 % apart is read as tetragonal, and the mean the constraint substitutes + // mispredicts the outermost reflections by a good ten pixels against an integration disc of + // four - so a genuinely orthorhombic crystal is integrated as tetragonal and every decision + // downstream, up to the space group, is read off the wreckage. + // + // So the equality is measured rather than assumed. The indexer already refines the same + // candidate a second time with nothing held, and pass 1 reports how far that free refinement + // leaves the two axes apart (lattice_length_split). A relative split of eps displaces a + // reflection at radius r by eps/2 * r pixels, so the question "do these data resolve it" has + // an answer in the units the integration works in: where that displacement at the far corner + // of the detector stays inside the integration disc, imposing the equality moves nothing out + // of its own box and the higher symmetry is kept with no pass run. Where it does not, both + // hypotheses are run - the promoted class, and the class the same walk carries when it is + // granted no length equality at all - and whichever REALISES the lower held-out residual on a + // re-integrated, re-indexed pass is kept, the + // promoted class on a tie, because it is the one that asserts more. Both arms are probe-only + // passes (postrefine_probe_only_): the residual is all the comparison reads and it is in hand + // before the scaling engine is built, so neither arm pays for a merge, a space-group search or + // a set of correction surfaces, and only the class that wins is ever run as a canonical pass. + std::string lattice_arm; // the arm decision, for the pass decision text + // + // An ANGLE promotion is the same question: the walk holds a monoclinic or orthorhombic angle at + // 90 when the unrefined cell puts it within LATTICE_SEARCH_ANGLE_TOLERANCE_DEG of it, and an + // angle error of delta displaces a reflection at radius r by up to delta/2 * r pixels. Its + // demoted arm is the indexer's free refinement itself; the space group, and with it any + // lower class the data do carry, is then found from the intensities as for any triclinic + // indexing. Measured: a monoclinic crystal whose beta sits 1.4 deg from 90 indexed every + // validation frame as primitive orthorhombic, so the per-frame guard never fired. + const bool length_arm = pass1.lattice_length_split.has_value(); + const bool angle_arm = !length_arm && pass1.lattice_angle_departure_deg.has_value(); + if (!cancelled_ && (length_arm || angle_arm) && pass1.rotation_lattice_type) { + const double split = length_arm ? *pass1.lattice_length_split + : *pass1.lattice_angle_departure_deg * PI / 180.0; + const double dx = std::max(experiment_.GetBeamX_pxl(), + static_cast(experiment_.GetXPixelsNum()) - experiment_.GetBeamX_pxl()); + const double dy = std::max(experiment_.GetBeamY_pxl(), + static_cast(experiment_.GetYPixelsNum()) - experiment_.GetBeamY_pxl()); + const double r_corner_px = std::hypot(dx, dy); + const double miss_px = 0.5 * split * r_corner_px; + const double disc_px = experiment_.GetBraggIntegrationSettings().GetR1(); + if (miss_px > disc_px) { + if (length_arm) + logger.Info("Metric symmetry: {} was promoted on a = b, but the free refinement leaves " + "the two axes {:.2f} % apart - {:.1f} px of misprediction at the far corner " + "against an integration disc of {:.1f} px. Both classes are re-integrated " + "and judged on the held-out residual each realises", + gemmi::crystal_system_str(pass1.rotation_lattice_type->crystal_system), + 100.0 * split, miss_px, disc_px); + else + logger.Info("Metric symmetry: {} holds its angles at 90 deg, but the free refinement " + "leaves one {:.2f} deg from it - {:.1f} px of misprediction at the far " + "corner against an integration disc of {:.1f} px. Both classes are " + "re-integrated and judged on the held-out residual each realises", + gemmi::crystal_system_str(pass1.rotation_lattice_type->crystal_system), + *pass1.lattice_angle_departure_deg, miss_px, disc_px); + step("Metric-symmetry check"); + note(fmt::format("{} re-integrated with and without its {} equality", + gemmi::crystal_system_str(pass1.rotation_lattice_type->crystal_system), + length_arm ? "a = b" : "90 deg angle")); + // The arms are compared on the post-refinement's held-out residual, so they have to + // measure one: a canonical pass only does where the pre-pass moved the geometry. + const bool probe_was = postrefine_probe_; + postrefine_probe_ = true; + postrefine_probe_only_ = true; + const auto promoted_arm = RunPipeline(observer, /*write_output=*/false, /*geometry_prepass=*/false); + ++arm_passes; + IndexingSettings demoted_settings = experiment_.GetIndexingSettings(); + demoted_settings.LatticeClassDemoted(length_arm); + experiment_.ImportIndexingSettings(demoted_settings); + lattice_angles_demoted_ = angle_arm; + const auto demoted_arm = RunPipeline(observer, /*write_output=*/false, /*geometry_prepass=*/false); + ++arm_passes; + postrefine_probe_only_ = false; + postrefine_probe_ = probe_was; + const double realised_promoted = promoted_arm.post_refine ? promoted_arm.post_refine->held_out_before : NAN; + const double realised_demoted = demoted_arm.post_refine ? demoted_arm.post_refine->held_out_before : NAN; + const auto class_text = [](const ProcessResult &r) { + return r.rotation_lattice_type + ? fmt::format("{}-centred {}", r.rotation_lattice_type->centering, + gemmi::crystal_system_str(r.rotation_lattice_type->crystal_system)) + : std::string("no lattice"); + }; + if (!cancelled_ && promoted_arm.post_refine && demoted_arm.post_refine + && HeldOutResidualFell(*promoted_arm.post_refine, *demoted_arm.post_refine)) { + logger.Warning("Metric symmetry: re-integrated as {} the held-out residual is {:.3e} " + "against {:.3e} as {} - the equality is not this crystal's, and the " + "run goes on without it", class_text(demoted_arm), realised_demoted, + realised_promoted, class_text(promoted_arm)); + note(fmt::format("the equality dropped: {} fits better", class_text(demoted_arm))); + lattice_arm = fmt::format( + "the metric symmetry was promoted to {} on {} the free refinement leaves " + "{:.2f} {}; re-integrated as {} the held-out residual is {:.3e} against " + "{:.3e}, so the equality was dropped", class_text(promoted_arm), + length_arm ? "axes" : "an angle", length_arm ? 100.0 * split : split * 180.0 / PI, + length_arm ? "% apart" : "deg from 90", + class_text(demoted_arm), realised_demoted, realised_promoted); + } else if (!cancelled_) { + note(fmt::format("the metric symmetry stands: {}", class_text(promoted_arm))); + IndexingSettings promoted_settings = experiment_.GetIndexingSettings(); + promoted_settings.LatticeClassDemoted(false); + experiment_.ImportIndexingSettings(promoted_settings); + lattice_angles_demoted_ = false; + // An arm that indexed nothing, or post-refined nothing, measures no residual. The + // metric symmetry stands either way - that is the arm whose absence of evidence is + // not evidence against it - but the run must not report a comparison it could not + // make: written as a number, a missing residual came out as "realised a held-out + // residual of nan against 1.234e-03, so the metric symmetry stands". + const bool compared = std::isfinite(realised_promoted) && std::isfinite(realised_demoted); + if (compared) { + logger.Info("Metric symmetry: re-integrated as {} the held-out residual is {:.3e}, " + "which {} does not beat ({:.3e}) - the higher symmetry stands", + class_text(promoted_arm), realised_promoted, class_text(demoted_arm), + realised_demoted); + lattice_arm = fmt::format( + "{} was run as well and realised a held-out residual of {:.3e} against {:.3e} " + "as {}, so the metric symmetry stands", class_text(demoted_arm), + realised_demoted, realised_promoted, class_text(promoted_arm)); + } else { + const char *which = !std::isfinite(realised_demoted) && !std::isfinite(realised_promoted) + ? "neither arm measured a held-out residual" + : !std::isfinite(realised_demoted) + ? "the demoted arm measured no held-out residual" + : "the promoted arm measured no held-out residual"; + logger.Info("Metric symmetry: {}, so the two could not be compared - the higher " + "symmetry stands", which); + lattice_arm = fmt::format( + "{} was run as well, but {}, so the two could not be compared and the " + "metric symmetry stands untested", class_text(demoted_arm), which); + } + } + } else { + logger.Info("Metric symmetry: {} - the free refinement departs from it by {:.2f} {}, " + "{:.1f} px at the far corner, inside the integration disc of {:.1f} px, so " + "these data do not resolve the difference", + gemmi::crystal_system_str(pass1.rotation_lattice_type->crystal_system), + length_arm ? 100.0 * split : split * 180.0 / PI, length_arm ? "%" : "deg", + miss_px, disc_px); + } + } + + logger.Info("Rotation two-pass geometry post-refinement: second pass (refined geometry, canonical) -> {}_*", + base_prefix); + speculate_geometry_probe_ = true; // a walk that follows starts with an indexing probe + rerun_if_starved_ = true; + auto pass2 = RunPipeline(observer, /*write_output=*/true, /*geometry_prepass=*/false); + rerun_if_starved_ = false; + speculate_geometry_probe_ = false; + // Run beside the rotation-scale walk, the passes stand only where the walk leaves them standing. + if (rotation_scale_check_) { + if (rotation_scale_check_->Overturns()) + return std::nullopt; + scale_walk = {rotation_scale_check_->passes, rotation_scale_check_->text}; + } + + // Walk the geometry to the fit's fixed point. The post-refinement is fitted to reflections + // integrated at the very geometry it is correcting, so one fit reaches only as far as those + // reflections see: on a header whose distance is several percent long, the pre-pass absorbs the + // error into an inflated cell, and from that self-consistent pair the fit finds a fraction of it + // and stops. The canonical pass has just re-integrated and re-indexed at what it committed, so + // asking the same fit there is the next step of the same walk - and that re-indexing is also the + // RATIFICATION the old size bound stood in for: a second lattice does not index better at a + // geometry it did not come from, a wrong header does, and a pass that lost the crystal is thrown + // out by the quality guard below, which returns the run to the header geometry. + // + // What starts the walk outright is a move of more than one step: that is the fit saying the + // geometry is somewhere else entirely rather than a fraction of a percent away. A smaller move + // has to be preferred by the validation frames first (below), so a run whose fit settles beside + // the geometry in hand costs two indexing probes and no pass. Once the run IS walking + // it keeps walking because the steps do not get smaller in proportion to what is left: measured + // on a header 3.9 % long, the first round took a third of the error and each of the next took a + // third of the rest. + // + // But a round is kept only for what it REALISES, not for what the fit predicts: the held-out + // residual of the pass re-integrated and re-indexed at the new geometry has to fall below the + // best round's by more than the cross-validation noise of the two (HeldOutResidualFell). With + // the walk allowed twelve rounds, every round's fit predicted a gain the re-integration did not + // show - the realised residual stayed flat, or passed a minimum and rose again, while the + // distance crept on along the distance/cell-scale degeneracy - so "the fit still commits" never + // ended a walk, and the cap decided where on the drift the run stopped. A round that does not + // pay ends the walk and the run goes back to the best round it reached. So does a fit whose + // committed cell the re-indexing pushes back the same way twice running (ReindexPushesCellBack): + // the fit keeps asking for a cell the indexer at the fit's own geometry does not return, and + // nothing ratifies it. A walk still paying when the rounds run out keeps its best round - the + // last - and says it did not converge; the quality guard below judges it against the header + // pass as it judges every refined pass. + // + // The residual is not the only thing a round realises. It is the mean over every reflection, + // measured by centroids taken inside a disc centred on the prediction - so they follow the + // prediction part of the way - and dominated by the low-resolution reflections, where a distance + // and the cell scale that compensates it move every spot alike. What does see such an error is + // the re-indexing: the share of the validation spots that land on the lattice, which the + // high-resolution spots lose first. Measured on a crystal whose canonical pass ran 0.6 % long, + // the round at the fit's distance put 70.4 % of the validation spots on the lattice against + // 58.1 %, while reading the residual only 0.74 of its noise lower - and the run the residual + // stopped kept the long distance and lost 0.05 A of resolution. So a round is kept when EITHER + // realises a gain beyond its noise: the residual (HeldOutResidualFell), or the validation + // frames (ValidationEvidencePrefers). + // + // And a move of less than one step no longer settles the geometry by being small: it is asked + // of the validation frames too, but cheaply first - an indexing probe at the fit's geometry + // against one at the geometry in hand, each scoring the lattice and stopping there - and only a + // move the probes prefer pays for a re-integrated round. A move of a step or more is run as a + // round directly, as it always was, and so is every round of the walk it starts. + const auto on_lattice_pct = [](const ValidationSpotEvidence &e) { + return 100.0 * static_cast(e.on_lattice - e.by_chance) + / static_cast(std::max(1, e.spots)); + }; + // An indexing probe at a geometry: the validation evidence of the lattice indexed there, and + // nothing else - the pass stops once the lattice is scored, and the experiment is put back. + const auto index_at_geometry = [&](const std::array &g) { + const DiffractionExperiment before_probe = experiment_; + const bool probe_was = postrefine_probe_; + set_geometry(g); + CollectSpeculativeProbe(); + indexing_probe_only_ = true; + postrefine_probe_ = false; + ProcessResult r; + try { + r = RunPipeline(observer, /*write_output=*/false, /*geometry_prepass=*/false); + } catch (const std::exception &e) { + if (IsFatalResourceError(e)) throw; + logger.Info("Two-pass: the indexing probe at distance {:.3f} mm did not complete ({})", + g[2], e.what()); + } + indexing_probe_only_ = false; + postrefine_probe_ = probe_was; + experiment_ = before_probe; + ++arm_passes; + return r.validation_evidence; + }; + constexpr int MAX_GEOMETRY_ROUNDS = 8; + int geometry_rounds = 0; // passes run at a geometry the walk moved to + int walk_passes = 0; // every pass the walk ran, the return to its best round included + int best_round = 0; + std::array best_geometry = current_geometry(); + PostRefineResult best_fit; // the fit measured in the best round's pass: its realised residual + int last_pushback = 0; + bool geometry_not_converged = false; + std::string walk_stop; // why the walk ended, where anything but the fit settling ended it + std::string walk_rounds; // distance / realised residual per round, for the pass decision + if (pass2.post_refine) { + best_fit = *pass2.post_refine; + walk_rounds = fmt::format("{:.3f} mm / {:.3e} / {:.1f}%", best_geometry[2], best_fit.held_out_before, + on_lattice_pct(pass2.validation_evidence)); + } + ValidationSpotEvidence best_evidence = pass2.validation_evidence; + std::optional probe_at_best; // the indexing probe at best_geometry, once run + bool large_walk = false; // a round of this walk was started by a move of a step or more + // What the last round started from: a pass can leave the run changed behind it (a spot budget + // it shortened, an axis sign it flipped), so a round is written + // from here, not from where its own probe left the run. + DiffractionExperiment last_round_start = experiment_; + bool walk_shown = false; + while (!cancelled_ && prepass_detector_geometry_ + && pass2.post_refine && pass2.post_refine->detector_refined) { + if (!walk_shown) { + step("Geometry check"); + walk_shown = true; + } + if (geometry_rounds == MAX_GEOMETRY_ROUNDS) { + geometry_not_converged = true; + walk_stop = fmt::format("the fit still moved the geometry after {} rounds, every one of " + "which lowered the realised residual", MAX_GEOMETRY_ROUNDS); + logger.Warning("Two-pass: {} - the walk did not converge; the run keeps its last round " + "and the quality guard judges it against the header pass", walk_stop); + break; + } + const PostRefineResult fit = *pass2.post_refine; + const std::array g = *prepass_detector_geometry_; + large_walk = large_walk || fit.large_move; + if (!large_walk) { + if (!probe_at_best) + probe_at_best = index_at_geometry(best_geometry); + const ValidationSpotEvidence probe_at_fit = index_at_geometry(g); + const bool prefers = ValidationEvidencePrefers(*probe_at_best, probe_at_fit); + logger.Info("Two-pass: the post-refinement moves the geometry by less than a step (distance " + "{:.3f} -> {:.3f} mm, beam {:.2f},{:.2f} -> {:.2f},{:.2f} px); indexing probes put " + "{:.1f}% of the validation spots on the lattice beyond chance there against {:.1f}% " + "at the geometry in hand - {}", fit.distance_before_mm, fit.distance_after_mm, + fit.beam_x_before_px, fit.beam_y_before_px, fit.beam_x_after_px, fit.beam_y_after_px, + on_lattice_pct(probe_at_fit), on_lattice_pct(*probe_at_best), + prefers ? "worth a round" : "the geometry in hand stands"); + if (!prefers) + break; + probe_at_best = probe_at_fit; + } + logger.Info("Two-pass: the post-refinement at the adopted geometry still moves it " + "(distance {:.3f} -> {:.3f} mm) - re-integrating and re-indexing at what it " + "asks for (round {} of at most {})", fit.distance_before_mm, + fit.distance_after_mm, geometry_rounds + 1, MAX_GEOMETRY_ROUNDS); + set_geometry(g); + last_round_start = experiment_; + // A round is a probe pass: the walk reads only its fit and its validation evidence, both in + // hand before the merge, so the files are written once, below, at the round the walk keeps. + speculate_geometry_probe_ = !large_walk; + postrefine_probe_only_ = true; + pass2 = RunPipeline(observer, /*write_output=*/false, /*geometry_prepass=*/false); + postrefine_probe_only_ = false; + speculate_geometry_probe_ = false; + ++geometry_rounds; + ++walk_passes; + const double realised = pass2.post_refine ? pass2.post_refine->held_out_before : NAN; + walk_rounds += fmt::format(", {:.3f} mm / {:.3e} / {:.1f}%", g[2], realised, + on_lattice_pct(pass2.validation_evidence)); + const bool residual_fell = pass2.post_refine && HeldOutResidualFell(best_fit, *pass2.post_refine); + const bool evidence_prefers = ValidationEvidencePrefers(best_evidence, pass2.validation_evidence); + if (!pass2.post_refine || !(residual_fell || evidence_prefers)) { + walk_stop = fmt::format( + "round {} lowered neither the realised held-out residual by more than its noise " + "({:.3e} against {:.3e}, standard errors {:.1e} and {:.1e}) nor the share of " + "validation spots off the lattice ({:.1f}% on it beyond chance against {:.1f}%)", + geometry_rounds, realised, best_fit.held_out_before, + pass2.post_refine ? pass2.post_refine->held_out_before_se : NAN, + best_fit.held_out_before_se, on_lattice_pct(pass2.validation_evidence), + on_lattice_pct(best_evidence)); + logger.Info("Two-pass: {}", walk_stop); + break; + } + best_round = geometry_rounds; + best_geometry = g; + best_fit = *pass2.post_refine; + best_evidence = pass2.validation_evidence; + const int pushback = ReindexPushesCellBack(fit, *pass2.post_refine); + if (pushback != 0 && pushback == last_pushback) { + walk_stop = fmt::format( + "re-indexing pushed the cell length {} back against the fit for the second " + "round running, so nothing ratifies the cell the fit asks for", + "abc"[std::abs(pushback) - 1]); + logger.Info("Two-pass: {} - the walk stops at round {}", walk_stop, geometry_rounds); + break; + } + last_pushback = pushback; + } + postrefine_probe_ = false; + if (walk_shown) + note(geometry_rounds == 0 ? std::string("the geometry in hand stands") + : fmt::format("geometry walked {} round{}, round {} kept: distance {:.2f} mm{}", geometry_rounds, + geometry_rounds == 1 ? "" : "s", best_round, best_geometry[2], + best_round > 0 ? " - the files are written again there" : "")); + // The rounds wrote nothing, so the round the walk kept is run again to write the canonical files. + if (!cancelled_ && geometry_rounds > 0) { + if (best_round == geometry_rounds) { + logger.Info("Two-pass: writing round {} of the geometry walk (distance {:.3f} mm)", + best_round, best_geometry[2]); + experiment_ = last_round_start; + } else { + logger.Info("Two-pass: going back to round {} of the geometry walk (distance {:.3f} mm), " + "the last one that lowered the realised residual", best_round, best_geometry[2]); + set_geometry(best_geometry); + } + rerun_if_starved_ = true; + pass2 = RunPipeline(observer, /*write_output=*/true, /*geometry_prepass=*/false); + rerun_if_starved_ = false; + ++walk_passes; + } + + // The post-refinement is measured by pass 1 and consumed by pass 2, so carry it onto whichever + // result is returned - it is a result of the run, not of the pass that happened to fit it. Where + // the walk took rounds they are ONE geometry decision, so what the report names is where the + // geometry started and where the run left it, not the first step of the way there. + if (best_round > 0 && pass1.post_refine) { + pass1.post_refine->beam_x_after_px = best_geometry[0]; + pass1.post_refine->beam_y_after_px = best_geometry[1]; + pass1.post_refine->distance_after_mm = best_geometry[2]; + // A first pass that held the header distance and a walk that then left it: the run's + // decision is the walk's. + pass1.post_refine->distance_held = false; + } + pass2.post_refine = pass1.post_refine; + pass2.pass_number = 2 + scale_walk.passes + arm_passes + walk_passes; + pass2.pass_count = 2 + scale_walk.passes + arm_passes + walk_passes; + if (geometry_rounds > 0) + pass2.pass_decision = fmt::format( + "post-refined geometry walked {} round{} and kept round {}, detector distance {:.3f} mm " + "against the header's {:.3f}: {}; distance / realised held-out residual / validation spots on the lattice beyond chance by round: {}", + geometry_rounds, geometry_rounds == 1 ? "" : "s", best_round, best_geometry[2], + pass1.post_refine ? pass1.post_refine->distance_before_mm : 0.0, + walk_stop.empty() ? "the fit at the kept geometry commits no further move" : walk_stop, + walk_rounds); + + // r2 = r1 + 2 is also the inner edge of the background ring, so widening the signal disk pushes + // that ring out into the neighbours; a reflection whose ring is left with five or fewer clean + // pixels has no background and is dropped whole. On a pattern dense enough in three dimensions + // at once that costs a quarter of the observations - and NOTHING available before integrating + // predicts it: the crystal it happens to has a mid-table predicted spot spacing, wider than + // crystals that survive r1 = 12. What does measure it is the integrator counting its own drops. + // The pass that integrates at the widened radius is now the canonical one, so the measurement + // and the remedy are both here: re-run it at the radius that keeps the data, the same remedy the + // two guards below use and, like them, a pass only on a crystal that was going to be wrong. + // Asked of every pass that can end the run - the two guards below re-run at whatever radius is + // in hand, and a starved refined pass has written nothing (see the superseded flag in + // RunPipeline) - so each is followed by it. After the first re-run the radius is the fixed one + // and this never fires again. + const auto rerun_if_starved = [&](ProcessResult &pass, const std::string decision) { + if (cancelled_ || !bragg_adaptive_ || !bkg_starved_fraction_ + || *bkg_starved_fraction_ <= spot_width::BKG_STARVED_MAX_FRACTION) + return; + logger.Info("Two-pass: at the widened integration radius r1={:.1f} the neighbouring " + "reflections left {:.2f}% of the predicted reflections without a background " + "ring (bound {:.2f}%), so this pass is re-run at r1={:.1f} r2={:.1f} r3={:.2f}", + bragg_adaptive_->GetR1(), 100.0 * *bkg_starved_fraction_, + 100.0 * spot_width::BKG_STARVED_MAX_FRACTION, + bragg_before_adaptive_->GetR1(), bragg_before_adaptive_->GetR2(), + bragg_before_adaptive_->GetR3()); + const double starved = *bkg_starved_fraction_; + const float wide_r1 = bragg_adaptive_->GetR1(); + const int passes = pass.pass_count + 1; + experiment_.ImportBraggIntegrationSettings(*bragg_before_adaptive_); + bragg_adaptive_.reset(); + note(fmt::format("{:.1f}% of the background rings starved: the pass runs again at r1 {:.1f} px", + 100.0 * starved, bragg_before_adaptive_->GetR1())); + pass = RunPipeline(observer, /*write_output=*/true, /*geometry_prepass=*/false); + pass.post_refine = pass1.post_refine; + pass.pass_number = passes; + pass.pass_count = passes; + pass.pass_decision = fmt::format( + "{}, re-run at the fixed integration radius: at r1={:.1f} neighbouring reflections " + "left {:.2f}% of the predicted reflections without a background ring", decision, wide_r1, + 100.0 * starved); + }; + rerun_if_starved(pass2, "post-refined geometry adopted"); + + // Supercell-collapse guard for the second pass. The de-novo lattice search can be BISTABLE on a + // periodically-modulated dataset: the tiny post-refine geometry move tips it out of the true-cell + // basin onto a spurious SUPERCELL (a large multiple of pass-1's cell volume), and the space group + // reused from pass-1 is then stamped onto that wrong-shaped cell - catastrophic. Pass 1 (header + // geometry, un-perturbed) found the correct lattice, so re-run the second pass with pass-1's FULL + // indexing result forced (its refined lattice + orientation + rotation axis + geometry - not just the + // cell, which loses the per-frame orientation and integrates worse): the re-run then matches de-novo + // quality but at the refined geometry. Only fires when pass 2 is markedly LARGER than pass 1 - a + // genuine de-novo demotion to a smaller primitive (the pseudo-symmetry case the second pass re-indexes + // de novo to catch) has pass2 <= pass1 and is left untouched. + if (!cancelled_ && prepass_result_ && pass1.consensus_cell && pass2.consensus_cell) { + // PRIMITIVE volumes, like the two guards in RunPipeline: a centred conventional cell is an + // exact integer multiple of its primitive one (C/I 2x, R 3x, F 4x), so two settings of the + // SAME lattice differ by that factor and comparing the conventional cells reads a mere + // change of setting as a supercell - which then forces pass 1's setting and, with it, its + // lower symmetry. Measured: every dataset this guard fired on was at an exact centring + // multiplicity, one of them an F-centred lattice held down to P1 at 3.99x. + const auto primitive_volume = [](const UnitCell &cell, std::optional centering) { + return std::abs(CrystalLattice(cell).ToPrimitive(centering.value_or('P')).CalcVolume()); + }; + const double v1 = primitive_volume(*pass1.consensus_cell, pass1.consensus_centering); + const double v2 = primitive_volume(*pass2.consensus_cell, pass2.consensus_centering); + if (v1 > 0.0 && v2 > 1.5 * v1) { + logger.Info("Two-pass: second-pass primitive cell volume {:.0f} A^3 is {:.2f}x pass-1's " + "({:.0f} A^3) - a spurious supercell; re-running the second pass with " + "pass-1's result forced", + v2, v2 / v1, v1); + note("a spurious supercell: the pass runs again on the pre-pass lattice"); + force_rotation_result_ = *prepass_result_; + // Pass 1's result carries pass 1's goniometer, and the per-image path takes its angles + // from there - forcing it whole would put the uncorrected angles back and silently undo + // the rotation scale for the re-run. + if (prepass_rotation_scale_ && force_rotation_result_->axis) + force_rotation_result_->axis = + ScaleRotation(*force_rotation_result_->axis, *prepass_rotation_scale_); + rerun_if_starved_ = true; + pass2 = RunPipeline(observer, /*write_output=*/true, /*geometry_prepass=*/false); + rerun_if_starved_ = false; + pass2.post_refine = pass1.post_refine; + pass2.pass_number = 3; + pass2.pass_count = 3; + pass2.pass_decision = fmt::format( + "post-refined geometry adopted, re-run with pass-1's lattice forced: the de-novo " + "primitive cell volume {:.0f} A^3 was {:.2f}x pass-1's ({:.0f} A^3), a spurious " + "supercell", v2, v2 / v1, v1); + // Still forced: the re-run at the fixed radius is the same pass. + rerun_if_starved(pass2, pass2.pass_decision); + force_rotation_result_.reset(); + } + } + // The refined pass is normally the better answer, which is why it is the canonical output - + // but it is not guaranteed to be, and the guard that decides is RefinedPassIsWorse above. It + // has already been asked once, inside the pass itself, which is how a pass that is about to be + // thrown away knows not to write a report; this is where the answer is acted on. + if (!cancelled_ && pass1.has_merge_statistics && pass2.has_merge_statistics) { + logger.Info("Two-pass quality guard: the refined pass holds {} reflections at I/sigma >= 2 and " + "{} at <= -2 of {} in a {:.0f} A^3 primitive cell, the header-geometry pass {} and {} " + "of {} in {:.0f} A^3; low-order axial {} against {}", + pass2.search_merge_strong_reflections, pass2.search_merge_negative_reflections, + pass2.search_merge_reflections, PrimitiveCellVolume(pass2), + pass1.search_merge_strong_reflections, pass1.search_merge_negative_reflections, + pass1.search_merge_reflections, PrimitiveCellVolume(pass1), + pass2.search_merge_axial_reflections, pass1.search_merge_axial_reflections); + const std::string worse = RefinedPassIsWorse(pass1, pass2); + if (!worse.empty()) { + logger.Warning("Two-pass: the refined pass is worse than the header-geometry pass ({}) " + "- going back to the header geometry. The refined geometry did not help " + "this crystal.", worse); + // The refined pass has already written the canonical files, so re-run at the header + // geometry to replace them - the same remedy the supercell collapse above uses, and it + // only costs a pass on a crystal that was going to be wrong otherwise. + experiment_.BeamX_pxl(header_geometry[0]).BeamY_pxl(header_geometry[1]) + .DetectorDistance_mm(header_geometry[2]) + .PoniRot1_rad(header_geometry[3]).PoniRot2_rad(header_geometry[4]); + if (prepass_rotation_scale_ && gonio_snapshot) { + // The header rotation angles with it - but not the axis DIRECTION, which is not + // part of the geometry being reverted and may have been corrected by the sign + // rescue (see the restore before pass 2). + GoniometerAxis restored = *gonio_snapshot; + if (const auto current = experiment_.GetGoniometer()) + restored.Axis(current->GetAxis()); + experiment_.Goniometer(restored); + prepass_rotation_scale_.reset(); + pass1.post_refine->rotation_scale_suspect = false; + } + config_.output_prefix = base_prefix; + // This pass is the answer whatever it measures - the guard has had its one chance - + // so it must not conclude from its own search merge that it is going to be re-run. + quality_guard_pass1_.reset(); + // What the guard preferred is pass 1 - its lattice, orientation and axis at this very + // geometry - so that is what is re-integrated, not a fresh de-novo index. A de-novo + // re-index here is a new hypothesis nobody judged: measured, at the same centre where + // pass 1 indexed 56/60 validation frames it found 5/60, took the opposite axis sign and + // shipped a merge with R_meas in the hundreds of percent. + if (prepass_result_) + force_rotation_result_ = *prepass_result_; + rerun_if_starved_ = true; + note("the refined geometry is worse: the pass runs again at the header geometry"); + auto redo = RunPipeline(observer, /*write_output=*/true, /*geometry_prepass=*/false); + rerun_if_starved_ = false; + redo.post_refine = pass1.post_refine; + redo.pass_number = pass2.pass_count + 1; + redo.pass_count = pass2.pass_count + 1; + redo.pass_decision = fmt::format( + "header geometry re-adopted: the post-refined pass was worse ({})", worse); + // Still forced: the re-run at the fixed radius is the same pass. + rerun_if_starved(redo, redo.pass_decision); + force_rotation_result_.reset(); + return redo; + } + if (pass2.pass_decision.empty()) + pass2.pass_decision = fmt::format( + "post-refined geometry adopted ({}, {})", SearchMergeCompletenessText(pass1, pass2), + SignalText(pass1, pass2)); + } + if (pass2.pass_decision.empty()) + pass2.pass_decision = (prepass_detector_geometry_ || prepass_rotation_scale_) + ? "post-refined geometry adopted" + : "the post-refinement committed no geometry change, so this pass reproduces the first"; + if (!lattice_arm.empty()) + pass2.pass_decision = lattice_arm + "; " + pass2.pass_decision; + if (!scale_walk.text.empty()) + pass2.pass_decision = scale_walk.text + "; " + pass2.pass_decision; + pass2.geometry_not_converged = geometry_not_converged; + return pass2; +} diff --git a/rugnux/RugnuxScaleMerge.cpp b/rugnux/RugnuxScaleMerge.cpp index fc4450246..914f71116 100644 --- a/rugnux/RugnuxScaleMerge.cpp +++ b/rugnux/RugnuxScaleMerge.cpp @@ -2679,11 +2679,15 @@ bool Rugnux::ScaleMergeAndSymmetry(PipelineLocals &p) { // Nothing below this point is read by a later pass: the analyses are report-only (see each), // the files are rewritten by the pass that supersedes this one, and the one place that touches // experiment_ - the model frame - is undone by the SetSpaceGroup at the top of RunPipeline. + // + // A refined pass run beside the rotation-scale walk is superseded too where the walk overturns it + // (see RunAllPasses); it waits here for the walk's answer. superseded = - !cancelled_ && quality_guard_pass1_ && quality_guard_pass1_->has_merge_statistics - && ((bragg_adaptive_ && bkg_starved_fraction_ - && *bkg_starved_fraction_ > spot_width::BKG_STARVED_MAX_FRACTION) - || !RefinedPassIsWorse(*quality_guard_pass1_, result).empty()); + (!cancelled_ && quality_guard_pass1_ && quality_guard_pass1_->has_merge_statistics + && ((bragg_adaptive_ && bkg_starved_fraction_ + && *bkg_starved_fraction_ > spot_width::BKG_STARVED_MAX_FRACTION) + || !RefinedPassIsWorse(*quality_guard_pass1_, result).empty())) + || (rotation_scale_check_ && rotation_scale_check_->Overturns()); if (superseded) { logger.Info("This pass is going to be re-run, so it makes no report and writes no files."); Note("this pass is to be re-run (see the log); it writes nothing");