Files
Jungfraujoch/image_analysis/structure_refinement/Refinement.h
T
leonarski_f c4d2d419ce Refinement score: the model's structure factors as REFMAC 5.8 scores them at 0 cycles
Three terms of the score of a model - the same F_model at every stage, the as-given start and the
refined end alike - and a breakdown of it:

- Riding hydrogens from the start: the dictionary's hydrogens are added before the model is first
  scored (REFMAC's 0-cycle restores them; they move R by 0.010-0.013 at 1.1 A). The engine is made
  once, with them.
- The bulk-solvent mask on a grid of its own, min(d_min/3, 0.4 A), at most 2^26 points. On the
  density grid (1.1 A at 3.3 A) gemmi's 0.8 A shrink found no grid offset and was skipped, which put
  R 0.015-0.03 high at >= 2.5 A. 0.3 and 0.4 A agree to 0.001.
- The overall scale and anisotropic B by robust least squares (pseudo-Huber, iteratively
  reweighted, c = median |residual|) in the fine pass of the k_sol/b_sol grid (ModelScaleBox::robust,
  refinement only; MR and validation keep the plain fit). Plain least squares on |F| is the exact LS
  optimum but lets a few badly-fitted strong reflections set the scale (1.1 A set: R 0.1706 against
  REFMAC's 0.1600). The scale fit of refinement now runs on the CPU (no ModelScaleGPUPool).

RefinementSettings::score_only scores the model as given and stops; RefinementResult::score_start
carries every term (k, B, anisotropic B, k_sol, b_sol, mask spacing, R in 20 shells, -lnL work/free,
the likelihood FOM, hydrogens; per-reflection terms with score_only). GeometryStatistics gains rmsZ.
rugnux_refine_test: --score-only, --dump.

Measured against REFMAC 5.8.0431 ncyc 0 (refi bref iso) on the same model, data and flags, 14 open-arm
sets 1.1-3.6 A: R-work/R-free within 0.002 on 12 (was +0.003..+0.03); 7n2s and 9yl4 score 0.003/0.005
below REFMAC, which a 0.6-0.8 A mask grid reproduces. REFMAC with ANISOU stripped scores identically,
so isotropic B is not a parity term. Open: the likelihood's D/FOM (ours 0.01-0.11 higher at high
resolution); geometry differs only by REFMAC's metal LINK restraints and residues outside the
embedded dictionary.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015CeEGgpKdfkCTJb3YNMJcu
(cherry picked from commit 4f94b21611874ad9dcf89e6771fe311a0e10bb06)
(cherry picked from commit 00db6a6f539ac2da515c0a649474335f4c4b07b8)
2026-10-26 01:38:23 +01:00

144 lines
7.2 KiB
C++

// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <array>
#include <cmath>
#include <complex>
#include <memory>
#include <string>
#include <vector>
#include "gemmi/grid.hpp"
#include "gemmi/model.hpp"
#include "gemmi/symmetry.hpp"
#include "gemmi/unitcell.hpp"
#include "../../common/Reflection.h" // MergedReflection
#include "DensityBlobs.h"
#include "ModelValidation.h" // ModelMaps
#include "RefinementRestraints.h" // GeometryStatistics
class Logger;
// Refinement of an atomic model already placed against the data (ValidateAgainstModel's placed model, or a
// molecular-replacement placement), in two stages:
//
// 1. Placement: each chain as a rigid body, then one B shift per residue, each kept only where it lowers
// R-free. Needs no dictionary.
// 2. Restrained: every atom's position and isotropic B, against the maximum-likelihood amplitude target with
// the geometry the dictionary describes (MonomerLibrary.h: bonds, angles, planes, chiral volumes,
// torsions, repulsions; B similarity of bonded atoms). Residues it does not describe are held fixed and
// stay in the structure factors and the bulk-solvent mask. The weight of the X-ray term against the
// geometry is chosen from a ladder of full refinements, by R-free among those whose geometry stays within
// bounds; then whether, and at what weight, to refine the B factors as well, the same way.
//
// The library reads and writes nothing: the model and the reflections come in, the refined model, the
// statistics and the map coefficients go out. Nothing it finds feeds back into processing decisions.
struct RefinementSettings {
bool restrained = true; // stage 2; false stops after the placement stage
bool score_only = false; // only score the model as given (RefinementResult::score_start), no stage
bool group_b = true; // the placement stage's B shift per residue
int macro_cycles = 10;
int xyz_iterations = 10; // L-BFGS iterations per macro-cycle
int b_iterations = 5;
// The positions' X-ray weight, times the gradient-balanced one (BalancedWeight), tried in this order.
std::vector<double> weight_ladder = {1.0 / 1024, 1.0 / 512, 1.0 / 256, 1.0 / 128, 1.0 / 64, 1.0 / 32};
// The X-ray weights of the B refinement tried next, times the positions' chosen weight.
std::vector<double> adp_ladder = {1.0, 4.0, 16.0};
bool riding_hydrogens = true; // the dictionary's hydrogens added, riding on their parents
bool gpu = true;
size_t nthreads = 1;
size_t gpu_resident_bytes = 0; // held on the card by what runs beside
};
// R by resolution: one of RefinementScore's shells, equal in width in 1/d^2 between the coarsest and the
// finest reflection.
struct RefinementShell {
double d_max = 0, d_min = 0;
int n_work = 0, n_free = 0;
double r_work = NAN, r_free = NAN;
};
// What scoring a model against the data gives, every term of it: the model's structure factors are
// F_model = k_overall exp(-s^T B s / 4) (Fcalc + k_sol exp(-b_sol s^2 / 4) Fmask), the scale and the solvent
// fitted to the working reflections; R-work and R-free; and the likelihood target, -ln L summed over the
// working and over the free reflections, at D and the variance estimated from the free set.
struct RefinementScore {
double k_overall = 0;
double b_iso = 0; // the overall B: a third of the trace of B (Cartesian, A^2)
std::array<double, 6> b_aniso{}; // B less b_iso: B11 B22 B33 B12 B13 B23 (Cartesian, A^2)
double k_sol = 0, b_sol = 0;
double mask_spacing = 0; // A, the grid the solvent mask is drawn on
double r_work = NAN, r_free = NAN;
int n_work = 0, n_free = 0;
double nll_work = NAN, nll_free = NAN;
double fom = NAN; // the likelihood's mean figure of merit, all reflections
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
// and k_overall exp(-s^T B s / 4), in the order of `hkl`, and the likelihood's parameters.
std::vector<gemmi::Miller> hkl;
std::vector<std::complex<float>> fcalc, fmask;
std::vector<float> k_total;
std::vector<float> d, var; // the likelihood's D and variance (epsilon beta + sigma^2)
};
// One rung of the weight ladder.
struct RefinementWeightTrial {
double weight = 0; // the X-ray term's weight
double adp_weight = 0; // the B refinement's X-ray weight; 0: the B factors were held
double r_work = 1, r_free = 1;
GeometryStatistics geometry;
bool within_bounds = false; // the geometry bounds the choice is made inside
};
struct RefinementResult {
bool ok = false;
std::string failure_reason;
bool on_gpu = false;
double seconds = 0;
double d_min = 0;
int n_work = 0, n_free = 0;
// The model as given, scaled to these reflections (B made isotropic; the dictionary's hydrogens riding
// where the restrained stage runs or the model is only scored), and every term of that score.
double r_work_start = 1, r_free_start = 1;
RefinementScore score_start;
// After the placement stage.
int rigid_bodies = 0; // the chains moved as rigid bodies, where that was kept
bool group_b = false; // the B shift per residue was kept
double r_work_placement = 1, r_free_placement = 1;
// After the restrained stage (NaN where it did not run).
bool restrained = false;
double r_work = NAN, r_free = NAN;
double weight = 0;
double adp_weight = 0; // 0: the B factors kept as placed
std::vector<RefinementWeightTrial> trials;
GeometryStatistics geometry_start, geometry;
int atoms = 0, refined_atoms = 0;
int restrained_residues = 0, fixed_residues = 0;
std::vector<std::string> fixed_names;
double k_sol = 0, b_sol = 0;
double mean_fom = 0;
std::shared_ptr<gemmi::Structure> model; // the refined model, in the data's cell and frame
std::shared_ptr<ModelMaps> maps; // its 2mFo-DFc and mFo-DFc coefficients (as _maps.mtz holds them)
// The mFo-DFc map of the refined model and its rms, for finding what it leaves unexplained (DensityBlobs.h).
std::shared_ptr<gemmi::Grid<float>> difference_map;
double difference_map_rms = 0;
// The anomalous difference map on the refined model's phases, where the merge kept the Bijvoet pairs.
std::shared_ptr<gemmi::Grid<float>> anomalous_map;
double anomalous_map_rms = 0;
// What the refined model leaves unexplained in the difference map (FindDensityBlobs).
std::vector<DensityBlob> blobs;
};
// `placed`: the model in the data's cell and space group. `merged`: the merge, with French-Wilson amplitudes
// and free flags, in the same group.
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);