diff --git a/image_analysis/scale_merge/SearchSpaceGroup.cpp b/image_analysis/scale_merge/SearchSpaceGroup.cpp index de1790b91..c546177f1 100644 --- a/image_analysis/scale_merge/SearchSpaceGroup.cpp +++ b/image_analysis/scale_merge/SearchSpaceGroup.cpp @@ -778,7 +778,14 @@ SearchSpaceGroupResult SearchSpaceGroup( // max_operator_r_over_best and max_operator_r_over_floor). Carried for the same // reason as h_ratio: to report the adopted candidate's whether or not it decided. double r_added = std::numeric_limits::quiet_NaN(); - double r_over_floor = std::numeric_limits::quiet_NaN(); }; + double r_over_floor = std::numeric_limits::quiet_NaN(); + // Report-only, for the finalist ledger: the subgroup b the tests below compared + // this candidate against, whether it survived every consistency test, and - when + // it was the highest refusal - why it did not. The selection loop computes all + // three already and drops them on the floor; the ledger is that table kept. + double parent_b_used = -1.0; + bool eligible = false; + std::string why; }; int refused_order = 0; std::string refused_pg_hm, refused_why; std::vector pg_cands; @@ -948,6 +955,7 @@ SearchSpaceGroupResult SearchSpaceGroup( if (n_new > 0 && pairs_new >= opt.min_pairs_for_h) r_added = r_new / n_new; } + c.parent_b_used = parent_b; c.r_added = r_added; c.r_over_floor = (std::isfinite(r_added) && std::isfinite(result.merge_r_floor) && result.merge_r_floor > 0.0) @@ -1020,6 +1028,10 @@ SearchSpaceGroupResult SearchSpaceGroup( consistent = false; if (!consistent) { + // Same three sentences the highest refusal gets below, but kept per candidate for the + // ledger: short, because the long form is written once for the group the user is told about. + c.why = h_refused ? "H ratio" : r_refused ? "added-operator R" : b_refused ? "systematic b" + : "merge chi^2"; // Record the highest-order refusal so the caller can say WHY it is processing lower. if (c.order > refused_order && c.pg->representative) { refused_order = c.order; @@ -1061,6 +1073,7 @@ SearchSpaceGroupResult SearchSpaceGroup( } continue; } + c.eligible = true; if (c.order > best_pg_order || (c.order == best_pg_order && c.min_class_cc > best_pg_min_cc)) { best_pg = c.pg; best_pg_order = c.order; @@ -1109,6 +1122,38 @@ SearchSpaceGroupResult SearchSpaceGroup( result.r_over_best = c.r_added / global_best_r; } result.h_ratio_bound = opt.max_operator_h_ratio; + result.r_over_best_bound = opt.max_operator_r_over_best; + result.r_over_floor_bound = opt.max_operator_r_over_floor; + + // The FINALIST LEDGER: every operator-confirmed hypothesis with its evidence vector, adopted and + // refused alike. Report-only - nothing below reads it back, and the choice above is already final. + // The numbers are the ones the selection loop formed anyway; what is new is that the losers keep + // theirs instead of being reduced to a single "refused" line. + for (const auto& c : pg_cands) { + PointGroupLedgerEntry e; + e.point_group_hm = c.pg->representative ? c.pg->representative->point_group_hm() : "1"; + e.order = c.order; + e.min_class_cc = c.min_class_cc; + e.chi2 = c.chi2; + if (std::isfinite(c.chi2) && std::isfinite(chi2_ref) && chi2_ref > 0.0) + e.chi2_over_best = c.chi2 / chi2_ref; + e.b_extra = c.b_extra; + if (c.parent_b_used > 1e-4) + e.b_over_parent = c.b_extra / c.parent_b_used; + e.h_ratio = c.h_ratio; + e.r_added = c.r_added; + if (std::isfinite(c.r_added) && std::isfinite(global_best_r) && global_best_r > 0.0) + e.r_over_best = c.r_added / global_best_r; + e.r_over_floor = c.r_over_floor; + e.adopted = (c.pg == best_pg); + e.eligible = c.eligible; + e.refused_reason = c.why; + result.point_group_ledger.push_back(e); + } + std::sort(result.point_group_ledger.begin(), result.point_group_ledger.end(), + [](const PointGroupLedgerEntry& a, const PointGroupLedgerEntry& b) { + return a.order > b.order; + }); // Only report a refusal that is actually ABOVE what was adopted. if (refused_order > best_pg_order) { @@ -1456,6 +1501,102 @@ SearchSpaceGroupResult SearchSpaceGroup( return result; } +static std::string LedgerCell(double v, int prec) { + return std::isfinite(v) ? FormatDouble(v, prec) : std::string("-"); +} + +std::string FinalistLedgerToText(const SearchSpaceGroupResult& result) { + std::ostringstream os; + os << "Finalist ledger - every point group whose operators the intensities confirmed on this " + "merge,\n adopted and refused alike. REPORT-ONLY: the group this run processed in was " + "chosen\n without any of it, and nothing below reads it back.\n"; + + // A search that confirmed no operator has no finalists, and an empty table under a header reads as + // "nothing was wrong" when it means "nothing was asked". Say which it is, and stop. + int confirmed_above_p1 = 0; + for (const auto& e : result.point_group_ledger) + if (e.order > 1) + ++confirmed_above_p1; + if (result.point_group_ledger.empty()) { + os << " No finalists: the search confirmed no point-group operator on this merge, so there is " + "no\n hypothesis to tabulate. This is the expected table for a crystal that is genuinely " + "P1,\n and for one whose operators the correlation stage never confirmed.\n"; + return os.str(); + } + if (confirmed_above_p1 == 0) { + os << " No finalists above P1: the only row is the trivial group, so the ledger has nothing to " + "weigh\n against anything. The table follows for completeness.\n"; + } + + if (std::isfinite(result.merge_r_floor)) { + os << " Reference R floor (random noise, half-set) " << FormatDouble(result.merge_r_floor, 4) + << "; best-agreeing operator R " << LedgerCell(result.global_best_operator_r, 4); + // On the FIRST step out of P1 there is no second operator to be the reference, so this ratio - + // not any row below - carries the whole of the evidence. Spell it out rather than leaving the + // reader to divide two numbers, because that is the case where the table itself is empty. + if (std::isfinite(result.global_best_operator_r) && result.merge_r_floor > 0.0) + os << " (" << FormatDouble(result.global_best_operator_r / result.merge_r_floor, 2) + << "x the floor, bound " << FormatDouble(result.r_over_floor_bound, 2) << ")"; + os << ".\n"; + } + else + os << " Best-agreeing operator R " << LedgerCell(result.global_best_operator_r, 4) + << " (no half-set intensities in this merge, so no random-noise floor;\n every R/floor " + "reads '-' and the first step out of P1 is not measurable here).\n"; + + os << "\n PG ord minCC R_add R/best R/floor | H chi2/best b b/par verdict\n" + " <-- calibrated evidence --> | <--- diagnostic only, NOT evidence --->\n"; + for (const auto& e : result.point_group_ledger) { + os << " " << std::left << std::setw(8) << e.point_group_hm << std::right << std::setw(3) + << e.order + << std::setw(8) << LedgerCell(e.min_class_cc, 3) + << std::setw(8) << LedgerCell(e.r_added, 4) + << std::setw(7) << LedgerCell(e.r_over_best, 2) + << std::setw(8) << LedgerCell(e.r_over_floor, 2) + << " |" << std::setw(6) << LedgerCell(e.h_ratio, 2) + << std::setw(10) << LedgerCell(e.chi2_over_best, 2) + << std::setw(9) << LedgerCell(e.b_extra, 4) + << std::setw(7) << LedgerCell(e.b_over_parent, 2) + << " " << (e.adopted ? "ADOPTED" : e.eligible ? "eligible" : "refused") + << (e.refused_reason.empty() ? "" : " (" + e.refused_reason + ")"); + // The margin, on the row that decided. The value alone does not say how close the run came to + // being refused, and on this corpus that distance is small enough to matter (below). + if (e.adopted && std::isfinite(e.r_over_best) && result.r_over_best_bound > 0.0) + os << " [" << FormatDouble(result.r_over_best_bound - e.r_over_best, 2) + << " below the " << FormatDouble(result.r_over_best_bound, 2) << " bound]"; + else if (e.adopted && std::isfinite(e.r_over_floor) && result.r_over_floor_bound > 0.0) + os << " [" << FormatDouble(result.r_over_floor_bound - e.r_over_floor, 2) + << " below the " << FormatDouble(result.r_over_floor_bound, 2) << " floor bound]"; + os << "\n"; + } + + // How to read it. Every sentence here is something the numbers above have been measured to NOT + // support, and each was a wrong reading somebody actually made. + os << "\n READ IT AS AN ADMISSION TEST, NOT A RANKING: R/best rises with point-group order by\n" + " construction - a larger group adds more operators - so the smallest non-trivial subgroup\n" + " very often has the lowest R/best in the table. Sorting these rows and taking the minimum\n" + " would demote nearly every genuinely high-symmetry crystal. The question the table answers\n" + " is 'the largest order whose R/best stays near 1', not 'which row is smallest'.\n" + "\n ONLY R/best AND R/floor ARE EVIDENCE. They are ratios to a reference a false hypothesis\n" + " cannot move: the best-agreeing operator anywhere in the data, and the crystal's own\n" + " half-set noise floor. H, chi2/best, b and b/par are printed because they are free, and are\n" + " DIAGNOSTIC ONLY - on the calibration set chi2/best and b/par put their LARGEST value on a\n" + " GENUINE crystal, with both known false cases inside the genuine range. A ratio to the\n" + " PARENT is contaminated whenever the parent is itself false, which is exactly the case\n" + " these columns would have to catch. Do not read them as a ranking or a second opinion.\n" + "\n BLIND SPOTS. This table is folded from merged intensities, so it can only see a\n" + " hypothesis that DEGRADES A MERGE. It is structurally blind to the other two ways a group\n" + " is over-called: a screw-axis over-call is in the same Laue class and folds a byte-identical\n" + " merge, and a wrong LATTICE is not a hypothesis here at all - the cell is an input to this\n" + " search, not something it weighs. A crystal whose only error is one of those has a\n" + " clean-looking ledger, and a clean ledger is therefore not a clean bill of health.\n" + "\n MARGIN. On the corpus this was calibrated on, the largest R/best ever seen on a GENUINE\n" + " adopted group is 1.90, against a refusal bound of 2.00. The accept side has ~0.10 of\n" + " headroom, not the wide gap the refused rows suggest, so a margin printed above as small is\n" + " a real one - and any future tightening of this bound has almost none to spend.\n"; + return os.str(); +} + std::string SearchSpaceGroupResultToText(const SearchSpaceGroupResult& result, size_t max_candidates_to_print) { std::ostringstream os; diff --git a/image_analysis/scale_merge/SearchSpaceGroup.h b/image_analysis/scale_merge/SearchSpaceGroup.h index 5e2f29411..c574ff112 100644 --- a/image_analysis/scale_merge/SearchSpaceGroup.h +++ b/image_analysis/scale_merge/SearchSpaceGroup.h @@ -510,6 +510,36 @@ struct SearchSpaceGroupOptions { size_t nthreads = 1; }; +// One row of the FINALIST LEDGER: what the intensities say about ONE point-group hypothesis, on the +// merge this search was handed. Every candidate the operator CCs confirmed gets a row, adopted or +// refused, so a run can show what the rival was and how far behind it came - the current flow keeps +// only the winner and the single highest refusal. +// +// Every number here is PAIRED or a RATIO TO A REFERENCE THE HYPOTHESIS CANNOT MOVE, never an absolute +// per-operator statistic: r_over_best divides by the best-agreeing operator anywhere in the data, +// r_over_floor by the merge's own random-noise floor, chi2_over_best and b_over_parent by the same +// quantity under a subgroup of this very candidate. An absolute score would be the joint-likelihood +// design that was already refuted; a ratio to a clean within-crystal reference is the form thread1_A +// measured to separate genuine operators (1.06-1.15x) from false ones (2.4-4.66x). +// +// REPORT-ONLY. Nothing in the search reads these back; the adoption is made exactly as before. +struct PointGroupLedgerEntry { + std::string point_group_hm; + int order = 0; + double min_class_cc = 0.0; // weakest operator CC among the group's own operators + double chi2 = std::numeric_limits::quiet_NaN(); // merge chi^2 folding under it + double chi2_over_best = std::numeric_limits::quiet_NaN(); // ... over the most consistent subgroup's + double b_extra = 0.0; // systematic-b refit under it + double b_over_parent = std::numeric_limits::quiet_NaN(); // ... over its largest confirmed subgroup's + double h_ratio = std::numeric_limits::quiet_NaN(); + double r_added = std::numeric_limits::quiet_NaN(); // added operators' mean intensity-weighted R + double r_over_best = std::numeric_limits::quiet_NaN(); // ... over the best-agreeing operator anywhere + double r_over_floor = std::numeric_limits::quiet_NaN(); // ... over the merge's random-noise R floor + bool adopted = false; // this is the group the search took + bool eligible = false; // it passed every consistency test (so it COULD have been taken) + std::string refused_reason; // why it did not, when it was the highest refusal +}; + struct SearchSpaceGroupResult { std::optional best_space_group; // Other space groups that fit the data equally well (same systematic absences): enantiomorphic @@ -567,12 +597,28 @@ struct SearchSpaceGroupResult { // Empty when nothing was refused. Surfaced to the user - a silent demotion is how a twin gets missed. std::string refused_point_group_hm; std::string refused_reason; + + // Every operator-confirmed point-group hypothesis with its full evidence vector, ranked by order. + // Report-only (see PointGroupLedgerEntry); the adoption above is unchanged by it. Empty on a search + // that confirmed no operator at all, which the report renders as "no finalists" rather than as an + // empty table - a blank one reads as "nothing was wrong" when it means "nothing was asked". + std::vector point_group_ledger; + // The refusal bounds the ledger's own channels were judged against, copied from the options so the + // report can print the MARGIN the adopted row had rather than only its value. The accept-side + // headroom is thin (measured: the largest genuine adopted r_over_best on a 63-dataset corpus is + // 1.90 against a bound of 2.00), and a margin is the only form in which that is visible per run. + double r_over_best_bound = 0.0; + double r_over_floor_bound = 0.0; }; SearchSpaceGroupResult SearchSpaceGroup( const std::vector& merged, const SearchSpaceGroupOptions& opt = {}); +// The finalist ledger as a ranked table, highest point group first. Report-only; printed behind +// --finalist-ledger so the numbers cannot be read as a decision before they have been calibrated. +std::string FinalistLedgerToText(const SearchSpaceGroupResult& result); + std::string SearchSpaceGroupResultToText( const SearchSpaceGroupResult& result, size_t max_candidates_to_print = 20); diff --git a/rugnux/CMakeLists.txt b/rugnux/CMakeLists.txt index 8883c0df2..b437e2e67 100644 --- a/rugnux/CMakeLists.txt +++ b/rugnux/CMakeLists.txt @@ -32,6 +32,11 @@ ADD_EXECUTABLE(rugnux rugnux_cli.cpp) TARGET_LINK_LIBRARIES(rugnux Rugnux JFJochReader JFJochImageAnalysis JFJochWriter) INSTALL(TARGETS rugnux RUNTIME COMPONENT rugnux) +# Offline finalist-ledger instrument (triage only, not installed): runs the space-group evidence +# table over a stored P1-merged MTZ. +ADD_EXECUTABLE(rugnux_ledger rugnux_ledger.cpp) +TARGET_LINK_LIBRARIES(rugnux_ledger JFJochImageAnalysis JFJochReader gemmi) + # libcufft_static.a carries a relocatable-device-code object (separate_callback.o), so an executable # linking it needs a CUDA device-link step -- without it the host link fails on an undefined # __cudaRegisterLinkedBinary_* symbol. CUDA 13 no longer ships libcufft_static_nocallback.a, which diff --git a/rugnux/Rugnux.cpp b/rugnux/Rugnux.cpp index b4f70e8d6..9e37ca379 100644 --- a/rugnux/Rugnux.cpp +++ b/rugnux/Rugnux.cpp @@ -5163,6 +5163,19 @@ ProcessResult Rugnux::RunPipeline(RugnuxObserver *observer, bool write_output, b logger.Warning("No P1 cross-check dataset written: the fixed space group's centring " "absences were never predicted, so a P1 merge of this run would be " "missing whole centring classes. Re-run without -S to get one."); + // The ledger runs off the P1 cross-check merge below, so every reason that merge is not + // built is also a reason there is no ledger. Say which one it was: a user who gave + // --finalist-ledger and got no table would otherwise have to read this function to find out + // whether the instrument declined, or the crystal simply had nothing to report. + if (config_.finalist_ledger + && !(config_.write_p1_crosscheck && p1_integration_complete && is_rotation)) + logger.Warning("No finalist ledger: it is folded from the P1 cross-check merge, and " + "this run builds none ({}).", + !is_rotation ? "stills - the cross-check is rotation-only for now" + : !config_.write_p1_crosscheck ? "--no-p1-crosscheck was given" + : "a fixed centred space group's absences were never predicted, so a P1 " + "merge would be missing whole centring classes"); + if (config_.write_p1_crosscheck && p1_integration_complete && is_rotation) { // The whole GROUP, not its number: the search can adopt a non-reference setting, and // a number only ever names the reference one - so restoring through the number would @@ -5186,6 +5199,33 @@ ProcessResult Rugnux::RunPipeline(RugnuxObserver *observer, bool write_output, b // the whole of it and restored after. experiment_.SpaceGroupNumber(1); const auto p1 = scale_and_merge("P1 cross-check", false); + + // FINALIST LEDGER (--finalist-ledger), report-only and deliberately behind a flag: these + // numbers are an instrument, and reading them as a decision before they are calibrated + // is the one way this can do harm. + // + // It runs here because THIS merge is the substrate the whole space-group audit says is + // missing and nothing else in the run has: the same observations at full resolution, + // production-scaled with the correction surfaces fitted, and folded under NO symmetry - + // so every hypothesis can be folded from it on equal terms. It is already being built + // for the P1 cross-check file, so the ledger costs one search over it and no merge at + // all. It also carries half-set intensities, which is what lets the random-noise R + // floor be formed - the only reference available to the first step out of P1, and the + // reason this cannot be done from the stored MTZ afterwards. + if (config_.finalist_ledger) { + SearchSpaceGroupOptions lopt; + lopt.nthreads = static_cast(std::max(1, config_.nthreads)); + lopt.merge_friedel = experiment_.GetScalingSettings().GetMergeFriedel(); + if (result.consensus_cell.has_value()) + lopt.cell = gemmi::UnitCell(*result.consensus_cell); + lopt.enumerate_all_settings = true; + lopt.enumerate_all_rotation_sets = true; + lopt.merge_isa = result.error_model_isa; + const auto led = SearchSpaceGroup(p1.merged, lopt); + logger.Info("Finalist ledger on the full-resolution P1 merge ({} reflections):\n{}", + p1.merged.size(), FinalistLedgerToText(led)); + } + const std::string path = config_.output_prefix + "_P1.mtz"; WriteMtzReflections(p1.merged, *result.consensus_cell, experiment_, path); experiment_.SetSpaceGroup(determined_group); diff --git a/rugnux/Rugnux.h b/rugnux/Rugnux.h index f1c43e3c5..2f460af2c 100644 --- a/rugnux/Rugnux.h +++ b/rugnux/Rugnux.h @@ -179,6 +179,7 @@ struct ProcessConfig { // declines it). Every de-novo rotation run writes it, including one that determined P1 itself; // a user-fixed -S writes nothing, because its centring absences were never integrated. bool write_p1_crosscheck = true; + bool finalist_ledger = false; // --finalist-ledger; report-only symmetry evidence table }; struct ProcessResult { diff --git a/rugnux/rugnux_cli.cpp b/rugnux/rugnux_cli.cpp index a403ca728..f37c27b2a 100644 --- a/rugnux/rugnux_cli.cpp +++ b/rugnux/rugnux_cli.cpp @@ -148,6 +148,7 @@ void print_usage() { std::cout << " --scale-fulls rot3d: after the 3D combine, refit a per-frame scale on the fulls (XDS order, Unity model). Default ON for rot3d" << std::endl; std::cout << " --no-scale-fulls Disable the rot3d scale-fulls refit (it is on by default for rot3d)" << std::endl; std::cout << " --write-process-h5 Also write the (large) _process.h5 when merging (default: only .mtz/.cif when merging)" << std::endl; + std::cout << " --finalist-ledger Report the full-resolution evidence for each space group the search considered, not only the one it adopted (report-only; the decision is unchanged)" << std::endl; std::cout << " --smooth-g[=deg] rot3d: smooth per-frame scale G over a deg-degree rotation range (XDS DELPHI-like) before the combine (default: 5 for rot3d; 0 = off)" << std::endl; std::cout << " --relative-b[=deg] rot3d: fit a per-batch relative-B (beyond the single decay slope) over deg-degree batches; cross-validated (default: 10 deg when bare; off otherwise)" << std::endl; std::cout << " --no-scaling-corrections rot3d: disable the (default-on) decay + absorption + modulation correction surfaces fitted on the fulls after scale-fulls" << std::endl; @@ -279,6 +280,7 @@ enum { OPT_ICE_MIN_SPOT_RATIO, OPT_NO_SCALE_FULLS, OPT_WRITE_PROCESS_H5, + OPT_FINALIST_LEDGER, OPT_FORCE_STILL, OPT_AZIM_MIN_Q, OPT_AZIM_MAX_Q, @@ -332,6 +334,7 @@ static option long_options[] = { {"scale-fulls", no_argument, nullptr, OPT_SCALE_FULLS}, {"no-scale-fulls", no_argument, nullptr, OPT_NO_SCALE_FULLS}, {"write-process-h5", no_argument, nullptr, OPT_WRITE_PROCESS_H5}, + {"finalist-ledger", no_argument, nullptr, OPT_FINALIST_LEDGER}, {"smooth-g", optional_argument, nullptr, OPT_SMOOTH_G}, {"relative-b", optional_argument, nullptr, OPT_RELATIVE_B}, {"no-scaling-corrections", no_argument, nullptr, OPT_NO_SCALING_CORRECTIONS}, @@ -681,6 +684,7 @@ static int RunRugnux(int argc, char **argv) { bool write_p1_crosscheck = true; // _P1.mtz is written by default; --no-p1-crosscheck declines it std::optional scale_fulls_arg; // --scale-fulls / --no-scale-fulls; default on for rot3d bool write_process_h5_flag = false; // --write-process-h5; also write _process.h5 when merging + bool finalist_ledger_flag = false; // --finalist-ledger; report-only symmetry evidence table std::optional detect_ice_rings; // --detect-ice-rings[=on|off]; unset => use the dataset (file) value bool index_ice_rings = false; // --index-ice-rings[=on|off]; index on the ice-band spots too std::optional ice_min_score_arg; // --ice-min-score: ice-presence gate on the measured score @@ -1123,6 +1127,9 @@ static int RunRugnux(int argc, char **argv) { case OPT_WRITE_PROCESS_H5: write_process_h5_flag = true; break; + case OPT_FINALIST_LEDGER: + finalist_ledger_flag = true; + break; case OPT_SMOOTH_G: smooth_g_deg_arg = optarg ? parse_double_arg(optarg, "--smooth-g", logger) : SMOOTH_G_DEFAULT_DEG; break; @@ -1443,6 +1450,14 @@ static int RunRugnux(int argc, char **argv) { // --mode scale: re-scale and merge the already-integrated reflections stored in the input file, // without re-running spot finding or integration (folded in from the former rugnux_scale tool). if (mode == RugnuxMode::Scale) { + // --mode scale re-merges reflections that are already integrated and already indexed; it runs + // no space-group search and writes no P1 cross-check, so there is no ledger to print here. Said + // out loud because this mode is the cheap CPU instrument someone calibrating the ledger will + // reach for first, and silence would read as "the ledger found nothing". + if (finalist_ledger_flag) + logger.Warning("No finalist ledger: --mode scale re-merges an already-determined group and " + "runs no space-group search. Use --mode mx, which builds the P1 cross-check " + "merge the ledger is folded from."); // Re-scaling reads reflections a previous run integrated, which only a _process.h5 holds. if (input_is_cbf) { logger.Error("--mode scale needs the integrated reflections in a _process.h5; " @@ -2300,6 +2315,14 @@ static int RunRugnux(int argc, char **argv) { // Scaling and merging are on by default (run_scaling initialised true); --no-merge turns them off // for both rotation and stills, in which case only the per-image _process.h5 is written. + // The finalist ledger is folded from the P1 cross-check merge, so a run that does no merging has + // none to fold. Said here, where the flag that decided it is in hand: the pipeline's own decline + // message sits inside the scaling block and is unreachable once that block is switched off, and + // silence would read as "the ledger found nothing to report" rather than "it never ran". + if (finalist_ledger_flag && !run_scaling) + logger.Warning("No finalist ledger: --no-merge skips scaling and merging, and the ledger is " + "folded from the P1 cross-check merge. Drop --no-merge to get one."); + // Configure Indexing IndexingSettings indexing_settings; indexing_settings.Algorithm(indexing_algorithm); @@ -2592,6 +2615,7 @@ static int RunRugnux(int argc, char **argv) { // When merging, the merged reflections (.mtz/.cif) are the wanted output; skip the large // _process.h5 unless explicitly requested. Without merging, the _process.h5 is the only output. config.write_process_h5 = run_scaling ? write_process_h5_flag : true; + config.finalist_ledger = finalist_ledger_flag; Rugnux process(reader, experiment, *dataset->pixel_mask, config); diff --git a/rugnux/rugnux_ledger.cpp b/rugnux/rugnux_ledger.cpp new file mode 100644 index 000000000..463049b75 --- /dev/null +++ b/rugnux/rugnux_ledger.cpp @@ -0,0 +1,107 @@ +// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute +// SPDX-License-Identifier: GPL-3.0-only + +// Offline finalist-ledger instrument. Reads a P1-merged MTZ - the P1 cross-check dataset every +// rotation run already writes, which is the run's own observations at FULL resolution, production +// scaled, and folded under no symmetry at all - and prints the ledger for it. +// +// The point of reading THAT file is the one the space-group audit keeps arriving at: the search +// decides on a low-resolution, zeta-filtered SEARCH merge, and the full-resolution merge where a +// false operator shows itself is never consulted. This tool consults it, changes nothing, and is +// only an instrument: it exists to measure whether the separation is there before any gate is +// allowed to read it. +// +// A resolution limit may be passed as the 4th argument. That is the paired contrast the whole +// hypothesis rests on: the production search decides on a low-resolution merge, so running the same +// vector twice - once at full range, once cut back to the search range - asks whether the contrast a +// false operator shows is actually being thrown away by the cut, on one crystal, with everything +// else held identical. +// +// Usage: rugnux_ledger [tag] [nthreads] [d_min_A] + +#include +#include +#include +#include +#include + +#include + +#include "../common/Reflection.h" +#include "../image_analysis/scale_merge/SearchSpaceGroup.h" + +int main(int argc, char** argv) { + if (argc < 2) { + std::cout << "Usage: rugnux_ledger [tag] [nthreads]" << std::endl; + return 1; + } + const std::string path = argv[1]; + const std::string tag = argc > 2 ? argv[2] : "-"; + const int nthreads = argc > 3 ? std::atoi(argv[3]) : 4; + const double d_min = argc > 4 ? std::atof(argv[4]) : 0.0; + + gemmi::Mtz mtz; + try { + mtz.read_file_gz(path, true); + } catch (const std::exception& e) { + std::cerr << "LEDGER\t" << tag << "\tREAD_FAIL\t" << e.what() << std::endl; + return 1; + } + + const gemmi::Mtz::Column* ci = mtz.column_with_label("IMEAN", nullptr, 'J'); + const gemmi::Mtz::Column* cs = mtz.column_with_label("SIGIMEAN", nullptr, 'Q'); + if (ci == nullptr || cs == nullptr) { + std::cerr << "LEDGER\t" << tag << "\tNO_IMEAN" << std::endl; + return 1; + } + + std::vector merged; + merged.reserve(static_cast(mtz.nreflections)); + for (int i = 0; i < mtz.nreflections; ++i) { + const size_t row = static_cast(i) * mtz.columns.size(); + MergedReflection r; + r.h = static_cast(std::lround(mtz.data[row + 0])); + r.k = static_cast(std::lround(mtz.data[row + 1])); + r.l = static_cast(std::lround(mtz.data[row + 2])); + r.I = mtz.data[row + ci->idx]; + r.sigma = mtz.data[row + cs->idx]; + if (!std::isfinite(r.I) || !std::isfinite(r.sigma) || r.sigma <= 0.0f) + continue; + r.d = static_cast(mtz.cell.calculate_d( + {{static_cast(r.h), static_cast(r.k), static_cast(r.l)}})); + // I_half stays NaN: the merged MTZ carries no half-set columns, so the random-noise R floor + // cannot be formed here. Every ratio that needs it reads "-" in the table below, and the + // first step out of P1 - the one case with no other operator to be the reference - is + // therefore NOT measurable from a stored MTZ. It needs the in-process hook. + merged.push_back(r); + } + + SearchSpaceGroupOptions opt; + opt.nthreads = static_cast(std::max(1, nthreads)); + opt.cell = mtz.cell; + opt.enumerate_all_settings = true; + opt.enumerate_all_rotation_sets = true; + opt.d_min_limit_A = d_min; + // No lattice_system cap: the metric class this run indexed on is not in the file. Measured over + // 40 crystals when the same question was asked before, the cap was non-binding on every one of + // them, so releasing it here costs nothing and keeps the tool independent of the run's lattice. + + const auto result = SearchSpaceGroup(merged, opt); + + std::cout << "LEDGER\t" << tag << "\tMETA\tdmin=" << d_min << "\tn=" << merged.size() + << "\tcell=" << mtz.cell.a << "," << mtz.cell.b << "," << mtz.cell.c + << "," << mtz.cell.alpha << "," << mtz.cell.beta << "," << mtz.cell.gamma + << "\tpg=" << (result.point_group_hm.empty() ? "?" : result.point_group_hm) + << "\torder=" << result.point_group_order + << "\tsg=" << (result.best_space_group ? result.best_space_group->xhm() : "-") + << "\tbest_op_r=" << result.global_best_operator_r << std::endl; + for (const auto& e : result.point_group_ledger) + std::cout << "LEDGER\t" << tag << "\tROW\t" << e.point_group_hm << "\t" << e.order + << "\t" << e.min_class_cc << "\t" << e.r_added << "\t" << e.r_over_best + << "\t" << e.h_ratio << "\t" << e.chi2_over_best << "\t" << e.b_extra + << "\t" << e.b_over_parent + << "\t" << (e.adopted ? "ADOPTED" : e.eligible ? "eligible" : "refused") + << "\t" << (e.refused_reason.empty() ? "-" : e.refused_reason) << std::endl; + std::cout << std::endl << FinalistLedgerToText(result) << std::endl; + return 0; +}