diff --git a/docs/ACKNOWLEDGEMENT.md b/docs/ACKNOWLEDGEMENT.md index 82d2ac334..8a2e79807 100644 --- a/docs/ACKNOWLEDGEMENT.md +++ b/docs/ACKNOWLEDGEMENT.md @@ -525,8 +525,10 @@ through maximum likelihood" (1996), Acta Cryst. A52, 659-668 [doi:10.1107/S0108767396004370](https://doi.org/10.1107/S0108767396004370); G. N. Murshudov, A. A. Vagin and E. J. Dodson, "Refinement of macromolecular structures by the maximum-likelihood method" (1997), Acta Cryst. D53, 240-255 [doi:10.1107/S0907444996012255](https://doi.org/10.1107/S0907444996012255). -Its two parameters, D and the variance, are fitted by maximum likelihood on the free reflections in -resolution bins: V. Y. Lunin and T. P. Skovoroda, "R-free likelihood-based estimates of errors for phases +Its two parameters are fitted by maximum likelihood in resolution bins - the variance on the free +reflections, D on the working reflections with the measurement error added to that variance, which is how +REFMAC5 divides them (Murshudov et al. 2011, above); the refined model's maps are weighted by the same D +and figure of merit. Estimating the likelihood's parameters on free reflections follows V. Y. Lunin and T. P. Skovoroda, "R-free likelihood-based estimates of errors for phases calculated from atomic models" (1995), Acta Cryst. A51, 880-887 [doi:10.1107/S010876739500688X](https://doi.org/10.1107/S010876739500688X); V. Y. Lunin, P. V. Afonine and A. G. Urzhumtsev, "Likelihood-based refinement. I. Irremovable model errors" (2002), Acta Cryst. A58, diff --git a/docs/RUGNUX_MODEL_AND_REFERENCE.md b/docs/RUGNUX_MODEL_AND_REFERENCE.md index adcb6e2be..e45ceb222 100644 --- a/docs/RUGNUX_MODEL_AND_REFERENCE.md +++ b/docs/RUGNUX_MODEL_AND_REFERENCE.md @@ -290,7 +290,7 @@ saying what had to be made of the input. | Option | Description | | --- | --- | | `--model ` | The model (required) | -| `--refine-score-only` | Score the model as given and refine nothing; every term of the score - R-work and R-free overall and in 20 resolution shells, the overall scale, B and anisotropic B, ksol and Bsol, the likelihood over the working and the free reflections and its figure of merit, and the geometry's rmsd and rmsZ - under `REFINE_SCORE_` keys (`--developer` prints them all) | +| `--refine-score-only` | Score the model as given and refine nothing; every term of the score - R-work and R-free overall and in 20 resolution shells, the overall scale, B and anisotropic B, ksol and Bsol, the likelihood over the working and the free reflections and its figure of merit over the working reflections, and the geometry's rmsd and rmsZ - under `REFINE_SCORE_` keys (`--developer` prints them all) | | `--refine-d-min ` | Leave out reflections finer than this | ## Free set and model bias diff --git a/image_analysis/structure_refinement/Refinement.cpp b/image_analysis/structure_refinement/Refinement.cpp index b055ddc82..3df00741f 100644 --- a/image_analysis/structure_refinement/Refinement.cpp +++ b/image_analysis/structure_refinement/Refinement.cpp @@ -29,7 +29,6 @@ #include "ModelScaling.h" #include "RefinementMath.h" #include "RefinementXray.h" -#include "SigmaA.h" #ifdef JFJOCH_USE_CUDA #include "../../common/CUDAWrapper.h" #include "RefinementGPU.h" @@ -50,6 +49,15 @@ constexpr double MAX_RMSD_BONDS = 0.02, MAX_RMSD_ANGLES = 2.0; // R-free differences smaller than this do not decide between two weights: the tighter geometry is taken. constexpr double R_FREE_TIE = 0.001; +// The figure of merit of the likelihood, , at X = 2 Fo D Fc / var: I1(X)/I0(X) for an acentric +// reflection, tanh(X / 2) for a centric one. +// Following Murshudov, Vagin & Dodson (1997) Acta Cryst. D53, 240-255 +double Fom(double x, bool centric) { + double log_i0 = 0, ratio = 0; + refine_math::BesselI0I1(x, log_i0, ratio); + return centric ? std::tanh(0.5 * x) : ratio; +} + std::string Joined(const std::vector &names) { std::string out; for (const std::string &n : names) @@ -252,21 +260,21 @@ struct Context { sc.n_free = r.n_free; sc.nll_work = sc.nll_free = 0; double fom_sum = 0; + int fom_n = 0; for (size_t m = 0; m < refl.Size(); m++) { double dfc = 0; const double fc = std::abs(fmodel[m]); const double nll = refine_math::AmplitudeNegLogLikelihood(refl.fo[m], fc, rows.d[m], rows.var[m], refl.centric[m], dfc); (refl.free[m] ? sc.nll_free : sc.nll_work) += nll; - // the figure of merit of the same likelihood: = I1(X)/I0(X), X = 2 Fo D Fc / var, for an - // acentric reflection; tanh(X / 2) for a centric one - // Following Murshudov, Vagin & Dodson (1997) Acta Cryst. D53, 240-255 + // the figure of merit of the same likelihood, over the working reflections const double x = 2.0 * refl.fo[m] * rows.d[m] * fc / rows.var[m]; - double log_i0 = 0, ratio = 0; - refine_math::BesselI0I1(x, log_i0, ratio); - fom_sum += refl.centric[m] ? std::tanh(0.5 * x) : ratio; + if (!refl.free[m]) { + fom_sum += Fom(x, refl.centric[m]); + fom_n++; + } } - sc.fom = fom_sum / static_cast(refl.Size()); + sc.fom = fom_n > 0 ? fom_sum / fom_n : NAN; for (int p : rider_parent) sc.hydrogens += p >= 0; constexpr int SHELLS = 20; @@ -614,18 +622,25 @@ double BalancedWeight(Context &ctx, const std::vector &refinable) { return nx > 0 ? std::sqrt(ng / nx) : 1.0; } -// The model's map coefficients and its difference map, as model validation makes them (sigma_A weighted). +// The model's map coefficients and its difference map, weighted by the refinement's own likelihood: m its figure +// of merit and D its D (2mFo - DFc, mFo - DFc). void MakeMaps(Context &ctx, const std::vector &merged, double wavelength_A, RefinementResult &result) { const RefinementStage stage("maps"); ctx.Refit(); const std::vector> fmodel = ctx.FModel(); const gemmi::GroupOps gops = ctx.sg->operations(); - std::vector sa; - for (size_t m = 0; m < ctx.refl.Size(); m++) - sa.push_back({ctx.refl.fo[m], std::abs(fmodel[m]), ctx.refl.inv_d2[m], static_cast(ctx.refl.epsilon[m]), - static_cast(ctx.refl.centric[m]), static_cast(ctx.refl.free[m])}); - const SigmaAResult sigma_a = EstimateSigmaA(sa, ctx.cell); - result.mean_fom = sigma_a.mean_fom; + std::vector fom(ctx.refl.Size()); + double fom_sum = 0; + int fom_n = 0; + for (size_t m = 0; m < ctx.refl.Size(); m++) { + const double x = 2.0 * ctx.refl.fo[m] * ctx.rows.d[m] * std::abs(fmodel[m]) / ctx.rows.var[m]; + fom[m] = Fom(x, ctx.refl.centric[m]); + if (!ctx.refl.free[m]) { + fom_sum += fom[m]; + fom_n++; + } + } + result.mean_fom = fom_n > 0 ? fom_sum / fom_n : 0; auto maps = std::make_shared(); MtzTable &mtz = maps->coefficients; @@ -645,7 +660,7 @@ void MakeMaps(Context &ctx, const std::vector &merged, double diff.spacegroup_ = ctx.sg; for (size_t m = 0; m < ctx.refl.Size(); m++) { const double fo = ctx.refl.fo[m], fc = std::abs(fmodel[m]); - const double mw = sigma_a.weight[m].m, d = sigma_a.weight[m].d; + const double mw = fom[m], d = ctx.rows.d[m]; const double fwt = ctx.refl.centric[m] ? mw * fo : 2 * mw * fo - d * fc; const double delfwt = mw * fo - d * fc; const double phi = std::arg(fmodel[m]); diff --git a/image_analysis/structure_refinement/Refinement.h b/image_analysis/structure_refinement/Refinement.h index 214bad54b..a2c10b2d2 100644 --- a/image_analysis/structure_refinement/Refinement.h +++ b/image_analysis/structure_refinement/Refinement.h @@ -82,7 +82,7 @@ struct RefinementScore { double r_work = NAN, r_free = NAN; int n_work = 0, n_free = 0; double nll_work = NAN, nll_free = NAN; - double fom = NAN; // the likelihood's mean figure of merit, all reflections + double fom = NAN; // the likelihood's mean figure of merit, working reflections int hydrogens = 0; // riding hydrogens in the model scored std::vector shells; // Per reflection, with settings.score_only only: the atoms' Fcalc, the solvent's k_sol exp(-b_sol s^2/4) Fmask diff --git a/image_analysis/structure_refinement/RefinementXray.cpp b/image_analysis/structure_refinement/RefinementXray.cpp index 7db2ae0d0..8337c8c68 100644 --- a/image_analysis/structure_refinement/RefinementXray.cpp +++ b/image_analysis/structure_refinement/RefinementXray.cpp @@ -41,14 +41,21 @@ gemmi::DensityCalculator Calculator(const gemmi::UnitCell &cell, c return dc; } +// The likelihood's variance of reflection i: epsilon beta, plus the measurement error of each of the structure +// factor's components that the observed amplitude measures - sigma^2 twice for an acentric reflection, once for a +// centric one (with_sigma = false leaves it out). +double Variance(const RefinementReflections &refl, size_t i, double beta, bool with_sigma) { + const double s2 = with_sigma ? double(refl.sigma[i]) * refl.sigma[i] : 0.0; + return refl.epsilon[i] * beta + (refl.centric[i] ? s2 : 2.0 * s2); +} + // -ln L summed over rows `idx` at D and beta. double BinNegLogLikelihood(const RefinementReflections &refl, const std::vector &fc, - const std::vector &idx, double d, double beta) { + const std::vector &idx, double d, double beta, bool with_sigma) { double sum = 0, dfc = 0; - for (size_t i : idx) { - const double var = refl.epsilon[i] * beta + double(refl.sigma[i]) * refl.sigma[i]; - sum += refine_math::AmplitudeNegLogLikelihood(refl.fo[i], fc[i], d, var, refl.centric[i], dfc); - } + for (size_t i : idx) + sum += refine_math::AmplitudeNegLogLikelihood(refl.fo[i], fc[i], d, Variance(refl, i, beta, with_sigma), + refl.centric[i], dfc); return sum; } @@ -260,18 +267,25 @@ void EstimateLikelihoodParameters(const RefinementReflections &refl, const std:: std::vector fc(n); for (size_t i = 0; i < n; i++) fc[i] = std::abs(fmodel[i]); - std::vector free; + std::vector free, work; for (size_t i = 0; i < n; i++) - if (refl.free[i] && fc[i] > 0) - free.push_back(i); + if (fc[i] > 0) + (refl.free[i] ? free : work).push_back(i); // Too few free reflections to bin: the working set, which says the model is better than it is, but // still gives the likelihood a scale. if (free.size() < FREE_PER_BIN) - for (size_t i = 0; i < n; i++) - if (!refl.free[i] && fc[i] > 0) - free.push_back(i); + free.insert(free.end(), work.begin(), work.end()); std::sort(free.begin(), free.end(), [&](size_t a, size_t b) { return refl.inv_d2[a] < refl.inv_d2[b]; }); const size_t bins = std::clamp(free.size() / FREE_PER_BIN, 1, MAX_BINS); + // the working reflections of each bin: those from its first free reflection's 1/d^2 to the next bin's + std::vector lower(bins); + for (size_t b = 0; b < bins; b++) + lower[b] = refl.inv_d2[free[b * free.size() / bins]]; + std::vector> work_in_bin(bins); + for (size_t i : work) { + const size_t b = std::upper_bound(lower.begin(), lower.end(), refl.inv_d2[i]) - lower.begin(); + work_in_bin[b > 0 ? b - 1 : 0].push_back(i); + } std::vector centre(bins), bin_d(bins), bin_beta(bins); // each bin is fitted on its own @@ -287,15 +301,23 @@ void EstimateLikelihoodParameters(const RefinementReflections &refl, const std:: centre[b] = s2 / static_cast(idx.size()); double d = sfc2 > 0 ? std::max(sfofc / sfc2, 0.05) : 1.0; double beta = std::max((sfo - d * d * sfc2) / static_cast(idx.size()), 1e-3 * sfo / idx.size()); - // Alternating one-dimensional minimisations of -ln L over ln D and ln beta. + // beta: the spread of the free amplitudes about D Fc, measurement error included, by maximum likelihood + // (alternating one-dimensional minimisations over ln D and ln beta) for (int round = 0; round < 4; round++) { - const double ld = GoldenMinimum([&](double x) { return BinNegLogLikelihood(refl, fc, idx, std::exp(x), beta); }, + const double ld = GoldenMinimum([&](double x) { return BinNegLogLikelihood(refl, fc, idx, std::exp(x), beta, false); }, std::log(d) - 2.0, std::log(std::min(d * 7.4, 3.0)), 40); d = std::exp(ld); - const double lb = GoldenMinimum([&](double x) { return BinNegLogLikelihood(refl, fc, idx, d, std::exp(x)); }, + const double lb = GoldenMinimum([&](double x) { return BinNegLogLikelihood(refl, fc, idx, d, std::exp(x), false); }, std::log(beta) - 3.0, std::log(beta) + 3.0, 40); beta = std::exp(lb); } + // D: by maximum likelihood on the working reflections, with the measurement error added to that beta. + // Where the error is a large part of the spread, the variance counts it twice and D falls towards 0 - + // the high-resolution D and figure of merit REFMAC 5.8 reports. + // Following Murshudov et al. (2011) Acta Cryst. D67, 355-367 (D from the working set, the variance from the free) + if (!work_in_bin[b].empty()) + d = GoldenMinimum([&](double x) { return BinNegLogLikelihood(refl, fc, work_in_bin[b], x, beta, true); }, + 0.0, 3.0, 50); bin_d[b] = d; bin_beta[b] = beta; }); @@ -315,7 +337,7 @@ void EstimateLikelihoodParameters(const RefinementReflections &refl, const std:: beta = bin_beta[b - 1] + t * (bin_beta[b] - bin_beta[b - 1]); } rows.d[i] = static_cast(d); - rows.var[i] = static_cast(refl.epsilon[i] * beta + double(refl.sigma[i]) * refl.sigma[i]); + rows.var[i] = static_cast(Variance(refl, i, beta, true)); } } diff --git a/image_analysis/structure_refinement/RefinementXray.h b/image_analysis/structure_refinement/RefinementXray.h index 4b3e9571c..6cd615d70 100644 --- a/image_analysis/structure_refinement/RefinementXray.h +++ b/image_analysis/structure_refinement/RefinementXray.h @@ -80,10 +80,11 @@ private: double spacing_; }; -// The ML parameters per reflection from the free reflections: D and beta fitted by maximum likelihood in -// resolution bins of the free set and interpolated between the bins' centres; the variance of a reflection is -// epsilon beta + sigma^2. `fmodel` is k_total (F + fmask), without D. -// Following Lunin & Skovoroda (1995) Acta Cryst. A51, 880-887, and Afonine et al. (2012) Acta Cryst. D68, 352-367 +// The ML parameters per reflection, in resolution bins of the free set interpolated between the bins' centres: +// beta fitted by maximum likelihood to the free reflections as the whole spread of Fo about D Fc, D then fitted to +// the working reflections with the variance epsilon beta + 2 sigma^2 (acentric; + sigma^2 centric), which is also +// the variance of a reflection in the target. `fmodel` is k_total (F + fmask), without D. +// Following Lunin & Skovoroda (1995) Acta Cryst. A51, 880-887, and Murshudov et al. (2011) Acta Cryst. D67, 355-367 void EstimateLikelihoodParameters(const RefinementReflections &refl, const std::vector> &fmodel, XrayRowModel &rows, size_t nthreads = 1); diff --git a/tests/RefinementTest.cpp b/tests/RefinementTest.cpp index 7c6cae710..9571e3f1b 100644 --- a/tests/RefinementTest.cpp +++ b/tests/RefinementTest.cpp @@ -408,6 +408,79 @@ TEST_CASE("RefinementRestraints_gradient", "[Refinement]") { #endif } +// A complete model whose every atom is off by a Gaussian error of sigma_x per axis: D(s) = = +// exp(-2 pi^2 sigma_x^2 s^2) (Luzzati). With a negligible measurement error D comes out at that; with an error of +// half the rms amplitude of the outermost shell it falls below it there, where the error is a large part of the +// spread and is counted twice, and stays where the amplitudes are strong. +TEST_CASE("RefinementLikelihood_D_coordinate_error", "[Refinement]") { + const char *group = "P 1"; + const gemmi::SpaceGroup &sg = *gemmi::find_spacegroup_by_name(group); + const gemmi::UnitCell cell(40, 45, 50, 90, 90, 90); + const double d_min = 1.5, sigma_x = 0.25; + gemmi::Structure truth = random_crystal(cell, group, 1500, 3); + gemmi::Model model = truth.models[0]; + std::mt19937 rng(4); + std::normal_distribution dx(0, sigma_x); + for (gemmi::Atom &a : model.chains[0].residues[0].atoms) + a.pos += gemmi::Position(dx(rng), dx(rng), dx(rng)); + RefinementReflections refl = PrepareRefinementReflections(asu_reflections(cell, sg, d_min), cell, sg, d_min); + auto cpu = MakeRefinementEngineCPU(cell, sg, d_min, refl, 4); + cpu->SetBlur(RefinementBlur(cell, sg, d_min, 5.0)); + std::vector> f; + cpu->Fcalc(truth.models[0], f); + for (size_t m = 0; m < refl.Size(); m++) + refl.fo[m] = std::abs(f[m]); + cpu->Fcalc(model, f); + + // mean D and mean Luzzati D in five shells of 1/d^2 + constexpr int SHELLS = 5; + const double s2_max = 1.0 / (d_min * d_min); + auto shells = [&](const XrayRowModel &rows, std::vector &d, std::vector &luzzati) { + std::vector n(SHELLS, 0); + d.assign(SHELLS, 0); + luzzati.assign(SHELLS, 0); + for (size_t m = 0; m < refl.Size(); m++) { + const int k = std::min(SHELLS - 1, static_cast(refl.inv_d2[m] / s2_max * SHELLS)); + d[k] += rows.d[m]; + luzzati[k] += std::exp(-2 * M_PI * M_PI * sigma_x * sigma_x * refl.inv_d2[m]); + n[k]++; + } + for (int k = 0; k < SHELLS; k++) { + d[k] /= n[k]; + luzzati[k] /= n[k]; + } + }; + XrayRowModel rows; + rows.k_total.assign(refl.Size(), 1.0f); + rows.fmask.assign(refl.Size(), {0, 0}); + for (float &s : refl.sigma) + s = 0.01f; + EstimateLikelihoodParameters(refl, f, rows); + std::vector d_clean, luzzati; + shells(rows, d_clean, luzzati); + for (int k = 0; k < SHELLS; k++) { + CAPTURE(k, d_clean[k], luzzati[k]); + CHECK(std::fabs(d_clean[k] - luzzati[k]) < 0.05); + } + CHECK(luzzati[SHELLS - 1] < 0.65); + + // a measurement error of half the rms amplitude of the outermost shell + double fo2 = 0; + int n = 0; + for (size_t m = 0; m < refl.Size(); m++) + if (refl.inv_d2[m] > s2_max * (SHELLS - 1) / SHELLS) { + fo2 += double(refl.fo[m]) * refl.fo[m]; + n++; + } + for (float &s : refl.sigma) + s = static_cast(0.5 * std::sqrt(fo2 / n)); + EstimateLikelihoodParameters(refl, f, rows); + std::vector d_noisy; + shells(rows, d_noisy, luzzati); + CHECK(d_noisy[0] > d_clean[0] - 0.03); + CHECK(d_noisy[SHELLS - 1] < d_clean[SHELLS - 1] - 0.1); +} + TEST_CASE("RefinementXray_gradient_CPU", "[Refinement]") { for (const char *group : {"P 1", "P 21 21 21", "C 1 2 1", "P 61 2 2"}) { CAPTURE(group);