Merge twin-refine into refine-merge: the twin decision between two whole refinements

On twin-refine the untwinned refinement ran without the water build, DecideTwin refined the placed model
again against the twinned data, and the build's rounds (each a RefineOnce) continued in the kept arm. With
the solvent build inside RefineOnce (solvent-p1) each arm is now a whole refinement: untwinned and twinned
each run the weight search, their own solvent build (placeholders, relabelling, the solvent-only judge
against their own target - the twinned arm's maps detwinned) and their own displacement-model and NCS
trials, and DecideTwin compares where the two ended (R-free, the fraction, the null at the twinned arm's
final model). The decision is taken late, on the finished models, and costs one more full refinement only
where the lattice admits a usable law; the alternative - deciding on solvent-less arms and refining the
kept one again with the build - would cost a third refinement. DecideTwin no longer returns the law (no
later round needs it). REFINE_TWIN_R_* / REFINE_UNTWINNED_R_* are the two arms as they ended.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HVeDQqN9qRD57vnShzTC37
This commit is contained in:
leonarski_fandClaude Opus 5.5 committed 2026-10-27 19:07:56 +01:00
commit ae5b52bfeb
12 files changed
+845 -56

No files matched your search

+11
View File
@@ -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
+69 -4
View File
@@ -313,7 +313,8 @@ are:
$-\ln L$ of the free reflections are lower: the free set tests the parameters a model adds, so the choice is made
on the evidence of each run, not at a resolution (Merritt 2012). The refined U are written as ANISOU and the TLS
groups as `_pdbx_refine_tls*` and `REMARK 3` (`REFINE_ADP_MODEL`, `REFINE_ANISO_ATOMS`, `REFINE_TLS_GROUPS`).
The rounds of the water build (§15.10) keep the model chosen: they hold each atom's U shape and refine its B.
It is decided after the solvent build (§15.10), on the model with its solvent: a water a round put in refines a U
of its own in the per-atom trial as every refinable atom does, and no TLS group holds a water.
Where the model has copies (§15.5), the NCS restraints are one more weight: every rung of the first ladder is run
without them and then with them at $\sigma = 0.1$ Å, and every step of the trajectory also tries them changed -
@@ -492,7 +493,67 @@ 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 <file>` 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. Each of the
two refinements is a whole one - its solvent built (§15.10) and its displacement model chosen (§15.7) against its
own target - and the decision is taken where they ended.
**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 `<prefix>_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 of the two refinements where they ended. 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:
@@ -504,7 +565,8 @@ What the refinement does not do yet - each a known gap, not a design choice:
- **Global NCS and NCS of B factors**: copies are restrained locally, on their interatomic distances (§15.5),
never by a superposition, and their B factors are refined independently; ligands and waters are not restrained
between copies.
- **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 beyond the six species**: waters and ions are relabelled among water, Mg²⁺, Na⁺, K⁺, Ca²⁺
and Cl⁻ (§15.10); NH₄⁺ is only reported, transition metals (Zn, Mn, ...) are measured but never relabelled, and no
ion is placed at a peak that is not a water first. A site's hypotheses are compared by a local fit of its
@@ -521,8 +583,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).
+6
View File
@@ -1211,6 +1211,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, each where it ended (its solvent built) |
| `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)) |
@@ -386,7 +386,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<RefinementStage> s3("refit.scale");
@@ -402,28 +402,52 @@ struct Context {
}
gemmi::Scaling<float> 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<std::complex<float>> fmodel(refl.Size());
for (size_t m = 0; m < refl.Size(); m++) {
rows.k_total[m] = static_cast<float>(scaling.get_overall_scale_factor(refl.hkl[m]));
rows.fmask[m] = static_cast<float>(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<float>(scaling.get_overall_scale_factor(refl.hkl[m]));
rows.fmask[m] = static_cast<float>(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<float>(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<float>(FitTwinFraction(refl, rows, fcalc));
const std::vector<std::complex<float>> 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<float>(tw > 0 ? refl.fo[m] * own / tw : refl.fo[m]), 1.0f}});
}
fit_scale();
rows.twin_fraction = static_cast<float>(FitTwinFraction(refl, rows, fcalc));
}
s3.reset();
const std::vector<std::complex<float>> fmodel = TwinnedModel(refl, rows, fcalc);
{
const RefinementStage s4("refit.ml");
EstimateLikelihoodParameters(refl, fmodel, rows, ml_threads);
@@ -459,6 +483,8 @@ struct Context {
rows.k_total[m] *= static_cast<float>(std::exp(b_iso * refl.inv_d2[m] / 4.0));
rows.fmask[m] *= static_cast<float>(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<float>(std::exp(-b_iso * cell.calculate_1_d2(refl.mate_hkl[m - refl.Size()]) / 4.0));
engine->SetRowModel(rows);
}
@@ -497,6 +523,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;
@@ -601,10 +628,7 @@ struct Context {
// F_model with the cycle's scale and solvent, for the atoms as they are now.
std::vector<std::complex<float>> FModel() {
engine->Fcalc(Model(), fcalc);
std::vector<std::complex<float>> 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);
}
};
@@ -1112,7 +1136,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<MergedReflection> &merged, double wavelength_A, RefinementResult &result) {
const RefinementStage stage("maps");
@@ -1149,7 +1174,13 @@ void MakeMaps(Context &ctx, const std::vector<MergedReflection> &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;
@@ -1213,6 +1244,50 @@ void MakeMaps(Context &ctx, const std::vector<MergedReflection> &merged, double
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<int> 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<std::complex<float>> 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<std::complex<float>> 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) {
@@ -1908,10 +1983,26 @@ RFactors ReadInputDisplacements(Context &ctx, const std::vector<TlsBody> &tls, L
}
// 1/d^2 of the finest amplitude of `merged`, 0 without any.
double MaxInvD2(const std::vector<MergedReflection> &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, with the solvent build in it where settings.solvent asks for it.
// `twin_law`: against the data as twinned by it, null for untwinned.
RefinementResult RefineOnce(const gemmi::Structure &placed, const std::vector<MergedReflection> &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;
@@ -1938,22 +2029,23 @@ RefinementResult RefineOnce(const gemmi::Structure &placed, const std::vector<Me
result.failure_reason = "the model has no atoms";
return result;
}
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));
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<BulkSolventMask>(cell, sg, ctx.d_min, settings.nthreads);
@@ -2010,8 +2102,12 @@ RefinementResult RefineOnce(const gemmi::Structure &placed, const std::vector<Me
result.r_work_start = r.r_work;
result.r_free_start = r.r_free;
result.score_start = ctx.Score();
logger.Info("Refinement: {} atoms ({} riding hydrogens), {} reflections to {:.2f} A ({} free), on the {}; as given "
"R-work {:.4f}, R-free {:.4f}; k_sol {:.3f}, b_sol {:.1f}, overall B {:.1f}, mask grid {:.2f} A",
logger.Info("Refinement{}: {} atoms ({} riding hydrogens), {} reflections to {:.2f} A ({} free), on the {}; as "
"given R-work {:.4f}, R-free {:.4f}; k_sol {:.3f}, b_sol {:.1f}, overall B {:.1f}, mask grid {:.2f} A",
ctx.refl.Twinned() ? fmt::format(" against the data twinned by {} (fraction {:.3f}, {} mates not "
"observed)", result.twin_law, ctx.rows.twin_fraction,
ctx.refl.mate_hkl.size())
: std::string(),
ctx.atoms.size(), result.score_start.hydrogens, ctx.refl.Size(), result.d_min, r.n_free,
result.on_gpu ? "GPU" : "CPU", r.r_work, r.r_free, ctx.k_sol, ctx.b_sol, result.score_start.b_iso,
result.score_start.mask_spacing);
@@ -2022,6 +2118,10 @@ RefinementResult RefineOnce(const gemmi::Structure &placed, const std::vector<Me
// The maps, the blobs and the model of where the refinement ended.
auto finish = [&]() {
MakeMaps(ctx, merged, wavelength_A, result);
if (ctx.refl.Twinned()) {
result.twin_fraction = ctx.rows.twin_fraction;
TwinNull(ctx, result);
}
// the anisotropic atoms' U into the model written out (ANISOU), and the TLS groups refined (the model's own
// stay where the U of their atoms was held, and go where every atom refined a U of its own)
ApplyAniso(ctx.Model(), ctx.aniso);
@@ -2667,12 +2767,108 @@ RefinementResult RefineOnce(const gemmi::Structure &placed, const std::vector<Me
return result;
}
// The R-free a refinement ended at: the restrained stage's, or the placement's where that did not run.
double FinalRFree(const RefinementResult &r) {
return r.restrained ? r.r_free : r.r_free_placement;
}
double FinalRWork(const RefinementResult &r) {
return r.restrained ? r.r_work : r.r_work_placement;
}
// The twin hypothesis beside the untwinned refinement `result`: the placed model refined again, solvent build and
// displacement model included, against the data as twinned by a law of the lattice, and the twinned refinement taken
// (into `result`) where its R-free is below the untwinned one's and the law beats its own null (TwinNull) on the free
// reflections by TWIN_NULL_Z standard errors - so that neither the drop in R any twin target buys by averaging, nor a
// pseudo-symmetry the model already carries (it predicts I(Th) ~ I(h), and the law then changes nothing) is read as
// a twin. A law is tested only where the free set keeps its twin pairs together; of several, the one the placed
// model asks the largest fraction of.
void DecideTwin(const gemmi::Structure &placed, const std::vector<MergedReflection> &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<gemmi::Op> laws = RefinementTwinLaws(cell, sg);
result.twin_laws = static_cast<int>(laws.size());
if (laws.empty()) {
result.twin_decision = "NO_TWIN_LAW";
return;
}
// the laws whose twin pairs the free set keeps together
RefinementReflections refl = PrepareRefinementReflections(merged, cell, sg, RefinementDMin(MaxInvD2(merged)));
std::vector<gemmi::Op> 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;
}
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;
}
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;
// 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);
}
} // namespace
RefinementResult RefineModel(const gemmi::Structure &placed, const std::vector<MergedReflection> &merged,
const gemmi::UnitCell &cell, const gemmi::SpaceGroup &sg, double wavelength_A,
Logger &logger, const RefinementSettings &settings) {
RefinementResult result = RefineOnce(placed, merged, cell, sg, wavelength_A, logger, settings);
// Each arm, untwinned and twinned, is a whole refinement - the solvent built and the displacement model chosen
// against its own target - and the decision is taken on where they ended.
if (settings.twin && !settings.score_only && result.ok && !result.cancelled)
DecideTwin(placed, merged, cell, sg, wavelength_A, logger, settings, result);
result.map.reset();
return result;
}
@@ -72,6 +72,9 @@ struct RefinementSettings {
// groups (the model's own, one per chain, the chains cut into TLSMD segments) with a residual B per atom, and an
// anisotropic U per atom with rigid-bond and similarity restraints (false: the isotropic B, or the model's U held).
bool adp_hypotheses = 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
@@ -106,6 +109,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<RefinementShell> shells;
// Per reflection, with settings.score_only only: the atoms' Fcalc, the solvent's k_sol exp(-b_sol s^2/4) Fmask
@@ -197,6 +201,24 @@ struct RefinementResult {
std::vector<SolventSite> solvent;
double b_ceiling = 0; // the highest B the refinement allowed
SolventBuildResult solvent_build; // the solvent build's rounds (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),
@@ -145,6 +145,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
@@ -155,9 +164,10 @@ public:
};
std::vector<std::pair<int, int>> entries;
const int n_ops = static_cast<int>(gops.sym_ops.size());
for (size_t m = 0; m < refl.Size(); m++)
const std::vector<gemmi::Miller> 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<int>(m) * n_ops + o) * 2;
if (k[0] > 0 && 2 * k[0] != nu)
entries.emplace_back(point(k[0], k[1], k[2]), term);
@@ -210,7 +220,12 @@ public:
std::vector<std::array<float, 2>> 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<float> 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; }
@@ -115,6 +115,48 @@ __global__ void compose_target_kernel(const float2 *f1, float norm, int nu, int
coef[m] = make_float2(static_cast<float>(cr), static_cast<float>(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<double>(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<float>(g * (1.0 - a) * u1r), static_cast<float>(-g * (1.0 - a) * u1i));
other[m] = make_float2(static_cast<float>(g * a * u2r), static_cast<float>(-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<float>(scale * (static_cast<double>(a.x) + b.x)),
static_cast<float>(scale * (static_cast<double>(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.
@@ -536,6 +578,10 @@ struct RefinementGPUEngineImpl {
CudaDevicePtr<double> row_scale;
CudaDevicePtr<float> k_total, ml_d, ml_var, fo;
CudaDevicePtr<float2> 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<int> mate;
CudaDevicePtr<float> twin_fraction;
CudaDevicePtr<float2> coef_own, coef_other;
CudaDevicePtr<char> work, centric;
CudaDevicePtr<double> nll, nll_sum;
CudaDevicePtr<char> reduce_temp;
@@ -583,6 +629,12 @@ struct RefinementGPUEngineImpl {
centric = CudaDevicePtr<char>(nr, sync);
nll = CudaDevicePtr<double>(nr, sync);
nll_sum = CudaDevicePtr<double>(1, sync);
if (!setup.mate.empty()) {
mate = CudaDevicePtr<int>(nr, sync);
twin_fraction = CudaDevicePtr<float>(1, sync);
coef_own = CudaDevicePtr<float2>(nr, sync);
coef_other = CudaDevicePtr<float2>(nr, sync);
}
reduce_bytes = ReduceBytes(nr);
reduce_temp = CudaDevicePtr<char>(std::max<size_t>(reduce_bytes, 1), sync);
scatter_point = CudaDevicePtr<int>(std::max<size_t>(setup.scatter_point.size(), 1), sync);
@@ -631,6 +683,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);
@@ -687,7 +741,17 @@ struct RefinementGPUEngineImpl {
void QueueEvaluate(bool grad) {
const int rows = static_cast<int>(setup.rows.size());
Transform();
Compose(true);
if (setup.mate.empty())
Compose(true);
else if (rows > 0) {
Compose(false);
twin_target_kernel<<<blocks(rows), THREADS, 0, stream>>>(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<<<blocks(rows), THREADS, 0, stream>>>(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));
@@ -785,6 +849,8 @@ size_t RefinementGPUEngine::DeviceBytes(const RefinementGPUSetup &s, size_t fft_
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);
@@ -822,10 +888,13 @@ void RefinementGPUEngine::SetBlur(double blur) {
}
void RefinementGPUEngine::SetRowModel(const std::vector<float> &k_total, const std::vector<std::array<float, 2>> &fmask,
const std::vector<float> &d, const std::vector<float> &var) {
const std::vector<float> &d, const std::vector<float> &var, float twin_fraction) {
RefinementGPUEngineImpl &e = *impl_;
DeviceGuard guard(e.device);
Upload(e.k_total, k_total, e.stream);
const std::vector<float> 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));
@@ -32,6 +32,9 @@ struct RefinementGPUSetup {
std::vector<double> inv_d2;
std::vector<float> fo;
std::vector<char> work, centric;
// With a twin law: per row the row of its twin mate (RefinementReflections::mate), an involution; empty
// without one.
std::vector<int> 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<int> 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<float> &k_total, const std::vector<std::array<float, 2>> &fmask,
const std::vector<float> &d, const std::vector<float> &var);
const std::vector<float> &d, const std::vector<float> &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
@@ -7,12 +7,14 @@
#include <cmath>
#include <map>
#include <mutex>
#include <set>
#include <fftw3.h>
#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<float> 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));
}
@@ -137,17 +139,35 @@ public:
// The target and, per reflection, dT/dF of the atoms' structure factor (dT/dRe F + i dT/dIm F).
std::vector<std::complex<double>> 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<double> fm = k * (f[m] + std::complex<double>(rows_.fmask[m]));
const double fc = std::abs(fm);
if (!refl_.Twinned()) {
const std::complex<double> fm = k * (f[m] + std::complex<double>(rows_.fmask[m]));
const double fc = std::abs(fm);
double dfc = 0;
sum += refine_math::AmplitudeNegLogLikelihood<double>(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<double> u1 = f[m] + std::complex<double>(rows_.fmask[m]);
const std::complex<double> u2 = f[j] + std::complex<double>(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<double>(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;
@@ -267,6 +287,157 @@ RefinementReflections PrepareRefinementReflections(const std::vector<MergedRefle
return out;
}
std::vector<gemmi::Miller> RefinementReflections::RowHkl() const {
std::vector<gemmi::Miller> out = hkl;
out.insert(out.end(), mate_hkl.begin(), mate_hkl.end());
return out;
}
std::vector<gemmi::Op> RefinementTwinLaws(const gemmi::UnitCell &cell, const gemmi::SpaceGroup &sg) {
const gemmi::GroupOps gops = sg.operations();
std::vector<gemmi::Op> laws;
std::vector<gemmi::Op> 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<gemmi::Miller, int> row;
for (size_t m = 0; m < n; m++)
row[refl.hkl[m]] = static_cast<int>(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<gemmi::Miller> mate_of(n);
std::set<gemmi::Miller> 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<gemmi::Miller> 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<int>(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<int>(m) : it->second;
if (refl.mate[m] >= static_cast<int>(n))
refl.mate[refl.mate[m]] = static_cast<int>(m);
}
int split = 0;
for (size_t m = 0; m < n; m++) {
const int j = refl.mate[m];
if (j > static_cast<int>(m) && j < static_cast<int>(n) && refl.free[m] != refl.free[j])
split++;
}
return split;
}
std::vector<std::complex<float>> TwinnedModel(const RefinementReflections &refl, const XrayRowModel &rows,
const std::vector<std::complex<float>> &f) {
const size_t n = refl.Size();
std::vector<std::complex<float>> 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<double> u1 = std::complex<double>(f[m]) + std::complex<double>(rows.fmask[m]);
const std::complex<double> u2 = std::complex<double>(f[j]) + std::complex<double>(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<float>(u1 * (amplitude / std::sqrt(i1))) : std::complex<float>(amplitude, 0);
}
return out;
}
double FitTwinFraction(const RefinementReflections &refl, const XrayRowModel &rows,
const std::vector<std::complex<float>> &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<Term> terms;
for (size_t m = 0; m < refl.Size(); m++) {
const int j = refl.mate[m];
if (refl.free[m] || j == static_cast<int>(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<double>(f[m]) + std::complex<double>(rows.fmask[m])),
k2 * std::norm(std::complex<double>(f[j]) + std::complex<double>(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<size_t>(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),
@@ -35,6 +35,19 @@ struct RefinementReflections {
std::vector<float> epsilon;
std::vector<double> 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<gemmi::Miller> mate_hkl;
std::vector<int> 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<gemmi::Miller> 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<MergedRefle
const gemmi::UnitCell &cell, const gemmi::SpaceGroup &sg,
double d_min);
// The twin laws a refinement in `sg` considers: the rotations of the lattice's metric symmetry that `sg` lacks
// (Le Page two-folds within 3 degrees of obliquity, as AssignRfreeFlags groups the free set), one per coset of
// the group, each with its square in the group - a law that exchanges two domains. Miller-index operators in the
// data's basis.
// Following Lebedev, Vagin & Murshudov (2006) Acta Cryst. D62, 83-95
std::vector<gemmi::Op> 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<float> k_total;
std::vector<std::complex<float>> fmask;
std::vector<float> d, var;
float twin_fraction = 0;
// D per likelihood bin, where EstimateLikelihoodParameters() found it - the next fit's start (empty: none)
std::vector<double> bin_d;
};
@@ -91,6 +121,25 @@ private:
void EstimateLikelihoodParameters(const RefinementReflections &refl, const std::vector<std::complex<float>> &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<std::complex<float>> TwinnedModel(const RefinementReflections &refl, const XrayRowModel &rows,
const std::vector<std::complex<float>> &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<std::complex<float>> &f);
// R-work and R-free of k_total (F + fmask) against the observations.
struct RFactors {
double r_work = 1, r_free = 1;
@@ -125,12 +174,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<std::complex<float>> &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<std::complex<float>> &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.
// For an anisotropic atom (SetAniso) the B derivative is the one along dev + B / (8 pi^2) I, its shape held.
virtual double Evaluate(const gemmi::Model &model, std::vector<std::array<double, 4>> *grad) = 0;
virtual bool OnGPU() const = 0;
+18
View File
@@ -580,6 +580,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<int>(b.kind)]++;
+163
View File
@@ -18,6 +18,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/ModelGrid.h"
#include "../image_analysis/structure_refinement/MonomerLibrary.h"
#include "../image_analysis/structure_refinement/Refinement.h"
@@ -1335,3 +1337,164 @@ TEST_CASE("RefinementADP_tls_segments", "[Refinement]") {
// too short for three segments of 25
CHECK(TlsSegments(residues, pos, b, 3, 25).size() == 2);
}
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<MergedReflection> merged;
RefinementReflections refl;
TwinCase() {
const std::vector<gemmi::Op> 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<float>(cell.a), static_cast<float>(cell.b), static_cast<float>(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<gemmi::Miller> 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<int>(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<std::complex<float>> f;
cpu->Fcalc(truth.models[0], f);
REQUIRE(f.size() == t.refl.Rows());
const std::vector<std::complex<float>> 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<std::array<double, 4>> 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<std::complex<float>> 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<float>(fraction);
const std::vector<std::complex<float>> twinned = TwinnedModel(t.refl, rows, f);
std::map<gemmi::Miller, double> amplitude;
for (size_t m = 0; m < t.refl.Size(); m++)
amplitude[t.refl.hkl[m]] = std::abs(twinned[m]);
std::vector<MergedReflection> merged = t.merged;
std::mt19937 rng(5);
std::normal_distribution<double> 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<float>(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);
}
}
}