XtalOptimizer: own Levenberg-Marquardt solver in place of Ceres

The crystal refinement (XtalOptimizer, both the seven-block and the reduced
beam+orientation form, and XtalOptimizerRotationOnly) no longer builds a
ceres::Problem. XtalRefine holds the problem as data and solves it with
LMSolver, which follows Ceres' trust-region LM step for step - Jacobi scaling,
damping and radius updates, stopping rules, box projection, the projected
Armijo line search with cubic interpolation on bounded problems, the
SphereManifold for the spindle - but takes J^T J and J^T r directly instead of
a Jacobian. The residual is the same XtalResidual code, now Ceres-free and
evaluated on a forward-mode Dual (Dual.h); everything that depends on
parameters alone (detector-angle trig, per-frame back-rotation, reciprocal
basis, orientation rotation) is worked out once per evaluation, and the
observed and predicted halves carry 6 and 9 derivative lanes rather than 16.
The sums are cut into blocks that depend on the residual count alone, so the
answer does not depend on the thread count. Because the line-search trial point
is the candidate point, a bounded iteration costs one evaluation instead of
Ceres' three.

Validation (rc174 + this, -march=x86-64-v3):
- p.mtz md5 identical to the Ceres build on myob/cytc/thau x10sa, GPU and CPU
  builds, and on the lyso8 stills reference.
- Solve corpus (every 16-parameter solve and every 10th per-image solve of the
  three sets, 8.3k problems, inputs and Ceres results dumped from a run that
  reproduced the md5s): usable/failed agree on all, iteration counts identical
  on all, parameters agree to <2e-11 (in px / rad / 0.01 A units), costs to
  1e-13.
- Same process, same threads: 7-9x faster per solve than Ceres.
- In-run (GPU, loaded box): xtal 16-parameter solves myob 22.2 -> 6.4 core-s,
  cytc 88 -> 26 core-s; per-image solves 5.4 -> 1.2 core-s (myob); cytc first
  pass indexing windows 1.9 -> 0.85 s, myob 1.1 -> 0.45 s; solver share of the
  whole cytc run 17% -> 4% of CPU samples.

New tests compare the solver with Ceres on synthetic rotation problems
(full/weighted/reduced) and check thread-count independence.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K5K8jvPPbmCrbqnWkddTuB
This commit is contained in:
leonarski_fandClaude Opus 5.5 committed 2026-10-03 09:46:26 +02:00
1 parent 2c97e654ed
commit a4bb6f74f1
13 files changed
+1529 -243

No files matched your search

