diff --git a/docs/RUGNUX_REPORT.md b/docs/RUGNUX_REPORT.md index 0aff309f5..df7b5f3d7 100644 --- a/docs/RUGNUX_REPORT.md +++ b/docs/RUGNUX_REPORT.md @@ -921,8 +921,14 @@ two. **`CELL_ESD_REFLECTIONS=`** is the number of distinct reflections used and number of observations behind them and **`CELL_DSPACING_FIT=`** the cell the d-spacing fit itself returned. -Neither estimate includes what is common to every observation - the wavelength and the detector -distance scale the whole cell - so the e.s.d. is a precision, not an accuracy. Stills runs have no +The least-squares fit frees the detector distance alongside the metric (a cell scale moves every +spacing in proportion, a distance by cos²θ·cos 2θ of that, so the spacings measure the distance by how +their residuals curve with 2θ), and `CELL_ESD_LSQ=` is the metric's e.s.d. with the distance free: the +distance's uncertainty, as far as the spacings measure it, carried onto the cell through their +correlation - near 1 at low angle, where it can make this the larger of the two estimates. The block +fits hold the distance, which is common to every block. Neither includes the wavelength, which scales +the whole cell, nor a distance error the spacings cannot see, so the e.s.d. is a precision, not an +accuracy. Stills runs have no cell e.s.d.: the crystals' cells differ from one another by more than any one of them is measured to. ## Mosaicity diff --git a/image_analysis/geom_refinement/CellEsd.cpp b/image_analysis/geom_refinement/CellEsd.cpp index 1c7924d9b..83011f8ff 100644 --- a/image_analysis/geom_refinement/CellEsd.cpp +++ b/image_analysis/geom_refinement/CellEsd.cpp @@ -11,9 +11,10 @@ namespace { using Vec6 = Eigen::Matrix; - // At most six parameters: fixed-capacity, so the per-observation products never touch the heap. - using VecK = Eigen::Matrix; - using MatK = Eigen::Matrix; + // At most seven parameters (six of the metric and the distance): fixed-capacity, so the + // per-observation products never touch the heap. + using VecK = Eigen::Matrix; + using MatK = Eigen::Matrix; // A symmetric matrix as (g11, g22, g33, g12, g13, g23) and back. Vec6 ToVec6(const Eigen::Matrix3d &m) { @@ -39,6 +40,26 @@ namespace { } double ToDeg(double rad) { return rad * 180.0 / PI; } + + // One observation's row of the design matrix: q^2 = a . p, the distance term last. Read at a + // distance (1 + e) times the observations', |q| is q + e dq_dlnd, so q^2 = h^T G* h - 2 q dq_dlnd e + // to first order. + VecK DesignRow(const CellObservation &o, const Eigen::Matrix &v, + bool fit_distance) { + const int nmetric = static_cast(v.cols()); + VecK a(nmetric + (fit_distance ? 1 : 0)); + a.head(nmetric) = v.transpose() * IndexProducts(o); + if (fit_distance) + a(nmetric) = -2.0 * static_cast(o.q) * o.dq_dlnd; + return a; + } + + Eigen::Matrix BasisColumns(const std::vector &basis) { + Eigen::Matrix v(6, static_cast(basis.size())); + for (size_t k = 0; k < basis.size(); k++) + v.col(static_cast(k)) = ToVec6(basis[k]); + return v; + } } std::vector MetricBasis(const gemmi::SpaceGroup &sg) { @@ -115,11 +136,10 @@ std::array CellEsdFromCovariance(const std::vector & return esd; } -MetricFit FitReciprocalMetric(std::span obs, const std::vector &basis) { - const int nparam = static_cast(basis.size()); - Eigen::Matrix v(6, nparam); - for (int k = 0; k < nparam; k++) - v.col(k) = ToVec6(basis[k]); +MetricFit FitReciprocalMetric(std::span obs, const std::vector &basis, + bool fit_distance) { + const auto v = BasisColumns(basis); + const int nparam = static_cast(basis.size()) + (fit_distance ? 1 : 0); MetricFit fit; fit.used.assign(obs.size(), true); @@ -134,7 +154,7 @@ MetricFit FitReciprocalMetric(std::span obs, const std::v if (!fit.used[i]) continue; const double q2 = static_cast(obs[i].q) * obs[i].q; - const VecK a = v.transpose() * IndexProducts(obs[i]); + const VecK a = DesignRow(obs[i], v, fit_distance); normal.noalias() += a * a.transpose() / q2; // weight 1/q^2 on q^2: one e.s.d. on q rhs.noalias() += a; // a * q^2 / q^2 n++; @@ -146,8 +166,7 @@ MetricFit FitReciprocalMetric(std::span obs, const std::v std::vector z(obs.size()); for (size_t i = 0; i < obs.size(); i++) { const double q2 = static_cast(obs[i].q) * obs[i].q; - const VecK a = v.transpose() * IndexProducts(obs[i]); - const double r = q2 - a.dot(fit.p); + const double r = q2 - DesignRow(obs[i], v, fit_distance).dot(fit.p); z[i] = r * r / q2; if (fit.used[i]) wr2 += z[i]; @@ -182,6 +201,15 @@ std::optional EstimateCellEsd(std::span obs, con CellEsd out; out.esd_lsq = CellEsdFromCovariance(basis, fit.p, fit.cov); + // The same fit with the distance free: its metric block is the metric's covariance with the distance's + // uncertainty in it, where the spacings determine the distance at all. + const MetricFit with_distance = FitReciprocalMetric(obs, basis, true); + if (with_distance.ok) { + const auto k = static_cast(basis.size()); + out.esd_lsq = CellEsdFromCovariance(basis, with_distance.p.head(k), with_distance.cov.topLeftCorner(k, k)); + out.distance_rel = with_distance.p(k); + out.distance_rel_esd = std::sqrt(std::max(0.0, with_distance.cov(k, k))); + } const auto cell = CellFromReciprocalMetric(metric(fit.p)); out.fitted = UnitCell{static_cast(cell[0]), static_cast(cell[1]), static_cast(cell[2]), static_cast(cell[3]), static_cast(cell[4]), static_cast(cell[5])}; @@ -243,13 +271,18 @@ std::vector GatherCellObservations(const std::vector> per_frame(outcomes.size()); ParallelFor(static_cast(outcomes.size()), nthreads, [&](int f) { const IntegrationOutcome &out = outcomes[f]; + constexpr double DLND = 1e-3; + DiffractionGeometry further = out.geom; + further.DetectorDistance_mm(static_cast(out.geom.GetDetectorDistance_mm() * (1.0 + DLND))); for (const auto &r : out.reflections) { if (!r.observed || r.clipped || r.overloaded || r.on_ice_ring || !(r.sigma > 0.0f) || !(r.I > 3.0f * r.sigma) || !std::isfinite(r.observed_x) || !std::isfinite(r.observed_y)) continue; const float q = out.geom.DetectorToRecip(r.observed_x, r.observed_y).Length(); + const float q_far = further.DetectorToRecip(r.observed_x, r.observed_y).Length(); if (q > 0.0f) - per_frame[f].push_back(CellObservation{r.h, r.k, r.l, q, f}); + per_frame[f].push_back(CellObservation{r.h, r.k, r.l, q, f, + static_cast((q_far - q) / DLND)}); } }); std::vector obs; diff --git a/image_analysis/geom_refinement/CellEsd.h b/image_analysis/geom_refinement/CellEsd.h index 8a112d290..429208b65 100644 --- a/image_analysis/geom_refinement/CellEsd.h +++ b/image_analysis/geom_refinement/CellEsd.h @@ -25,6 +25,12 @@ // cell with respect to G*. A length the group ties to another gets the same e.s.d., an angle it fixes // gets zero. // +// The distance the observations were taken at is uncertain too, and a cell measured at a wrong distance is +// scaled with it - the two are correlated near 1 at low angle. So the least-squares fit frees the distance +// alongside the metric (see fit_distance below) and the cell's e.s.d.s are those of the metric with the +// distance free: the distance's uncertainty, as far as the spacings themselves can measure it, propagated +// through its correlation with the cell. +// // Least-squares cell e.s.d.s are known to be too small (Herbstein (2000) Acta Cryst. B56, 547-557): // they see only the scatter of the centroids, not what changes over the sweep. The same fit is // therefore also made on blocks of consecutive frames, and the scatter of the block cells, over the @@ -36,6 +42,8 @@ struct CellObservation { int32_t h = 0, k = 0, l = 0; float q = 0.0f; int32_t frame = 0; + // How |q| at the observed centroid moves with the detector distance: d|q| / d(ln distance), in 1/A. + float dq_dlnd = 0.0f; }; struct CellEsd { @@ -48,6 +56,9 @@ struct CellEsd { double theta_min_deg = 0.0; double theta_max_deg = 0.0; UnitCell fitted{}; // the d-spacing fit's own cell, for comparison with the reported one + // The detector distance as the spacings measure it, relative to the observations' own (FitReciprocalMetric, + // fit_distance), and its e.s.d.: the distance uncertainty esd_lsq carries. + double distance_rel = 0.0, distance_rel_esd = 0.0; }; // Symmetric 3x3 matrices spanning the reciprocal metrics G* the point group of `sg` allows @@ -64,14 +75,21 @@ std::array CellEsdFromCovariance(const std::vector & struct MetricFit { bool ok = false; - Eigen::VectorXd p; + Eigen::VectorXd p; // the metric's components, then (fit_distance) the relative distance change Eigen::MatrixXd cov; // scaled by the goodness of fit std::vector used; }; // Weighted linear least squares of q^2 = h^T G* h, |q| taken at one constant e.s.d. (weight 1/q^2 on // q^2), with the observations further than 4 sigma off the fit rejected and the fit repeated. -MetricFit FitReciprocalMetric(std::span obs, const std::vector &basis); +// fit_distance: the detector distance is a parameter too, as e = (distance / the observations' +// distance) - 1, the last element of p: each |q| is then read as q + e dq_dlnd. A distance error and +// a cell scale move a spot the same way at low angle; they part with 2theta (a cell scale shifts +// |q| in proportion, a distance by cos^2(theta) cos(2theta) of that), so e is measured by how the +// spacings' residuals curve with 2theta, and its covariance with the metric is what a cell measured +// at an uncertain distance inherits. +MetricFit FitReciprocalMetric(std::span obs, const std::vector &basis, + bool fit_distance = false); // Both estimates for observations in the setting of `sg`; blocks are cut by frame. Empty with too // few observations to fit. diff --git a/rugnux/RugnuxScaleMerge.cpp b/rugnux/RugnuxScaleMerge.cpp index cff894305..3e33beedd 100644 --- a/rugnux/RugnuxScaleMerge.cpp +++ b/rugnux/RugnuxScaleMerge.cpp @@ -5757,10 +5757,11 @@ bool Rugnux::ScaleMergeAndSymmetry(PipelineLocals &p) { if (result.cell_esd) { const CellEsd &e = *result.cell_esd; logger.Info("Cell e.s.d.s from {} observations of {} reflections: {:.5f} {:.5f} {:.5f} {:.4f} {:.4f} {:.4f}" - " (least squares {:.5f} {:.5f} {:.5f} {:.4f} {:.4f} {:.4f}, {} frame blocks)", + " (least squares, the distance free, {:.5f} {:.5f} {:.5f} {:.4f} {:.4f} {:.4f}, {} frame blocks);" + " the spacings put the detector {:+.4f} +- {:.4f} % from the distance integrated at", e.observations, e.reflections, e.esd[0], e.esd[1], e.esd[2], e.esd[3], e.esd[4], e.esd[5], e.esd_lsq[0], e.esd_lsq[1], e.esd_lsq[2], e.esd_lsq[3], e.esd_lsq[4], e.esd_lsq[5], - e.blocks); + e.blocks, 100.0 * e.distance_rel, 100.0 * e.distance_rel_esd); } } diff --git a/tests/CellEsdTest.cpp b/tests/CellEsdTest.cpp index 55c1d5242..6976718d9 100644 --- a/tests/CellEsdTest.cpp +++ b/tests/CellEsdTest.cpp @@ -105,6 +105,12 @@ TEST_CASE("CellEsd: the metric basis has the free parameters of each crystal sys CHECK(MetricBasis(Sg("I a -3 d")).size() == 1); } +// d|q| / d(ln distance) on a detector square to the beam: -q cos^2(theta) cos(2 theta). +static double DqDlnd(double q, double lambda) { + const double theta = std::asin(lambda * q / 2.0); + return -q * std::cos(theta) * std::cos(theta) * std::cos(2.0 * theta); +} + TEST_CASE("CellEsd: the metric basis spans the reciprocal metric of a cell of the group", "[cell_esd]") { // R G* R^T, not R^T G* R: only the right one keeps a hexagonal G* (g12* = +a*^2/2) in the span. double residual = 1.0; @@ -148,7 +154,8 @@ TEST_CASE("CellEsd: the d-spacing fit recovers the cell, and its e.s.d. is its s const double q = std::sqrt(v.dot(gstar * v)); if (q > 0.0 && q < 1.0 / 1.0) clean.push_back(CellObservation{h, k, l, static_cast(q), - static_cast(clean.size() * 37 % 100)}); + static_cast(clean.size() * 37 % 100), + static_cast(DqDlnd(q, 0.62))}); } REQUIRE(clean.size() > 2500); @@ -179,7 +186,11 @@ TEST_CASE("CellEsd: the d-spacing fit recovers the cell, and its e.s.d. is its s return std::sqrt(s); }; const CellEsd &e = fits.front(); - CHECK(sd(fitted_a) == Catch::Approx(e.esd_lsq[0]).epsilon(0.3)); + // The e.s.d. carries the distance's uncertainty as well, so it is above the scatter of cells + // fitted at the one distance the observations were read at - by the correlation of the two. + CHECK(e.esd_lsq[0] > sd(fitted_a)); + CHECK(e.esd_lsq[0] < 10.0 * sd(fitted_a)); + CHECK(std::abs(e.distance_rel) < 5.0 * e.distance_rel_esd); CHECK(sd(fitted_beta) == Catch::Approx(e.esd_lsq[4]).epsilon(0.3)); CHECK(std::abs(e.fitted.a - a) < 5 * e.esd_lsq[0] + 1e-4); // float cell CHECK(e.esd_lsq[3] < CELL_ESD_FIXED); @@ -187,12 +198,37 @@ TEST_CASE("CellEsd: the d-spacing fit recovers the cell, and its e.s.d. is its s // Pure centroid noise: the blocks agree with the least squares, and the larger of the two is written. REQUIRE(e.esd_blocks.has_value()); CHECK(e.blocks == 8); - CHECK((*e.esd_blocks)[0] == Catch::Approx(e.esd_lsq[0]).epsilon(0.8)); for (int j = 0; j < 6; j++) CHECK(e.esd[j] == std::max(e.esd_lsq[j], (*e.esd_blocks)[j])); CHECK(e.theta_max_deg == Catch::Approx(std::asin(0.62 / 2.0) * 180.0 / M_PI).margin(0.1)); } +TEST_CASE("CellEsd: the spacings measure a distance error by how it curves with 2theta", "[cell_esd]") { + const double lambda = 0.62; + const Eigen::Matrix3d gstar = ReciprocalMetric(10.0, 7.0, 12.0, 90, 100, 90); // synthetic + for (const double read_at : {0.0, 0.005}) { + // Read at a distance (1 + read_at) times the true one: every |q| comes out dq_dlnd * read_at off. + std::mt19937 rng(5); + std::normal_distribution noise(0.0, 2e-4); + std::vector obs; + for (int h = -8; h <= 8; h++) + for (int k = -5; k <= 5; k++) + for (int l = -8; l <= 8; l++) { + const Eigen::Vector3d v(h, k, l); + const double q = std::sqrt(v.dot(gstar * v)); + if (!(q > 0.0 && q < 1.0)) + continue; + const double dq = DqDlnd(q, lambda); + obs.push_back(CellObservation{h, k, l, static_cast(q + dq * read_at + noise(rng)), + static_cast(obs.size() * 37 % 100), static_cast(dq)}); + } + const auto e = EstimateCellEsd(obs, Sg("P 1 21 1"), lambda); + REQUIRE(e.has_value()); + CHECK(std::abs(e->distance_rel + read_at) < 4.0 * e->distance_rel_esd); + CHECK(e->distance_rel_esd < 0.1 * 0.005); + } +} + TEST_CASE("CellEsd: the SHELX .ins carries CELL, ZERR, LATT and SYMM", "[cell_esd][write_reflections]") { CellEsd esd; esd.esd = {0.0014, 0.0013, 0.0012, 0.0, 0.0034, 0.0};