diff --git a/image_analysis/indexing/CMakeLists.txt b/image_analysis/indexing/CMakeLists.txt index dc8f716ab..e1c88e219 100644 --- a/image_analysis/indexing/CMakeLists.txt +++ b/image_analysis/indexing/CMakeLists.txt @@ -17,7 +17,9 @@ ADD_LIBRARY(JFJochIndexing STATIC MultiLatticeSearch.cpp MultiLatticeSearch.h SpindleBlindFraction.cpp - SpindleBlindFraction.h) + SpindleBlindFraction.h + HarmonicContamination.cpp + HarmonicContamination.h) TARGET_LINK_LIBRARIES(JFJochIndexing JFJochCommon JFJochLatticeSearch) IF (JFJOCH_CUDA_AVAILABLE) diff --git a/image_analysis/indexing/HarmonicContamination.cpp b/image_analysis/indexing/HarmonicContamination.cpp new file mode 100644 index 000000000..a83364203 --- /dev/null +++ b/image_analysis/indexing/HarmonicContamination.cpp @@ -0,0 +1,153 @@ +// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute +// SPDX-License-Identifier: GPL-3.0-only + +#include +#include +#include + +#include "HarmonicContamination.h" + +namespace { + + // A frame's orientation as the map from a spot's reciprocal vector to its Miller indices, fitted + // by least squares on the spots the indexer took. Read from the spots rather than from the + // indexer's own matrix so that whatever per-frame refinement it applied is already in it, and so + // that no convention has to be shared with it. + struct Orientation { + std::array row; // hkl = {row[0]*q, row[1]*q, row[2]*q} + }; + + bool FitOrientation(const std::vector &spots, const DiffractionGeometry &geometry, + Orientation &fit) { + double n[3][3] = {}; // sum q q^T + double rhs[3][3] = {}; // sum q h, one column per Miller index + size_t used = 0; + for (const auto &s : spots) { + // The first lattice only: on a multi-lattice frame the other lattices' Miller indices + // belong to a different orientation and fitting one map through both gives neither. + if (!s.indexed || s.lattice > 0) + continue; + const Coord q = s.ReciprocalCoord(geometry); + const double h[3] = {static_cast(s.h), static_cast(s.k), + static_cast(s.l)}; + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) + n[i][j] += static_cast(q[i]) * q[j]; + for (int j = 0; j < 3; j++) + rhs[i][j] += static_cast(q[i]) * h[j]; + } + used++; + } + if (used < HARMONIC_MIN_INDEXED_SPOTS) + return false; + + // Invert the 3x3 normal matrix by cofactors. It is singular when the frame's spots span fewer + // than three directions in reciprocal space, which no real frame does but a degenerate one can. + double c[3][3]; + c[0][0] = n[1][1] * n[2][2] - n[1][2] * n[2][1]; + c[0][1] = n[0][2] * n[2][1] - n[0][1] * n[2][2]; + c[0][2] = n[0][1] * n[1][2] - n[0][2] * n[1][1]; + c[1][0] = n[1][2] * n[2][0] - n[1][0] * n[2][2]; + c[1][1] = n[0][0] * n[2][2] - n[0][2] * n[2][0]; + c[1][2] = n[0][2] * n[1][0] - n[0][0] * n[1][2]; + c[2][0] = n[1][0] * n[2][1] - n[1][1] * n[2][0]; + c[2][1] = n[0][1] * n[2][0] - n[0][0] * n[2][1]; + c[2][2] = n[0][0] * n[1][1] - n[0][1] * n[1][0]; + const double det = n[0][0] * c[0][0] + n[0][1] * c[1][0] + n[0][2] * c[2][0]; + const double scale = n[0][0] + n[1][1] + n[2][2]; + if (!(std::fabs(det) > 1e-12 * scale * scale * scale)) + return false; + + for (int j = 0; j < 3; j++) { + float v[3]; + for (int i = 0; i < 3; i++) { + double sum = 0; + for (int k = 0; k < 3; k++) + sum += c[i][k] * rhs[k][j]; + v[i] = static_cast(sum / det); + } + fit.row[j] = Coord(v[0], v[1], v[2]); + } + return true; + } + + // How far the scaled spot is from the nearest lattice point, as the largest of the three Miller + // indices' distances to an integer. + float IndexResidual(const Orientation &fit, const Coord &q, float scale) { + float worst = 0; + for (int j = 0; j < 3; j++) { + const float f = scale * (fit.row[j] * q); + worst = std::max(worst, std::fabs(f - std::round(f))); + } + return worst; + } +} + +void HarmonicEvidence::Add(const HarmonicEvidence &other) { + frames += other.frames; + tested += other.tested; + hits += other.hits; + null_hits += other.null_hits; + hit_d_sum_A += other.hit_d_sum_A; + indexed_d_sum_A += other.indexed_d_sum_A; + indexed += other.indexed; +} + +void AddHarmonicEvidence(const std::vector &spots, const DiffractionGeometry &geometry, + HarmonicEvidence &evidence) { + Orientation fit; + if (!FitOrientation(spots, geometry, fit)) + return; + + evidence.frames++; + for (const auto &s : spots) { + const Coord q = s.ReciprocalCoord(geometry); + const float d_A = 1.0f / std::max(q.Length(), 1e-6f); + if (s.indexed) { + evidence.indexed++; + evidence.indexed_d_sum_A += d_A; + continue; + } + if (IndexResidual(fit, q, 1.0f) < HARMONIC_NEAR_MISS_TOLERANCE) + continue; + evidence.tested++; + if (IndexResidual(fit, q, HARMONIC_SCALE) < HARMONIC_INDEX_TOLERANCE) { + evidence.hits++; + evidence.hit_d_sum_A += d_A; + } + if (IndexResidual(fit, q, HARMONIC_SCALE_NULL) < HARMONIC_INDEX_TOLERANCE) + evidence.null_hits++; + } +} + +HarmonicContaminationResult HarmonicFromEvidence(const HarmonicEvidence &evidence) { + HarmonicContaminationResult result; + result.frames = evidence.frames; + result.tested = evidence.tested; + result.hits = evidence.hits; + // Frames enough for the question to have been asked of this crystal at all. A run that indexed + // this much and found nothing left to test has answered it: there is no second population. + if (evidence.frames < 20 || evidence.indexed < 1000) + return result; + + result.measurable = true; + if (evidence.tested > 0) { + result.fraction = 100.0f * static_cast(evidence.hits) + / static_cast(evidence.tested); + result.null_fraction = 100.0f * static_cast(evidence.null_hits) + / static_cast(evidence.tested); + } + if (evidence.hits > 0) + result.mean_d_A = static_cast(evidence.hit_d_sum_A / static_cast(evidence.hits)); + if (evidence.indexed > 0) + result.mean_indexed_d_A = static_cast(evidence.indexed_d_sum_A + / static_cast(evidence.indexed)); + // Ten per cent of the tested spots, five times whatever the same test finds at a scale that is + // not a harmonic, and enough spots for the rate to be a rate. Measured over datasets with no + // reported contamination the harmonic rate runs at or below the null's own per cent or so, and + // on a set whose depositors reported a harmonic it is ninety. + result.detected = evidence.hits >= 200 + && result.fraction >= 10.0f + && result.fraction >= 5.0f * std::max(result.null_fraction, 0.5f); + return result; +} diff --git a/image_analysis/indexing/HarmonicContamination.h b/image_analysis/indexing/HarmonicContamination.h new file mode 100644 index 000000000..0bbcacad6 --- /dev/null +++ b/image_analysis/indexing/HarmonicContamination.h @@ -0,0 +1,77 @@ +// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute +// SPDX-License-Identifier: GPL-3.0-only + +#pragma once + +#include +#include + +#include "../../common/DiffractionGeometry.h" +#include "../../common/SpotToSave.h" + +// Higher-order contamination of the beam, read off the spots a run could not index. +// +// A Si(111) monochromator passes lambda/3 as well as lambda, and an undulator harmonic can feed it. +// A reflection excited by the lambda/3 photons scatters into the same direction as a reflection with +// three times its d-spacing would at lambda, so the crystal writes a SECOND spot population that no +// single lattice explains, all of it at coarse apparent resolution. +// +// The test is exact rather than empirical. A spot's reciprocal vector read at the fundamental is +// q = (s_hat - z_hat) / lambda, so at lambda/n it is n*q - and n*q automatically sits on the Ewald +// sphere that wavelength draws. Contamination therefore asks one question of each spot the lattice +// did not take: is 3*q an integer point of the lattice the frame indexed? The same question at a +// scale no monochromator passes (SCALE_NULL) is the null, and it is a real null rather than a +// nominal one: the distance from a random point to the nearest lattice point does not depend on the +// scale, so the two rates are directly comparable. +// +// This does not distinguish a contaminated beam from a crystal whose true cell is three times the +// one indexed: a genuine 3x superlattice puts its extra reflections in exactly these places. What +// separates them is where the population stops. A harmonic spot's true d is a third of its apparent +// one, so the population dies out at three times the crystal's resolution limit, while a superlattice +// runs as far as the crystal diffracts - which is why the apparent resolution of the hits is reported +// beside their number. + +// How near an integer a scaled spot has to fall before it counts as a lattice point of that harmonic. +constexpr float HARMONIC_INDEX_TOLERANCE = 0.10f; +// A spot this close to a lattice point as it stands is a reflection the indexer only just rejected. +// It then lands on an integer at EVERY integer scale and says nothing about a harmonic, so it is not +// asked. On a clean run this is most of the unindexed list. +constexpr float HARMONIC_NEAR_MISS_TOLERANCE = 0.20f; +// The harmonic looked for, and the scale used as its null. 2.5 is not a harmonic of anything. +constexpr float HARMONIC_SCALE = 3.0f; +constexpr float HARMONIC_SCALE_NULL = 2.5f; +// Indexed spots a frame must carry before its orientation is fitted from them. +constexpr size_t HARMONIC_MIN_INDEXED_SPOTS = 20; + +// What the run has counted so far. Counts only, so the total does not depend on the order the images +// were summed in or on how many threads found them. +struct HarmonicEvidence { + int64_t frames = 0; // frames whose orientation could be fitted + int64_t tested = 0; // unindexed spots that are not near-misses of that frame's lattice + int64_t hits = 0; // of those, the ones 3*q places on the lattice + int64_t null_hits = 0; // the same at HARMONIC_SCALE_NULL + double hit_d_sum_A = 0.0; // apparent d of the hits, summed + double indexed_d_sum_A = 0.0; + int64_t indexed = 0; + + void Add(const HarmonicEvidence &other); +}; + +// Fit this frame's orientation from its indexed spots and ask the question above of the rest. Does +// nothing when the frame has too few indexed spots to fit one. +void AddHarmonicEvidence(const std::vector &spots, const DiffractionGeometry &geometry, + HarmonicEvidence &evidence); + +struct HarmonicContaminationResult { + bool measurable = false; + bool detected = false; + float fraction = 0.0f; // per cent of the tested spots that 3*q puts on the lattice + float null_fraction = 0.0f; // the same at HARMONIC_SCALE_NULL + int64_t tested = 0; + int64_t hits = 0; + int64_t frames = 0; + float mean_d_A = 0.0f; // apparent resolution the extra population sits at + float mean_indexed_d_A = 0.0f; // and where the crystal's own spots sit, for comparison +}; + +HarmonicContaminationResult HarmonicFromEvidence(const HarmonicEvidence &evidence); diff --git a/rugnux/ReportDocument.h b/rugnux/ReportDocument.h index 24dc8f6ae..48b42c917 100644 --- a/rugnux/ReportDocument.h +++ b/rugnux/ReportDocument.h @@ -42,6 +42,7 @@ namespace PathologyCode { // does not declare is present in the data, so the centring or the cell is wrong - and differ only // in how exact it is. ANISOTROPY and RESOLUTION_FIT are already shared this way. constexpr const char *LATTICE_TRANSLATION = "LATTICE_TRANSLATION"; // a translation the cell does not declare + constexpr const char *HARMONIC_CONTAMINATION = "HARMONIC_CONTAMINATION"; // the beam carries a higher harmonic } // A closed type plus an open description. The type is what machinery switches on; the text is what a diff --git a/rugnux/ResultReport.cpp b/rugnux/ResultReport.cpp index 7fc3f34d7..40e32dd0a 100644 --- a/rugnux/ResultReport.cpp +++ b/rugnux/ResultReport.cpp @@ -702,6 +702,44 @@ ReportDocument BuildReportDocument(const std::string &output_prefix, ReportSection s; s.title = "4. DIAGNOSTICS"; + // ---- higher-order contamination of the beam + // Read off the images rather than off the merge, so it is reported whether or not anything + // merged. Report-only: nothing downstream reads it, and no spot was treated differently for + // it. See HarmonicContamination.h for the test and for the one thing it cannot separate a + // contaminated beam from - a crystal whose true cell really is three times the one indexed. + { + const auto &hc = result.harmonic; + if (hc.measurable) { + Add(s, KeyEnum("HARMONIC_CONTAMINATION", hc.detected ? "TRUE" : "FALSE", + {"TRUE", "FALSE", "NOT_MEASURED"})); + Add(s, KeyReal("HARMONIC_SPOT_PCT", hc.fraction, "{:.1f}")); + Add(s, KeyReal("HARMONIC_NULL_PCT", hc.null_fraction, "{:.1f}")); + Add(s, KeyInt("HARMONIC_SPOTS_TESTED", hc.tested, true)); + if (hc.detected) + Add(s, KeyReal("HARMONIC_MEAN_D", hc.mean_d_A, "{:.1f}")); + } else { + Add(s, KeyEnum("HARMONIC_CONTAMINATION", "NOT_MEASURED", + {"TRUE", "FALSE", "NOT_MEASURED"})); + } + Add(s, Blank()); + if (hc.detected) { + Add(s, Prose(fmt::format( + " Higher-order contamination: INDICATED. Of the {} spots this run found and could\n" + " not put on the lattice, {:.0f}% are on that same lattice at one third of the stated\n" + " wavelength, against {:.1f}% for the same test at a scale no monochromator passes.\n" + " A Si(111) monochromator passes lambda/3 with lambda, so the crystal writes a second\n" + " diffraction pattern; it sits at {:.1f} A apparent resolution against {:.1f} A for the\n" + " indexed spots, which is where a harmonic puts it. Nothing here was excluded for it -\n" + " a spot on the second pattern that falls near a real reflection is integrated with it.", + hc.tested, hc.fraction, hc.null_fraction, hc.mean_d_A, + hc.mean_indexed_d_A))); + Warn(doc, PathologyCode::HARMONIC_CONTAMINATION, + fmt::format("The beam carries a higher harmonic: {:.0f}% of the unindexed spots are " + "lattice points at lambda/3, mostly around {:.1f} A apparent resolution", + hc.fraction, hc.mean_d_A)); + } + } + // ---- translational pseudo-symmetry // Printed immediately before the twinning block, and in the same section, because the two // interact: a pseudo-translation that is not a half-integer vector biases <|L|> upwards and @@ -1406,6 +1444,9 @@ ReportDocument BuildReportDocument(const std::string &output_prefix, row("Space group", group); if (result.consensus_cell) row("Unit cell", CellString(*result.consensus_cell)); + if (result.harmonic.detected) + row("Beam", fmt::format("higher harmonic INDICATED ({:.0f} % of the unindexed spots " + "are lattice points at lambda/3)", result.harmonic.fraction)); if (merged) { std::string res = fmt::format("{:.2f} A written", o.d_min); if (fitted_resolution) diff --git a/rugnux/Rugnux.cpp b/rugnux/Rugnux.cpp index 2ff3a5a3c..64a249ad8 100644 --- a/rugnux/Rugnux.cpp +++ b/rugnux/Rugnux.cpp @@ -36,6 +36,7 @@ #include "../image_analysis/beam_stop/ShadowFinder.h" #include "../image_analysis/IndexAndRefine.h" #include "../image_analysis/indexing/AnalyzeIndexing.h" +#include "../image_analysis/indexing/HarmonicContamination.h" #include "../image_analysis/geom_refinement/BeamCenterFromBackground.h" #include "../image_analysis/geom_refinement/BeamCenterFromSpots.h" #include "../image_analysis/geom_refinement/GeometryRefiner.h" @@ -3393,6 +3394,12 @@ ProcessResult Rugnux::RunPipeline(RugnuxObserver *observer, bool write_output, b std::mutex calibration_spot_m; std::vector calibration_spot_list; + // Higher-order beam contamination, counted on the spots the lattice did not take. Each worker + // keeps its own tally and adds it in when it is done, so the total is a sum of counts and does + // not depend on how the images were shared out. + std::mutex harmonic_m; + HarmonicEvidence harmonic_evidence; + auto azint_worker = [&]() { std::vector decompression_buffer; ImagePreprocessorCPU preprocessor(experiment_, pixel_mask_); @@ -3458,6 +3465,7 @@ ProcessResult Rugnux::RunPipeline(RugnuxObserver *observer, bool write_output, b MXAnalysisWithoutFPGA analysis(experiment_, mapping, pixel_mask_, *indexer, /*enable_fused_adaptive_gpu=*/true); AzimuthalIntegrationProfile profile(mapping); + HarmonicEvidence worker_harmonic; while (!cancelled_) { const int ordinal = next_ordinal.fetch_add(1); @@ -3500,6 +3508,8 @@ ProcessResult Rugnux::RunPipeline(RugnuxObserver *observer, bool write_output, b calibration_spot_list.push_back(msg.spots[i]); } + AddHarmonicEvidence(msg.spots, experiment_.GetDiffractionGeometry(), worker_harmonic); + plots.Add(msg, profile); if (writer_queue) writer_queue->Post(msg, img); note_written(ordinal); @@ -3508,6 +3518,11 @@ ProcessResult Rugnux::RunPipeline(RugnuxObserver *observer, bool write_output, b if (observer) observer->OnProgress(done, images_to_process); } + { + std::lock_guard lock(harmonic_m); + harmonic_evidence.Add(worker_harmonic); + } + const auto bragg = analysis.BraggCounts(); bragg_predicted += bragg.predicted; bragg_starved += bragg.bkg_starved; @@ -3560,6 +3575,14 @@ ProcessResult Rugnux::RunPipeline(RugnuxObserver *observer, bool write_output, b result.cancelled = cancelled_; result.images_processed = finished_count.load(); + result.harmonic = HarmonicFromEvidence(harmonic_evidence); + if (result.harmonic.detected) + logger.Warning("Higher-order beam contamination: {:.0f}% of the {} unindexed spots this run " + "could not put on the lattice are on it at one third the wavelength (the same " + "test off a harmonic finds {:.1f}%). They sit at {:.1f} A apparent resolution", + result.harmonic.fraction, result.harmonic.tested, + result.harmonic.null_fraction, result.harmonic.mean_d_A); + // What the stencil cost, as the integrator measured it: the reflections dropped whole for a // background ring left below six clean pixels, and - of those - the ones the NEIGHBOURS took // rather than the detector. The second is what a wider r1 can change, and it is what the two-pass diff --git a/rugnux/Rugnux.h b/rugnux/Rugnux.h index de46a641d..183747851 100644 --- a/rugnux/Rugnux.h +++ b/rugnux/Rugnux.h @@ -19,6 +19,7 @@ #include "../image_analysis/scale_merge/Merge.h" // MergeStatistics #include "../image_analysis/scale_merge/TwinningAnalysis.h" // TwinningAnalysisResult #include "../image_analysis/scale_merge/TranslationalNCS.h" // TranslationalNCSResult +#include "../image_analysis/indexing/HarmonicContamination.h" // HarmonicContaminationResult #include "ModelValidation.h" // ModelValidationResult #include "ReportDocument.h" // ReportWarning, PathologyCode #include "../image_analysis/scale_merge/SearchSpaceGroup.h" // SearchSpaceGroupResult @@ -281,6 +282,10 @@ struct ProcessResult { // has to know that. TranslationalNCSResult tncs; + // Higher-order contamination of the beam, read off the spots the lattice did not take. Measured + // on the images themselves, so it is there whether or not anything merged. + HarmonicContaminationResult harmonic; + // The same analysis measured BEFORE the space group was decided, on the subgroup merge the search // was given. It is the only twinning number a promotion cannot contaminate: once a higher Laue // class is adopted, its own twinning test can say no more than "no twin law exists inside this