+127 -224
View File
@@ -7,84 +7,11 @@
#include "XtalOptimizer.h"
#include "XtalResidual.h"
#include "ceres/ceres.h"
#include "XtalRefine.h"
#include "ceres/rotation.h"
#include "Dual.h"
#include "LatticeReduction.h"
// Soft header prior on ONE beam-centre component (the spindle-parallel, gauge-weak one). Residual = w*(b - b0);
// the caller sets w so the prior behaves like a sigma-pixel restraint that competes with the (unit-weight)
// positional residuals - strong enough to pin the gauge direction, negligible in the well-constrained one.
// Soft restraint on one direction of a two-component block: g.(p - p0), weighted. Used for the beam
// centre and for the detector tilt, which are the same gauge seen twice (see the gauge block below),
// so they take the same direction g and cannot disagree about it.
struct GaugeDirectionPrior {
GaugeDirectionPrior(double gx, double gy, double p0, double weight)
: gx(gx), gy(gy), p0(p0), weight(weight) {}
template<typename T>
bool operator()(const T *const p, T *residual) const {
residual[0] = T(weight) * (T(gx) * p[0] + T(gy) * p[1] - T(p0));
return true;
}
double gx, gy, p0, weight;
};
struct XtalResidualRotationOnlyPrecomp {
XtalResidualRotationOnlyPrecomp(const Coord &recip_obs,
const CrystalLattice &latt,
double h, double k, double l)
: s_obs(recip_obs),
astar(latt.Astar()), bstar(latt.Bstar()), cstar(latt.Cstar()),
h(h), k(k), l(l) {
}
template<typename T>
bool operator()(const T *const rot_aa, T *residual) const {
const T astar_unrot[3] = {T(astar.x), T(astar.y), T(astar.z)};
const T bstar_unrot[3] = {T(bstar.x), T(bstar.y), T(bstar.z)};
const T cstar_unrot[3] = {T(cstar.x), T(cstar.y), T(cstar.z)};
T astar_rot[3], bstar_rot[3], cstar_rot[3];
const AngleAxisRotator<T> rot(rot_aa);
rot.Rotate(astar_unrot, astar_rot);
rot.Rotate(bstar_unrot, bstar_rot);
rot.Rotate(cstar_unrot, cstar_rot);
const Eigen::Matrix<T, 3, 1> s_pred(T(h) * astar_rot[0] + T(k) * bstar_rot[0] + T(l) * cstar_rot[0],
T(h) * astar_rot[1] + T(k) * bstar_rot[1] + T(l) * cstar_rot[1],
T(h) * astar_rot[2] + T(k) * bstar_rot[2] + T(l) * cstar_rot[2]
);
// Residual in reciprocal space
residual[0] = T(s_obs.x) - s_pred[0];
residual[1] = T(s_obs.y) - s_pred[1];
residual[2] = T(s_obs.z) - s_pred[2];
return true;
}
const Coord s_obs;
const Coord astar, bstar, cstar;
const double h, k, l;
};
// Regularizer: penalises ||rot_aa|| to prefer the smallest rotation that
// explains the data. Weight should be chosen in the same units as the
// reciprocal-space residuals (Å⁻¹ per radian). A value of ~0.01–0.1 is
// typically enough to break degeneracy without biasing the solution.
struct RotationNormRegularizer {
explicit RotationNormRegularizer(double weight) : weight(weight) {}
template<typename T>
bool operator()(const T *const rot_aa, T *residual) const {
residual[0] = T(weight) * rot_aa[0];
residual[1] = T(weight) * rot_aa[1];
residual[2] = T(weight) * rot_aa[2];
return true;
}
const double weight;
};
// Prior confidence weight per spot: how strong the spot is FOR ITS RESOLUTION. The frame's spots are
// ordered by resolution and cut into equal-count shells, and each intensity is divided by its shell
// median. Refinement needs the high-resolution spots (they carry the cell and distance information) and
@@ -153,12 +80,11 @@ bool XtalOptimizerInternal(XtalOptimizerData &data,
const int num_threads) {
try {
// A coplanar basis has no reciprocal cell: 1/V is infinite, every predicted reciprocal vector
// comes out NaN, and Ceres fails on the very first evaluation - after dumping the offending
// block to stderr. There is nothing for the refinement to recover here, so refuse the lattice
// before the problem is built rather than let the solver discover it. The check has to be on
// the vectors: this close to flat, float cell angles no longer carry even the SIGN of the
// metric determinant, and the triclinic branch of XtalResidual then clamps c into the a-b
// plane and divides by the zero volume that makes.
// comes out NaN, and the solver fails on the very first evaluation. There is nothing for the
// refinement to recover here, so refuse the lattice before the problem is built rather than let
// the solver discover it. The check has to be on the vectors: this close to flat, float cell
// angles no longer carry even the SIGN of the metric determinant, and the triclinic branch of
// XtalResidual then clamps c into the a-b plane and divides by the zero volume that makes.
if (data.latt.VolumeFraction() < MIN_BASIS_VOLUME_FRACTION)
return false;
@@ -168,24 +94,21 @@ bool XtalOptimizerInternal(XtalOptimizerData &data,
double beta = data.latt.GetUnitCell().beta;
// Initial guess for the parameters
double beam[2] = {data.geom.GetBeamX_pxl(), data.geom.GetBeamY_pxl()};
double distance_mm = data.geom.GetDetectorDistance_mm();
const double distance_mm = data.geom.GetDetectorDistance_mm();
double detector_rot[2] = {data.geom.GetPoniRot1_rad(), data.geom.GetPoniRot2_rad()};
// The per-frame constants of the reduced residual (see XtalFrameConstants), one entry per frame
// that contributes. Reserved up front and never grown past that, so the residual blocks' pointers
// into it stay valid, and declared before the problem so that it outlives it.
std::vector<XtalFrameConstants> frame_const;
frame_const.reserve(spots.size());
ceres::Problem problem;
double latt_vec0[3] = {0.0, 0.0, 0.0};
double latt_vec1[3] = {0.0, 0.0, 0.0};
double latt_vec2[3] = {0.0, 0.0, 0.0};
double rot_vec[3] = {1, 0, 0};
XtalRefineProblem problem;
problem.crystal_system = data.crystal_system;
problem.distance_mm = distance_mm;
double *beam = problem.beam;
beam[0] = data.geom.GetBeamX_pxl();
beam[1] = data.geom.GetBeamY_pxl();
double *detector_rot = problem.detector_rot;
detector_rot[0] = data.geom.GetPoniRot1_rad();
detector_rot[1] = data.geom.GetPoniRot2_rad();
double *latt_vec0 = problem.latt_vec0;
double *latt_vec1 = problem.latt_vec1;
double *latt_vec2 = problem.latt_vec2;
double *rot_vec = problem.rot_vec;
switch (data.crystal_system) {
case gemmi::CrystalSystem::Orthorhombic:
@@ -252,14 +175,15 @@ bool XtalOptimizerInternal(XtalOptimizerData &data,
const double sin_rot3 = std::sin(data.geom.GetPoniRot3_rad());
// Per-image rotation refinement frees only the beam and the orientation and holds the other five
// blocks constant, so the seven-block residual makes Ceres differentiate 17 parameters to use 5.
// Where that is the configuration, use the reduced residual instead - identical fit, Jet<5>
// autodiff. Any other combination (stills also free the cell, the offline refiner frees distance
// and detector angles) keeps the general form below.
// blocks constant. Where that is the configuration, the solver uses the reduced residual - the
// identical fit, with the crystal half worked out once (see XtalResidualBeamOrientation). Any
// other combination (stills also free the cell, the rotation indexer frees detector angles and
// spindle) keeps the general form.
const bool beam_and_orientation_only = data.refine_beam_center
&& !data.refine_detector_angles
&& !data.refine_rotation_axis
&& !data.refine_unit_cell;
problem.beam_and_orientation_only = beam_and_orientation_only;
// Sum of w^2 over the spots that entered - the beam prior below is scaled by it so that its
// strength relative to the data is the same weighted or not. Equals the residual block count
@@ -281,9 +205,8 @@ bool XtalOptimizerInternal(XtalOptimizerData &data,
rot_matr = data.axis->GetTransformationAngle(angle_deg);
}
if (beam_and_orientation_only)
frame_const.emplace_back(detector_rot, rot_vec, angle_rad, latt_vec1, latt_vec2,
data.crystal_system);
const int frame_index = static_cast<int>(problem.frame_angle_rad.size());
problem.frame_angle_rad.push_back(angle_rad);
// Add residuals for each point
for (size_t j = 0; j < spots[i].size(); j++) {
@@ -333,7 +256,7 @@ bool XtalOptimizerInternal(XtalOptimizerData &data,
const double weight_sq = weight.empty() ? 1.0 : weight[j] * weight[j];
effective_spots += weight_sq;
const XtalResidual residual(pt.x, pt.y,
problem.residuals.emplace_back(pt.x, pt.y,
data.geom.GetWavelength_A(),
data.geom.GetPixelSize_mm(),
cos_rot3, sin_rot3,
@@ -341,38 +264,14 @@ bool XtalOptimizerInternal(XtalOptimizerData &data,
h, k, l,
data.crystal_system,
data.geom.GetOrientation());
// Ceres has no per-residual weight; ScaledLoss(nullptr, a) multiplies the squared
// residual by the constant a, i.e. it applies a weight of sqrt(a) to the residual.
ceres::LossFunction *loss = weight.empty()
? nullptr
: new ceres::ScaledLoss(nullptr, weight_sq,
ceres::TAKE_OWNERSHIP);
if (beam_and_orientation_only)
problem.AddResidualBlock(
new ceres::AutoDiffCostFunction<XtalResidualBeamOrientation, 3, 2, 3>(
new XtalResidualBeamOrientation(residual, distance_mm, frame_const.back())),
loss,
beam,
latt_vec0
);
else
problem.AddResidualBlock(
new ceres::AutoDiffCostFunction<XtalResidualFixedDistance, 3, 2, 2, 3, 3, 3, 3>(
new XtalResidualFixedDistance(residual, distance_mm)),
loss,
beam,
detector_rot,
rot_vec,
latt_vec0,
latt_vec1,
latt_vec2
);
problem.frame.push_back(frame_index);
// A per-residual weight w enters the squared residual as w^2.
if (!weight.empty())
problem.weight_sq.push_back(weight_sq);
}
}
if (problem.NumResidualBlocks() < data.min_spots)
if (static_cast<int64_t>(problem.residuals.size()) < data.min_spots)
return false;
// The gauge direction of a single-axis rotation experiment - parallel to the spindle - written
@@ -440,9 +339,8 @@ bool XtalOptimizerInternal(XtalOptimizerData &data,
const double gauge_w = data.geom.GetPixelSize_mm() / (distance_mm * data.geom.GetWavelength_A())
* std::sqrt(effective_spots) / sigma_px;
if (!data.refine_beam_center)
problem.SetParameterBlockConstant(beam);
else if (data.axis) {
problem.beam_constant = !data.refine_beam_center;
if (data.refine_beam_center && data.axis) {
// Gauge handling (single-axis rotation): rotating the whole experiment about the spindle leaves every
// spot position unchanged, so the beam-centre component PARALLEL to the spindle is a null/gauge-weak
// direction. Refining it freely lets it wander (~+3 px) and absorb centroid systematics into a wrong
@@ -450,23 +348,19 @@ bool XtalOptimizerInternal(XtalOptimizerData &data,
// does drift - it is only LaB6-monitored to ~a few px), RESTRAIN it toward the header with a soft
// prior: the gauge direction has ~zero data sensitivity so the prior pins it near the header, while a
// real, well-supported drift can still overcome it.
problem.AddResidualBlock(
new ceres::AutoDiffCostFunction<GaugeDirectionPrior, 1, 2>(
new GaugeDirectionPrior(gauge_beam_x, gauge_beam_y,
gauge_beam_x * beam[0] + gauge_beam_y * beam[1], gauge_w)),
nullptr, beam);
problem.priors.push_back({XtalRefinePrior::Block::Beam, gauge_beam_x, gauge_beam_y,
gauge_beam_x * beam[0] + gauge_beam_y * beam[1], gauge_w});
}
// Distance, detector angles, rotation axis and cell are parameter blocks only in the general
// seven-block residual; the reduced one bakes them in, so there is nothing left to configure.
if (!beam_and_orientation_only) {
if (!data.refine_detector_angles) {
problem.SetParameterBlockConstant(detector_rot);
} else {
problem.detector_rot_constant = !data.refine_detector_angles;
if (data.refine_detector_angles) {
const double rot_range = 3.0 / 180.0 * PI;
for (int i = 0; i < 2; ++i) {
problem.SetParameterLowerBound(detector_rot, i, detector_rot[i] - rot_range);
problem.SetParameterUpperBound(detector_rot, i, detector_rot[i] + rot_range);
problem.detector_rot_lower[i] = detector_rot[i] - rot_range;
problem.detector_rot_upper[i] = detector_rot[i] + rot_range;
}
// The same gauge as the beam prior above, described a second time: the tilt moves the
// direct beam exactly as the beam centre does, at D/pixel px per radian, so leaving
@@ -497,20 +391,15 @@ bool XtalOptimizerInternal(XtalOptimizerData &data,
for (int i = 0; i < 2; ++i) {
if (budget[i] <= 0.0)
continue;
problem.AddResidualBlock(
new ceres::AutoDiffCostFunction<GaugeDirectionPrior, 1, 2>(
new GaugeDirectionPrior(dirs[i][0], dirs[i][1],
dirs[i][0] * detector_rot[0]
+ dirs[i][1] * detector_rot[1],
gauge_w * (sigma_px / budget[i]) * lever)),
nullptr, detector_rot);
problem.priors.push_back({XtalRefinePrior::Block::DetectorRot, dirs[i][0], dirs[i][1],
dirs[i][0] * detector_rot[0] + dirs[i][1] * detector_rot[1],
gauge_w * (sigma_px / budget[i]) * lever});
}
}
}
if (!data.refine_rotation_axis) {
problem.SetParameterBlockConstant(rot_vec);
} else {
problem.rot_vec_constant = !data.refine_rotation_axis;
if (data.refine_rotation_axis) {
// Only the DIRECTION of the goniometer axis is a parameter. The residual applies
// angle_rad * |rot_vec|, so a free three-vector also fits a rotation SCALE - which
// GoniometerAxis::Axis() then normalises away, leaving the candidate scored by
@@ -520,63 +409,46 @@ bool XtalOptimizerInternal(XtalOptimizerData &data,
// data it recovers 54 % of a known scale error, repeated first passes on one dataset
// disagree with each other in SIGN, and on the one dataset with a real 1.3 % stage
// fault it comes out negative. The rotation scale is measured properly, once, with
// four gates and a jackknife, in PostRefine.
problem.SetManifold(rot_vec, new ceres::SphereManifold<3>);
// four gates and a jackknife, in PostRefine. Refined on the sphere (see SolveXtalRefine).
}
if (!data.refine_unit_cell) {
problem.SetParameterBlockConstant(latt_vec1);
problem.SetParameterBlockConstant(latt_vec2);
} else {
problem.latt_vec1_constant = !data.refine_unit_cell;
problem.latt_vec2_constant = !data.refine_unit_cell;
if (data.refine_unit_cell) {
// Parameter bounds
// Lengths
for (int i = 0; i < 3; ++i) {
problem.SetParameterLowerBound(latt_vec1, i, data.min_length_A);
problem.SetParameterUpperBound(latt_vec1, i, data.max_length_A);
problem.latt_vec1_lower[i] = data.min_length_A;
problem.latt_vec1_upper[i] = data.max_length_A;
}
if (data.crystal_system == gemmi::CrystalSystem::Monoclinic) {
const double beta_lo = std::max(1e-6, PI * (data.min_angle_deg / 180.0));
const double beta_hi = std::min(PI - 1e-6, PI * (data.max_angle_deg / 180.0));
problem.SetParameterLowerBound(latt_vec2, 0, beta_lo);
problem.SetParameterUpperBound(latt_vec2, 0, beta_hi);
problem.latt_vec2_constant = false;
problem.latt_vec2_lower[0] = std::max(1e-6, PI * (data.min_angle_deg / 180.0));
problem.latt_vec2_upper[0] = std::min(PI - 1e-6, PI * (data.max_angle_deg / 180.0));
} else if (data.crystal_system == gemmi::CrystalSystem::Triclinic) {
// α, β, γ bounds (radians)
const double alo = PI * (data.min_angle_deg / 180.0);
const double ahi = PI * (data.max_angle_deg / 180.0);
for (int i = 0; i < 3; ++i) {
problem.SetParameterLowerBound(latt_vec2, i, alo);
problem.SetParameterUpperBound(latt_vec2, i, ahi);
problem.latt_vec2_lower[i] = alo;
problem.latt_vec2_upper[i] = ahi;
}
} else {
// Orthorhombic / Tetragonal / Cubic / Hexagonal:
// latt_vec2 has no meaning for these systems — always freeze it.
problem.SetParameterBlockConstant(latt_vec2);
problem.latt_vec2_constant = true;
}
}
}
// Configure solver
ceres::Solver::Options options;
// Normal equations, not QR. The problem is very tall and thin - thousands of spots against at
// most 17 parameters - and that is the shape DENSE_QR handles worst: it copies the Jacobian out
// of Ceres' row-major storage into a column-major buffer on every solve, and Eigen's blocked
// Householder then degenerates to the unblocked path because its block size is min(48, columns).
// Accumulating J^T J reads the Jacobian once instead. Both solve the same damped system, so the
// step is the same to round-off; the column scaling Ceres applies by default and the LM diagonal
// keep the squared condition number in hand.
options.linear_solver_type = ceres::DENSE_NORMAL_CHOLESKY;
options.minimizer_progress_to_stdout = false;
// Stopping rule: a bound on iterations is reproducible, a bound on wall-clock time is not (see
// XtalOptimizerData::max_iterations).
if (data.max_iterations > 0)
options.max_num_iterations = data.max_iterations;
problem.options.max_iterations = data.max_iterations;
else
options.max_solver_time_in_seconds = data.max_time;
options.logging_type = ceres::LoggingType::SILENT;
options.num_threads = num_threads; // usually 1 (called from many threads); caller may raise it
ceres::Solver::Summary summary;
// Run optimization
ceres::Solve(options, &problem, &summary);
problem.options.max_time_s = data.max_time;
const LMSummary summary = SolveXtalRefine(problem, num_threads);
// Only a genuine numerical failure is rejected here: a solve that ran out of iterations or
// out of time but still descended counts as usable, which is what the real-time caller
@@ -653,7 +525,7 @@ bool XtalOptimizerRotationOnly(XtalOptimizerData &data,
return false;
// Parameter: angle-axis for the extra rotation. Identity == {0,0,0}.
double rot_aa[3] = {0.0, 0.0, 0.0};
std::vector<double> rot_aa = {0.0, 0.0, 0.0};
// Spot selection by current indexing (same approach as XtalOptimizerInternal)
const Coord a0 = data.latt.Vec0();
@@ -662,7 +534,12 @@ bool XtalOptimizerRotationOnly(XtalOptimizerData &data,
const float tol_sq = tolerance * tolerance;
ceres::Problem problem;
// Each selected spot: its observed reciprocal vector and the indices it is fitted to.
struct Observation {
Coord s_obs;
double h, k, l;
};
std::vector<Observation> observations;
for (const auto &pt : spots) {
if (!data.index_ice_rings && pt.ice_ring)
@@ -697,42 +574,68 @@ bool XtalOptimizerRotationOnly(XtalOptimizerData &data,
if (data.axis.has_value())
s_obs = data.axis->GetTransformationAngle(pt.phi) * s_obs;
auto *cost =
new ceres::AutoDiffCostFunction<XtalResidualRotationOnlyPrecomp, 3, 3>(
new XtalResidualRotationOnlyPrecomp(s_obs, data.latt, h, k, l)
);
problem.AddResidualBlock(cost, nullptr, rot_aa);
observations.push_back({s_obs, h, k, l});
}
if (problem.NumResidualBlocks() < data.min_spots)
if (static_cast<int64_t>(observations.size()) < data.min_spots)
return false;
// Regularization: prefer the smallest rotation correction that fits the
// data. This is essential when spots are nearly coplanar in reciprocal
// space (e.g. still images), where the rotation component perpendicular
// to the scattering plane is otherwise underdetermined.
// The weight is in Å⁻¹ rad⁻¹; tune relative to your typical residual.
{
const double reg_weight = 0.05; // e.g. 0.05
problem.AddResidualBlock(
new ceres::AutoDiffCostFunction<RotationNormRegularizer, 3, 3>(
new RotationNormRegularizer(reg_weight)),
nullptr, rot_aa);
}
// Residual: s_obs - R(rot_aa) (h a* + k b* + l c*), the reciprocal basis rotated once per
// evaluation and shared by every spot.
//
// Regularization: prefer the smallest rotation correction that fits the data, w * rot_aa. This is
// essential when spots are nearly coplanar in reciprocal space (e.g. still images), where the
// rotation component perpendicular to the scattering plane is otherwise underdetermined. The
// weight is in A^-1 rad^-1, relative to the typical residual.
const double reg_weight = 0.05;
const Coord astar = data.latt.Astar(), bstar = data.latt.Bstar(), cstar = data.latt.Cstar();
const auto evaluate = [&](const double *aa, double &cost, Eigen::VectorXd *g, Eigen::MatrixXd *H) {
using D = Dual<3>;
const D aa_d[3] = {D::Variable(aa[0], 0), D::Variable(aa[1], 1), D::Variable(aa[2], 2)};
const AngleAxisRotator<D> rot(aa_d);
const double astar_unrot[3] = {astar.x, astar.y, astar.z};
const double bstar_unrot[3] = {bstar.x, bstar.y, bstar.z};
const double cstar_unrot[3] = {cstar.x, cstar.y, cstar.z};
D astar_rot[3], bstar_rot[3], cstar_rot[3];
rot.Rotate(astar_unrot, astar_rot);
rot.Rotate(bstar_unrot, bstar_rot);
rot.Rotate(cstar_unrot, cstar_rot);
ceres::Solver::Options options;
options.linear_solver_type = ceres::DENSE_NORMAL_CHOLESKY; // tall and thin, as above
options.minimizer_progress_to_stdout = false;
cost = 0.0;
const auto add = [&](double r, const double *J) {
cost += 0.5 * r * r;
if (!g)
return;
for (int i = 0; i < 3; i++) {
(*g)[i] += J[i] * r;
for (int j = 0; j < 3; j++)
(*H)(i, j) += J[i] * J[j];
}
};
for (const auto &o: observations) {
const double s_obs[3] = {o.s_obs.x, o.s_obs.y, o.s_obs.z};
for (int c = 0; c < 3; c++) {
const D pred = o.h * astar_rot[c] + o.k * bstar_rot[c] + o.l * cstar_rot[c];
const double J[3] = {-pred.v[0], -pred.v[1], -pred.v[2]};
add(s_obs[c] - pred.a, J);
}
}
for (int c = 0; c < 3; c++) {
double J[3] = {0.0, 0.0, 0.0};
J[c] = reg_weight;
add(reg_weight * aa[c], J);
}
return std::isfinite(cost) && (!g || (g->allFinite() && H->allFinite()));
};
std::vector<LMBlock> blocks(1);
blocks[0].size = 3;
LMOptions options;
if (data.max_iterations > 0)
options.max_num_iterations = data.max_iterations;
options.max_iterations = data.max_iterations;
else
options.max_solver_time_in_seconds = data.max_time;
options.logging_type = ceres::LoggingType::SILENT;
options.num_threads = 1;
ceres::Solver::Summary summary;
ceres::Solve(options, &problem, &summary);
options.max_time_s = data.max_time;
const LMSummary summary = SolveLM(rot_aa, blocks, options, evaluate);
if (!summary.IsSolutionUsable())
return false;
@@ -747,7 +650,7 @@ bool XtalOptimizerRotationOnly(XtalOptimizerData &data,
// rotating the reciprocal vectors (a*, b*, c*) by the same R. No
// transpose or inversion of R is needed here.
double R_raw[9];
ceres::AngleAxisToRotationMatrix(rot_aa, R_raw); // row-major 3x3
ceres::AngleAxisToRotationMatrix(rot_aa.data(), R_raw); // row-major 3x3
Eigen::Matrix3d R;
R << R_raw[0], R_raw[3], R_raw[6],