diff --git a/image_analysis/IndexAndRefine.cpp b/image_analysis/IndexAndRefine.cpp index b21475948..f4fca96c5 100644 --- a/image_analysis/IndexAndRefine.cpp +++ b/image_analysis/IndexAndRefine.cpp @@ -484,7 +484,8 @@ void IndexAndRefine::QuickPredictAndIntegrate(DataMessage &msg, const SpotFindingSettings &spot_finding_settings, BraggPrediction &prediction, const BraggIntegrateFn &integrate, - const IndexAndRefine::IndexingOutcome &outcome) { + const IndexAndRefine::IndexingOutcome &outcome, + const BraggIntegrateFn &probe_integrate) { if (!outcome.lattice_candidate) return; @@ -611,6 +612,78 @@ void IndexAndRefine::QuickPredictAndIntegrate(DataMessage &msg, const std::unique_lock ul(reflections_mutex); integration_outcome[msg.number] = std::move(i_outcome); } + + if (probe_integrate && std::binary_search(supercell_probe_frames_.begin(), supercell_probe_frames_.end(), + msg.number)) + ProbeSupercellFrame(msg, prediction, probe_integrate, outcome, settings_prediction); +} + +SupercellProbeFit FitSupercellProbe(const SupercellProbeClass &c) { + SupercellProbeFit f; + if (c.n < 3) + return f; + const double n = static_cast(c.n); + const double mp = c.sum_p / n, mi = c.sum_i / n; + const double spp = c.sum_pp - n * mp * mp, spi = c.sum_pi - n * mp * mi, sii = c.sum_ii - n * mi * mi; + f.mean_i = mi; + f.mean_p = mp; + f.mean_i_over_sigma = c.sum_i_over_sigma / n; + if (spp > 0.0) { + f.b = spi / spp; + f.b_se = std::sqrt(std::max(0.0, sii - f.b * spi) / (n - 2.0) / spp); + } + f.a = mi - f.b * mp; + return f; +} + +void IndexAndRefine::ProbeSupercell(std::vector image_numbers) { + std::sort(image_numbers.begin(), image_numbers.end()); + supercell_probe_frames_ = std::move(image_numbers); + supercell_probe_ = {}; +} + +SupercellProbe IndexAndRefine::GetSupercellProbe() { + const std::unique_lock ul(supercell_probe_mutex_); + return supercell_probe_; +} + +void IndexAndRefine::ProbeSupercellFrame(const DataMessage &msg, BraggPrediction &prediction, + const BraggIntegrateFn &integrate, const IndexingOutcome &outcome, + const BraggPredictionSettings &settings) { + // The band the classes are read over. A superstructure class is weakest at low resolution (the two + // halves of the cell differ in detail, not in position), so the band reaches to 3 A; 20 A keeps the + // strongest, most overlap-prone low-order reflections of the lattice out of the denominator. The + // prediction stops at 3 A as well, which is what keeps eight times the nodes of a frame affordable. + constexpr float BAND_LOW_RES_A = 20.0f; + constexpr float BAND_HIGH_RES_A = 3.0f; + + const CrystalLattice prim = outcome.lattice_candidate->ToPrimitive(outcome.symmetry.centering); + const CrystalLattice super(prim.Vec0() * 2.0f, prim.Vec1() * 2.0f, prim.Vec2() * 2.0f); + BraggPredictionSettings s = settings; + s.centering = 'P'; + s.high_res_A = std::max(settings.high_res_A, BAND_HIGH_RES_A); + ApplyPredictionRange(s, experiment, super); + const auto nrefl = prediction.Calc(outcome.experiment, super, s); + const std::vector integrated = integrate(prediction.GetReflections(), nrefl, msg.number); + + SupercellProbe frame{}; + for (const auto &r : integrated) { + if (!(r.d > BAND_HIGH_RES_A && r.d <= BAND_LOW_RES_A) || !(r.sigma > 0.0f) || !std::isfinite(r.I) + || !std::isfinite(r.partiality)) + continue; + auto &c = frame[4 * (r.h & 1) + 2 * (r.k & 1) + (r.l & 1)][r.d > 5.0f ? 0 : 1]; + c.n++; + c.sum_i += r.I; + c.sum_i_over_sigma += r.I / r.sigma; + c.sum_p += r.partiality; + c.sum_pp += r.partiality * r.partiality; + c.sum_pi += r.partiality * r.I; + c.sum_ii += static_cast(r.I) * r.I; + } + const std::unique_lock ul(supercell_probe_mutex_); + for (int i = 0; i < 8; i++) + for (int j = 0; j < 2; j++) + supercell_probe_[i][j] += frame[i][j]; } std::optional @@ -652,10 +725,11 @@ IndexAndRefine::DetermineRefineAnalyze(DataMessage &msg, const SpotFindingSettin void IndexAndRefine::ProcessImage(DataMessage &msg, const SpotFindingSettings &spot_finding_settings, BraggPrediction &prediction, - const BraggIntegrateFn &integrate) { + const BraggIntegrateFn &integrate, + const BraggIntegrateFn &probe_integrate) { auto outcome = DetermineRefineAnalyze(msg, spot_finding_settings); if (outcome && spot_finding_settings.quick_integration) - QuickPredictAndIntegrate(msg, spot_finding_settings, prediction, integrate, *outcome); + QuickPredictAndIntegrate(msg, spot_finding_settings, prediction, integrate, *outcome, probe_integrate); } bool IndexAndRefine::IndexFrameOnly(DataMessage &msg, const SpotFindingSettings &spot_finding_settings) { diff --git a/image_analysis/IndexAndRefine.h b/image_analysis/IndexAndRefine.h index 56904f78e..7d5537fe0 100644 --- a/image_analysis/IndexAndRefine.h +++ b/image_analysis/IndexAndRefine.h @@ -3,6 +3,7 @@ #pragma once +#include #include #include #include @@ -29,6 +30,33 @@ using BraggIntegrateFn = std::function( const std::vector &predicted, size_t npredicted, int64_t image_number)>; +// What the supercell probe (IndexAndRefine::ProbeSupercell) reads for one of the eight parity classes +// of the 2a x 2b x 2c primitive supercell in one resolution shell: class 4*(h&1) + 2*(k&1) + (l&1) in +// supercell indices, so class 0 is the adopted lattice and each of the other seven is one index-2 +// superstructure. The partiality sums are for the fit I = a + b p over the class: b is the part of +// it that rocks like a Bragg reflection, a what sits at its position whatever the rocking. +struct SupercellProbeClass { + int64_t n = 0; + double sum_i = 0.0, sum_i_over_sigma = 0.0; + double sum_p = 0.0, sum_pp = 0.0, sum_pi = 0.0, sum_ii = 0.0; + SupercellProbeClass &operator+=(const SupercellProbeClass &o) { + n += o.n; + sum_i += o.sum_i; sum_i_over_sigma += o.sum_i_over_sigma; + sum_p += o.sum_p; sum_pp += o.sum_pp; sum_pi += o.sum_pi; sum_ii += o.sum_ii; + return *this; + } +}; +// [class][shell], the shells 20-5 A and 5-3 A. +using SupercellProbe = std::array, 8>; + +// One parity class of the supercell probe, fitted I = a + b p over partiality p: b (with its standard +// error) is what rocks like a Bragg reflection, a what does not. +struct SupercellProbeFit { + double mean_i = 0.0, mean_i_over_sigma = 0.0, mean_p = 0.0; + double a = 0.0, b = 0.0, b_se = 0.0; +}; +SupercellProbeFit FitSupercellProbe(const SupercellProbeClass &c); + class IndexAndRefine { // When false, the current image's result is still returned via the outgoing message, but the // whole-run integration_outcome vector is not retained (viewer live/interactive use, which never @@ -92,6 +120,14 @@ class IndexAndRefine { std::vector scale_cc; std::vector > unit_cells; + // Supercell probe: the image numbers it reads, and what it has read (see ProbeSupercell). + std::vector supercell_probe_frames_; + SupercellProbe supercell_probe_{}; + std::mutex supercell_probe_mutex_; + void ProbeSupercellFrame(const DataMessage &msg, BraggPrediction &prediction, + const BraggIntegrateFn &integrate, const IndexingOutcome &outcome, + const BraggPredictionSettings &settings); + IndexingOutcome DetermineLatticeAndSymmetryRotation(DataMessage &msg); IndexingOutcome DetermineLatticeAndSymmetry(DataMessage &msg); // Shared indexing path: determine the lattice/symmetry, refine geometry, and run AnalyzeIndexing. @@ -106,7 +142,8 @@ class IndexAndRefine { const SpotFindingSettings &spot_finding_settings, BraggPrediction &prediction, const BraggIntegrateFn &integrate, - const IndexingOutcome &outcome); + const IndexingOutcome &outcome, + const BraggIntegrateFn &probe_integrate); std::unique_ptr reindex_resolver; void ScaleImage(DataMessage &msg, IntegrationOutcome& outcome); @@ -138,8 +175,20 @@ public: // Returns whether the frame indexed (a lattice was found and refined). Integration, when it runs, // is a further step gated on quick_integration. + // probe_integrate integrates the supercell probe's reflections (ProbeSupercell); a caller that + // gives none takes no part in the probe. void ProcessImage(DataMessage &msg, const SpotFindingSettings &settings, - BraggPrediction &prediction, const BraggIntegrateFn &integrate); + BraggPrediction &prediction, const BraggIntegrateFn &integrate, + const BraggIntegrateFn &probe_integrate = {}); + + // Does the lattice each frame is refined on have an index-2 superstructure? On the given frames, + // after the frame's own integration, predict the 2a x 2b x 2c supercell of its PRIMITIVE lattice + // (the per-frame refinement and geometry unchanged), integrate it out to 3 A, and sum the eight + // parity classes in two shells over 20-3 A (SupercellProbe). Class 0 is the lattice itself; the + // other seven are the seven index-2 superlattices, at most one of which a single doubling fills. + // The probe's integrations are the caller's to keep out of anything else it counts. + void ProbeSupercell(std::vector image_numbers); + [[nodiscard]] SupercellProbe GetSupercellProbe(); // Index a single frame (no integration) with the current forced rotation lattice; used to score // first-pass sampling schemes on the real per-image path. Returns whether the frame indexed. bool IndexFrameOnly(DataMessage &msg, const SpotFindingSettings &settings); diff --git a/image_analysis/MXAnalysisWithoutFPGA.cpp b/image_analysis/MXAnalysisWithoutFPGA.cpp index 93a3d736d..538201c15 100644 --- a/image_analysis/MXAnalysisWithoutFPGA.cpp +++ b/image_analysis/MXAnalysisWithoutFPGA.cpp @@ -165,6 +165,19 @@ void MXAnalysisWithoutFPGA::Analyze(DataMessage &output, int64_t image_number) { return bragg_engine->Run(*preprocessor_buffer, predicted, npredicted, image_number); }; + // The supercell probe integrates on the same engine, but what the engine counts is the run's + // measurement of its own stencil, and the probe's reflections are not the run's: keep them out. + const auto probe_integrate_fn = [this](const std::vector &predicted, size_t npredicted, + int64_t image_number) { + const BraggIntegrationCounts before = bragg_engine->Counts(); + auto ret = bragg_engine->Run(*preprocessor_buffer, predicted, npredicted, image_number); + const BraggIntegrationCounts after = bragg_engine->Counts(); + probe_counts.predicted += after.predicted - before.predicted; + probe_counts.bkg_starved += after.bkg_starved - before.bkg_starved; + probe_counts.bkg_starved_by_neighbour += after.bkg_starved_by_neighbour - before.bkg_starved_by_neighbour; + probe_counts.profile_fallback += after.profile_fallback - before.profile_fallback; + return ret; + }; // The radial background correction has to be decided BEFORE this image is integrated, so the // ice score is taken here rather than with the other per-image quantities at the end of the @@ -240,7 +253,7 @@ void MXAnalysisWithoutFPGA::Analyze(DataMessage &output, s.min_pix_per_spot = best_mp; SpotAnalyze(experiment, s, best_spots, output); decide_radial_background(); - indexer.ProcessImage(output, s, *prediction, integrate_fn); + indexer.ProcessImage(output, s, *prediction, integrate_fn, probe_integrate_fn); indexing_time_s += output.indexing_time_s.value_or(0.0f); } // Each indexer call reports only its own time, so the escalation's total is summed here. @@ -253,7 +266,7 @@ void MXAnalysisWithoutFPGA::Analyze(DataMessage &output, output.spot_finding_time_s = std::chrono::duration(std::chrono::steady_clock::now() - spot_finding_start_time).count(); decide_radial_background(); if (spot_finding_settings.indexing) - indexer.ProcessImage(output, spot_finding_settings, *prediction, integrate_fn); + indexer.ProcessImage(output, spot_finding_settings, *prediction, integrate_fn, probe_integrate_fn); } // Recorded whichever way the frame went. A frame holding StrongPixelLimit of them is given up @@ -372,7 +385,14 @@ void MXAnalysisWithoutFPGA::RunROIOnly(DataMessage &output) { } BraggIntegrationCounts MXAnalysisWithoutFPGA::BraggCounts() const { - return bragg_engine ? bragg_engine->Counts() : BraggIntegrationCounts{}; + if (!bragg_engine) + return {}; + BraggIntegrationCounts c = bragg_engine->Counts(); + c.predicted -= probe_counts.predicted; + c.bkg_starved -= probe_counts.bkg_starved; + c.bkg_starved_by_neighbour -= probe_counts.bkg_starved_by_neighbour; + c.profile_fallback -= probe_counts.profile_fallback; + return c; } void MXAnalysisWithoutFPGA::UpdateMaskResolution(const SpotFindingSettings &settings) { diff --git a/image_analysis/MXAnalysisWithoutFPGA.h b/image_analysis/MXAnalysisWithoutFPGA.h index 54ec41a44..573714609 100644 --- a/image_analysis/MXAnalysisWithoutFPGA.h +++ b/image_analysis/MXAnalysisWithoutFPGA.h @@ -57,6 +57,8 @@ class MXAnalysisWithoutFPGA { IndexAndRefine &indexer; std::unique_ptr prediction; std::unique_ptr bragg_engine; + // What the supercell probe's integrations added to bragg_engine's counts (see BraggCounts). + BraggIntegrationCounts probe_counts; std::unique_ptr preprocessor_buffer; const PixelMask &mask; diff --git a/rugnux/Rugnux.cpp b/rugnux/Rugnux.cpp index da5945c80..fd6207325 100644 --- a/rugnux/Rugnux.cpp +++ b/rugnux/Rugnux.cpp @@ -5042,6 +5042,25 @@ ProcessResult Rugnux::RunPipeline(RugnuxObserver *observer, bool write_output, b } } + // 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 + // strong reflections, so a crystal whose cell is doubled by a weak superstructure class is adopted + // at the half cell by every arbiter. The probe reads the question in intensities instead, on the + // same frames the first pass validates on (see IndexAndRefine::ProbeSupercell). + // + // REPORT ONLY - it decides nothing. Measured on the battery, a weak real class is not yet told apart + // from what sits at the half-integer nodes of crystals whose cell is right: a class at a fifth of + // the lattice's intensity on a crystal whose axis is truly doubled, against up to a tenth on + // correct cells (diffuse scattering and the tails of long-axis neighbours, which do not rock like + // Bragg reflections - but neither, on that crystal, does its real class). The line it logs is the + // population the decision has to be calibrated on. + if (full && indexer && experiment_.IsRotationIndexing()) { + std::vector frames; + for (const int o : select_equally_spaced_image_ordinals(images_to_process, 60)) + frames.push_back(o); + indexer->ProbeSupercell(frames); + } + // Main per-image loop, spread over N worker threads pulling from a shared counter. HDF5 reads // are serialized by the global hdf5_mutex; the analysis runs in parallel. std::atomic next_ordinal = 0; @@ -5269,6 +5288,33 @@ ProcessResult Rugnux::RunPipeline(RugnuxObserver *observer, bool write_output, b result.cancelled = cancelled_; result.images_processed = finished_count.load(); + if (full && indexer && experiment_.IsRotationIndexing() && !cancelled_) { + const SupercellProbe probe = indexer->GetSupercellProbe(); + if (probe[0][0].n > 0 && probe[0][1].n > 0) { + std::string table; + for (int sh = 0; sh < 3; sh++) { + table += sh == 0 ? "\n 20-5 A:" : sh == 1 ? "\n 5-3 A:" : "\n 20-3 A:"; + const auto sums = [&](int c) { + SupercellProbeClass x = sh < 2 ? probe[c][sh] : probe[c][0]; + if (sh == 2) x += probe[c][1]; + return x; + }; + const SupercellProbeFit f0 = FitSupercellProbe(sums(0)); + table += fmt::format(" 000 {:.2f} a {:.1f} b {:.1f}

{:.3f} n {};", f0.mean_i_over_sigma, f0.a, + f0.b, f0.mean_p, sums(0).n); + for (int c = 1; c < 8; c++) { + const SupercellProbeFit f = FitSupercellProbe(sums(c)); + table += fmt::format(" {}{}{}: {:.2f} occ {:.2f}% rock {:.2f}+-{:.2f}% flat {:.2f}%;", + (c >> 2) & 1, (c >> 1) & 1, c & 1, f.mean_i_over_sigma, + 100.0 * f.mean_i / f0.mean_i, 100.0 * f.b / f0.b, 100.0 * f.b_se / f0.b, + 100.0 * f.a / f0.a); + } + } + logger.Info("Supercell probe (the eight parity classes of the doubled primitive cell; , " + "mean intensity, and the fit I = a + b p against the lattice's own):{}", table); + } + } + result.harmonic = HarmonicFromEvidence(harmonic_evidence); result.powder = powder_; result.powder_excluded_from_indexing = !config_.spot_finding.measured_ring_q_recipA.empty(); diff --git a/tests/IndexingUnitTest.cpp b/tests/IndexingUnitTest.cpp index acdda00fe..33f43a920 100644 --- a/tests/IndexingUnitTest.cpp +++ b/tests/IndexingUnitTest.cpp @@ -7,6 +7,7 @@ #include "../writer/HDF5Objects.h" #include "../image_analysis/indexing/IndexerFactory.h" #include "../image_analysis/indexing/PostIndexingRefinement.h" +#include "../image_analysis/IndexAndRefine.h" #include "../image_analysis/bragg_prediction/BraggPrediction.h" #include "../common/Logger.h" @@ -757,3 +758,30 @@ TEST_CASE("FFTIndexer_ManyNoiseFrames", "[Indexing]") { SUCCEED(lattices << " candidate lattices from noise frames"); } } + +TEST_CASE("FitSupercellProbe", "[SupercellProbe]") { + // A class whose intensity is 3 at any rocking plus 40 times its partiality: the fit separates the + // two, and the part that rocks is known to the noise the scatter about the line allows. + SupercellProbeClass c; + std::mt19937 rng(1); + std::normal_distribution noise(0.0, 1.0); + for (int i = 0; i < 20000; i++) { + const double p = (i % 100) / 100.0; + const double I = 3.0 + 40.0 * p + noise(rng); + c.n++; + c.sum_i += I; + c.sum_i_over_sigma += I; + c.sum_p += p; + c.sum_pp += p * p; + c.sum_pi += p * I; + c.sum_ii += I * I; + } + const SupercellProbeFit f = FitSupercellProbe(c); + CHECK(f.b == Catch::Approx(40.0).margin(0.1)); + CHECK(f.a == Catch::Approx(3.0).margin(0.05)); + CHECK(f.b_se == Catch::Approx(1.0 / std::sqrt(20000.0 * (0.9999 / 12.0))).epsilon(0.05)); + CHECK(f.mean_p == Catch::Approx(0.495)); + + // Too few reflections to fit a line: nothing. + CHECK(FitSupercellProbe(SupercellProbeClass{}).b == 0.0); +}