From 3b7cc499c2f31f73df8fe1f4e15707160b5cf3f0 Mon Sep 17 00:00:00 2001 From: Filip Leonarski Date: Sat, 10 Oct 2026 00:53:37 +0200 Subject: [PATCH 1/3] rugnux: the metric-symmetry check integrates the class that stands once Where the free refinement splits a promoted equality beyond the integration disc, RefinedPasses ran two probe passes (promoted, then demoted) and then integrated the winner a third time as the canonical pass, although the promoted probe and the canonical pass predict the same reflections. Now the demoted arm runs first as a probe, and the canonical pass is the promoted arm itself: it fits its post-refinement before the merge (lattice_arm_check_), compares the held-out residual there with HeldOutResidualFell as before, and stops before merging only if it loses, in which case the demoted class runs as the canonical pass (same number of passes as before). A pass that does not measure a post-refinement as canonical pass drops the one it fitted, and the geometry the fits leave behind is the one the two-probe order left, so every pass downstream starts where it did. Exactness E: merged data and all output files identical to rc175 e9d4f2221 on the 8 sets where the check runs (9sl0, 6yqf, 7atg, lysoI_micromax_pink, myob_x06da_powder_2 promoted kept; 9t6s, 8v2t, lyso_micromax_pink demoted wins), 2 runs each; the only difference is p_report.txt PASS= n-1 of n-1 where the promoted class stands (one pass fewer is run). Decisions and residuals identical. Wall (time -v, base -> new, rep1 / rep2, shared machine): 9sl0 48.4->40.2 / 48.9->39.6 7atg 49.5->31.2 / 33.2->28.7 6yqf 29.4->25.1 / 30.0->39.6 (noisy) lysoI_micromax_pink 23.2->13.0 / 14.5->13.2 myob_x06da_powder_2 13.5->12.0 / 12.6->11.5 losers 8v2t, lyso_micromax_pink, 9t6s: within +-2 s Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01SVmAWnzCmRKAXVUCdc4iNi --- rugnux/Rugnux.h | 11 +++ rugnux/RugnuxPasses.cpp | 151 ++++++++++++++++++++---------------- rugnux/RugnuxScaleMerge.cpp | 36 ++++++++- 3 files changed, 130 insertions(+), 68 deletions(-) diff --git a/rugnux/Rugnux.h b/rugnux/Rugnux.h index 1147a40f1..3a1404ad1 100644 --- a/rugnux/Rugnux.h +++ b/rugnux/Rugnux.h @@ -804,6 +804,17 @@ class Rugnux { // The demoted arm of an ANGLE promotion (see RunAllPasses): the first pass takes the indexer's // free (triclinic) refinement in place of a monoclinic or orthorhombic class. bool lattice_angles_demoted_ = false; + // The metric-symmetry check of the refined passes (see RefinedPasses): the demoted arm has run as + // a probe, and the canonical pass after it is the promoted arm. That pass fits its post-refinement + // before it merges, compares the held-out residual against the demoted arm's, and stops there if + // it loses (lost), so the class that wins is integrated once. + struct LatticeArmCheck { + std::optional demoted; // the demoted arm's post-refinement + std::optional promoted; // the canonical pass's own + bool asked = false; + bool lost = false; + }; + std::optional lattice_arm_check_; // Whether a pass exists only to index: it stops as soon as its first-pass indexing has scored the // lattice on the validation frames (ProcessResult::validation_evidence), before a single image is // integrated. The rotation-scale walk (see RunAllPasses) compares angle models on that score. diff --git a/rugnux/RugnuxPasses.cpp b/rugnux/RugnuxPasses.cpp index ad420551e..caf84a643 100644 --- a/rugnux/RugnuxPasses.cpp +++ b/rugnux/RugnuxPasses.cpp @@ -341,6 +341,7 @@ ProcessResult Rugnux::RunAllPasses(RugnuxObserver *observer) { force_rotation_result_.reset(); bragg_adaptive_.reset(); beam_center_same_lattice_alternative_.reset(); + lattice_arm_check_.reset(); logger.Info("Rotation two-pass geometry post-refinement: first pass (header geometry) -> {}_01_*", base_prefix); @@ -805,10 +806,13 @@ std::optional Rugnux::RefinedPasses(RugnuxObserver *observer, Pro // 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. + // promoted class on a tie, because it is the one that asserts more. The residual is all the + // comparison reads and it is in hand before the scaling engine is built, so the demoted arm is a + // probe-only pass (postrefine_probe_only_), and the promoted arm is the canonical pass itself: it + // fits its post-refinement before it merges, compares there (lattice_arm_check_), and stops only + // if it loses - and only then is the demoted class run as the canonical pass. So no arm pays for + // a merge, a space-group search or a set of correction surfaces, and the class that stands is + // integrated once. 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 @@ -820,9 +824,10 @@ std::optional Rugnux::RefinedPasses(RugnuxObserver *observer, Pro // 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(); + double split = 0.0; + std::optional demoted_arm; // run where the data resolve the equality 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; + 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(), @@ -849,77 +854,25 @@ std::optional Rugnux::RefinedPasses(RugnuxObserver *observer, Pro 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. + // The demoted arm runs first, as a probe: it is compared on the post-refinement's held-out + // residual, so it has to measure one, and a canonical pass only does where the pre-pass + // moved the geometry. The canonical pass below is the promoted arm (lattice_arm_check_). 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); + 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); - } - } + IndexingSettings promoted_settings = experiment_.GetIndexingSettings(); + promoted_settings.LatticeClassDemoted(false); + experiment_.ImportIndexingSettings(promoted_settings); + lattice_angles_demoted_ = false; + lattice_arm_check_ = LatticeArmCheck{.demoted = demoted_arm->post_refine}; } 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 " @@ -935,6 +888,70 @@ std::optional Rugnux::RefinedPasses(RugnuxObserver *observer, Pro 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); + if (lattice_arm_check_) { + // The metric-symmetry check above, decided inside the pass just run (the promoted arm). + const LatticeArmCheck arm = *lattice_arm_check_; + lattice_arm_check_.reset(); + const double realised_promoted = arm.promoted ? arm.promoted->held_out_before : NAN; + const double realised_demoted = arm.demoted ? arm.demoted->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"); + }; + const std::string promoted_class = class_text(pass2); + const std::string demoted_class = class_text(*demoted_arm); + if (arm.lost) { + 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", demoted_class, realised_demoted, + realised_promoted, promoted_class); + note(fmt::format("the equality dropped: {} fits better", demoted_class)); + 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", promoted_class, + length_arm ? "axes" : "an angle", length_arm ? 100.0 * split : split * 180.0 / PI, + length_arm ? "% apart" : "deg from 90", + demoted_class, realised_demoted, realised_promoted); + // The promoted arm stopped before its merge; the demoted class is the canonical pass. + ++arm_passes; + IndexingSettings demoted_settings = experiment_.GetIndexingSettings(); + demoted_settings.LatticeClassDemoted(length_arm); + experiment_.ImportIndexingSettings(demoted_settings); + lattice_angles_demoted_ = angle_arm; + pass2 = RunPipeline(observer, /*write_output=*/true, /*geometry_prepass=*/false); + } else if (!cancelled_) { + note(fmt::format("the metric symmetry stands: {}", promoted_class)); + // 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", + promoted_class, realised_promoted, demoted_class, 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", demoted_class, + realised_demoted, realised_promoted, promoted_class); + } 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", demoted_class, which); + } + } + } rerun_if_starved_ = false; speculate_geometry_probe_ = false; // Run beside the rotation-scale walk, the passes stand only where the walk leaves them standing. diff --git a/rugnux/RugnuxScaleMerge.cpp b/rugnux/RugnuxScaleMerge.cpp index 65d5b7d04..be7bef8ca 100644 --- a/rugnux/RugnuxScaleMerge.cpp +++ b/rugnux/RugnuxScaleMerge.cpp @@ -801,7 +801,40 @@ bool Rugnux::ScaleMergeAndSymmetry(PipelineLocals &p) { config_.nthreads, engine_log, config_.observation_dump_path); rsm->IngestHost(); }); - if (postrefine_probe_ && !geometry_prepass && is_rotation && !postrefine_probe_only_) { + // The canonical pass that is the promoted arm of the metric-symmetry check (RefinedPasses): the + // comparison reads the held-out residual of its post-refinement, so the fit runs here, before the + // merge, and the pass stops if the demoted arm realised the lower residual. Otherwise it goes on + // exactly as the canonical pass it is, leaving behind what the check, run as two probes before + // it, left: the post-refinement only where the pass measures one anyway (postrefine_probe_), and + // the geometry it asks for as the later of the two arms' fits that asked for one. + const bool lattice_arm_asked = lattice_arm_check_ && !lattice_arm_check_->asked && !geometry_prepass + && is_rotation && !postrefine_probe_only_; + if (lattice_arm_asked) { + LatticeArmCheck &arm = *lattice_arm_check_; + arm.asked = true; + const auto geometry_before = prepass_detector_geometry_; + post_refine_geometry(); + arm.promoted = result.post_refine; + arm.lost = !cancelled_ && arm.promoted && arm.demoted && HeldOutResidualFell(*arm.promoted, *arm.demoted); + if ((arm.lost || !postrefine_probe_) && arm.demoted && arm.demoted->ok && arm.demoted->detector_refined) + prepass_detector_geometry_ = geometry_before; + if (arm.lost) { + if (census_future.valid()) + census_future.wait(); + result.processing_time_s = std::chrono::duration( + std::chrono::steady_clock::now() - start_time).count(); + logger.Info("Metric-symmetry check: {} images integrated and post-refined in {:.2f} s - the " + "demoted class realises the lower held-out residual, so this pass does not merge", + result.images_processed, result.processing_time_s); + if (!writer) + return true; + } else if (!postrefine_probe_) + result.post_refine.reset(); + else if (speculate_geometry_probe_ && !cancelled_ && prepass_detector_geometry_ && result.post_refine + && result.post_refine->detector_refined && !result.post_refine->large_move) + StartSpeculativeGeometryProbe(std::make_shared(*this), *prepass_detector_geometry_); + } + if (postrefine_probe_ && !geometry_prepass && is_rotation && !postrefine_probe_only_ && !lattice_arm_asked) { // Nothing in the merge chain reads the fit (RunAllPasses does, after RunPipeline has joined // it), so only the gather runs here: it reads the outcomes, which the chain re-indexes in // place once the space group is settled. The fit and the speculative probe it may start @@ -2749,6 +2782,7 @@ bool Rugnux::ScaleMergeAndSymmetry(PipelineLocals &p) { && ((bragg_adaptive_ && bkg_starved_fraction_ && *bkg_starved_fraction_ > spot_width::BKG_STARVED_MAX_FRACTION) || !RefinedPassIsWorse(*quality_guard_pass1_, result).empty())) + || (lattice_arm_check_ && lattice_arm_check_->lost) // only with a _process.h5 open, see above || (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."); From 5cedb69833cb720b5ff58d63611e4aa17df1fb01 Mon Sep 17 00:00:00 2001 From: Filip Leonarski Date: Sat, 10 Oct 2026 00:54:51 +0200 Subject: [PATCH 2/3] rugnux: a canonical pass the geometry walk will replace stops early Every round the geometry walk takes ends in a pass that writes the files again, so the canonical pass before it spent its space-group search, merges, analyses, model validation and files on an answer nobody reads. The walk's first question needs only that pass's post-refinement and, for a move of less than a step, two indexing probes. The speculative probe now runs both beside the merge - at the fit's geometry as before, then at the geometry in hand, which the walk otherwise indexed after the pass (a memo hit where the pass's own first pass left one) - and GeometryWalkTakesRound reads the walk's answer from the same first-pass memos the walk's probes then read. The canonical pass asks it, without waiting, before its space-group search (stops there; not with a _process.h5 open) and again at the superseded point before the analyses. An answer not yet in leaves the pass to finish as before, so only timing depends on when the probes finish; the walk itself is unchanged. Exactness E (not F): merged data and all output files identical to rc175 e9d4f2221 on every walking set, 2 runs each; decisions identical. Fired: before the search on 7ph1, 5m17, 8pqd; at the superseded point on 2xfw, 6zr0, 9t6s; on 6zqy the probes were not in by either point in these runs; 8xtf's canonical pass is starved and never merges. Wall (time -v, base -> new, rep1 / rep2, shared machine): 5m17 65.9->57.0 / 68.5->56.7 8pqd 49.8->43.0 / 50.0->43.1 7ph1 51.1->48.9 / 51.1->45.3 6zr0 31.1->22.7 / 24.4->21.1 2xfw 101.2->66.7 / 48.2->48.2 (rep1 base noisy) 6zqy 27.3->26.1 / 26.8->25.7 controls myob_x10sa, cytc_x10sa, 11if, kdp_x10sa_20keV, 8a1a: no change beyond machine noise Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01SVmAWnzCmRKAXVUCdc4iNi --- rugnux/Rugnux.cpp | 26 ++++++++++++++++++------- rugnux/Rugnux.h | 16 +++++++++++---- rugnux/RugnuxPasses.cpp | 39 +++++++++++++++++++++++++++++++++++++ rugnux/RugnuxScaleMerge.cpp | 14 +++++++++++-- 4 files changed, 82 insertions(+), 13 deletions(-) diff --git a/rugnux/Rugnux.cpp b/rugnux/Rugnux.cpp index 3c482e382..1b4aa19da 100644 --- a/rugnux/Rugnux.cpp +++ b/rugnux/Rugnux.cpp @@ -397,22 +397,28 @@ void Rugnux::StartSpeculativeGeometryProbe(std::shared_ptr run, const st run->prepass_detector_geometry_ = prepass_detector_geometry_; run->speculative_probe_.reset(); run->speculate_geometry_probe_ = false; - run->experiment_.BeamX_pxl(geometry[0]).BeamY_pxl(geometry[1]).DetectorDistance_mm(geometry[2]) - .PoniRot1_rad(geometry[3]).PoniRot2_rad(geometry[4]); run->indexing_probe_only_ = true; run->postrefine_probe_ = false; run->postrefine_probe_only_ = false; run->rerun_if_starved_ = false; + // The walk's other probe, at the geometry in hand, on a copy of its own: where this pass's own + // first pass has not left its memo the walk would index there too, after the pass. + auto hand = std::make_shared(*run); + run->experiment_.BeamX_pxl(geometry[0]).BeamY_pxl(geometry[1]).DetectorDistance_mm(geometry[2]) + .PoniRot1_rad(geometry[3]).PoniRot2_rad(geometry[4]); auto sp = std::make_shared(); sp->run = run; + sp->hand = hand; // A probe that fails leaves no memo, and the walk's own probe then runs it again and meets the // failure itself. It runs beside the merge of the pass that started it, on the same card: a merge // that does not fit beside it waits for it to end (GPUWorkBeside). - sp->done = std::async(std::launch::async, [run] { + sp->done = std::async(std::launch::async, [run, hand] { GPUWorkBeside beside; - try { - run->RunPipeline(nullptr, /*write_output=*/false, /*geometry_prepass=*/false); - } catch (const std::exception &) { + for (const auto &r : {run, hand}) { + try { + r->RunPipeline(nullptr, /*write_output=*/false, /*geometry_prepass=*/false); + } catch (const std::exception &) { + } } }); speculative_probe_ = std::move(sp); @@ -432,6 +438,8 @@ void Rugnux::CollectSpeculativeProbe() { speculative_probe_->done.wait(); for (const auto &m : speculative_probe_->run->first_pass_memo_) AddFirstPassMemo(m); + for (const auto &m : speculative_probe_->hand->first_pass_memo_) + AddFirstPassMemo(m); speculative_probe_.reset(); } @@ -491,7 +499,11 @@ std::vector Rugnux::SpotFindingKey(const DiffractionExperiment &x, } std::vector Rugnux::FirstPassInputKey() const { - std::vector k = ExperimentKey(); + return FirstPassInputKey(experiment_); +} + +std::vector Rugnux::FirstPassInputKey(const DiffractionExperiment &e) const { + std::vector k = ExperimentKey(e); // Run state the first pass reads besides the experiment. k.insert(k.end(), {static_cast(lattice_angles_demoted_), prepass_rotation_scale_.value_or(-1.0f), static_cast(force_rotation_result_.has_value()), diff --git a/rugnux/Rugnux.h b/rugnux/Rugnux.h index 3a1404ad1..65bcdf160 100644 --- a/rugnux/Rugnux.h +++ b/rugnux/Rugnux.h @@ -851,14 +851,17 @@ class Rugnux { [[nodiscard]] std::vector SpotFindingKey(const DiffractionExperiment &x, const AzimuthalIntegrationMapping &mapping) const; void AddFirstPassMemo(const FirstPassMemo &memo); - // The geometry walk's next indexing probe, started on a copy of the run as soon as the canonical - // pass has post-refined - it depends on nothing that pass does afterwards - so that it runs beside - // the pass's scaling, merge and output. It leaves its evidence in the copy's first-pass memo, and - // the walk's own probe takes it from there through the usual key check (CollectSpeculativeProbe). + // The geometry walk's next indexing probes - at the fit's geometry, then at the geometry in hand + // (a memo hit where the pass's own first pass left one) - started on copies of the run as soon as + // the canonical pass has post-refined - they depend on nothing that pass does afterwards - so that + // they run beside the pass's scaling, merge and output. They leave their evidence in the copies' + // first-pass memos, and the walk's own probes take it from there through the usual key check + // (CollectSpeculativeProbe). // RunAllPasses sets speculate_geometry_probe_ on the passes whose post-refinement the walk will // probe with an indexing pass. struct SpeculativeProbe { std::shared_ptr run; + std::shared_ptr hand; // the walk's probe at the geometry in hand, after run's std::future done; }; std::shared_ptr speculative_probe_; @@ -869,6 +872,11 @@ class Rugnux { void StartSpeculativeGeometryProbe(std::shared_ptr run, const std::array &geometry); void CollectSpeculativeProbe(); [[nodiscard]] std::vector FirstPassInputKey() const; + // The same, with another experiment in place of the run's. + [[nodiscard]] std::vector FirstPassInputKey(const DiffractionExperiment &e) const; + // Whether the geometry walk after the canonical pass will take a round, asked by that pass from + // what it already has in hand; `fit` is its post-refinement running beside the merge (RefinedPasses). + [[nodiscard]] bool GeometryWalkTakesRound(const ProcessResult &result, const std::future &fit) 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 { diff --git a/rugnux/RugnuxPasses.cpp b/rugnux/RugnuxPasses.cpp index caf84a643..787290c16 100644 --- a/rugnux/RugnuxPasses.cpp +++ b/rugnux/RugnuxPasses.cpp @@ -727,6 +727,45 @@ RotationScaleWalk Rugnux::WalkRotationScaleBeside(const ProcessResult &pass1, Ro } } +// The geometry walk's first question (see RefinedPasses), asked by the canonical pass before its +// space-group search and again before its analyses: every round the walk takes ends in a pass that +// writes the files again, so a canonical pass the walk is going to replace only spends its merge, +// model validation and files on an answer nobody reads. The question needs the pass's own +// post-refinement and, for a move of less than a step, the walk's two indexing probes, which the +// speculative probe runs beside the merge (or the pass's own first pass has run) - taken from the +// first-pass memos the walk's probes read them from, so the answer is the walk's own. Nothing waits +// for it: an answer not yet in leaves the pass to finish as it always did. +bool Rugnux::GeometryWalkTakesRound(const ProcessResult &result, const std::future &fit) const { + const auto ready = [](const std::future &f) { + return !f.valid() || f.wait_for(std::chrono::seconds(0)) == std::future_status::ready; + }; + if (!speculate_geometry_probe_ || cancelled_ || !ready(fit) || !prepass_detector_geometry_ + || !result.post_refine || !result.post_refine->detector_refined) + return false; + if (result.post_refine->large_move) + return true; + if (config_.verify_first_pass_memo || !speculative_probe_ || !ready(speculative_probe_->done)) + return false; + const auto evidence_at = [&](const std::array &g) -> std::optional { + DiffractionExperiment e = experiment_; + e.SetSpaceGroup(user_fixed_sg_); // as RunPipeline starts every pass + e.BeamX_pxl(g[0]).BeamY_pxl(g[1]).DetectorDistance_mm(g[2]).PoniRot1_rad(g[3]).PoniRot2_rad(g[4]); + const std::vector key = FirstPassInputKey(e); + const std::vector *memos[] = {&first_pass_memo_, &speculative_probe_->run->first_pass_memo_, + &speculative_probe_->hand->first_pass_memo_}; + for (const auto *list : memos) + for (const auto &m : *list) + if (m.key == key) + return m.evidence; + return std::nullopt; + }; + const auto at_hand = evidence_at({experiment_.GetBeamX_pxl(), experiment_.GetBeamY_pxl(), + experiment_.GetDetectorDistance_mm(), experiment_.GetPoniRot1_rad(), + experiment_.GetPoniRot2_rad()}); + const auto at_fit = evidence_at(*prepass_detector_geometry_); + return at_hand && at_fit && ValidationEvidencePrefers(*at_hand, *at_fit); +} + // 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, diff --git a/rugnux/RugnuxScaleMerge.cpp b/rugnux/RugnuxScaleMerge.cpp index be7bef8ca..55e5a2fd7 100644 --- a/rugnux/RugnuxScaleMerge.cpp +++ b/rugnux/RugnuxScaleMerge.cpp @@ -1243,6 +1243,14 @@ bool Rugnux::ScaleMergeAndSymmetry(PipelineLocals &p) { // above triclinic - i.e. a promotion was made, which is what makes a later "the Laue class is // holohedral so there is no twin law" conclusion circular. bool promoted_point_group = false; + // A canonical pass the geometry walk is going to replace stops here, where the answer is + // already in (GeometryWalkTakesRound); it is asked again below, before the analyses. Not with a + // _process.h5 open: that file is written whole by every pass that opens it. + if (!writer && GeometryWalkTakesRound(result, p.postrefine_ahead)) { + logger.Info("The geometry walk will re-integrate at the geometry the post-refinement asks for, " + "so this pass stops before its space-group search"); + return true; + } TimingMark search_mark(logger, "space-group search"); if (search_space_group) { SearchSpaceGroupOptions sg_opts; @@ -2775,14 +2783,16 @@ bool Rugnux::ScaleMergeAndSymmetry(PipelineLocals &p) { // 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. + // So is a canonical pass the geometry walk is going to replace, where that answer is in by now + // (GeometryWalkTakesRound). 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())) || (lattice_arm_check_ && lattice_arm_check_->lost) // only with a _process.h5 open, see above + || GeometryWalkTakesRound(result, p.postrefine_ahead) || (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."); From 7664b22ea6a8f68dfa61eb86906cada1acd31bda Mon Sep 17 00:00:00 2001 From: Filip Leonarski Date: Sat, 10 Oct 2026 00:56:14 +0200 Subject: [PATCH 3/3] rugnux: the rotation-scale walk runs first where pass 1's fit is a step off Where pass 1's rotation-scale fit is a step or more (STEP_BOUND, 1 %) off the stored angles, the walk runs on its own before the refined passes instead of beside an output pass that a refit calls off and throws away. Scheduling only: the run ends where the sequential walk leaves it either way (the overturned path already re-ran the refined passes on the run itself). Exactness E: all output files identical to rc175 e9d4f2221 on 9gdj, 9qw8, 6ttn, lalanine, 9t6s, 2 runs each. Note: "the walk will then always refit" does not hold. Of the four battery sets with the fit >= 1 % off (9gdj 0.980, 9qw8 0.988, 9t6s 1.012, lalanine 1.012), the stored angles stand on 9t6s and lalanine, which now walk first and lose the overlap of the walk's two probes with the output pass (~0.5-0.8 s of probe time); 6ttn (0.998) is below the step and unchanged. Wall (time -v, base -> new, rep1 / rep2, shared machine): 9gdj 99.6->109.7 / 107.4->101.4 (rep1 new run noisy) 9qw8 43.1->39.2 / 34.4->33.3 9t6s 18.1->18.2 / 18.9->18.5 lalanine 20.5->19.7 / 7.9->8.3 Pre-rebase run on rc175 0b2dde214: 9gdj 99.6->93.8 and 99.6->93.4. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01SVmAWnzCmRKAXVUCdc4iNi --- rugnux/RugnuxPasses.cpp | 59 +++++++++++++++++++++++++---------------- 1 file changed, 36 insertions(+), 23 deletions(-) diff --git a/rugnux/RugnuxPasses.cpp b/rugnux/RugnuxPasses.cpp index 787290c16..2dae6e2b3 100644 --- a/rugnux/RugnuxPasses.cpp +++ b/rugnux/RugnuxPasses.cpp @@ -557,33 +557,46 @@ ProcessResult Rugnux::RunAllPasses(RugnuxObserver *observer) { // 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. + // + // Except where pass 1's fit is a step or more off the stored angles (STEP_BOUND in + // PostRefine.cpp): there the walk moves off them and refits as a rule, which calls the output + // pass off and throws it away, so the walk runs first, on its own, and the refined passes + // after it. Either way the run ends where the sequential walk leaves it. + constexpr double ROTATION_SCALE_STEP = 0.01; if (!cancelled_ && gonio_snapshot && pass1.post_refine && !config_.rotation_scale) { 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); - }); + RotationScaleWalk walk; + if (std::fabs(pass1.post_refine->rotation_scale - 1.0) >= ROTATION_SCALE_STEP) { + check->Set(check->output_indexed); + check->Set(check->output_ended); + walk = WalkRotationScaleBeside(pass1, *check, CancelFlag()); + } else { + 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(); - } - 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; + std::optional result; + std::exception_ptr output_error; + try { + result = output->RefinedPasses(observer, pass1, start); + } catch (...) { + output_error = std::current_exception(); + } + check->Set(check->output_indexed); + check->Set(check->output_ended); + walk = walk_done.get(); + if (!check->overturns) { + if (output_error) + std::rethrow_exception(output_error); + return *result; + } } - // Overturned: the refined passes run again, on the run itself. + // Overturned, or the walk ran first: the refined passes run on the run itself. start.scale_walk = {check->passes, check->text}; if (walk.scale != 1.0f) { step("Rotation-scale check"); @@ -596,7 +609,7 @@ 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 + } else if (check->overturns) logger.Info("Two-pass: the rotation-scale walk changed the spot finding the refined passes " "start from, so they run again after it"); }