diff --git a/image_analysis/geom_refinement/PostRefine.cpp b/image_analysis/geom_refinement/PostRefine.cpp index fcb1f15ff..54988e124 100644 --- a/image_analysis/geom_refinement/PostRefine.cpp +++ b/image_analysis/geom_refinement/PostRefine.cpp @@ -820,8 +820,14 @@ PostRefineResult PostRefineRotationGeometry(PostRefineObservations observations, // rocking angles then refuse (measured: a header 1.4 % long leaves the held fit's // excitation residual seventeen times the free fit's). Where freeing the distance // lowers the held-out excitation residual below the held fit's by more than the - // standard error of that residual - the same noise a round of the geometry walk has - // to beat (HeldOutResidualFell) - the free fit is committed exactly as before. Where + // standard error of that change, the free fit is committed exactly as before. The + // error is the PAIRED one (paired_change): both fits are read on the same held-out + // rocking events, so what a change has to beat is the scatter of what each event sees + // change, not the scatter of either fit's residuals, which is mostly the centroids' own + // and common to both. Read unpaired, a header 0.5 % short whose free fit lowered the + // excitation residual by 4.7 paired standard errors was held. A move this lets through + // is still only a candidate: re-integrated at, it has to show the fixed point the + // distance check looks for (FixedPointDistance in rugnux) before the run keeps it. Where // it does not, the held fit is the candidate from here on: what the walk, the gate // and the commit below see. The positional residual is deliberately not consulted // for this. Its in-fit gain along the degenerate direction is the one re-integration @@ -837,8 +843,12 @@ PostRefineResult PostRefineRotationGeometry(PostRefineObservations observations, if (convH) cv_h = joint_cost(VAL, bm_h, ds_h, rv_h, q0_h, q1_h, q2_h, pos_h, exc_h, nullptr, &exc_h_se); - const double noise = std::hypot(exc_ref_se, exc_h_se); - const bool hold_distance = convH && !(std::isfinite(noise) && exc_ref < exc_h - noise); + const PairedChange free_vs_held = convH + ? paired_change(VAL, bm_h, ds_h, rv_h, q0_h, q1_h, q2_h, bm_f, ds_f, rv_f, q0_f, q1_f, q2_f) + : PairedChange{}; + const double noise = free_vs_held.exc_se; + const bool hold_distance = convH && (settings.distance_decided + || !(std::isfinite(noise) && free_vs_held.exc < -noise)); if (settings.distance_at_header) logger.Info("Post-refine GEOM distance: free {:.3f} mm gives held-out excitation {:.3e} +- " "{:.1e} (positional {:.3e}); held at the header {:.3f} mm gives {:.3e} +- " @@ -846,7 +856,7 @@ PostRefineResult PostRefineRotationGeometry(PostRefineObservations observations, "=> {}; the free fit's formal sd(distance) {:.4f} %, corr(distance, cell " "a/b/c) {:.4f} {:.4f} {:.4f}", ds_f[0], exc_ref, exc_ref_se, pos_ref, dist0, exc_h, exc_h_se, pos_h, - exc_ref - exc_h, noise, + free_vs_held.exc, noise, hold_distance ? "the rocking angles do not ask for it, the header distance is held" : convH ? "the free distance pays" : "the held fit did not converge, the free distance stands", @@ -929,6 +939,12 @@ PostRefineResult PostRefineRotationGeometry(PostRefineObservations observations, // (2 %), and on a crystal whose geometry was already right it cut through the noise: two // builds read 1.9 % and 2.05 % for the same 0.03 px move, and one committed and the other // did not. + // Not where the distance test above has just freed the distance: that noise is mostly the + // centroids' own scatter, common to both geometries, so it refused distance moves the + // paired change put at 3 to 14 standard errors - and a freed distance has a ratification + // of its own, by re-integrating along it (FixedPointDistance in rugnux), which a move of + // the beam or the cell alone does not. + const bool distance_freed = convH && !hold_distance; double cv_ref_se = NAN; { double pos_tmp = 0.0, exc_tmp = 0.0; @@ -943,8 +959,34 @@ PostRefineResult PostRefineRotationGeometry(PostRefineObservations observations, "({:+.1f} sd), excitation {:+.3e} +- {:.1e} ({:+.1f} sd)", change.pos, change.pos_se, change.pos / change.pos_se, change.exc, change.exc_se, change.exc / change.exc_se); + // A freed distance can still be refused downstream, and the run is then left where a fit + // with the distance held would have left it: at the held fit's beam where that fit passes + // the gate below as such a fit has to, the pooled test included; at the geometry the pass + // ran at where it does not. + if (distance_freed) { + double pos_tmp = 0.0, exc_tmp = 0.0, cv_h_se = NAN; + joint_cost(VAL, bm_h, ds_h, rv_h, q0_h, q1_h, q2_h, pos_tmp, exc_tmp, &cv_h_se); + const PairedChange c = paired_change(VAL, beam, dist, axv, p0, p1, p2, + bm_h, ds_h, rv_h, q0_h, q1_h, q2_h); + const double held_noise = std::hypot(cv_nom_se, cv_h_se); + if (std::isfinite(held_noise) && cv_h < cv_nom - held_noise && c.pos_n >= 2 + && c.pos < -c.pos_se && (c.exc_n < 2 || c.exc <= c.exc_se) + && out_of_bounds(bm_h, ds_h, q2_h) == nullptr) { + // Re-fitted on all the data from nominal, as the commit below re-fits what it commits. + double bm_a[2] = {beam_x0, beam_y0}, ds_a[1] = {dist0}; + double rv_a[3], q0_a[3], q1_a[3], q2_a[3]; + for (int j = 0; j < 3; ++j) { + rv_a[j] = ax0[j]; q0_a[j] = p0_0[j]; q1_a[j] = p1_0[j]; q2_a[j] = p2_0[j]; + } + if (solve_joint(ALL, /*wide=*/true, /*fix_distance=*/true, bm_a, ds_a, rv_a, q0_a, q1_a, q2_a) + && out_of_bounds(bm_a, ds_a, q2_a) == nullptr) { + result.beam_x_held_px = bm_a[0]; + result.beam_y_held_px = bm_a[1]; + } + } + } - // The two residual families are asked separately as well as together. Pooled, the + // The two residual families are asked separately, not pooled. Pooled, the // positional values outnumber the excitation ones about three to one where both caps // saturate, and the excitation residual is the only one that identifies the cell SCALE - // so a pooled mean can improve on the strength of the positions alone while the one @@ -971,7 +1013,7 @@ PostRefineResult PostRefineRotationGeometry(PostRefineObservations observations, // a weak 7 A crystal whose fit asked for another 1 % at every one of five steps // and 4.3 % in all, against the 1.2 % its cell is actually out by. : steps >= MAX_STEPS ? "the fit used every step it was given and never settled" - : !(std::isfinite(cv_noise) && cv_ref < cv_nom - cv_noise) + : !distance_freed && !(std::isfinite(cv_noise) && cv_ref < cv_nom - cv_noise) ? "the held-out residual did not fall by more than its noise" // Fewer than two values have no noise to fall by more than: the positions cannot show // an improvement, and an excitation family that small is no evidence against one. diff --git a/image_analysis/geom_refinement/PostRefine.h b/image_analysis/geom_refinement/PostRefine.h index 6ae1b3e74..d7ddc80c2 100644 --- a/image_analysis/geom_refinement/PostRefine.h +++ b/image_analysis/geom_refinement/PostRefine.h @@ -64,6 +64,11 @@ struct PostRefineResult { double distance_free_mm = std::numeric_limits::quiet_NaN(); double beam_x_free_px = std::numeric_limits::quiet_NaN(); double beam_y_free_px = std::numeric_limits::quiet_NaN(); + // Where the distance was freed: the beam of the fit with the distance held at the header, where that + // fit would have been committed on its own (NaN otherwise) - what a run that refuses the free distance + // later goes back to. + double beam_x_held_px = std::numeric_limits::quiet_NaN(); + double beam_y_held_px = std::numeric_limits::quiet_NaN(); // The held-out residual at the geometry the fit STARTED from - what the integration this fit was // handed actually realises there, before the fit moves anything - and its standard error over the // held-out values. Two passes at two geometries are compared on this, not on the fit's own @@ -100,6 +105,9 @@ struct PostRefineSettings { // the header - a walk, see RunAllPasses - that hypothesis is already refuted and the distance is // simply free. bool distance_at_header = true; + // The run has already searched along the move this fit would ask for and kept the header distance + // (FixedPointDistance in rugnux): the fit holds it rather than asking again. + bool distance_decided = false; int min_events = 50; int num_threads = 1; // An independent measurement of the beam centre in pixels, where the run has one (rugnux's pre-scan diff --git a/rugnux/Rugnux.h b/rugnux/Rugnux.h index 59ecca013..89dd91128 100644 --- a/rugnux/Rugnux.h +++ b/rugnux/Rugnux.h @@ -1700,6 +1700,9 @@ class Rugnux { // 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. double header_distance_mm_ = std::numeric_limits::quiet_NaN(); + // The distance check refused a move pass 1 committed: the passes after it hold the header distance + // (PostRefineSettings::distance_decided). + bool header_distance_decided_ = false; // Pre-scan: read a spread sample of frames and take what the run needs off them - the shadow of the // beam stop and its holder, added to the pixel mask (config_.detect_beam_stop), the beam centre the diff --git a/rugnux/RugnuxPasses.cpp b/rugnux/RugnuxPasses.cpp index 344c5ecaa..06e82b22c 100644 --- a/rugnux/RugnuxPasses.cpp +++ b/rugnux/RugnuxPasses.cpp @@ -637,7 +637,8 @@ ProcessResult Rugnux::RunAllPasses(RugnuxObserver *observer) { pass1.post_refine->distance_after_mm = (*g)[2]; pass1.post_refine->beam_x_after_px = (*g)[0]; pass1.post_refine->beam_y_after_px = (*g)[1]; - pass1.post_refine->distance_held = false; + pass1.post_refine->distance_held = (*g)[2] == header_geometry[2]; + header_distance_decided_ = pass1.post_refine->distance_held; } if (cancelled_) return pass1; if (prepass_detector_geometry_) { @@ -734,6 +735,8 @@ ProcessResult Rugnux::RunAllPasses(RugnuxObserver *observer) { // asked for 104.4 mm from data integrated at 103 and for 108.6 mm from data integrated at 109, each a // third of the way to where the other started, so a walk that moves to what each round asks for crawls // and stalls short; spot-finder centroids in place of the integrated ones moved neither number. +// Where pass 1 committed a move of the distance itself, that move is searched along in the same way, and +// the run keeps the header distance unless the search finds a fixed point and the fixed point realises. // // So the distance is asked for as what it is, the point where the data integrated there ask for no // move: a few pre-passes at distances along the free fit's direction (the direct beam held where the free @@ -749,10 +752,16 @@ std::optional> Rugnux::FixedPointDistance(RugnuxObserver *o return std::nullopt; const PostRefineResult &held = *pass1.post_refine; const double d0 = experiment_.GetDetectorDistance_mm(); - if (prepass_detector_geometry_ && std::fabs((*prepass_detector_geometry_)[2] - d0) > 1e-3 * d0) - return std::nullopt; // pass 1 moved the distance itself; the walk takes it from there - const double move = held.distance_free_mm - d0; - if (!std::isfinite(move) || std::fabs(move) < POSTREFINE_STEP_BOUND * d0) + // Pass 1 committed a move of the distance itself: the rocking angles asked for it beyond their noise. + // That is a claim about the data as integrated at the header, and it is ratified here like any other + // move, by integrating along it: a header that is wrong asks for a move that shrinks as the data are + // integrated closer to the fixed point, while a move along the direction the data do not determine - + // the distance and the cell scale trading against each other - asks for as much again, or for its + // opposite, from wherever it is integrated. Refused, the run goes back to the header distance. + const bool moved = held.detector_refined && !held.distance_held && prepass_detector_geometry_ + && (*prepass_detector_geometry_)[2] != static_cast(d0); + const double move = (moved ? (*prepass_detector_geometry_)[2] : held.distance_free_mm) - d0; + if (!std::isfinite(move) || (!moved && std::fabs(move) < POSTREFINE_STEP_BOUND * d0)) return std::nullopt; Logger logger("Rugnux"); if (observer) @@ -768,10 +777,23 @@ std::optional> Rugnux::FixedPointDistance(RugnuxObserver *o } const double direct_beam[2] = {held.beam_x_free_px + per_mm[0] * held.distance_free_mm, held.beam_y_free_px + per_mm[1] * held.distance_free_mm}; + // The tilt pass 1's indexing settled on, where pass 1 committed a geometry: it travels with it. + const float tilt[2] = {moved ? (*prepass_detector_geometry_)[3] : experiment_.GetPoniRot1_rad(), + moved ? (*prepass_detector_geometry_)[4] : experiment_.GetPoniRot2_rad()}; const auto geometry_at = [&](double d) { return std::array{static_cast(direct_beam[0] - per_mm[0] * d), static_cast(direct_beam[1] - per_mm[1] * d), static_cast(d), - experiment_.GetPoniRot1_rad(), experiment_.GetPoniRot2_rad()}; + tilt[0], tilt[1]}; + }; + // A committed move the check refuses goes back to what a fit with the distance held at the header + // would have left: its beam where it would have been committed (the free fit's beam was fitted beside + // the distance that is being refused), the geometry the run started from where it would not. + const auto at_header = [&] { + if (!std::isfinite(held.beam_x_held_px) || !std::isfinite(held.beam_y_held_px)) + return std::array{experiment_.GetBeamX_pxl(), experiment_.GetBeamY_pxl(), static_cast(d0), + experiment_.GetPoniRot1_rad(), experiment_.GetPoniRot2_rad()}; + return std::array{static_cast(held.beam_x_held_px), static_cast(held.beam_y_held_px), + static_cast(d0), tilt[0], tilt[1]}; }; // A pre-pass at a distance, on a copy of the run as pass 1 started it: it leaves nothing on the run // but its first-pass memo. @@ -836,7 +858,7 @@ std::optional> Rugnux::FixedPointDistance(RugnuxObserver *o "fixed point - the header stands", text); if (observer) observer->OnNote("the header distance stands"); - return std::nullopt; + return moved ? std::optional(at_header()) : std::nullopt; } const double d_star = std::clamp(-intercept / slope, std::min(d0, points.back().first), std::max(d0, points.back().first)); @@ -854,7 +876,7 @@ std::optional> Rugnux::FixedPointDistance(RugnuxObserver *o observer->OnNote(adopt ? fmt::format("detector distance {:.2f} mm, where the data ask for no move", d_star) : std::string("the header distance stands")); if (!adopt) - return std::nullopt; + return moved ? std::optional(at_header()) : std::nullopt; return geometry_at(d_star); } @@ -1528,6 +1550,23 @@ std::optional Rugnux::RefinedPasses(RugnuxObserver *observer, Pro 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)); + // A distance the round moved to has to be a step toward a fixed point: integrated there, the data + // ask for less of a move than the one just made. Along the direction the data do not determine - + // the distance and the cell scale trading against each other - every distance asks for as much + // again, the realised residual can still fall a little each round, and the walk ratchets away + // (measured: a cubic crystal of a few reflections asked 0.8 % more from every distance it was + // integrated at). + const double distance_moved = g[2] - best_geometry[2]; + const double distance_asked = !pass2.post_refine ? NAN + : std::isfinite(pass2.post_refine->distance_free_mm) ? pass2.post_refine->distance_free_mm + : pass2.post_refine->distance_after_mm; + if (distance_moved != 0.0 && !(std::fabs(distance_asked - g[2]) < std::fabs(distance_moved))) { + walk_stop = fmt::format("round {} moved the distance {:.3f} -> {:.3f} mm and, integrated there, the " + "data ask for {:.3f} mm - no less of a move, so the walk is not approaching " + "a fixed point", geometry_rounds, best_geometry[2], g[2], distance_asked); + logger.Info("Two-pass: {}", walk_stop); + break; + } 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)) { diff --git a/rugnux/RugnuxScaleMerge.cpp b/rugnux/RugnuxScaleMerge.cpp index fb78fc3d0..8de4d8e65 100644 --- a/rugnux/RugnuxScaleMerge.cpp +++ b/rugnux/RugnuxScaleMerge.cpp @@ -1385,6 +1385,7 @@ bool Rugnux::ScaleMergeAndSymmetry(PipelineLocals &p) { prs.distance_at_header = !std::isfinite(header_distance_mm_) || std::fabs(experiment_.GetDetectorDistance_mm() - header_distance_mm_) < 1e-3 * header_distance_mm_; + prs.distance_decided = header_distance_decided_; // The centre the pre-scan measured, where the fit was precise enough to be used as // a centre at all (MAX_BEAM_CENTER_SIGMA_PXL). It does // not move the geometry - it only tells the bound on step B's beam move where else