From 26469ca8e82a3c9865b825ddbe75c70fe3b424e8 Mon Sep 17 00:00:00 2001 From: Filip Leonarski Date: Tue, 27 Oct 2026 17:58:20 +0100 Subject: [PATCH] RESULT-CHANGING: Refinement: twin-law refinement, decided against the untwinned one and a null Where the lattice admits a twin law for the group (Le Page two-folds within 3 deg, coset representatives whose square is in the group), the placed model is refined a second time against the data as twinned by the law: the Rice amplitude likelihood with the model amplitude k sqrt((1-a)|F(h)+Fsol(h)|^2 + a|F(Th)+Fsol(Th)|^2), D and Sigma fitted against it, exact at a = 0. Twin mates not observed are composed as structure-factor-only rows, so no extra FFT; the GPU engine adds a twinned-term kernel and a mate-derivative gather (deterministic, no atomics), the CPU engine the same sum. Per macro-cycle: scale/solvent, the fraction, the scale refitted on the model-detwinned Fo, the fraction again. The fraction is the regression of shell-normalised Fo^2 on the model's intensities at h and Th (intercept included), which gives 0 for unrelated partners; least squares on the twinned amplitudes gave 0.16 for unrelated partners and wrong laws on a model at R-free 0.31. The twinned refinement is kept where a > 0, its R-free is below the untwinned one by more than 0.001, and the law beats its null - the same model at the same fraction with every mate replaced by an unrelated reflection of the same resolution - on the free set by 3 standard errors (paired). A law whose twin pairs the free set splits is reported, not tested. The water build continues in the arm kept. Maps of a twinned refinement use Fo detwinned in proportion to the model. Keys REFINE_TWIN, REFINE_TWIN_LAW, REFINE_TWIN_FRACTION, REFINE_TWIN_R_WORK/_R_FREE, REFINE_TWIN_R_FREE_NULL, REFINE_TWIN_NULL_Z, REFINE_UNTWINNED_R_WORK/_R_FREE. Measured (--mode refine on the rc180 battery's placed models and merges, 32 sets): adopted on every entry deposited as twinned (6iu6 0.231->0.200, 6iu8 0.285->0.199, 6iu9 0.307->0.212, 9i80 0.237->0.212, 2wnn 0.292->0.246, 2xfw 0.210->0.202, 5j23 0.250->0.192), on the twinned frames of 3mc4 (0.265->0.157) and 3r6o (0.264->0.169), and on 6p8j, 6vww, 7k1l, 8xte, 8xtg, 9qw2, 2wnz, 9hnc; not adopted on 15 sets with a law (fractions 0-0.11, z <= 2.5), whose refined models and REFINE_ keys are byte-identical to the build without this change. Holohedral groups: NO_TWIN_LAW, unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HVeDQqN9qRD57vnShzTC37 --- docs/ACKNOWLEDGEMENT.md | 11 + docs/CPU_DATA_ANALYSIS_REFINEMENT.md | 69 ++++- docs/RUGNUX_REPORT.md | 6 + .../structure_refinement/Refinement.cpp | 281 +++++++++++++++--- .../structure_refinement/Refinement.h | 22 ++ .../structure_refinement/RefinementGPU.cpp | 21 +- .../structure_refinement/RefinementGPU.cu | 73 ++++- .../RefinementGPUEngine.h | 8 +- .../structure_refinement/RefinementXray.cpp | 185 +++++++++++- .../structure_refinement/RefinementXray.h | 57 +++- rugnux/ResultReport.cpp | 18 ++ tests/RefinementTest.cpp | 163 ++++++++++ 12 files changed, 858 insertions(+), 56 deletions(-) diff --git a/docs/ACKNOWLEDGEMENT.md b/docs/ACKNOWLEDGEMENT.md index ac8c70426..023511d8d 100644 --- a/docs/ACKNOWLEDGEMENT.md +++ b/docs/ACKNOWLEDGEMENT.md @@ -229,6 +229,17 @@ H = |I(h) − I(Th)|/(I(h) + I(Th)) of the pairs a law relates is uniform on [0, gives the fraction. T. O. Yeates, "Detecting and overcoming crystal twinning" (1997), Methods Enzymol. 276, 344-358 [doi:10.1016/S0076-6879(97)76068-3](https://doi.org/10.1016/S0076-6879%2897%2976068-3). +**Twin refinement** (§15.12) refines the model against Yeates's twinned intensity, (1−α) I(h) + α I(Th), with the +twin fraction refined beside it as SHELXL refines BASF: R. Herbst-Irmer and G. M. Sheldrick, "Refinement of twinned +structures with SHELXL97" (1998), Acta Cryst. B54, 443-449 +[doi:10.1107/S0108768197018454](https://doi.org/10.1107/S0108768197018454). The twin laws come from the lattice's +metric as A. A. Lebedev, A. A. Vagin and G. N. Murshudov describe, "Intensity statistics in twinned crystals with +examples from the PDB" (2006), Acta Cryst. D62, 83-95 +[doi:10.1107/S0907444905036759](https://doi.org/10.1107/S0907444905036759), and the fractions are refined by +least squares at every cycle, as REFMAC5 refines them (Murshudov et al. 2011, Acta Cryst. D67, 355-367, cited +above). REFMAC5's target is a twinned-intensity likelihood; ours keeps the amplitude likelihood with the twinned +model amplitude in it, a simplification of that. + **A first-pass cell that is the coincidence lattice of two twin domains** (twinning by reticular merohedry of index 2 or 3, e.g. obverse/reverse rhombohedral domains or a cubic crystal twinned about [111]) is recognised by the nodes that belong to neither domain being empty. The twin index is diff --git a/docs/CPU_DATA_ANALYSIS_REFINEMENT.md b/docs/CPU_DATA_ANALYSIS_REFINEMENT.md index 0c9d74b4f..96fc567b4 100644 --- a/docs/CPU_DATA_ANALYSIS_REFINEMENT.md +++ b/docs/CPU_DATA_ANALYSIS_REFINEMENT.md @@ -377,7 +377,66 @@ the card's budget, or with `--no-gpu`, or on a build without CUDA (macOS include Metal path), the CPU engine computes the same target, to rounding, several times more slowly (seconds on a GPU, typically 2-15 minutes on the CPU). -### 15.12 Not yet +### 15.12 Twinned data + +Where the lattice admits a **twin law** for the group the data are merged in - a rotation of the lattice's metric +symmetry (Le Page two-folds within 3° of obliquity, the search the free set is grouped by, §10.7) that the group +lacks, one per coset of the group, with its square in the group so that it exchanges two domains - the placed +model is refined a second time, against the data as twinned by the law, and the two refinements are compared. +`rugnux ` does this on its own; nothing has to be given. + +**The target.** A crystal twinned by law $T$ at fraction $\alpha$ records $(1-\alpha)I(\mathbf{h}) + \alpha I(T\mathbf{h})$ +(Yeates 1997), so the model an observation is compared with is + +$$ +|F_\mathrm{twin}(\mathbf{h})| = k\,e^{-\mathbf{s}^\top\mathbf{B}\mathbf{s}/4}\sqrt{(1-\alpha)\,|F_\mathrm{calc}(\mathbf{h}) + F_\mathrm{sol}(\mathbf{h})|^2 + \alpha\,|F_\mathrm{calc}(T\mathbf{h}) + F_\mathrm{sol}(T\mathbf{h})|^2}, +$$ + +and the target is the likelihood of §15.2 with $|F_\mathrm{model}|$ replaced by $|F_\mathrm{twin}|$, $D$ and $\Sigma$ +fitted against it (§15.3). At $\alpha = 0$ it is the untwinned target exactly. It is an approximation: a twinned +amplitude is treated as Rice-distributed about $D|F_\mathrm{twin}|$, while the distribution of a sum of two +intensities is narrower; $\Sigma$, fitted to the free set, absorbs that, and REFMAC5's twinned-intensity likelihood +(Murshudov et al. 2011) is the treatment this one simplifies. The mates $T\mathbf{h}$ that were not observed are +composed as rows of their own, with no observation: their structure factors come from the same transform, so a +twinned evaluation costs no extra FFT, only one more kernel per evaluation on the GPU (the twinned term per +reflection and the gather of its mate's derivative, the law being an involution on the rows). + +**The fraction, the scale and the solvent** are fitted inside the twin sum at every macro-cycle: the scale and the +solvent as in §15.3, then $\alpha$, then the scale and the solvent again against $F_o$ detwinned by the model as it +stands, $F_o|F_\mathrm{model}(\mathbf{h})|/|F_\mathrm{twin}(\mathbf{h})|$ (at which scale the twinned model meets $F_o$ +as the untwinned one meets the detwinned $F_o$), then $\alpha$ again. $\alpha \in [0, 1/2]$ comes from the regression +of $F_o^2$, with an intercept, on the model's intensities at $\mathbf{h}$ and at $T\mathbf{h}$, all normalised in +resolution shells of 500 reflections: $\alpha = b_{T\mathbf{h}}/(b_\mathbf{h} + b_{T\mathbf{h}})$, over the working +reflections that are not their own mate. The expectation of $F_o^2$ given the model, $D^2|F_\mathrm{model}|^2 + \Sigma$, +is linear in the two intensities, so an unrelated partner takes a coefficient of 0 however poor the model; a +least-squares fit of the twinned amplitudes instead took a fraction of 0.16 for unrelated partners of one model at +R-free 0.31, the average of two predictions being a better prediction than either. + +**The decision.** The twinned refinement is kept where its fraction is above 0, its R-free is below the +untwinned refinement's by more than 0.001, and the law beats its own **null** on the free reflections by at least +three standard errors - the null being the same twinned model at the same fraction with every reflection's mate +replaced by an unrelated reflection of the same resolution: what the averaging of two intensities buys whatever +they are (it lifts a weak reflection's model amplitude off zero). The comparison is paired, reflection by reflection, $|F_o - |F_\mathrm{null}|| - |F_o - |F_\mathrm{twin}||$ +over the free set, its mean against its standard error (`REFINE_TWIN_NULL_Z`): two refinements of one model +differ in R-free by a few thousandths from their trajectories alone, more than a fixed tie, and a fraction of one +or two percent is not resolved by them. A pseudo-symmetry the model already carries (non-crystallographic +symmetry parallel to the law) predicts $I(T\mathbf{h}) \approx I(\mathbf{h})$, so the law changes nothing and is not +taken for a twin. A law is tested only where the free set keeps its twin pairs together, and is otherwise reported +(`REFINE_TWIN` `FREE_SET_SPLIT`) rather than tested. The free set rugnux draws (§10.7) keeps together the pairs of +every law that is a rotation of the cell's own basis vectors; a law of a centred lattice that is not (its matrix +fractional in the cell's basis) can be split by it, and so can a free set `--mode refine` reads from a file. Of several laws, the one the placed model asks the largest fraction of is refined. The water +build (§15.10) then continues against whichever data the decision kept. + +**Maps.** Against twinned data the map coefficients use $F_o$ detwinned in proportion to the model's own share of +the twinned intensity, $F_o|F_\mathrm{model}(\mathbf{h})|/|F_\mathrm{twin}(\mathbf{h})|$, and $DF_c$ of the model's own +$|F_\mathrm{model}(\mathbf{h})|$; `FP` in `_refined_maps.mtz` is the detwinned amplitude. + +The keys are `REFINE_TWIN` (`NO_TWIN_LAW`, `FREE_SET_SPLIT`, `ZERO_FRACTION`, `UNTWINNED`, `TWINNED`), +`REFINE_TWIN_LAW`, `REFINE_TWIN_FRACTION`, `REFINE_TWIN_R_WORK`/`_R_FREE`, `REFINE_TWIN_R_FREE_NULL`, `REFINE_TWIN_NULL_Z` and +`REFINE_UNTWINNED_R_WORK`/`_R_FREE`, the last five before the water build. Where `REFINE_TWIN` is `TWINNED`, every +other `REFINE_` key, `REFINE_R_FREE_START` and the `REFINE_SCORE_` terms included, is of the twinned refinement. + +### 15.13 Not yet What the refinement does not do yet - each a known gap, not a design choice: @@ -388,7 +447,8 @@ What the refinement does not do yet - each a known gap, not a design choice: - **Anisotropic ADPs**: an anisotropic B is replaced by its isotropic equivalent, and only isotropic B is refined. - **NCS restraints**: copies are refined independently. -- **Twin refinement**: the target is not a twinned one, also where the twin hypothesis' merge was written. +- **More than two twin domains** (tetartohedral twinning): one law at a time is refined, and laws whose square is + not in the group are not considered. - **Ion identification**: waters are built and removed (§15.10), but no ion is placed or relabelled; the solvent audit scores the waters and ions there are. - **Alternative conformations and occupancies**: existing conformers are refined in place; no occupancy is @@ -403,8 +463,11 @@ What the refinement does not do yet - each a known gap, not a design choice: - R. C. Agarwal, "A new least-squares refinement technique based on the fast Fourier transform algorithm", *Acta Cryst.* **A34** (1978), 791-809 (the gradient by the FFT method, §15.2). - N. S. Pannu & R. J. Read, "Improved structure refinement through maximum likelihood", *Acta Cryst.* **A52** (1996), 659-668, and G. N. Murshudov, A. A. Vagin & E. J. Dodson, "Refinement of macromolecular structures by the maximum-likelihood method", *Acta Cryst.* **D53** (1997), 240-255 (the maximum-likelihood amplitude target and its figure of merit, §15.2, §15.8). -- G. N. Murshudov, P. Skubák, A. A. Lebedev, N. S. Pannu, R. A. Steiner, R. A. Nicholls, M. D. Winn, F. Long & A. A. Vagin, "REFMAC5 for the refinement of macromolecular crystal structures", *Acta Cryst.* **D67** (2011), 355-367 (D from the working set and the variance from the free, §15.3; the Kullback-Leibler form of the B restraints, §15.5). +- G. N. Murshudov, P. Skubák, A. A. Lebedev, N. S. Pannu, R. A. Steiner, R. A. Nicholls, M. D. Winn, F. Long & A. A. Vagin, "REFMAC5 for the refinement of macromolecular crystal structures", *Acta Cryst.* **D67** (2011), 355-367 (D from the working set and the variance from the free, §15.3; the Kullback-Leibler form of the B restraints, §15.5; the twinned refinement §15.12 simplifies, its twin laws pruned by fraction and its fractions refined by least squares). - R. J. Read, "Improved Fourier coefficients for maps using phases from partial structures with errors", *Acta Cryst.* **A42** (1986), 140-149 (the m, D weighting of the map coefficients, §15.8). +- T. O. Yeates, "Detecting and overcoming crystal twinning", *Methods Enzymol.* **276** (1997), 344-358 (the twinned intensity, §15.12). +- A. A. Lebedev, A. A. Vagin & G. N. Murshudov, "Intensity statistics in twinned crystals with examples from the PDB", *Acta Cryst.* **D62** (2006), 83-95 (twin laws from the lattice's metric, §15.12). +- R. Herbst-Irmer & G. M. Sheldrick, "Refinement of twinned structures with SHELXL97", *Acta Cryst.* **B54** (1998), 443-449 (twinned refinement with the fraction refined beside the model, §15.12). - V. Y. Lunin & T. P. Skovoroda, "R-free likelihood-based estimates of errors for phases calculated from atomic models", *Acta Cryst.* **A51** (1995), 880-887, and V. Y. Lunin, P. V. Afonine & A. G. Urzhumtsev, "Likelihood-based refinement. I. Irremovable model errors", *Acta Cryst.* **A58** (2002), 270-282 (the likelihood's parameters from the free set, §15.3). - J.-S. Jiang & A. T. Brünger, "Protein hydration observed by X-ray diffraction: solvation properties of penicillopepsin and neuraminidase crystal structures", *J. Mol. Biol.* **243** (1994), 100-115, and A. Fokine & A. Urzhumtsev, "Flat bulk-solvent model: obtaining optimal parameters", *Acta Cryst.* **D58** (2002), 1387-1392 (the flat bulk-solvent mask and its parameters, §15.3). - P. V. Afonine, R. W. Grosse-Kunstleve & P. D. Adams, "A robust bulk-solvent correction and anisotropic scaling procedure", *Acta Cryst.* **D61** (2005), 850-855 (the grid search over the solvent parameters, §15.3). diff --git a/docs/RUGNUX_REPORT.md b/docs/RUGNUX_REPORT.md index 8865f17d4..cd132b4b5 100644 --- a/docs/RUGNUX_REPORT.md +++ b/docs/RUGNUX_REPORT.md @@ -1200,6 +1200,12 @@ Where a model was placed and refined ([Refinement](RUGNUX_MODEL_AND_REFERENCE.md | `REFINE_ATOMS`, `REFINE_ATOMS_REFINED` | The model's atoms (hydrogens not counted) and those refined: the atoms of the residues the dictionary describes, with an occupancy above zero | | `REFINE_RESIDUES_FIXED`, `REFINE_RESIDUES_FIXED_NAMES` | The residues the embedded dictionary does not describe, held fixed but kept in the structure factors, the solvent mask and the clash terms, and their names | | `REFINE_BULK_SOLVENT_K_SOL`, `REFINE_BULK_SOLVENT_B_SOL` | *dev*. The flat bulk solvent of the refined model | +| `REFINE_TWIN` | The twin hypothesis ([§15.12](CPU_DATA_ANALYSIS_REFINEMENT.md#1512-twinned-data)): `NO_TWIN_LAW` (the lattice admits none for the group), `FREE_SET_SPLIT` (the free set splits the law's twin pairs; not tested), `ZERO_FRACTION`, `UNTWINNED` (tested, not better), `TWINNED` (the refined model and every other `REFINE_` key are of the refinement against the twinned data), `NOT_TESTED` | +| `REFINE_TWIN_LAW`, `REFINE_TWIN_FRACTION` | The twin law tested (an hkl operator in the data's basis) and the fraction it refined to | +| `REFINE_TWIN_SPLIT_PAIRS` | Where `FREE_SET_SPLIT`: the twin pairs with one member in the working and one in the free set | +| `REFINE_TWIN_R_WORK`, `REFINE_TWIN_R_FREE`, `REFINE_UNTWINNED_R_WORK`, `REFINE_UNTWINNED_R_FREE` | The twinned and the untwinned refinement, before the water build | +| `REFINE_TWIN_R_FREE_NULL` | The twinned model's R-free at its fraction with every mate replaced by an unrelated reflection of the same resolution: what averaging alone buys. `REFINE_TWIN_FRACTION_NULL` (*dev*) is the fraction those unrelated mates ask for, about 0 | +| `REFINE_TWIN_NULL_Z` | The law's lead over that null on the free reflections, paired reflection by reflection, in standard errors; `TWINNED` needs 3 | | `REFINE_BLOBS` | The blobs of the refined mFo-DFc map (above 3 σ, peaking above 4 σ) | | `REFINE_BLOBS_LIGAND`, `REFINE_BLOBS_WATER`, `REFINE_BLOBS_ION`, `REFINE_BLOBS_MODEL_ERROR` | How many of them are read as each ([§15.9](CPU_DATA_ANALYSIS_REFINEMENT.md#159-unexplained-density-blobs)); the rest are unassigned | | `REFINE_SOLVENT_SITES` | The waters and single-atom ions of the refined model the solvent audit scored ([§15.10](CPU_DATA_ANALYSIS_REFINEMENT.md#1510-the-solvent-audit)) | diff --git a/image_analysis/structure_refinement/Refinement.cpp b/image_analysis/structure_refinement/Refinement.cpp index ed119cd3f..56d19ff89 100644 --- a/image_analysis/structure_refinement/Refinement.cpp +++ b/image_analysis/structure_refinement/Refinement.cpp @@ -262,7 +262,7 @@ struct Context { if (engine->OnGPU()) engine->Fmask(Model(), fmask); else - mask->Fmask(Model(), refl.hkl, fmask); + mask->Fmask(Model(), refl.RowHkl(), fmask); } std::optional s3("refit.scale"); @@ -278,28 +278,52 @@ struct Context { } gemmi::Scaling scaling(cell, sg); scaling.use_solvent = true; - scaling.prepare_points(fc, fo, &fm); // the scale of the score: by robust least squares (ModelScaleBox::robust) + auto fit_scale = [&]() { + scaling.points.clear(); + scaling.prepare_points(fc, fo, &fm); #ifdef JFJOCH_USE_CUDA - if (scale_gpu) - scale_gpu->Fit(scaling, SolventBMax(Model()), nthreads, true, grid_k_sol, grid_b_sol); - else + if (scale_gpu) + scale_gpu->Fit(scaling, SolventBMax(Model()), nthreads, true, grid_k_sol, grid_b_sol); + else #endif - FitModelScale(scaling, {.b_hi = SolventBMax(Model()), .robust = true, .k_start = grid_k_sol, - .b_start = grid_b_sol}, nthreads); - s3.reset(); - k_sol = grid_k_sol = scaling.k_sol; - b_sol = grid_b_sol = scaling.b_sol; - k_overall = scaling.k_overall; - b_star = scaling.b_star; - rows.k_total.resize(refl.Size()); - rows.fmask.resize(refl.Size()); - std::vector> fmodel(refl.Size()); - for (size_t m = 0; m < refl.Size(); m++) { - rows.k_total[m] = static_cast(scaling.get_overall_scale_factor(refl.hkl[m])); - rows.fmask[m] = static_cast(scaling.get_solvent_scale(cell.calculate_stol_sq(refl.hkl[m]))) * fmask[m]; - fmodel[m] = rows.k_total[m] * (fcalc[m] + rows.fmask[m]); + FitModelScale(scaling, {.b_hi = SolventBMax(Model()), .robust = true, .k_start = grid_k_sol, + .b_start = grid_b_sol}, nthreads); + k_sol = grid_k_sol = scaling.k_sol; + b_sol = grid_b_sol = scaling.b_sol; + k_overall = scaling.k_overall; + b_star = scaling.b_star; + rows.k_total.resize(refl.Size()); + rows.fmask.resize(refl.Rows()); + for (size_t m = 0; m < refl.Size(); m++) { + rows.k_total[m] = static_cast(scaling.get_overall_scale_factor(refl.hkl[m])); + rows.fmask[m] = static_cast(scaling.get_solvent_scale(cell.calculate_stol_sq(refl.hkl[m]))) * fmask[m]; + } + for (size_t m = refl.Size(); m < refl.Rows(); m++) { + const gemmi::Miller &h = refl.mate_hkl[m - refl.Size()]; + rows.fmask[m] = static_cast(scaling.get_solvent_scale(cell.calculate_stol_sq(h))) * fmask[m]; + } + }; + fit_scale(); + if (refl.Twinned()) { + // The scale and the solvent inside the twin sum: the fraction for the untwinned fit, then the scale + // fitted again against Fo detwinned by the model as it stands, Fo |F_model(h)| / |F_twin(h)| - which + // the twinned model at that scale meets as the untwinned one meets Fo - and the fraction again. + rows.twin_fraction = static_cast(FitTwinFraction(refl, rows, fcalc)); + const std::vector> twinned = TwinnedModel(refl, rows, fcalc); + fo.v.clear(); + for (size_t m = 0; m < refl.Size(); m++) { + if (refl.free[m]) + continue; + const double own = std::abs(rows.k_total[m] * (fcalc[m] + rows.fmask[m])); + const double tw = std::abs(twinned[m]); + fo.v.push_back({refl.hkl[m], {static_cast(tw > 0 ? refl.fo[m] * own / tw : refl.fo[m]), 1.0f}}); + } + fit_scale(); + rows.twin_fraction = static_cast(FitTwinFraction(refl, rows, fcalc)); } + s3.reset(); + const std::vector> fmodel = TwinnedModel(refl, rows, fcalc); { const RefinementStage s4("refit.ml"); EstimateLikelihoodParameters(refl, fmodel, rows, ml_threads); @@ -333,6 +357,8 @@ struct Context { rows.k_total[m] *= static_cast(std::exp(b_iso * refl.inv_d2[m] / 4.0)); rows.fmask[m] *= static_cast(std::exp(-b_iso * refl.inv_d2[m] / 4.0)); } + for (size_t m = refl.Size(); m < refl.Rows(); m++) + rows.fmask[m] *= static_cast(std::exp(-b_iso * cell.calculate_1_d2(refl.mate_hkl[m - refl.Size()]) / 4.0)); engine->SetRowModel(rows); } @@ -371,6 +397,7 @@ struct Context { } } sc.fom = fom_n > 0 ? fom_sum / fom_n : NAN; + sc.twin_fraction = rows.twin_fraction; for (int p : rider_parent) sc.hydrogens += p >= 0; constexpr int SHELLS = 20; @@ -475,10 +502,7 @@ struct Context { // F_model with the cycle's scale and solvent, for the atoms as they are now. std::vector> FModel() { engine->Fcalc(Model(), fcalc); - std::vector> fmodel(refl.Size()); - for (size_t m = 0; m < refl.Size(); m++) - fmodel[m] = rows.k_total[m] * (fcalc[m] + rows.fmask[m]); - return fmodel; + return TwinnedModel(refl, rows, fcalc); } }; @@ -837,7 +861,8 @@ double BalancedADPWeight(Context &ctx, const RestraintSet &b_restraints, const s } // 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). +// of merit and D its D (2mFo - DFc, mFo - DFc). With a twin law, Fo is detwinned by the model in proportion to its +// own share of the twinned intensity, Fo |F_model(h)| / |F_twin(h)|, and Fc is the model's own |F_model(h)|. // Following Read (1986) Acta Cryst. A42, 140-149 void MakeMaps(Context &ctx, const std::vector &merged, double wavelength_A, RefinementResult &result) { const RefinementStage stage("maps"); @@ -874,7 +899,13 @@ void MakeMaps(Context &ctx, const std::vector &merged, double diff.unit_cell_ = fwt_data.unit_cell_ = ctx.cell; diff.spacegroup_ = fwt_data.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]); + double fo = ctx.refl.fo[m], fc = std::abs(fmodel[m]); + if (ctx.refl.Twinned()) { + const double own = std::abs(ctx.rows.k_total[m] * (ctx.fcalc[m] + ctx.rows.fmask[m])); + if (fc > 0) + fo *= own / fc; + fc = own; + } 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; @@ -935,6 +966,50 @@ void MakeMaps(Context &ctx, const std::vector &merged, double difference_map.get(); } +// The null of a twinned refinement, for the model as the last Refit() left it: its R-free at the same fraction with +// every reflection's mate replaced by an unrelated observed one of the same resolution - the reflections in order of +// 1/d^2 paired TWIN_NULL_SHIFT apart, beyond any run of equal 1/d^2 a twin law relates. What the averaging of two +// intensities buys on its own, whatever they are. +constexpr size_t TWIN_NULL_SHIFT = 8; +// The twinned refinement is taken only where the law beats its null on the free set by this many standard errors. +constexpr double TWIN_NULL_Z = 3.0; +void TwinNull(const Context &ctx, RefinementResult &result) { + RefinementReflections null = ctx.refl; + const size_t n = null.Size(); + null.mate_hkl.clear(); + std::vector order(n); + std::iota(order.begin(), order.end(), 0); + std::stable_sort(order.begin(), order.end(), [&](int a, int b) { return null.inv_d2[a] < null.inv_d2[b]; }); + null.mate.assign(n, 0); + for (size_t r = 0; r < n; r++) { + // in blocks of twice the shift, the first half with the second + const size_t p = r % (2 * TWIN_NULL_SHIFT) < TWIN_NULL_SHIFT ? r + TWIN_NULL_SHIFT : r - TWIN_NULL_SHIFT; + null.mate[order[r]] = order[p < n ? p : r]; + } + // at the law's fraction: averaging any two intensities lifts the weak reflections' model amplitudes off zero + // by itself (the fraction the unrelated mates ask for, reported beside it, is about 0) + XrayRowModel rows = ctx.rows; + result.twin_fraction_null = FitTwinFraction(null, rows, ctx.fcalc); + const std::vector> f_null = TwinnedModel(null, rows, ctx.fcalc); + result.twin_r_free_null = ComputeRFactors(null, f_null).r_free; + // How far the law beats its null on the free reflections, paired: the mean of |Fo - |F_null|| - |Fo - |F_twin|| + // over its standard error. + const std::vector> f_law = TwinnedModel(ctx.refl, ctx.rows, ctx.fcalc); + double sum = 0, sum2 = 0; + int n_free = 0; + for (size_t m = 0; m < n; m++) + if (ctx.refl.free[m]) { + const double d = std::fabs(ctx.refl.fo[m] - std::abs(f_null[m])) - std::fabs(ctx.refl.fo[m] - std::abs(f_law[m])); + sum += d; + sum2 += d * d; + n_free++; + } + if (n_free > 1) { + const double mean = sum / n_free, var = (sum2 - n_free * mean * mean) / (n_free - 1); + result.twin_null_z = var > 0 ? mean / std::sqrt(var / n_free) : 0.0; + } +} + // The engine for the model as it is now: on the GPU where it is wanted and takes the case within its budget, // on the CPU otherwise. void MakeEngine(Context &ctx, bool gpu, const RefinementSettings &settings, Logger &logger) { @@ -1228,10 +1303,26 @@ std::vector RunTrials(const std::vector &trial_slots, namespace { +// 1/d^2 of the finest amplitude of `merged`, 0 without any. +double MaxInvD2(const std::vector &merged) { + double max_inv_d2 = 0; + for (const MergedReflection &r : merged) + if (std::isfinite(r.F) && r.d > 0) + max_inv_d2 = std::max(max_inv_d2, 1.0 / (double(r.d) * r.d)); + return max_inv_d2; +} + +// The d_min a refinement composes to: just past the finest reflection, so that prepare_asu_data()'s strict limit +// keeps it. +double RefinementDMin(double max_inv_d2) { + return 0.999 / std::sqrt(max_inv_d2); +} + // One refinement of a model whose atoms stay as they are (RefineModel adds and removes waters between calls). +// `twin_law`: against the data as twinned by it, null for untwinned. RefinementResult RefineOnce(const gemmi::Structure &placed, const std::vector &merged, const gemmi::UnitCell &cell, const gemmi::SpaceGroup &sg, double wavelength_A, - Logger &logger, const RefinementSettings &settings) { + Logger &logger, const RefinementSettings &settings, const gemmi::Op *twin_law = nullptr) { const auto start = std::chrono::steady_clock::now(); RefinementResult result; Context ctx; @@ -1251,22 +1342,23 @@ RefinementResult RefineOnce(const gemmi::Structure &placed, const std::vector 0) - max_inv_d2 = std::max(max_inv_d2, 1.0 / (double(r.d) * r.d)); + const double max_inv_d2 = MaxInvD2(merged); if (max_inv_d2 <= 0) { result.failure_reason = "no amplitudes"; return result; } - // just past the finest reflection, so that prepare_asu_data()'s strict limit keeps it - ctx.d_min = 0.999 / std::sqrt(max_inv_d2); + ctx.d_min = RefinementDMin(max_inv_d2); result.d_min = 1.0 / std::sqrt(max_inv_d2); ctx.refl = PrepareRefinementReflections(merged, cell, sg, ctx.d_min); if (ctx.refl.Size() < 100) { result.failure_reason = "too few reflections"; return result; } + if (twin_law != nullptr) { + result.twin_split_pairs = SetTwinLaw(ctx.refl, cell, sg, ctx.d_min, *twin_law); + result.twinned = true; + result.twin_law = twin_law->as_hkl().triplet('h'); + } ctx.mask = std::make_unique(cell, sg, ctx.d_min, settings.nthreads); @@ -1294,8 +1386,12 @@ RefinementResult RefineOnce(const gemmi::Structure &placed, const std::vector DecideTwin(const gemmi::Structure &placed, const std::vector &merged, + const gemmi::UnitCell &cell, const gemmi::SpaceGroup &sg, double wavelength_A, + Logger &logger, const RefinementSettings &settings, RefinementResult &result) { + const RefinementStage stage("twin"); + result.untwinned_r_work = FinalRWork(result); + result.untwinned_r_free = FinalRFree(result); + const std::vector laws = RefinementTwinLaws(cell, sg); + result.twin_laws = static_cast(laws.size()); + if (laws.empty()) { + result.twin_decision = "NO_TWIN_LAW"; + return std::nullopt; + } + // the laws whose twin pairs the free set keeps together + RefinementReflections refl = PrepareRefinementReflections(merged, cell, sg, RefinementDMin(MaxInvD2(merged))); + std::vector usable; + for (const gemmi::Op &law : laws) { + const int split = SetTwinLaw(refl, cell, sg, RefinementDMin(MaxInvD2(merged)), law); + if (split == 0) + usable.push_back(law); + else { + logger.Info("Refinement, twin law {}: not tested - {} of its twin pairs are split between the working and " + "the free set", law.as_hkl().triplet('h'), split); + result.twin_law = law.as_hkl().triplet('h'); + result.twin_split_pairs = split; + } + } + if (usable.empty()) { + result.twin_decision = "FREE_SET_SPLIT"; + return std::nullopt; + } + result.twin_split_pairs = 0; + gemmi::Op law = usable[0]; + if (usable.size() > 1) { + RefinementSettings score = settings; + score.score_only = true; + double best = -1; + for (const gemmi::Op &candidate : usable) { + const RefinementResult s = RefineOnce(placed, merged, cell, sg, wavelength_A, logger, score, &candidate); + logger.Info("Refinement, twin law {}: the placed model asks a fraction of {:.3f}", + candidate.as_hkl().triplet('h'), s.score_start.twin_fraction); + if (s.ok && s.score_start.twin_fraction > best) { + best = s.score_start.twin_fraction; + law = candidate; + } + } + } + result.twin_law = law.as_hkl().triplet('h'); + RefinementResult twinned = RefineOnce(placed, merged, cell, sg, wavelength_A, logger, settings, &law); + if (!twinned.ok || twinned.cancelled) { + result.twin_decision = "UNTWINNED"; + return std::nullopt; + } + result.twin_fraction = twinned.twin_fraction; + result.twin_r_work = FinalRWork(twinned); + result.twin_r_free = FinalRFree(twinned); + result.twin_r_free_null = twinned.twin_r_free_null; + result.twin_fraction_null = twinned.twin_fraction_null; + result.twin_null_z = twinned.twin_null_z; + const bool adopt = twinned.twin_fraction > 0 && result.twin_r_free < result.untwinned_r_free - R_FREE_TIE && + result.twin_null_z >= TWIN_NULL_Z; + result.twin_decision = twinned.twin_fraction == 0 ? "ZERO_FRACTION" : adopt ? "TWINNED" : "UNTWINNED"; + logger.Info("Refinement, twin law {}: fraction {:.3f}, R-work {:.4f}, R-free {:.4f}; untwinned R-free {:.4f}; null " + "(mates unrelated, fraction {:.3f}) R-free {:.4f}, the law ahead of it by {:.1f} standard errors -> {}", + result.twin_law, result.twin_fraction, result.twin_r_work, result.twin_r_free, result.untwinned_r_free, + result.twin_fraction_null, result.twin_r_free_null, result.twin_null_z, result.twin_decision); + if (!adopt) + return std::nullopt; + // the twinned refinement is the result, with the evidence that chose it + twinned.twin_decision = result.twin_decision; + twinned.twin_laws = result.twin_laws; + twinned.twin_r_work = result.twin_r_work; + twinned.twin_r_free = result.twin_r_free; + twinned.untwinned_r_work = result.untwinned_r_work; + twinned.untwinned_r_free = result.untwinned_r_free; + result = std::move(twinned); + return law; +} + } // namespace RefinementResult RefineModel(const gemmi::Structure &placed, const std::vector &merged, @@ -1581,6 +1773,9 @@ RefinementResult RefineModel(const gemmi::Structure &placed, const std::vector twin_law; + if (settings.twin && !settings.score_only && result.ok && !result.cancelled) + twin_law = DecideTwin(placed, merged, cell, sg, wavelength_A, logger, settings, result); // The water build: a round of waters added and removed on the refined model's maps (SolventBuild.h), then a // refinement of the model so changed, kept where its R-free is lower; until a round changes nothing. const bool build = settings.solvent && settings.restrained && !settings.score_only && result.ok && @@ -1616,7 +1811,8 @@ RefinementResult RefineModel(const gemmi::Structure &placed, const std::vector(added.size()); diff --git a/image_analysis/structure_refinement/Refinement.h b/image_analysis/structure_refinement/Refinement.h index cefde1799..f267ce8f9 100644 --- a/image_analysis/structure_refinement/Refinement.h +++ b/image_analysis/structure_refinement/Refinement.h @@ -62,6 +62,9 @@ struct RefinementSettings { // Waters added at the difference map's peaks and removed where the maps no longer hold them, between refinements // (SolventBuild.h), to SOLVENT_BUILD_D_MIN. bool solvent = true; + // A refinement against the data as twinned by each twin law the lattice admits (RefinementTwinLaws), beside the + // untwinned one, and the model of whichever the evidence favours (RefineModel). + bool twin = true; bool gpu = true; size_t nthreads = 1; size_t gpu_resident_bytes = 0; // held on the card by what runs beside @@ -96,6 +99,7 @@ struct RefinementScore { int n_work = 0, n_free = 0; double nll_work = NAN, nll_free = NAN; double fom = NAN; // the likelihood's mean figure of merit, working reflections + double twin_fraction = 0; // against a twin law: the fraction fitted with the scale 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 @@ -165,6 +169,24 @@ struct RefinementResult { std::vector solvent; double b_ceiling = 0; // the highest B the refinement allowed SolventBuildResult solvent_build; // the waters added and removed (settings.solvent) + + // Twin refinement (settings.twin): what was decided (twin_decision: NO_TWIN_LAW, FREE_SET_SPLIT - the free + // set does not keep the law's twin pairs together -, ZERO_FRACTION - the model asks for none -, UNTWINNED, + // TWINNED), the law tested and the fraction it refined to, and the evidence: the R-free of the untwinned and + // the twinned refinement, and the null of the twinned one - its final model at its fraction with every mate + // replaced by an unrelated reflection of the same resolution - the R-free that averaging alone buys, + // and the law's lead over it on the free set in standard errors. + // `twinned`: the model and every number above it are the twinned refinement's. + std::string twin_decision; + bool twinned = false; + std::string twin_law; // hkl triplet, in the data's basis + double twin_fraction = NAN; + int twin_laws = 0; // the laws the lattice admits + int twin_split_pairs = 0; // the tested law's twin pairs split between work and free + double twin_r_work = NAN, twin_r_free = NAN; + double untwinned_r_work = NAN, untwinned_r_free = NAN; + double twin_r_free_null = NAN, twin_fraction_null = NAN; + double twin_null_z = NAN; // the law's lead over the null on the free set, in standard errors }; // `placed`: the model in the data's cell and space group. With settings.solvent (and restrained, not score_only), diff --git a/image_analysis/structure_refinement/RefinementGPU.cpp b/image_analysis/structure_refinement/RefinementGPU.cpp index dc886f577..c167767f2 100644 --- a/image_analysis/structure_refinement/RefinementGPU.cpp +++ b/image_analysis/structure_refinement/RefinementGPU.cpp @@ -121,6 +121,15 @@ public: setup_.work.push_back(!refl.free[m]); setup_.centric.push_back(refl.centric[m]); } + // a twin law's mates not observed: structure factors only + for (const gemmi::Miller &h : refl.mate_hkl) { + setup_.rows.push_back({h[0], h[1], h[2]}); + setup_.inv_d2.push_back(cell.calculate_1_d2(h)); + setup_.fo.push_back(0); + setup_.work.push_back(0); + setup_.centric.push_back(0); + } + setup_.mate = refl.mate; // The adjoint of the composition on cuFFT's half-u spectrum: the term of row m and operator o, at // k = hR, goes to k where k_u > 0, conjugated to -k where k_u < 0, and to both on the planes k_u = 0 @@ -131,9 +140,10 @@ public: }; std::vector> entries; const int n_ops = static_cast(gops.sym_ops.size()); - for (size_t m = 0; m < refl.Size(); m++) + const std::vector row_hkl = refl.RowHkl(); + for (size_t m = 0; m < row_hkl.size(); m++) for (int o = 0; o < n_ops; o++) { - const gemmi::Miller k = gops.sym_ops[o].apply_to_hkl(refl.hkl[m]); + const gemmi::Miller k = gops.sym_ops[o].apply_to_hkl(row_hkl[m]); const int term = (static_cast(m) * n_ops + o) * 2; if (k[0] > 0 && 2 * k[0] != nu) entries.emplace_back(point(k[0], k[1], k[2]), term); @@ -186,7 +196,12 @@ public: std::vector> fmask(rows.fmask.size()); for (size_t m = 0; m < fmask.size(); m++) fmask[m] = {rows.fmask[m].real(), rows.fmask[m].imag()}; - engine_->SetRowModel(rows.k_total, fmask, rows.d, rows.var); + // per row of the engine: the mates' rows have no observation, and nothing of theirs is read but fmask + std::vector k_total = rows.k_total, d = rows.d, var = rows.var; + k_total.resize(setup_.rows.size(), 0.0f); + d.resize(setup_.rows.size(), 0.0f); + var.resize(setup_.rows.size(), 1.0f); + engine_->SetRowModel(k_total, fmask, d, var, rows.twin_fraction); } bool OnGPU() const override { return true; } diff --git a/image_analysis/structure_refinement/RefinementGPU.cu b/image_analysis/structure_refinement/RefinementGPU.cu index 90d9672ec..e2b142975 100644 --- a/image_analysis/structure_refinement/RefinementGPU.cu +++ b/image_analysis/structure_refinement/RefinementGPU.cu @@ -115,6 +115,48 @@ __global__ void compose_target_kernel(const float2 *f1, float norm, int nu, int coef[m] = make_float2(static_cast(cr), static_cast(ci)); } +// With a twin law, the target's term of a working row against the twinned model, +// |F_model| = k sqrt((1-a) |U(h)|^2 + a |U(Th)|^2) with U = F + fmask, from F of every row (compose_target_kernel +// without `evaluate`); and the conjugates of its derivatives with respect to U(h) and to U(Th), unscaled, in `own` +// and `other` - zero for a row that is not a working observation. +__global__ void twin_target_kernel(const float2 *f, const float2 *fmask, const int *mate, const float *twin_fraction, + int rows, const float *k_total, const float *ml_d, const float *ml_var, + const float *fo, const char *work, const char *centric, double *nll, float2 *own, + float2 *other) { + const int m = blockIdx.x * blockDim.x + threadIdx.x; + if (m >= rows) + return; + double term = 0, g = 0; + const int j = mate[m]; + const double u1r = f[m].x + fmask[m].x, u1i = f[m].y + fmask[m].y; + const double u2r = f[j].x + fmask[j].x, u2i = f[j].y + fmask[j].y; + const double a = twin_fraction[0]; + if (work[m]) { + const double k = k_total[m]; + const double fc = k * sqrt((1.0 - a) * (u1r * u1r + u1i * u1i) + a * (u2r * u2r + u2i * u2i)); + double dfc = 0; + term = refine_math::AmplitudeNegLogLikelihood(fo[m], fc, ml_d[m], ml_var[m], centric[m], dfc); + if (fc > 0) + g = dfc * k * k / fc; + } + nll[m] = term; + own[m] = make_float2(static_cast(g * (1.0 - a) * u1r), static_cast(-g * (1.0 - a) * u1i)); + other[m] = make_float2(static_cast(g * a * u2r), static_cast(-g * a * u2i)); +} + +// The gradient's coefficient of every row under a twin law: its own term's derivative and that of the row whose +// mate it is - its own mate, the law being an involution - times the row's scale. +__global__ void twin_gather_kernel(const float2 *own, const float2 *other, const int *mate, const double *row_scale, + int rows, float2 *coef) { + const int n = blockIdx.x * blockDim.x + threadIdx.x; + if (n >= rows) + return; + const double scale = row_scale[n]; + const float2 a = own[n], b = other[mate[n]]; + coef[n] = make_float2(static_cast(scale * (static_cast(a.x) + b.x)), + static_cast(scale * (static_cast(a.y) + b.y))); +} + // The gradient's coefficients on the half-u spectrum: each point the sum, in order, of the terms // (coef[row] exp(2 pi i h.t_op)) / 2 that land on it, conjugated where they land as a Friedel mate. A term is // its row * 2 + conj, and its phase the table's entry at term_phase. @@ -495,6 +537,10 @@ struct RefinementGPUEngineImpl { CudaDevicePtr row_scale; CudaDevicePtr k_total, ml_d, ml_var, fo; CudaDevicePtr fmask_scaled, f, fm, coef; + // a twin law's (setup.mate non-empty): the mates, the fraction, the two parts of each row's derivative + CudaDevicePtr mate; + CudaDevicePtr twin_fraction; + CudaDevicePtr coef_own, coef_other; CudaDevicePtr work, centric; CudaDevicePtr nll, nll_sum; CudaDevicePtr reduce_temp; @@ -538,6 +584,12 @@ struct RefinementGPUEngineImpl { centric = CudaDevicePtr(nr, sync); nll = CudaDevicePtr(nr, sync); nll_sum = CudaDevicePtr(1, sync); + if (!setup.mate.empty()) { + mate = CudaDevicePtr(nr, sync); + twin_fraction = CudaDevicePtr(1, sync); + coef_own = CudaDevicePtr(nr, sync); + coef_other = CudaDevicePtr(nr, sync); + } reduce_bytes = ReduceBytes(nr); reduce_temp = CudaDevicePtr(std::max(reduce_bytes, 1), sync); scatter_point = CudaDevicePtr(std::max(setup.scatter_point.size(), 1), sync); @@ -586,6 +638,8 @@ struct RefinementGPUEngineImpl { Upload(fo, setup.fo, stream); Upload(work, setup.work, stream); Upload(centric, setup.centric, stream); + if (!setup.mate.empty()) + Upload(mate, setup.mate, stream); Upload(scatter_point, setup.scatter_point, stream); Upload(scatter_start, setup.scatter_start, stream); Upload(scatter_term, term, stream); @@ -642,7 +696,17 @@ struct RefinementGPUEngineImpl { void QueueEvaluate(bool grad) { const int rows = static_cast(setup.rows.size()); Transform(); - Compose(true); + if (setup.mate.empty()) + Compose(true); + else if (rows > 0) { + Compose(false); + twin_target_kernel<<>>(f, fmask_scaled, mate, twin_fraction, rows, k_total, + ml_d, ml_var, fo, work, centric, nll, coef_own, + coef_other); + cuda_err(cudaGetLastError()); + twin_gather_kernel<<>>(coef_own, coef_other, mate, row_scale, rows, coef); + cuda_err(cudaGetLastError()); + } if (rows > 0) { size_t temp = reduce_bytes; cuda_err(cub::DeviceReduce::Sum(reduce_temp.get(), temp, nll.get(), nll_sum.get(), rows, stream)); @@ -735,6 +799,8 @@ size_t RefinementGPUEngine::DeviceBytes(const RefinementGPUSetup &s, size_t fft_ size_t bytes = na * (2 * sizeof(float4) + 3 * sizeof(int) + sizeof(ModelMaskAtom) + sizeof(ModelDensityAtom)); bytes += GridPoints(s.grid) * sizeof(float) + ComplexPoints(s.grid) * sizeof(float2) + fft_work_bytes; bytes += nr * (3 * sizeof(int) + 2 * sizeof(double) + 4 * sizeof(float) + 4 * sizeof(float2) + 2); + if (!s.mate.empty()) + bytes += nr * (sizeof(int) + 2 * sizeof(float2)); bytes += (s.scatter_point.size() + s.scatter_start.size() + 2 * s.scatter_term.size()) * sizeof(int); int phase_min = 0, phase_max = 0; PhaseRange(s, phase_min, phase_max); @@ -772,10 +838,13 @@ void RefinementGPUEngine::SetBlur(double blur) { } void RefinementGPUEngine::SetRowModel(const std::vector &k_total, const std::vector> &fmask, - const std::vector &d, const std::vector &var) { + const std::vector &d, const std::vector &var, float twin_fraction) { RefinementGPUEngineImpl &e = *impl_; DeviceGuard guard(e.device); Upload(e.k_total, k_total, e.stream); + const std::vector fraction{twin_fraction}; // kept until the wait below + if (e.twin_fraction) + Upload(e.twin_fraction, fraction, e.stream); if (!fmask.empty()) cuda_err(cudaMemcpyAsync(e.fmask_scaled, fmask.data(), fmask.size() * sizeof(float2), cudaMemcpyHostToDevice, e.stream)); diff --git a/image_analysis/structure_refinement/RefinementGPUEngine.h b/image_analysis/structure_refinement/RefinementGPUEngine.h index 4b8c86d7c..595aa8a7e 100644 --- a/image_analysis/structure_refinement/RefinementGPUEngine.h +++ b/image_analysis/structure_refinement/RefinementGPUEngine.h @@ -32,6 +32,9 @@ struct RefinementGPUSetup { std::vector inv_d2; std::vector fo; std::vector work, centric; + // With a twin law: per row the row of its twin mate (RefinementReflections::mate), an involution; empty + // without one. + std::vector mate; // The adjoint of the composition, as a gather: the half-u spectrum points the gradient's coefficients // land on (ascending), and for each the terms (row * ops + op) * 2 + conj adding to it, in order. std::vector scatter_point, scatter_start, scatter_term; @@ -51,9 +54,10 @@ public: // n_cen exp(blur s^2 / 4) per reflection: prepare_asu_data()'s unblur. void SetBlur(double blur); - // Per macro-cycle: F_model = k_total (F + fmask), and the likelihood's D and variance. + // Per macro-cycle: F_model = k_total (F + fmask), the likelihood's D and variance, and with a twin law the twin + // fraction (XrayRowModel). void SetRowModel(const std::vector &k_total, const std::vector> &fmask, - const std::vector &d, const std::vector &var); + const std::vector &d, const std::vector &var, float twin_fraction = 0); // The atoms' densities, as ModelStructureFactorsGPU takes them (the boxes of ModelDensityGPU::Boxes() made // from them): called again only where some atom's density changed. Read until the call returns; from pinned diff --git a/image_analysis/structure_refinement/RefinementXray.cpp b/image_analysis/structure_refinement/RefinementXray.cpp index faba0a11d..17ac3515a 100644 --- a/image_analysis/structure_refinement/RefinementXray.cpp +++ b/image_analysis/structure_refinement/RefinementXray.cpp @@ -7,12 +7,14 @@ #include #include #include +#include #include #include "gemmi/dencalc.hpp" #include "gemmi/it92.hpp" #include "gemmi/math.hpp" +#include "gemmi/twin.hpp" #include "../../common/Logger.h" #include "../../common/ParallelFor.h" @@ -107,7 +109,7 @@ public: RefinementEngineCPU(const gemmi::UnitCell &cell, const gemmi::SpaceGroup &sg, double d_min, const RefinementReflections &refl, size_t nthreads) : cell_(cell), sg_(sg), d_min_(d_min), refl_(refl), nthreads_(nthreads), - grid_(RigidBodyZoneGrid(cell, sg, d_min)), composition_(grid_, d_min, refl.hkl), + grid_(RigidBodyZoneGrid(cell, sg, d_min)), composition_(grid_, d_min, refl.RowHkl()), orbit_leaders_(OrbitLeaders(grid_, nthreads)) {} void SetBlur(double blur) override { blur_ = blur; } @@ -125,7 +127,7 @@ public: PutMaskOnGrid(mask, model, orbit_leaders_, nthreads_); const gemmi::FPhiGrid fm = MapToFPhi(mask); f.clear(); - for (const gemmi::Miller &h : refl_.hkl) + for (const gemmi::Miller &h : refl_.RowHkl()) f.push_back(fm.get_value_by_hkl(h)); } @@ -136,17 +138,35 @@ public: // The target and, per reflection, dT/dF of the atoms' structure factor (dT/dRe F + i dT/dIm F). std::vector> dt_df(n, 0.0); double sum = 0; - for (size_t m = 0; m < n; m++) { + const double a = rows_.twin_fraction; + for (size_t m = 0; m < refl_.Size(); m++) { if (refl_.free[m]) continue; const double k = rows_.k_total[m]; - const std::complex fm = k * (f[m] + std::complex(rows_.fmask[m])); - const double fc = std::abs(fm); + if (!refl_.Twinned()) { + const std::complex fm = k * (f[m] + std::complex(rows_.fmask[m])); + const double fc = std::abs(fm); + double dfc = 0; + sum += refine_math::AmplitudeNegLogLikelihood(refl_.fo[m], fc, rows_.d[m], rows_.var[m], + refl_.centric[m], dfc); + if (fc > 0) + dt_df[m] = k * dfc * fm / fc; + continue; + } + // twinned: |F_model| = k sqrt((1-a) |U(h)|^2 + a |U(Th)|^2), U = F + fmask, so that + // dT/dU(h) = dT/d|F_model| k^2 (1-a) U(h) / |F_model| and dT/dU(Th) the same with a U(Th) + const int j = refl_.mate[m]; + const std::complex u1 = f[m] + std::complex(rows_.fmask[m]); + const std::complex u2 = f[j] + std::complex(rows_.fmask[j]); + const double fc = k * std::sqrt((1.0 - a) * std::norm(u1) + a * std::norm(u2)); double dfc = 0; sum += refine_math::AmplitudeNegLogLikelihood(refl_.fo[m], fc, rows_.d[m], rows_.var[m], refl_.centric[m], dfc); - if (fc > 0) - dt_df[m] = k * dfc * fm / fc; + if (fc > 0) { + const double g = dfc * k * k / fc; + dt_df[m] += g * (1.0 - a) * u1; + dt_df[j] += g * a * u2; + } } if (grad == nullptr) return sum; @@ -253,6 +273,157 @@ RefinementReflections PrepareRefinementReflections(const std::vector RefinementReflections::RowHkl() const { + std::vector out = hkl; + out.insert(out.end(), mate_hkl.begin(), mate_hkl.end()); + return out; +} + +std::vector RefinementTwinLaws(const gemmi::UnitCell &cell, const gemmi::SpaceGroup &sg) { + const gemmi::GroupOps gops = sg.operations(); + std::vector laws; + std::vector found; + try { + found = gemmi::find_twin_laws(cell, &sg, 3.0, false); + } catch (const std::exception &) { + return laws; // a setting whose centring the lattice search does not reproduce: no law is looked for + } + for (const gemmi::Op &op : found) { + const gemmi::Op law{op.rot, {0, 0, 0}, 'x'}; + const gemmi::Op square = law * law; + if (gops.find_by_rotation(square.rot) != nullptr || gops.find_by_rotation(square.negated_rot()) != nullptr) + laws.push_back(law); + } + return laws; +} + +int SetTwinLaw(RefinementReflections &refl, const gemmi::UnitCell &cell, const gemmi::SpaceGroup &sg, double d_min, + const gemmi::Op &law) { + const gemmi::GroupOps gops = sg.operations(); + const gemmi::ReciprocalAsu asu(&sg); + const size_t n = refl.Size(); + std::map row; + for (size_t m = 0; m < n; m++) + row[refl.hkl[m]] = static_cast(m); + // each observed reflection's mate in the ASU, and those not observed - where the grid composes them - as rows + // of their own + std::vector mate_of(n); + std::set unobserved; + for (size_t m = 0; m < n; m++) { + mate_of[m] = asu.to_asu(law.apply_to_hkl(refl.hkl[m]), gops).first; + if (row.find(mate_of[m]) == row.end()) + unobserved.insert(mate_of[m]); + } + const std::vector candidates(unobserved.begin(), unobserved.end()); + const SymmetryComposition composition(RigidBodyZoneGrid(cell, sg, d_min), d_min, candidates); + refl.twin_law = law; + refl.mate_hkl.clear(); + for (size_t i = 0; i < candidates.size(); i++) + if (composition.Row()[i] >= 0) { + row[candidates[i]] = static_cast(n + refl.mate_hkl.size()); + refl.mate_hkl.push_back(candidates[i]); + } + refl.mate.assign(refl.Rows(), -1); + for (size_t m = 0; m < n; m++) { + const auto it = row.find(mate_of[m]); + refl.mate[m] = it == row.end() ? static_cast(m) : it->second; + if (refl.mate[m] >= static_cast(n)) + refl.mate[refl.mate[m]] = static_cast(m); + } + int split = 0; + for (size_t m = 0; m < n; m++) { + const int j = refl.mate[m]; + if (j > static_cast(m) && j < static_cast(n) && refl.free[m] != refl.free[j]) + split++; + } + return split; +} + +std::vector> TwinnedModel(const RefinementReflections &refl, const XrayRowModel &rows, + const std::vector> &f) { + const size_t n = refl.Size(); + std::vector> out(n); + if (!refl.Twinned()) { + for (size_t m = 0; m < n; m++) + out[m] = rows.k_total[m] * (f[m] + rows.fmask[m]); + return out; + } + const double a = rows.twin_fraction; + for (size_t m = 0; m < n; m++) { + const int j = refl.mate[m]; + const std::complex u1 = std::complex(f[m]) + std::complex(rows.fmask[m]); + const std::complex u2 = std::complex(f[j]) + std::complex(rows.fmask[j]); + const double i1 = std::norm(u1); + const double amplitude = rows.k_total[m] * std::sqrt((1.0 - a) * i1 + a * std::norm(u2)); + out[m] = i1 > 0 ? std::complex(u1 * (amplitude / std::sqrt(i1))) : std::complex(amplitude, 0); + } + return out; +} + +double FitTwinFraction(const RefinementReflections &refl, const XrayRowModel &rows, + const std::vector> &f) { + if (!refl.Twinned()) + return 0; + // the working reflections whose mate is another reflection: Fo^2 and the model's intensity at h and at Th + struct Term { + double inv_d2, io, i1, i2; + }; + std::vector terms; + for (size_t m = 0; m < refl.Size(); m++) { + const int j = refl.mate[m]; + if (refl.free[m] || j == static_cast(m)) + continue; + const double k2 = double(rows.k_total[m]) * rows.k_total[m]; + terms.push_back({refl.inv_d2[m], double(refl.fo[m]) * refl.fo[m], + k2 * std::norm(std::complex(f[m]) + std::complex(rows.fmask[m])), + k2 * std::norm(std::complex(f[j]) + std::complex(rows.fmask[j]))}); + } + if (terms.size() < 3) + return 0; + // normalised per resolution shell of TWIN_FRACTION_SHELL reflections: Fo^2 by its mean, the model's by its own + std::stable_sort(terms.begin(), terms.end(), [](const Term &a, const Term &b) { return a.inv_d2 < b.inv_d2; }); + const size_t shells = std::max(1, terms.size() / TWIN_FRACTION_SHELL); + // the normal equations of y = b0 + b1 x1 + b2 x2 + double n[3][3] = {}, r[3] = {}; + for (size_t k = 0; k < shells; k++) { + const size_t lo = k * terms.size() / shells, hi = (k + 1) * terms.size() / shells; + double so = 0, sc = 0; + for (size_t i = lo; i < hi; i++) { + so += terms[i].io; + sc += terms[i].i1; + } + if (so <= 0 || sc <= 0) + continue; + for (size_t i = lo; i < hi; i++) { + const double x[3] = {1.0, terms[i].i1 / sc, terms[i].i2 / sc}, y = terms[i].io / so; + for (int p = 0; p < 3; p++) { + r[p] += x[p] * y; + for (int q = 0; q < 3; q++) + n[p][q] += x[p] * x[q]; + } + } + } + // Cramer's rule for b1 and b2 + auto det3 = [](const double m[3][3]) { + return m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) + + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]); + }; + const double d = det3(n); + if (!(std::fabs(d) > 0)) + return 0; + double b[3]; + for (int c = 1; c < 3; c++) { + double m[3][3]; + for (int p = 0; p < 3; p++) + for (int q = 0; q < 3; q++) + m[p][q] = q == c ? r[p] : n[p][q]; + b[c] = det3(m) / d; + } + if (!(b[1] + b[2] > 0)) + return 0; + return std::clamp(b[2] / (b[1] + b[2]), 0.0, 0.5); +} + BulkSolventMask::BulkSolventMask(const gemmi::UnitCell &cell, const gemmi::SpaceGroup &sg, double d_min, size_t nthreads) : grid_(MaskGrid(cell, sg, d_min)), nthreads_(nthreads), diff --git a/image_analysis/structure_refinement/RefinementXray.h b/image_analysis/structure_refinement/RefinementXray.h index d7062afbf..fff451c95 100644 --- a/image_analysis/structure_refinement/RefinementXray.h +++ b/image_analysis/structure_refinement/RefinementXray.h @@ -35,6 +35,19 @@ struct RefinementReflections { std::vector epsilon; std::vector inv_d2; size_t Size() const { return hkl.size(); } + + // With a twin law (SetTwinLaw) the structure factors are needed at every observed reflection's twin mate too: + // the mates not observed follow the observed rows as rows of their own, with no observation (mate_hkl), and + // `mate` holds per row, observed or not, the row of its mate - the row itself where the mate is the reflection + // or is not composed. A law whose square is in the group makes it an involution: mate[mate[m]] == m. + // Empty without a law. + gemmi::Op twin_law = gemmi::Op::identity(); + std::vector mate_hkl; + std::vector mate; + bool Twinned() const { return !mate.empty(); } + // The observed rows, then the mates': the rows the structure factors are computed at. + size_t Rows() const { return hkl.size() + mate_hkl.size(); } + std::vector RowHkl() const; }; // The French-Wilson amplitudes of `merged` (NaN dropped) into the ASU of `sg`, those the grid of @@ -43,14 +56,31 @@ RefinementReflections PrepareRefinementReflections(const std::vector RefinementTwinLaws(const gemmi::UnitCell &cell, const gemmi::SpaceGroup &sg); + +// `refl` with twin law `law` (RefinementReflections::mate). Returns how many twin pairs of observed reflections +// have one member in the working set and the other in the free set: with any, the free set is not independent +// of the working one under the law. +int SetTwinLaw(RefinementReflections &refl, const gemmi::UnitCell &cell, const gemmi::SpaceGroup &sg, double d_min, + const gemmi::Op &law); + // What turns the atoms' structure factors F into the model the target compares with the data, per reflection: // F_model = k_total (F + fmask), // with k_total the overall scale and anisotropic B and fmask the bulk solvent already scaled by k_sol // exp(-b_sol s^2/4); and the two parameters of the likelihood, D and the variance. Fixed for one macro-cycle. +// With a twin law, the model compared with an observation at h is the twinned one (TwinnedModel): +// |F_model(h)|^2 = k_total(h)^2 ((1-a) |F(h) + fmask(h)|^2 + a |F(Th) + fmask(Th)|^2), +// a the twin fraction; fmask is then per row of refl.Rows(), the other per observed row. struct XrayRowModel { std::vector k_total; std::vector> fmask; std::vector d, var; + float twin_fraction = 0; // D per likelihood bin, where EstimateLikelihoodParameters() found it - the next fit's start (empty: none) std::vector bin_d; }; @@ -91,6 +121,25 @@ private: void EstimateLikelihoodParameters(const RefinementReflections &refl, const std::vector> &fmodel, XrayRowModel &rows, size_t nthreads = 1); +// F_model per observed row from F at every row: k_total (F + fmask), or with a twin law the twinned model - its +// amplitude, with the phase of the row's own k_total (F + fmask). +// Following Yeates (1997) Methods Enzymol. 276, 344-358 (I_obs(h) = (1-a) I(h) + a I(Th)) +std::vector> TwinnedModel(const RefinementReflections &refl, const XrayRowModel &rows, + const std::vector> &f); + +// The twin fraction a in [0, 1/2] the working observations ask of the model: Fo^2 regressed, with an intercept, on +// the model's intensities at h and at Th, all normalised per resolution shell of TWIN_FRACTION_SHELL reflections, +// a = b(Th) / (b(h) + b(Th)). The expectation of Fo^2 given the model is linear in the two, D^2 |F_model|^2 + Sigma, +// so an unrelated reflection takes a coefficient of 0 however poor the model is - where a least-squares fit of the +// twinned amplitudes took a fraction of 0.16 for unrelated partners of one model at R-free 0.31, the average of two +// predictions being the better prediction. Reflections that are their own mate say nothing of a and are left out. `f` is F at every row, `rows` +// gives k_total and fmask. +// Following Yeates (1997) Methods Enzymol. 276, 344-358 (the twinned intensity), refined as Murshudov et al. (2011) +// Acta Cryst. D67, 355-367 refine the fractions, by least squares +constexpr size_t TWIN_FRACTION_SHELL = 500; +double FitTwinFraction(const RefinementReflections &refl, const XrayRowModel &rows, + const std::vector> &f); + // R-work and R-free of k_total (F + fmask) against the observations. struct RFactors { double r_work = 1, r_free = 1; @@ -111,12 +160,12 @@ public: // Every atom's B must stay above what the blur was chosen for (RefinementBlur) while it is in use. virtual void SetBlur(double blur) = 0; virtual void SetRowModel(const XrayRowModel &rows) = 0; - // F of the atoms at the reflections. + // F of the atoms at the rows (refl.Rows(): the observed reflections, then the twin mates not observed). virtual void Fcalc(const gemmi::Model &model, std::vector> &f) = 0; - // The bulk-solvent mask's structure factors at the reflections (unscaled). + // The bulk-solvent mask's structure factors at the rows (unscaled). virtual void Fmask(const gemmi::Model &model, std::vector> &f) = 0; - // The sum of -ln L over the working reflections and, with `grad`, its derivatives with respect to every - // atom's x, y, z (Cartesian, A) and B (A^2), in model order. + // The sum of -ln L over the working reflections - against the twinned model where refl has a twin law - and, + // with `grad`, its derivatives with respect to every atom's x, y, z (Cartesian, A) and B (A^2), in model order. virtual double Evaluate(const gemmi::Model &model, std::vector> *grad) = 0; virtual bool OnGPU() const = 0; diff --git a/rugnux/ResultReport.cpp b/rugnux/ResultReport.cpp index ec448e6b6..1e169741b 100644 --- a/rugnux/ResultReport.cpp +++ b/rugnux/ResultReport.cpp @@ -558,6 +558,24 @@ namespace { } Add(s, KeyReal("REFINE_BULK_SOLVENT_K_SOL", rf.k_sol, "{:.3f}", true)); Add(s, KeyReal("REFINE_BULK_SOLVENT_B_SOL", rf.b_sol, "{:.1f}", true)); + // The twin hypothesis (RefinementResult::twin_decision): TWINNED where the model and every REFINE_ key + // above are of the refinement against the twinned data. + Add(s, KeyEnum("REFINE_TWIN", rf.twin_decision.empty() ? "NOT_TESTED" : rf.twin_decision, + {"NOT_TESTED", "NO_TWIN_LAW", "FREE_SET_SPLIT", "ZERO_FRACTION", "UNTWINNED", "TWINNED"})); + if (!rf.twin_law.empty()) + Add(s, KeyText("REFINE_TWIN_LAW", rf.twin_law)); + if (rf.twin_split_pairs > 0) + Add(s, KeyInt("REFINE_TWIN_SPLIT_PAIRS", rf.twin_split_pairs)); + if (std::isfinite(rf.twin_r_free)) { + Add(s, KeyReal("REFINE_TWIN_FRACTION", rf.twin_fraction, "{:.3f}")); + Add(s, KeyReal("REFINE_TWIN_R_WORK", rf.twin_r_work, "{:.4f}")); + Add(s, KeyReal("REFINE_TWIN_R_FREE", rf.twin_r_free, "{:.4f}")); + Add(s, KeyReal("REFINE_TWIN_R_FREE_NULL", rf.twin_r_free_null, "{:.4f}")); + Add(s, KeyReal("REFINE_TWIN_FRACTION_NULL", rf.twin_fraction_null, "{:.3f}", true)); + Add(s, KeyReal("REFINE_TWIN_NULL_Z", rf.twin_null_z, "{:.1f}")); + Add(s, KeyReal("REFINE_UNTWINNED_R_WORK", rf.untwinned_r_work, "{:.4f}")); + Add(s, KeyReal("REFINE_UNTWINNED_R_FREE", rf.untwinned_r_free, "{:.4f}")); + } int kinds[5] = {0, 0, 0, 0, 0}; for (const DensityBlob &b : rf.blobs) kinds[static_cast(b.kind)]++; diff --git a/tests/RefinementTest.cpp b/tests/RefinementTest.cpp index d9fd7a09f..1e4a2c2dd 100644 --- a/tests/RefinementTest.cpp +++ b/tests/RefinementTest.cpp @@ -15,6 +15,8 @@ #include "../common/CUDAWrapper.h" #include "../common/Logger.h" +#include "../common/UnitCell.h" +#include "../image_analysis/scale_merge/RfreeFlags.h" #include "../image_analysis/structure_refinement/MonomerLibrary.h" #include "../image_analysis/structure_refinement/Refinement.h" #include "../image_analysis/structure_refinement/RefinementMath.h" @@ -836,3 +838,164 @@ TEST_CASE("Refinement_restrained_recovers_model", "[Refinement]") { CHECK_FALSE(r.cancelled); } } + +namespace { + +// A twinned test case in P 4, whose lattice adds the twin law: the reflections of the group's ASU to 2.2 A with +// every fourth of the zone l = 1 left out, so that some twin mates are rows of their own, and the free set drawn +// on the lattice's holohedry (AssignRfreeFlags) so that no twin pair is split. +struct TwinCase { + gemmi::UnitCell cell{30, 30, 40, 90, 90, 90}; + const gemmi::SpaceGroup &sg = *gemmi::find_spacegroup_by_name("P 4"); + gemmi::Op law; + std::vector merged; + RefinementReflections refl; + + TwinCase() { + const std::vector laws = RefinementTwinLaws(cell, sg); + REQUIRE(laws.size() == 1); + law = laws[0]; + merged = asu_reflections(cell, sg, 2.2); + int i = 0; + std::erase_if(merged, [&](const MergedReflection &r) { return r.l == 1 && i++ % 4 == 0; }); + AssignRfreeFlags(merged, sg, 0.05, 0, + UnitCell{static_cast(cell.a), static_cast(cell.b), static_cast(cell.c), + 90, 90, 90}); + refl = PrepareRefinementReflections(merged, cell, sg, 2.2); + CHECK(SetTwinLaw(refl, cell, sg, 2.2, law) == 0); + } +}; + +} // namespace + +TEST_CASE("RefinementTwin_laws_and_mates", "[Refinement]") { + TwinCase t; + CHECK(RefinementTwinLaws(t.cell, *gemmi::find_spacegroup_by_name("P 4 2 2")).empty()); + REQUIRE(t.refl.Twinned()); + CHECK(!t.refl.mate_hkl.empty()); + const gemmi::GroupOps gops = t.sg.operations(); + const gemmi::ReciprocalAsu asu(&t.sg); + const std::vector rows = t.refl.RowHkl(); + for (size_t m = 0; m < t.refl.Rows(); m++) { + const int j = t.refl.mate[m]; + CAPTURE(m, j); + REQUIRE(j >= 0); + CHECK(t.refl.mate[j] == static_cast(m)); // an involution + if (m < t.refl.Size()) + CHECK(rows[j] == asu.to_asu(t.law.apply_to_hkl(rows[m]), gops).first); + } + // a free set drawn on the merging group alone splits twin pairs + RefinementReflections split = t.refl; + for (size_t m = 0; m < split.Size(); m++) + split.free[m] = m % 20 == 0; + CHECK(SetTwinLaw(split, t.cell, t.sg, 2.2, t.law) > 0); +} + +TEST_CASE("RefinementTwin_gradient", "[Refinement]") { + TwinCase t; + gemmi::Structure truth = random_crystal(t.cell, "P 4", 240, 17); + const gemmi::Model model = shaken(truth.models[0], 0.3, 4.0, 18); + auto cpu = MakeRefinementEngineCPU(t.cell, t.sg, 2.2, t.refl, 4); + cpu->SetBlur(RefinementBlur(t.cell, t.sg, 2.2, 5.0)); + XrayRowModel rows; + rows.k_total.assign(t.refl.Size(), 1.0f); + rows.fmask.assign(t.refl.Rows(), {0, 0}); + rows.twin_fraction = 0.3f; + std::vector> f; + cpu->Fcalc(truth.models[0], f); + REQUIRE(f.size() == t.refl.Rows()); + const std::vector> twinned = TwinnedModel(t.refl, rows, f); + for (size_t m = 0; m < t.refl.Size(); m++) + t.refl.fo[m] = std::abs(twinned[m]); + // the fraction comes back from the data + CHECK(FitTwinFraction(t.refl, rows, f) == Catch::Approx(0.3).margin(0.01)); + cpu->Fcalc(model, f); + EstimateLikelihoodParameters(t.refl, TwinnedModel(t.refl, rows, f), rows); + cpu->SetRowModel(rows); + // the CPU engine kept a reference to t.refl and reads the observations set above + check_xray_gradient(*cpu, model, 0.03); +#ifdef JFJOCH_USE_CUDA + if (get_gpu_count() > 0) { + auto gpu = MakeRefinementEngineGPU(0, t.cell, t.sg, 2.2, t.refl, model, 300.0, SIZE_MAX); + REQUIRE(gpu); + gpu->SetBlur(RefinementBlur(t.cell, t.sg, 2.2, 5.0)); + gpu->SetRowModel(rows); + std::vector> gc, gg; + const double tc = cpu->Evaluate(model, &gc); + const double tg = gpu->Evaluate(model, &gg); + CHECK(tg == Catch::Approx(tc).epsilon(1e-4)); + double max_g = 0; + for (const auto &g : gc) + for (int c = 0; c < 4; c++) + max_g = std::max(max_g, std::fabs(g[c])); + for (size_t i = 0; i < gc.size(); i++) + for (int c = 0; c < 4; c++) { + CAPTURE(i, c); + CHECK(std::fabs(gg[i][c] - gc[i][c]) < 0.01 * max_g); + } + } +#endif +} + +TEST_CASE("Refinement_twin_decided", "[Refinement]") { + TwinCase t; + gemmi::Structure truth = residue_crystal({"PHE", "TRP", "DA", "DG", "TYR", "HOH", "HOH", "HOH"}, t.cell, "P 4", 21); + gemmi::Structure start = truth; + start.models[0] = shaken(truth.models[0], 0.2, 4.0, 22); + std::vector> f; + { + RefinementReflections refl = t.refl; + auto cpu = MakeRefinementEngineCPU(t.cell, t.sg, 2.2, refl, 4); + cpu->SetBlur(RefinementBlur(t.cell, t.sg, 2.2, 5.0)); + cpu->Fcalc(truth.models[0], f); + } + Logger logger("RefinementTest"); + RefinementSettings settings; + settings.gpu = false; + settings.nthreads = 4; + settings.weight_ladder = {0.0625}; + settings.adp_ladder = {0.0}; + settings.max_steps = 1; + settings.final_ladder = {1.0}; + settings.riding_hydrogens = false; + settings.solvent = false; + for (double fraction : {0.0, 0.3}) { + CAPTURE(fraction); + // the observations as twinned at `fraction`, with 3% noise + XrayRowModel rows; + rows.k_total.assign(t.refl.Size(), 1.0f); + rows.fmask.assign(t.refl.Rows(), {0, 0}); + rows.twin_fraction = static_cast(fraction); + const std::vector> twinned = TwinnedModel(t.refl, rows, f); + std::map amplitude; + for (size_t m = 0; m < t.refl.Size(); m++) + amplitude[t.refl.hkl[m]] = std::abs(twinned[m]); + std::vector merged = t.merged; + std::mt19937 rng(5); + std::normal_distribution noise(0.0, 0.03); + for (MergedReflection &r : merged) { + const auto it = amplitude.find(gemmi::Miller{{r.h, r.k, r.l}}); + r.F = it == amplitude.end() ? NAN : static_cast(it->second * (1 + noise(rng))); + r.sigmaF = 0.03f * r.F + 0.01f; + } + const RefinementResult r = RefineModel(start, merged, t.cell, t.sg, 1.0, logger, settings); + REQUIRE(r.ok); + CHECK(r.twin_law == t.law.as_hkl().triplet('h')); + if (fraction > 0) { + CHECK(r.twin_decision == "TWINNED"); + CHECK(r.twinned); + CHECK(r.twin_fraction == Catch::Approx(fraction).margin(0.03)); + CHECK(r.r_free < r.untwinned_r_free - 0.02); + CHECK(r.twin_r_free < r.twin_r_free_null - 0.02); + } else { + CHECK(r.twin_decision != "TWINNED"); + CHECK_FALSE(r.twinned); + // the untwinned refinement, as it is without the twin hypothesis + RefinementSettings plain = settings; + plain.twin = false; + const RefinementResult u = RefineModel(start, merged, t.cell, t.sg, 1.0, logger, plain); + CHECK(u.r_free == r.r_free); + CHECK(u.r_work == r.r_work); + } + } +}