// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute // 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 #include #include #include #include #include #include #include #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> hkl; std::vector stol2; // (sin theta / lambda)^2 std::vector fo, d, var; std::vector centric, work; // work: not a free reflection std::vector k_total; std::vector> 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 atoms; std::vector start = {0}; std::vector current; std::vector combo_states; std::vector combo_start = {0}; void Add(const std::vector &a) { atoms.insert(atoms.end(), a.begin(), a.end()); start.push_back(static_cast(atoms.size())); } void AddCombo(const std::vector &states) { combo_states.insert(combo_states.end(), states.begin(), states.end()); combo_start.push_back(static_cast(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; // -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> &f) = 0; // -ln L (work) per combination of `states`. virtual std::vector 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> Contribution(const FieldStates &states, int s) = 0; }; // The group's operators as the evaluator takes them: rotation (row-major) and translation, fractional. std::vector> 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 MakeSideChainFieldEvaluatorCPU(const FieldReflections &refl, const std::vector> &ops, const std::vector &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 MakeSideChainFieldEvaluatorGPU(int device, const FieldReflections &refl, const std::vector> &ops, const std::vector &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 MakeSideChainFieldEvaluatorGPUs(const std::vector &devices, const FieldReflections &refl, const std::vector> &ops, const std::vector &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 chi_before, chi_after; // degrees (empty after: absent) bool absent = false; std::vector> atoms; // every atom of the residue beyond CB, hydrogens included std::vector 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 chi_given, chi_best; // degrees (empty best: absent); the first copy's }; struct SideChainFieldResult { int candidates = 0; // residues searched std::vector 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 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 &element_of, const std::vector &refinable, const std::vector &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 FieldAtomsOf(const gemmi::Residue &res, const SideChain &sc, const std::vector &p, const gemmi::UnitCell &cell, const std::vector &element_of, int first_atom);