Files
Jungfraujoch/gemmi_gph/gemmi/levmar.hpp
T
leonarski_f dd0bffb283
Build Packages / Unit tests (push) Skipped
Build Packages / build:windows:nocuda (push) Successful in 11m6s
Build Packages / build:rpm (rocky8_nocuda) (push) Successful in 10m27s
Build Packages / build:rpm (rocky9_nocuda) (push) Successful in 10m54s
Build Packages / build:rpm (ubuntu2204_nocuda) (push) Successful in 9m25s
Build Packages / build:rpm (ubuntu2404_nocuda) (push) Successful in 10m5s
Build Packages / build:rpm (rocky8_sls9) (push) Successful in 11m33s
Build Packages / build:rpm (rocky9_sls9) (push) Successful in 11m19s
Build Packages / build:rpm (rocky8) (push) Successful in 12m23s
Build Packages / build:rpm (rocky9) (push) Successful in 13m21s
Build Packages / build:rpm (ubuntu2204) (push) Successful in 12m30s
Build Packages / build:rpm (ubuntu2404) (push) Successful in 11m55s
Build Packages / DIALS test (push) Successful in 13m42s
Build Packages / XDS test (durin plugin) (push) Successful in 9m26s
Build Packages / XDS test (JFJoch plugin) (push) Successful in 6m41s
Build Packages / XDS test (neggia plugin) (push) Successful in 6m12s
Build Packages / Generate python client (push) Successful in 19s
Build Packages / Build documentation (push) Successful in 52s
Build Packages / Create release (push) Skipped
Build Packages / build:viewer-tgz:cpu (push) Successful in 5m29s
Build Packages / build:viewer-tgz:cuda (push) Successful in 6m12s
Build Packages / build:windows:cuda (push) Successful in 18m36s
v1.0.0-rc.159 (#69)
This is an UNSTABLE release. It includes many experimental features, as well as many AI generated fixes. We recommend using rc.152 for production use.

* rugnux: Add `--model model.pdb` - score the merged data against an atomic model and compute initial maps. It reports R-work/R-free (scaling the model to the observed amplitudes with an overall scale, an anisotropic B and a flat bulk solvent - the standard few-parameter model, so a batch of maps stays directly comparable) and writes 2Fo-Fc / Fo-Fc electron-density maps (CCP4) plus a map-coefficient MTZ. The structure itself is not refined; the model is only re-fractionalised into the data cell.
* rugnux: The merged reflection output now carries French-Wilson amplitudes (|F| and its sigma) next to the intensities - MTZ `F`/`SIGF`, mmCIF `_refln.F_meas_au`, and the text HKL - computed with the correct centric/acentric Wilson prior and epsilon multiplicity, so a downstream program (e.g. phenix.refine) can refine against amplitudes. The intensity columns are unchanged.
* rugnux: R-free test-set flags are now assigned deterministically and consistently across symmetry - a Bijvoet pair I(+)/I(-) is never split between the work and free sets, and the assignment is a reproducible per-hkl hash that depends only on the reflection index, so every dataset of one crystal form gets the same ~5% free set (what a multi-dataset campaign such as PanDDA needs). On small data the fraction is floored so the test set stays large enough for a stable R-free (~500 reflections, capped at 10%); it stays flat at 5% on ordinary data. When a reference MTZ carries a `FreeR_flag` column its test set is imported instead, letting a whole campaign inherit one shared free set.
* rugnux: A reference MTZ (`--reference-mtz`) can now fix the space group and cell for rotation data too (previously rejected), without being used to scale - the rotation merge stays self-consistent. When the crystal has an indexing (merohedral) ambiguity - a lattice symmetry higher than its Laue symmetry, e.g. P3/P4/P6/C2 - the reference also resolves it: each candidate reindexing (identity plus the twin-law cosets of the metric symmetry) is scored by its intensity correlation against the reference and the data are re-merged in the best-correlating one. This is a metric-preserving relabelling of hkl (the cell is unchanged) and a no-op for a holohedral crystal such as lysozyme.
* rugnux: `--model` validation now aligns the data to the model before scoring - the observed reflections are reindexed into the model's enantiomorph when the two differ only by hand (indistinguishable from merged intensities). A merohedral indexing ambiguity is resolved against the reference MTZ when one is given (so a whole campaign shares one indexing convention); only with a model and no reference does validation fall back to fitting each candidate reindexing and keeping the lowest R-free.
* rugnux: De-novo symmetry - recover a genuine high-symmetry group whose data are imperfectly scaled. Such a merge's within-orbit chi² lands just past the self-consistency bound (each real symmetry step adds a little systematic scatter), right where a merohedral twin also lands, so the chi² ratio alone cannot separate them. The candidate is now rescued when the extra intensity-proportional systematic error it invokes stays small relative to the confirmed subgroup - a genuine symmetry step gains multiplicity without inflating the merge error model's b, whereas a twin forces non-equivalent reflections together and b balloons. Fixes cubic insulin (I23 instead of I222) with no change to any other crystal in the test battery, including the twins that must stay in their lower symmetry.
* Docs: Document the French-Wilson amplitude estimation, R-free flagging, reference-based space-group/ambiguity resolution, and model-based validation/maps in CPU_DATA_ANALYSIS.md.
* Frontend: The status-bar pill now shows a progress bar during detector calibration (previously only during measurement), and the calibration state and its button are labelled "Calibration"/"CALIBRATE" (the internal `Pedestal` state name is unchanged for back-compatibility).Reviewed-on: #69

Co-authored-by: Filip Leonarski <filip.leonarski@psi.ch>
2026-07-13 13:54:03 +02:00

268 lines
8.3 KiB
C++

// Copyright 2020 Global Phasing Ltd.
//
// Least-squares fitting - Levenberg-Marquardt method.
//
// Based on the code from fityk (but here it's under MPL 2.0).
#ifndef GEMMI_LEVMAR_HPP_
#define GEMMI_LEVMAR_HPP_
#include <cassert>
#include <cmath> // for fabs
#include <algorithm> // for min
#include <vector>
#include "fail.hpp" // for fail
#include "math.hpp" // for sq
//#define GEMMI_DEBUG_LEVMAR
namespace gemmi {
/// This function solves a set of linear algebraic equations using
/// Gauss-Jordan elimination with partial pivoting.
///
/// A * x = b
///
/// a is n x n matrix (in vector)
/// b is vector of length n,
/// This function returns vector x[] in b[], and 1-matrix in a[].
inline void jordan_solve(double* a, double* b, int n) {
for (int i = 0; i < n; i++) {
// looking for a pivot element
int maxnr = -1;
double amax = 0;
for (int j = i; j < n; j++) {
double aji = std::fabs(a[n * j + i]);
if (aji > amax) {
maxnr = j;
amax = aji;
}
}
// handle singular matrix
if (maxnr == -1) {
// i-th column has only zeros.
// If it's the same about i-th row, and b[i]==0, let x[i]==0.
for (int j = i; j < n; j++)
if (a[n * i + j] != 0. || b[i] != 0.)
fail("Trying to reverse singular matrix. Column ", std::to_string(i), " is zeroed.");
continue; // x[i]=b[i], b[i]==0
}
// interchanging rows
if (maxnr != i) {
for (int j = i; j < n; j++)
std::swap(a[n * maxnr + j], a[n * i + j]);
std::swap(b[i], b[maxnr]);
}
// divide by a_ii -- to get a_ii=1
double c = 1.0 / a[i * n + i];
for (int j = i; j < n; j++)
a[i * n + j] *= c;
b[i] *= c;
// subtract -- to zero all remaining elements of this row
for (int k = 0; k < n; k++)
if (k != i) {
double d = a[k * n + i];
for (int j = i; j < n; j++)
a[k * n + j] -= a[i * n + j] * d;
b[k] -= b[i] * d;
}
}
}
inline void jordan_solve(std::vector<double>& a, std::vector<double>& b) {
assert(a.size() == b.size() * b.size());
jordan_solve(a.data(), b.data(), (int)b.size());
}
inline void print_parameters(const std::string& name, std::vector<double> &a) {
fprintf(stderr, " %s:", name.c_str());
for (double& x : a)
fprintf(stderr, " %g", x);
fprintf(stderr, "\n");
}
template<typename Target>
double compute_wssr(const Target& target) {
long double wssr = 0; // long double here notably increases the accuracy
for (const auto& p : target.points)
wssr += sq(p.get_weight() * (p.get_y() - target.compute_value(p)));
return (double) wssr;
}
template<typename Target>
double compute_gradients(const Target& target, unsigned n, double* grad) {
double wssr = 0;
for (unsigned i = 0; i < n; ++i)
grad[i] = 0;
std::vector<double> dy_da(n);
for (const auto& p : target.points) {
double y = target.compute_value_and_derivatives(p, dy_da);
double dy = p.get_weight() * (p.get_y() - y);
wssr += sq(dy);
for (unsigned i = 0; i < n; ++i)
grad[i] += -2 * dy * dy_da[i];
}
#if 0
// calculate numerical derivatives to check analytical formulas
fprintf(stderr, ">> y=%g\n", wssr);
std::vector<double> x = target.get_parameters();
assert(x.size() == n);
for (unsigned i = 0; i < n; ++i) {
double x_orig = x[i];
double h = std::max(std::fabs(x[i]), 1e-6) * 1e-3;
x[i] = x_orig - h;
const_cast<Target&>(target).set_parameters(x);
double y_left = compute_wssr(target);
x[i] = x_orig + h;
const_cast<Target&>(target).set_parameters(x);
double y_right = compute_wssr(target);
double numeric = (y_right - y_left) / (2 * h);
x[i] = x_orig;
double m = std::max(std::fabs(grad[i]), std::fabs(numeric));
if (m > 1e-3 && std::fabs(grad[i] - numeric) > 0.02 * m)
fprintf(stderr, "!! grad[%u]: %g vs %g (value: %g)\n", i, grad[i], numeric, x[i]);
}
const_cast<Target&>(target).set_parameters(x);
#endif
return wssr;
}
// alpha and beta are matrices outputted for the Levenberg-Marquardt algorithm.
// Ignoring weights, alpha is a squared Jacobian J^T J (which approximates the
// Hessian, as discussed in Numerical Recipes, chapter 15.5), not "damped" yet.
// The return value is the same as from compute_wssr().
template<typename Target>
double compute_lm_matrices(const Target& target,
std::vector<double>& alpha,
std::vector<double>& beta) {
assert(!beta.empty());
assert(alpha.size() == beta.size() * beta.size());
long double wssr = 0; // long double here notably increases the accuracy
size_t na = beta.size();
std::fill(alpha.begin(), alpha.end(), 0.0);
std::fill(beta.begin(), beta.end(), 0.0);
std::vector<double> dy_da(na);
for (const auto& p : target.points) {
double y = target.compute_value_and_derivatives(p, dy_da);
double weight = p.get_weight();
double dy_sig = weight * (p.get_y() - y);
for (size_t j = 0; j != na; ++j) {
if (dy_da[j] != 0) {
dy_da[j] *= weight;
for (size_t k = j+1; k-- != 0;)
alpha[na * j + k] += dy_da[j] * dy_da[k];
beta[j] += dy_sig * dy_da[j];
}
}
wssr += sq(dy_sig);
}
// Only half of the alpha matrix was filled above. Fill the rest.
for (size_t j = 1; j < na; j++)
for (size_t k = 0; k < j; k++)
alpha[na * k + j] = alpha[na * j + k];
return (double) wssr;
}
struct LevMar {
// termination criteria
int eval_limit = 100;
double lambda_limit = 1e+15;
double stop_rel_change = 1e-5;
// adjustable parameters (normally the default values work fine)
double lambda_up_factor = 10;
double lambda_down_factor = 0.1;
double lambda_start = 0.001;
// values set in fit() that can be inspected later
double initial_wssr = NAN;
int eval_count = 0; // number of function evaluations
// arrays used during refinement
std::vector<double> alpha; // matrix
std::vector<double> beta; // vector
std::vector<double> temp_alpha, temp_beta; // working arrays
template<typename Target>
double fit(Target& target) {
std::vector<double> initial_a = target.get_parameters();
#ifdef GEMMI_DEBUG_LEVMAR
print_parameters("ini", initial_a);
#endif
std::vector<double> best_a = initial_a;
size_t na = initial_a.size();
double lambda = lambda_start;
alpha.resize(na * na);
beta.resize(na);
initial_wssr = compute_lm_matrices(target, alpha, beta);
double wssr = initial_wssr;
int small_change_counter = 0;
eval_count = 1; // number of function evaluations so far
for (int iter = 0; ; iter++) {
if (eval_limit > 0 && eval_count >= eval_limit)
break;
// prepare next parameters -> temp_beta
temp_alpha = alpha;
// Using '*=' not '+=' below applies the dampling factor as:
// J^T J + lambda * diag(J^T J); not ... + lambda * I.
for (size_t j = 0; j < na; j++)
temp_alpha[na * j + j] *= (1.0 + lambda);
temp_beta = beta;
// Matrix solution (Ax=b) temp_alpha * da == temp_beta
jordan_solve(temp_alpha, temp_beta);
for (size_t i = 0; i < na; i++)
// put new a[] into temp_beta[]
temp_beta[i] += best_a[i];
target.set_parameters(temp_beta);
double new_wssr = compute_wssr(target);
++eval_count;
#ifdef GEMMI_DEBUG_LEVMAR
fprintf(stderr, " #%d WSSR=%.8g %+g%% (%+.4g%%) lambda=%g\n",
iter, new_wssr, 100. * (new_wssr / initial_wssr - 1.),
100. * (new_wssr / wssr - 1.), lambda);
if (new_wssr < wssr)
print_parameters("", temp_beta);
#else
(void) iter;
#endif
if (new_wssr < wssr) {
double rel_change = (wssr - new_wssr) / wssr;
wssr = new_wssr;
best_a = temp_beta;
if (wssr == 0)
break;
// termination criterion: negligible change of wssr
if (rel_change < stop_rel_change) {
if (++small_change_counter >= 2)
break;
} else {
small_change_counter = 0;
}
compute_lm_matrices(target, alpha, beta);
++eval_count;
lambda *= lambda_down_factor;
} else { // worse fitting
if (lambda > lambda_limit) // termination criterion: large lambda
break;
lambda *= lambda_up_factor;
}
}
target.set_parameters(wssr < initial_wssr ? best_a : initial_a);
return wssr;
}
};
} // namespace gemmi
#endif