diff --git a/rugnux/CMakeLists.txt b/rugnux/CMakeLists.txt index 0f7b1cac8..569fc7d16 100644 --- a/rugnux/CMakeLists.txt +++ b/rugnux/CMakeLists.txt @@ -21,6 +21,8 @@ ADD_LIBRARY(Rugnux STATIC ResultReport.cpp ResultReport.h ReportDocument.h + LeftoverLattices.cpp + LeftoverLattices.h SpotWidth.cpp SpotWidth.h HotPixels.cpp diff --git a/rugnux/LeftoverLattices.cpp b/rugnux/LeftoverLattices.cpp new file mode 100644 index 000000000..f488dc6c6 --- /dev/null +++ b/rugnux/LeftoverLattices.cpp @@ -0,0 +1,75 @@ +// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute +// SPDX-License-Identifier: GPL-3.0-only + +#include "LeftoverLattices.h" + +#include +#include +#include +#include "../common/JFJochMath.h" // PI + +const char *LeftoverLatticeKindName(LeftoverLatticeKind kind) { + switch (kind) { + case LeftoverLatticeKind::Self: return "SELF"; + case LeftoverLatticeKind::Domain: return "DOMAIN"; + case LeftoverLatticeKind::TwinDomain: return "TWIN_DOMAIN"; + case LeftoverLatticeKind::Segmented: return "SEGMENTED"; + case LeftoverLatticeKind::RelatedCell: return "RELATED_CELL"; + case LeftoverLatticeKind::Foreign: return "FOREIGN"; + } + return "FOREIGN"; +} + +double LatticeMisorientationDeg(const CrystalLattice &a, const CrystalLattice &b) { + auto mat = [](const CrystalLattice &l) { + Eigen::Matrix3d M; + const Coord v[3] = {l.Vec0(), l.Vec1(), l.Vec2()}; + for (int c = 0; c < 3; c++) + M.col(c) = Eigen::Vector3d(v[c].x, v[c].y, v[c].z); + return M; + }; + const Eigen::Matrix3d A = mat(a), B = mat(b); + const Eigen::Matrix3d GA = A.transpose() * A; + const double scale = GA.diagonal().mean(); + // Every unimodular change of basis with entries -1..1: enough for two reduced cells. + double best = NAN; + for (int code = 0; code < 19683; code++) { + Eigen::Matrix3d M; + int c = code; + for (int e = 0; e < 9; e++) { + M(e / 3, e % 3) = c % 3 - 1; + c /= 3; + } + if (std::abs(M.determinant() - 1.0) > 1e-6) + continue; + const Eigen::Matrix3d BM = B * M; + if ((BM.transpose() * BM - GA).cwiseAbs().maxCoeff() > 0.06 * scale) + continue; + // The rotation nearest to the (slightly non-orthogonal) map from A to BM. + Eigen::JacobiSVD svd(BM * A.inverse(), Eigen::ComputeFullU | Eigen::ComputeFullV); + const Eigen::Matrix3d R = svd.matrixU() * svd.matrixV().transpose(); + if (R.determinant() < 0) + continue; + const double ang = std::acos(std::clamp((R.trace() - 1.0) / 2.0, -1.0, 1.0)) * 180.0 / PI; + if (std::isnan(best) || ang < best) + best = ang; + } + return best; +} + +LeftoverLatticeKind ClassifyLeftoverLattice(double misorientation_deg, double volume_ratio, + double sweep_concentration) { + if (std::isfinite(misorientation_deg)) { + if (misorientation_deg <= 1.0) + return LeftoverLatticeKind::Self; + if (sweep_concentration >= 0.6) + return LeftoverLatticeKind::Segmented; + if (misorientation_deg >= 177.0) + return LeftoverLatticeKind::TwinDomain; + return LeftoverLatticeKind::Domain; + } + for (int n = 1; n <= 8; n++) + if (std::abs(volume_ratio / n - 1.0) < 0.06 || std::abs(volume_ratio * n - 1.0) < 0.06) + return LeftoverLatticeKind::RelatedCell; + return LeftoverLatticeKind::Foreign; +} diff --git a/rugnux/LeftoverLattices.h b/rugnux/LeftoverLattices.h new file mode 100644 index 000000000..22a9dbdfd --- /dev/null +++ b/rugnux/LeftoverLattices.h @@ -0,0 +1,54 @@ +// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute +// SPDX-License-Identifier: GPL-3.0-only + +#pragma once + +#include +#include +#include "../common/CrystalLattice.h" +#include "../common/UnitCell.h" + +// What a lattice indexed from the spots the crystal's lattice left over is, relative to that lattice. +enum class LeftoverLatticeKind { + Self, // the same cell within 1 deg: spots of the crystal's own lattice its tolerance missed + Domain, // the same cell, misoriented, spread over the sweep: a split crystal + TwinDomain, // the same, turned by ~180 deg: a non-merohedral twin domain + Segmented, // the same cell, but its spots are concentrated in part of the sweep: the crystal in + // the beam changes along the rotation + RelatedCell, // a cell n or 1/n times the volume: a question about the crystal's own cell + Foreign // an unrelated cell: a second crystal species, or a wrong main lattice +}; + +const char *LeftoverLatticeKindName(LeftoverLatticeKind kind); + +// The smallest rotation, in degrees, taking lattice `a` onto lattice `b`, over every basis of `b` whose +// metric matches `a`'s (so a symmetry of the lattice is not read as a misorientation). Both are +// primitive reduced cells. NaN where no basis of `b` matches `a`'s metric. +double LatticeMisorientationDeg(const CrystalLattice &a, const CrystalLattice &b); + +// `volume_ratio` is the reduced volume against the crystal's lattice, `sweep_concentration` the share of +// the lattice's spots in the 2 densest of 8 equal blocks of the sweep (0.25 is uniform). +LeftoverLatticeKind ClassifyLeftoverLattice(double misorientation_deg, double volume_ratio, + double sweep_concentration); + +struct LeftoverLattice { + LeftoverLatticeKind kind = LeftoverLatticeKind::Foreign; + UnitCell cell{}; + char centering = 'P'; + std::string system; + double volume_ratio = 0.0; + double misorientation_deg = 0.0; // NaN where the cell differs + double z = 0.0; // leftover validation spots on it, against a wrong spindle angle + double spots_pct = 0.0; // of the non-ice spots of the census frames + double intensity_pct = 0.0; // of their summed intensity + double sweep_concentration = 0.0; +}; + +// The lattices the leftover spots index to, beside the crystal's own share of the same spots. +// Only lattices clear of the displaced-angle null (z >= 5) and not the crystal's own lattice. +struct LeftoverLatticeCensus { + double primary_spots_pct = 0.0; + double primary_intensity_pct = 0.0; + int frames = 0; + std::vector lattices; +}; diff --git a/rugnux/ReportDocument.h b/rugnux/ReportDocument.h index a1c68697a..1c9d058e7 100644 --- a/rugnux/ReportDocument.h +++ b/rugnux/ReportDocument.h @@ -45,6 +45,7 @@ namespace PathologyCode { 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 constexpr const char *SUPERCELL_POSSIBLE = "SUPERCELL_POSSIBLE"; // Bragg-like intensity at half-integer positions + constexpr const char *MULTIPLE_LATTICES = "MULTIPLE_LATTICES"; // a second lattice carries much of the spot intensity constexpr const char *GEOMETRY_NOT_CONVERGED = "GEOMETRY_NOT_CONVERGED"; // the geometry walk ran out of rounds constexpr const char *SCALING_NOT_CONVERGED = "SCALING_NOT_CONVERGED"; // the per-frame scales hit their cap still moving } diff --git a/rugnux/ResultReport.cpp b/rugnux/ResultReport.cpp index 0a0ad42f9..b026f160e 100644 --- a/rugnux/ResultReport.cpp +++ b/rugnux/ResultReport.cpp @@ -59,6 +59,41 @@ namespace { return sc.i_over_sigma >= 0.5 && sc.rock_pct >= 2.0 && sc.rock_pct > 3.0 * sc.rock_se_pct; } + // A misoriented domain, a twin domain, a segment of the sweep or an unrelated crystal that together + // hold at least this share of the non-ice spot intensity is worth the user's look. A related cell + // is a question about the crystal's own cell and is left to the supercell keys. On 200 battery + // rotation sets this names 29: 25 with split-crystal or twin domains and 4 with an unrelated cell. + constexpr double MULTIPLE_LATTICES_INTENSITY_PCT = 10.0; + + bool CountsAsSecondCrystal(const LeftoverLattice &l) { + return l.kind != LeftoverLatticeKind::Self && l.kind != LeftoverLatticeKind::RelatedCell; + } + + double SecondCrystalIntensityPct(const LeftoverLatticeCensus &c) { + double pct = 0.0; + for (const auto &l : c.lattices) + if (CountsAsSecondCrystal(l)) + pct += l.intensity_pct; + return pct; + } + + std::string LeftoverLatticeLine(const LeftoverLattice &l) { + switch (l.kind) { + case LeftoverLatticeKind::Domain: + return fmt::format("split crystal, {:.1f} deg from the main lattice", l.misorientation_deg); + case LeftoverLatticeKind::TwinDomain: + return fmt::format("non-merohedral twin domain, {:.1f} deg from the main lattice", + l.misorientation_deg); + case LeftoverLatticeKind::Segmented: + return fmt::format("same cell {:.1f} deg away, in part of the sweep only (the crystal in " + "the beam changes)", l.misorientation_deg); + case LeftoverLatticeKind::RelatedCell: + return fmt::format("a cell {:.2f} x the volume of the main one", l.volume_ratio); + default: + return "an unrelated cell"; + } + } + std::string CellString(const UnitCell &c) { return fmt::format("{:.3f} {:.3f} {:.3f} {:.3f} {:.3f} {:.3f}", c.a, c.b, c.c, c.alpha, c.beta, c.gamma); @@ -503,6 +538,13 @@ ReportDocument BuildReportDocument(const std::string &output_prefix, Add(s, KeyBool("LATTICE_FOUND", result.consensus_cell.has_value())); if (result.consensus_cell.has_value()) Add(s, KeyText("UNIT_CELL_CONSTANTS", CellString(*result.consensus_cell))); + // Kabsch's sigma_M, the Gaussian e.s.d. of the rocking width in degrees - XDS's + // REFLECTING_RANGE_E.S.D. - that the merge computed partiality from. + if (std::isfinite(result.mosaicity_deg)) { + Add(s, KeyReal("MOSAICITY_DEG", result.mosaicity_deg, "{:.3f}")); + Add(s, KeyReal("MOSAICITY_DEG_P10", result.mosaicity_deg_p10, "{:.3f}")); + Add(s, KeyReal("MOSAICITY_DEG_P90", result.mosaicity_deg_p90, "{:.3f}")); + } if (result.space_group.has_value()) { Add(s, KeyInt("SPACE_GROUP_NUMBER", result.space_group->number)); // The number alone does not name the setting, and the search can return one that is not @@ -1135,6 +1177,59 @@ ReportDocument BuildReportDocument(const std::string &output_prefix, Add(s, Blank()); } + // ---- further lattices + // Report only: what the spots the crystal's lattice leaves over index to (rotation, measured once + // the first pass has its lattice). Nothing downstream uses it. + if (result.leftover_lattices) { + const auto &c = *result.leftover_lattices; + Add(s, KeyReal("MAIN_LATTICE_SPOTS_PCT", c.primary_spots_pct, "{:.1f}")); + Add(s, KeyReal("MAIN_LATTICE_INTENSITY_PCT", c.primary_intensity_pct, "{:.1f}")); + Add(s, KeyInt("EXTRA_LATTICE_COUNT", static_cast(c.lattices.size()))); + for (size_t i = 0; i < c.lattices.size(); i++) { + const auto &l = c.lattices[i]; + const auto key = [&](const char *what) { return fmt::format("EXTRA_LATTICE_{}_{}", i + 1, what); }; + Add(s, KeyEnum(key("KIND").c_str(), LeftoverLatticeKindName(l.kind), + {"DOMAIN", "TWIN_DOMAIN", "SEGMENTED", "RELATED_CELL", "FOREIGN"})); + Add(s, KeyText(key("LATTICE").c_str(), fmt::format("{} {}", l.system, l.centering))); + Add(s, KeyText(key("CELL").c_str(), CellString(l.cell))); + Add(s, KeyReal(key("VOLUME_RATIO").c_str(), l.volume_ratio, "{:.3f}")); + if (std::isfinite(l.misorientation_deg)) + Add(s, KeyReal(key("MISORIENTATION_DEG").c_str(), l.misorientation_deg, "{:.2f}")); + Add(s, KeyReal(key("SPOTS_PCT").c_str(), l.spots_pct, "{:.1f}")); + Add(s, KeyReal(key("INTENSITY_PCT").c_str(), l.intensity_pct, "{:.1f}")); + Add(s, KeyReal(key("SWEEP_CONCENTRATION").c_str(), l.sweep_concentration, "{:.2f}")); + Add(s, KeyReal(key("Z").c_str(), l.z, "{:.1f}")); + } + const double second = SecondCrystalIntensityPct(c); + const bool multiple = second >= MULTIPLE_LATTICES_INTENSITY_PCT; + Add(s, KeyReal("EXTRA_LATTICE_INTENSITY_PCT", second, "{:.1f}")); + Add(s, KeyBool("MULTIPLE_LATTICES", multiple)); + if (multiple) { + const LeftoverLattice *strongest = nullptr; + for (const auto &l : c.lattices) + if (CountsAsSecondCrystal(l) && (!strongest || l.intensity_pct > strongest->intensity_pct)) + strongest = &l; + Warn(doc, PathologyCode::MULTIPLE_LATTICES, + fmt::format("Further lattices carry {:.0f}% of the spot intensity against {:.0f}% on the " + "main one (the strongest: {}); only the main lattice is integrated. This does " + "not by itself make the data worse - check the crystal, and the result", + second, c.primary_intensity_pct, LeftoverLatticeLine(*strongest))); + } + Add(s, Blank()); + Add(s, Prose( + " The spots the main lattice does not take (ice left out) are indexed again, up to three\n" + " times; a lattice is listed when the leftover spots sit on it far more often than at a\n" + " displaced spindle angle (Z >= 5). Percentages are of the non-ice spots of the spread and\n" + " validation frames and of their summed intensity. KIND: DOMAIN - the same cell misoriented,\n" + " over the whole sweep (a split crystal); TWIN_DOMAIN - the same, turned by 180 deg (a\n" + " non-merohedral twin); SEGMENTED - the same cell, but SWEEP_CONCENTRATION >= 0.6 of its\n" + " spots fall in 2 of 8 blocks of the sweep (the crystal in the beam changes); RELATED_CELL -\n" + " a cell an integer multiple or fraction of the main one's volume, a question about the\n" + " main cell (see SUPERCELL_* and the harmonic above); FOREIGN - an unrelated cell (a second\n" + " crystal, or a wrong main lattice). Only the main lattice is integrated.")); + Add(s, Blank()); + } + // ---- powder contamination // A crystalline phase other than the crystal, diffracting as rings among its reflections. // Measured in the pre-scan on every run, from the spots found there for the width and the @@ -2010,9 +2105,25 @@ ReportDocument BuildReportDocument(const std::string &output_prefix, row("Space group", group); if (result.consensus_cell) row("Unit cell", CellString(*result.consensus_cell)); + if (std::isfinite(result.mosaicity_deg)) + row("Mosaicity", fmt::format("{:.3f} deg (sigma_M as XDS; {:.3f}-{:.3f} over 80% of the frames)", + result.mosaicity_deg, result.mosaicity_deg_p10, + result.mosaicity_deg_p90)); 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 (result.leftover_lattices) { + const auto &c = *result.leftover_lattices; + const auto strongest = std::ranges::max_element(c.lattices, {}, &LeftoverLattice::intensity_pct); + row("Multiple lattices", strongest == c.lattices.end() ? std::string("none found") + : fmt::format("{}{}: {:.0f}% of spot intensity (main lattice {:.0f}%){}", + c.lattices.size() > 1 ? fmt::format("{} further lattices, the strongest: ", + c.lattices.size()) : "", + LeftoverLatticeLine(*strongest), strongest->intensity_pct, + c.primary_intensity_pct, + SecondCrystalIntensityPct(c) >= MULTIPLE_LATTICES_INTENSITY_PCT + ? " - check the crystal" : "")); + } 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 27ab6d8dc..9180a991b 100644 --- a/rugnux/Rugnux.cpp +++ b/rugnux/Rugnux.cpp @@ -4983,6 +4983,169 @@ ProcessResult Rugnux::RunPipeline(RugnuxObserver *observer, bool write_output, b "{}/{} validation spots = {:.1f}% against {:.1f}% at a wrong spindle angle)", best.name, best.score, static_cast(validation.size()), evidence.on_lattice, evidence.spots, 100.0 * pooled, 100.0 * pooled_chance); + // Leftover-lattice census, report only: index what the crystal's lattice leaves over, to name + // a split crystal, a twin domain or a second crystal in the report. Every spot of the spread + // and validation frames the lattice takes is marked; the rest (not on ice) goes to a fresh + // rotation indexer; a lattice it finds is judged on the validation leftovers against the same + // displaced-spindle-angle null as the first pass, its spots are marked in turn, and the search + // goes on for up to three lattices. Its own IndexAndRefine instances and indexer, so nothing + // the run goes on with is touched. Run on the pass that writes the result only. + if (!geometry_prepass) { + const auto census_start = std::chrono::steady_clock::now(); + const bool ice_ok = experiment_.GetIndexingSettings().GetIndexIceRings(); + std::vector census_frames = spread_ordinals; + census_frames.insert(census_frames.end(), validation.begin(), validation.end()); + std::ranges::sort(census_frames); + census_frames.erase(std::unique(census_frames.begin(), census_frames.end()), census_frames.end()); + prefetch_spots(census_frames); + // assign[frame][spot]: -2 ice, -1 no lattice, 0 the crystal's lattice, 1.. a leftover lattice + std::map> assign; + for (const int f : census_frames) { + auto &a = assign[f]; + a.assign(spot_cache.at(f).size(), -1); + for (size_t k = 0; k < a.size(); k++) + if (!ice_ok && spot_cache.at(f)[k].ice_ring) + a[k] = -2; + } + // Mark the still unassigned spots lattice `r` takes as `id`. + auto mark = [&](const RotationIndexerResult &r, int id) { + IndexAndRefine idx(experiment_, indexer_pool.get(), /*retain_outcomes=*/false); + idx.ForceRotationIndexerResult(r); + idx.IntegrateEveryFrame(true); + std::mutex m_assign; + ParallelFor(static_cast(census_frames.size()), + std::min(census_frames.size(), config_.nthreads), [&](int i) { + const int f = census_frames[i]; + DataMessage m{}; + m.number = f; + m.spots = spot_cache.at(f); + idx.CountSpotsOnLattice(m, validation_settings); + std::unique_lock ul(m_assign); + auto &a = assign[f]; + if (m.spots.size() != a.size()) + return; + for (size_t k = 0; k < a.size(); k++) + if (a[k] == -1 && m.spots[k].indexed && m.spots[k].lattice == 0) + a[k] = id; + }); + }; + // Leftover validation spots on `r` at the true spindle angles, and the median of five + // displaced ones - the first pass's null (pooled_evidence) on the leftovers. + auto leftover_evidence = [&](const RotationIndexerResult &r) -> std::pair { + IndexAndRefine idx(experiment_, indexer_pool.get(), /*retain_outcomes=*/false); + idx.ForceRotationIndexerResult(r); + const int nv = static_cast(validation.size()); + auto at_shift = [&](int shift) { + std::atomic n = 0; + ParallelFor(nv, std::min(validation.size(), config_.nthreads), [&](int i) { + DataMessage m{}; + m.number = validation[(i + shift) % nv]; + const auto &sp = spot_cache.at(validation[i]); + const auto &a = assign.at(validation[i]); + for (size_t k = 0; k < sp.size(); k++) + if (a[k] == -1) + m.spots.push_back(sp[k]); + n += idx.CountSpotsOnLattice(m, validation_settings); + }); + return n.load(); + }; + std::vector chance; + for (int k = 1; k <= 5; k++) + chance.push_back(at_shift(std::max(1, k * nv / 7))); + std::ranges::sort(chance); + return {at_shift(0), chance[2]}; + }; + // Spots and summed intensity assigned `id`, and the share of them in the 2 densest of 8 + // equal blocks of the census frames (0.25 is uniform over the sweep). + struct Tally { int64_t n = 0; double intensity = 0.0; double concentration = 0.0; }; + auto tally = [&](int id) { + Tally t; + std::array block{}; + const size_t nf = census_frames.size(); + for (size_t i = 0; i < nf; i++) { + const int f = census_frames[i]; + const auto &a = assign.at(f); + for (size_t k = 0; k < a.size(); k++) + if (a[k] == id) { + t.n++; + t.intensity += spot_cache.at(f)[k].intensity; + // numpy.array_split: the first nf % 8 blocks hold one frame more + const size_t q = nf / 8, r = nf % 8; + block[i < r * (q + 1) ? i / (q + 1) : r + (i - r * (q + 1)) / std::max(1, q)]++; + } + } + std::ranges::sort(block); + t.concentration = static_cast(block[6] + block[7]) / std::max(1, t.n); + return t; + }; + auto reduced = [](const RotationIndexerResult &r) { + return LatticeSearch(r.lattice.ToPrimitive(r.search_result.centering)).primitive_reduced; + }; + + mark(*best.result, 0); + int64_t n_all = 0; + double i_all = 0.0; + for (const auto &[f, a] : assign) + for (size_t k = 0; k < a.size(); k++) + if (a[k] != -2) { + n_all++; + i_all += spot_cache.at(f)[k].intensity; + } + const Tally t0 = tally(0); + LeftoverLatticeCensus census; + census.frames = static_cast(census_frames.size()); + census.primary_spots_pct = 100.0 * t0.n / std::max(1, n_all); + census.primary_intensity_pct = 100.0 * t0.intensity / std::max(1.0, i_all); + const CrystalLattice primary_reduced = reduced(*best.result); + for (int id = 1; id <= 3; id++) { + RotationIndexer ri(experiment_, *indexer_pool); + for (const int f : spread_ordinals) { + std::vector left; + const auto &sp = spot_cache.at(f); + const auto &a = assign.at(f); + for (size_t k = 0; k < sp.size(); k++) + if (a[k] == -1) + left.push_back(sp[k]); + ri.ProcessImage(f, left, rot_angle(f)); + } + ri.RunIndexing(); + const auto r = ri.GetLattice(); + if (!r) + break; + const auto [real, chance] = leftover_evidence(*r); + mark(*r, id); + const Tally t = tally(id); + const CrystalLattice r_reduced = reduced(*r); + LeftoverLattice l; + l.cell = r->search_result.conventional.GetUnitCell(); + l.centering = r->search_result.centering; + l.system = gemmi::crystal_system_str(r->search_result.system); + l.volume_ratio = std::abs(r_reduced.CalcVolume()) / std::max(1.0f, std::abs(primary_reduced.CalcVolume())); + l.misorientation_deg = LatticeMisorientationDeg(primary_reduced, r_reduced); + l.z = (real - chance) / std::sqrt(std::max(1.0, chance)); + l.spots_pct = 100.0 * t.n / std::max(1, n_all); + l.intensity_pct = 100.0 * t.intensity / std::max(1.0, i_all); + l.sweep_concentration = t.concentration; + l.kind = ClassifyLeftoverLattice(l.misorientation_deg, l.volume_ratio, l.sweep_concentration); + logger.Info("Leftover lattice {}: {}-centred {} {:.2f} {:.2f} {:.2f} {:.2f} {:.2f} {:.2f}, " + "volume ratio {:.3f}, misorientation {:.2f} deg, z {:.1f} ({} vs {} at a wrong " + "angle), {:.1f}% of non-ice spots, {:.1f}% of their intensity, sweep " + "concentration {:.2f} -> {}", + id, l.centering, l.system, l.cell.a, l.cell.b, l.cell.c, l.cell.alpha, l.cell.beta, + l.cell.gamma, l.volume_ratio, l.misorientation_deg, l.z, real, chance, l.spots_pct, + l.intensity_pct, l.sweep_concentration, LeftoverLatticeKindName(l.kind)); + if (l.z >= 5.0 && l.kind != LeftoverLatticeKind::Self) + census.lattices.push_back(l); + if (real - chance < 3.0 * std::sqrt(std::max(1.0, chance)) + 5) + break; + } + logger.Info("Leftover-lattice census: the crystal's lattice takes {:.1f}% of {} non-ice spots " + "({:.1f}% of their intensity) on {} frames; {} further lattice(s); {:.1f} s", + census.primary_spots_pct, n_all, census.primary_intensity_pct, census.frames, + census.lattices.size(), + std::chrono::duration(std::chrono::steady_clock::now() - census_start).count()); + result.leftover_lattices = census; + } if (best.result->tilt_walk) { // What the walked tilt does to the prediction: the keystone at the far corner of the // detector, against the disc the integration sums over, and the whole-pattern shift @@ -8294,6 +8457,19 @@ ProcessResult Rugnux::RunPipeline(RugnuxObserver *observer, bool write_output, b /*trusted_path=*/true); } + // The per-frame sigma_M the merge wrote back onto the outcomes (the _plots.txt column), for the report. + if (indexer && experiment_.IsRotationIndexing()) { + std::vector mos; + for (const float m : ScalingResult(indexer->GetIntegrationOutcome()).mosaicity_deg) + if (std::isfinite(m)) + mos.push_back(m); + if (!mos.empty()) { + std::ranges::sort(mos); + result.mosaicity_deg = mos[mos.size() / 2]; + result.mosaicity_deg_p10 = mos[mos.size() / 10]; + result.mosaicity_deg_p90 = mos[mos.size() * 9 / 10]; + } + } // The two files a person checks the run by eye with. Not on the geometry pre-pass or a pass that // is thrown away, which would otherwise leave a stale _01 copy beside the real one. The table is // written on a stills run too - it is the only per-image scaling table there is, and the columns diff --git a/rugnux/Rugnux.h b/rugnux/Rugnux.h index f85aace6c..ee72237e6 100644 --- a/rugnux/Rugnux.h +++ b/rugnux/Rugnux.h @@ -24,6 +24,7 @@ #include "../image_analysis/scale_merge/TranslationalNCS.h" // TranslationalNCSResult #include "../image_analysis/indexing/HarmonicContamination.h" // HarmonicContaminationResult #include "ModelValidation.h" // ModelValidationResult +#include "LeftoverLattices.h" // LeftoverLatticeCensus #include "ReportDocument.h" // ReportWarning, PathologyCode #include "../image_analysis/scale_merge/SearchSpaceGroup.h" // SearchSpaceGroupResult #include "../image_analysis/scale_merge/CrystalSetting.h" // MetricViolation, MAX_METRIC_VIOLATION @@ -392,6 +393,14 @@ struct ProcessResult { UnitCell doubled_cell{}; }; std::optional supercell; + // Rotation: what the spots the crystal's lattice leaves over index to (split-crystal domains, twin + // domains, a second crystal). Measured once the first pass has its lattice; report only - nothing + // downstream uses it. Empty where the first pass did not index (a forced lattice, stills). + std::optional leftover_lattices; + // Rotation: the mosaic spread the merge computed partiality from - Kabsch's sigma_M in degrees, as + // XDS's REFLECTING_RANGE_E.S.D. - fitted per frame and smoothed in frame order; median and the 10th + // and 90th percentiles over the frames. NaN where nothing was merged. + double mosaicity_deg = NAN, mosaicity_deg_p10 = NAN, mosaicity_deg_p90 = NAN; // Powder contamination measured in the pre-scan: a crystalline phase other than the crystal, // diffracting as rings among its reflections. Measured and reported on every run. PowderRings powder; diff --git a/tests/ResultReportTest.cpp b/tests/ResultReportTest.cpp index c9f18d039..45e32b488 100644 --- a/tests/ResultReportTest.cpp +++ b/tests/ResultReportTest.cpp @@ -866,3 +866,89 @@ TEST_CASE("ResultReport_RotationScale", "[Diagnostics]") { CHECK(kept.find("\nOSCILLATION_RANGE= 0.1000\n") != std::string::npos); CHECK(kept.find("\nGONIOMETER_ROTATION_SCALE_SUSPECT= FALSE\n") != std::string::npos); } + +TEST_CASE("LeftoverLattice_Misorientation", "[Diagnostics]") { + const CrystalLattice triclinic(52.0f, 61.0f, 73.0f, 81.0f, 76.0f, 69.0f); + const auto rotated = [](const CrystalLattice &l, float deg, const Coord &axis) { + const RotMatrix r(deg * static_cast(PI) / 180.0f, axis); + return CrystalLattice(r * l.Vec0(), r * l.Vec1(), r * l.Vec2()); + }; + const CrystalLattice turned = rotated(triclinic, 3.0f, Coord(0.3f, -0.5f, 0.8f)); + CHECK(LatticeMisorientationDeg(triclinic, turned) == Catch::Approx(3.0).margin(0.01)); + // The same lattice in another basis of the same metric (a cyclic relabelling written back) is + // still 3 deg away. + const CrystalLattice relabelled(turned.Vec1(), turned.Vec2(), turned.Vec0()); + CHECK(LatticeMisorientationDeg(triclinic, relabelled) == Catch::Approx(3.0).margin(0.01)); + // Turned by 180 deg about an axis that is no symmetry of a triclinic lattice: a twin domain. + CHECK(LatticeMisorientationDeg(triclinic, rotated(triclinic, 180.0f, Coord(0.2f, 0.9f, 0.1f))) + == Catch::Approx(180.0).margin(0.01)); + // A lattice symmetry is not a misorientation: tetragonal turned 90 deg about c. + const CrystalLattice tetragonal(40.0f, 40.0f, 90.0f, 90.0f, 90.0f, 90.0f); + CHECK(LatticeMisorientationDeg(tetragonal, rotated(tetragonal, 90.0f, tetragonal.Vec2())) < 0.01); + // An unrelated cell has no matching basis. + CHECK(std::isnan(LatticeMisorientationDeg(triclinic, CrystalLattice(45.0f, 45.0f, 120.0f, 90.0f, 90.0f, 90.0f)))); +} + +TEST_CASE("LeftoverLattice_Classify", "[Diagnostics]") { + CHECK(ClassifyLeftoverLattice(0.4, 1.0, 0.3) == LeftoverLatticeKind::Self); + CHECK(ClassifyLeftoverLattice(2.7, 1.0, 0.3) == LeftoverLatticeKind::Domain); + CHECK(ClassifyLeftoverLattice(179.9, 1.0, 0.3) == LeftoverLatticeKind::TwinDomain); + CHECK(ClassifyLeftoverLattice(71.0, 1.0, 0.8) == LeftoverLatticeKind::Segmented); + CHECK(ClassifyLeftoverLattice(NAN, 0.5, 0.3) == LeftoverLatticeKind::RelatedCell); + CHECK(ClassifyLeftoverLattice(NAN, 3.02, 0.3) == LeftoverLatticeKind::RelatedCell); + CHECK(ClassifyLeftoverLattice(NAN, 1.34, 0.3) == LeftoverLatticeKind::Foreign); +} + +TEST_CASE("ResultReport_LeftoverLattices", "[Diagnostics]") { + DiffractionExperiment x(DetJF(1)); + ProcessResult result; + result.consensus_cell = UnitCell{.a = 50.0f, .b = 60.0f, .c = 70.0f, + .alpha = 90.0f, .beta = 100.0f, .gamma = 90.0f}; + LeftoverLatticeCensus census; + census.primary_spots_pct = 60.0; + census.primary_intensity_pct = 70.0; + result.leftover_lattices = census; + + auto text = RenderResultReport("p", "in.h5", x, result); + CHECK(text.find("EXTRA_LATTICE_COUNT= 0") != std::string::npos); + CHECK(text.find("Multiple lattices none found") != std::string::npos); + CHECK(text.find("MULTIPLE_LATTICES= FALSE") != std::string::npos); + + // A related cell carries intensity but is a question about the main cell, not a second crystal. + LeftoverLattice related{.kind = LeftoverLatticeKind::RelatedCell, .cell = *result.consensus_cell, + .volume_ratio = 0.5, .misorientation_deg = NAN, .z = 40.0, + .spots_pct = 15.0, .intensity_pct = 12.0, .sweep_concentration = 0.3}; + result.leftover_lattices->lattices = {related}; + text = RenderResultReport("p", "in.h5", x, result); + CHECK(text.find("EXTRA_LATTICE_1_KIND= RELATED_CELL") != std::string::npos); + CHECK(text.find("EXTRA_LATTICE_1_MISORIENTATION_DEG") == std::string::npos); + CHECK(text.find("MULTIPLE_LATTICES= FALSE") != std::string::npos); + + LeftoverLattice domain{.kind = LeftoverLatticeKind::Domain, .cell = *result.consensus_cell, + .volume_ratio = 1.0, .misorientation_deg = 2.7, .z = 250.0, + .spots_pct = 20.0, .intensity_pct = 25.0, .sweep_concentration = 0.3}; + result.leftover_lattices->lattices = {domain, related}; + text = RenderResultReport("p", "in.h5", x, result); + CHECK(text.find("EXTRA_LATTICE_COUNT= 2") != std::string::npos); + CHECK(text.find("EXTRA_LATTICE_1_MISORIENTATION_DEG= 2.70") != std::string::npos); + CHECK(text.find("EXTRA_LATTICE_INTENSITY_PCT= 25.0") != std::string::npos); + CHECK(text.find("MULTIPLE_LATTICES= TRUE") != std::string::npos); + CHECK(text.find("split crystal, 2.7 deg from the main lattice") != std::string::npos); + const auto flags = text.find("\nPATHOLOGY_FLAGS= "); + REQUIRE(flags != std::string::npos); + CHECK(text.substr(flags, text.find('\n', flags + 1) - flags).find("MULTIPLE_LATTICES") != std::string::npos); +} + +TEST_CASE("ResultReport_Mosaicity", "[Diagnostics]") { + DiffractionExperiment x(DetJF(1)); + ProcessResult result; + CHECK(RenderResultReport("p", "in.h5", x, result).find("MOSAICITY_DEG") == std::string::npos); + result.mosaicity_deg = 0.091; + result.mosaicity_deg_p10 = 0.080; + result.mosaicity_deg_p90 = 0.105; + const auto text = RenderResultReport("p", "in.h5", x, result); + CHECK(text.find("MOSAICITY_DEG= 0.091") != std::string::npos); + CHECK(text.find("MOSAICITY_DEG_P10= 0.080") != std::string::npos); + CHECK(text.find("MOSAICITY_DEG_P90= 0.105") != std::string::npos); + CHECK(text.find("Mosaicity 0.091 deg") != std::string::npos); +}