The field's search is iterated conditional modes over the residues, one after another, and each step evaluates -ln L over every working reflection for each combination of states. On a large model it ran on the main engine's card alone while the others idled: a 242k-atom model with 45 NCS copies and 663k reflections spent 1743 s of a 2392 s refinement in it on one of four T4s. -ln L is a sum over the reflections, so MakeSideChainFieldEvaluatorGPUs gives each card a contiguous part of them and adds the parts' sums in card order. The search, its order and its decisions are unchanged; only the last bits of each sum move, where the parts meet. One card keeps the evaluator as it was. On that model, 4 x T4: the field 1743 -> 456 s, the refinement 2392 -> 1119 s, the refined model bit-identical (same R-free, same md5). Two small models refine bit-identically, in the same time. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UqXYdJz9sA2BQBEgKkuVuL
158 lines
9.7 KiB
C++
158 lines
9.7 KiB
C++
// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
|
|
// SPDX-License-Identifier: GPL-3.0-only
|
|
|
|
#pragma once
|
|
|
|
// The side chains of a model as a discrete field, each residue in one of its rotamers (SideChainRotamers.h: the
|
|
// staggered chi angles, the planar ends every 30 degrees), as it was given, or absent (pruned to CB), searched
|
|
// against the refinement's own target in reciprocal space. The structure factors are linear in the atoms: with
|
|
// F_model = F_rest + dF_r(state_r), dF_r the direct-summation structure factors of residue r's side chain in that
|
|
// state, a residue's change of state moves F by dF_new - dF_old, and -ln L over the working reflections - the
|
|
// scale, the solvent and the likelihood's parameters held where the refinement fitted them - is re-evaluated
|
|
// at every reflection in one pass, a few microseconds on the GPU. The energy of the field is that -ln L plus the
|
|
// repulsion term of the refinement's geometry (the overlaps with the rest of the model, symmetry mates and the other
|
|
// copies included) at the refinement's own X-ray weight. The field is minimised by iterated conditional modes: the
|
|
// residues in turn, each put in the state of least energy given the others, small residues first and arginine last
|
|
// (the order PDB-REDO rebuilds in: Joosten et al. (2011) Bioinformatics 27, 3392-3398), until a sweep changes
|
|
// nothing. The free reflections are never seen: the caller refines from the field and judges on them.
|
|
// Side chains as a discrete field and ICM: following Desmet et al. (1992) Nature 356, 539-542 and
|
|
// Besag (1986) J. R. Statist. Soc. B48, 259-279.
|
|
|
|
#include <array>
|
|
#include <complex>
|
|
#include <memory>
|
|
#include <string>
|
|
#include <vector>
|
|
|
|
#include <gemmi/model.hpp>
|
|
#include <gemmi/symmetry.hpp>
|
|
#include <gemmi/unitcell.hpp>
|
|
|
|
#include "SideChainRotamers.h"
|
|
|
|
// What the evaluator needs of the data: the observed rows at the scale, the solvent and the likelihood's parameters
|
|
// of the last fit. F_model(row) = k_total (F_atoms + fmask).
|
|
struct FieldReflections {
|
|
std::vector<std::array<float, 3>> hkl;
|
|
std::vector<float> stol2; // (sin theta / lambda)^2
|
|
std::vector<float> fo, d, var;
|
|
std::vector<char> centric, work; // work: not a free reflection
|
|
std::vector<float> k_total;
|
|
std::vector<std::complex<float>> fmask; // scaled
|
|
size_t Size() const { return hkl.size(); }
|
|
};
|
|
|
|
// An atom of a state: fractional position, isotropic B, occupancy, and its element's entry in the form-factor table.
|
|
struct FieldAtom {
|
|
float x, y, z, b, occ;
|
|
int element;
|
|
};
|
|
|
|
// A set of side-chain states, each a list of atoms (CSR: state s is atoms[start[s]..start[s+1])), and the
|
|
// combinations evaluated: each the states (one per copy of a residue) put in place of the current ones, F =
|
|
// F_total - sum dF(current) + sum dF(combination).
|
|
struct FieldStates {
|
|
std::vector<FieldAtom> atoms;
|
|
std::vector<int> start = {0};
|
|
std::vector<int> current;
|
|
std::vector<int> combo_states;
|
|
std::vector<int> combo_start = {0};
|
|
void Add(const std::vector<FieldAtom> &a) {
|
|
atoms.insert(atoms.end(), a.begin(), a.end());
|
|
start.push_back(static_cast<int>(atoms.size()));
|
|
}
|
|
void AddCombo(const std::vector<int> &states) {
|
|
combo_states.insert(combo_states.end(), states.begin(), states.end());
|
|
combo_start.push_back(static_cast<int>(combo_states.size()));
|
|
}
|
|
size_t Count() const { return start.size() - 1; }
|
|
size_t Combos() const { return combo_start.size() - 1; }
|
|
};
|
|
|
|
// The IT92 form factor of an element: c + sum a_i exp(-b_i stol2), as a0..a3 b0..b3 c.
|
|
using FormFactor = std::array<float, 9>;
|
|
|
|
// -ln L over the working reflections of F_total with one residue's side chain (or the copies of one) taken from
|
|
// its current states to each combination of states, by direct summation of the states' atoms over the group's
|
|
// operators.
|
|
class SideChainFieldEvaluator {
|
|
public:
|
|
virtual ~SideChainFieldEvaluator() = default;
|
|
// F of the model's atoms at the rows, as the refinement's engine computes them: what the field starts from.
|
|
virtual void SetTotal(const std::vector<std::complex<float>> &f) = 0;
|
|
// -ln L (work) per combination of `states`.
|
|
virtual std::vector<double> Evaluate(const FieldStates &states) = 0;
|
|
// The field moved to combination `to`: F_total += sum dF(to) - sum dF(current).
|
|
virtual void Move(const FieldStates &states, int to) = 0;
|
|
// The direct-summation F of one state's atoms at the rows (for checking the sum against the engine).
|
|
virtual std::vector<std::complex<float>> Contribution(const FieldStates &states, int s) = 0;
|
|
};
|
|
|
|
// The group's operators as the evaluator takes them: rotation (row-major) and translation, fractional.
|
|
std::vector<std::array<float, 12>> FieldOperators(const gemmi::SpaceGroup &sg);
|
|
|
|
// With `gpu`, the direct sums on the Apple GPU where there is one (SideChainFieldMetal.h, macOS): the same values,
|
|
// bit for bit.
|
|
std::unique_ptr<SideChainFieldEvaluator> MakeSideChainFieldEvaluatorCPU(const FieldReflections &refl,
|
|
const std::vector<std::array<float, 12>> &ops,
|
|
const std::vector<FormFactor> &elements,
|
|
size_t nthreads, bool gpu = false);
|
|
#ifdef JFJOCH_USE_CUDA
|
|
// The device memory the GPU evaluator takes at most for `rows` reflections under `n_ops` operators, bytes.
|
|
size_t SideChainFieldDeviceBytes(size_t rows, size_t n_ops);
|
|
// On `device`; throws JFJochException on a CUDA failure.
|
|
std::unique_ptr<SideChainFieldEvaluator> MakeSideChainFieldEvaluatorGPU(int device, const FieldReflections &refl,
|
|
const std::vector<std::array<float, 12>> &ops,
|
|
const std::vector<FormFactor> &elements);
|
|
// On every card of `devices`, the reflections split among them in contiguous parts that the cards evaluate side by
|
|
// side; on one card, the evaluator above.
|
|
std::unique_ptr<SideChainFieldEvaluator> MakeSideChainFieldEvaluatorGPUs(const std::vector<int> &devices,
|
|
const FieldReflections &refl,
|
|
const std::vector<std::array<float, 12>> &ops,
|
|
const std::vector<FormFactor> &elements);
|
|
#endif
|
|
|
|
// A residue the field moved: its atoms (index in the model's atom list) at their new positions, or absent.
|
|
struct SideChainFieldMove {
|
|
std::string name; // "LYS A87"
|
|
std::vector<double> chi_before, chi_after; // degrees (empty after: absent)
|
|
bool absent = false;
|
|
std::vector<std::pair<int, gemmi::Position>> atoms; // every atom of the residue beyond CB, hydrogens included
|
|
std::vector<int> pruned; // the atoms put to occupancy 0 (absent only)
|
|
double energy_gain = 0; // -ln L (work) units, the field's energy lowered by the move
|
|
};
|
|
|
|
// What a residue's best alternative would gain over the state as given, before the margin for the number of
|
|
// alternatives (for the log: a gain below the margin moves nothing).
|
|
struct SideChainFieldAlternative {
|
|
std::string name; // "LYS A87", "ASN A104 x3" for the copies
|
|
double gain = 0; // -ln L (work) units
|
|
std::vector<double> chi_given, chi_best; // degrees (empty best: absent); the first copy's
|
|
};
|
|
|
|
struct SideChainFieldResult {
|
|
int candidates = 0; // residues searched
|
|
std::vector<SideChainFieldAlternative> alternatives; // per variable, in the order searched
|
|
int sweeps = 0; // the first over every residue, the others over those near a move
|
|
bool copies_together = false; // the copies of a residue searched together only (the sweep budget)
|
|
double energy_before = 0, energy_after = 0;
|
|
std::vector<SideChainFieldMove> moves;
|
|
};
|
|
|
|
// `st`: the model as it is (hydrogens riding), with its cell and group; `element_of`: per atom in model order its
|
|
// entry in the form-factor table the evaluator was made with; `refinable`: per atom (RefinementTopology's);
|
|
// `ncs_group`: per residue (numbered over the model in order) the NCS group of its copies, -1 where it has none
|
|
// (or empty): the copies of a residue are one variable, searched in each rotamer together - the NCS restraints of
|
|
// the step after would pull a copy moved alone back - and each alone, for the copy whose environment differs (a
|
|
// crystal contact) where a sweep stays within its budget; `weight`: the X-ray term's weight in the refinement's target, which the repulsion term is
|
|
// divided by; `rows`: the evaluator's reflections. The residues searched: amino acids with a complete side chain, no alternative conformations, every
|
|
// atom at full occupancy, refinable and not bound by a LINK. `st` is left as it was; the moves say what changed.
|
|
SideChainFieldResult OptimiseSideChainField(const gemmi::Structure &st, const std::vector<int> &element_of,
|
|
const std::vector<char> &refinable, const std::vector<int> &ncs_group,
|
|
double weight, size_t rows, SideChainFieldEvaluator &evaluator);
|
|
|
|
// The state of the field's atoms of one residue (depth 2 and beyond, hydrogens included) at positions `p`, at full
|
|
// occupancy.
|
|
std::vector<FieldAtom> FieldAtomsOf(const gemmi::Residue &res, const SideChain &sc, const std::vector<gemmi::Position> &p,
|
|
const gemmi::UnitCell &cell, const std::vector<int> &element_of, int first_atom);
|