Loading...
Searching...
No Matches
InternalCoordinates.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
6
7#include <Eigen/Eigenvalues>
8#include <Eigen/SparseQR>
9#include <algorithm>
10#include <array>
11#include <cmath>
12#include <limits>
13#include <set>
14#include <stdexcept>
15
17#include "MinImage.h"
18
19namespace gpr {
20namespace geometry {
21
22namespace {
23
24constexpr double kPi = 3.141592653589793238462643383279502884;
25
26void validateAtomIndex(int atom, int n_atoms)
27{
28 if (atom < 0 || atom >= n_atoms) {
29 throw std::invalid_argument(
30 "internal coordinate atom index is invalid");
31 }
32}
33
34void validateMovingAtoms(int n_atoms, const std::vector<char>& moving_atoms)
35{
36 if (!moving_atoms.empty() &&
37 static_cast<int>(moving_atoms.size()) != n_atoms) {
38 throw std::invalid_argument(
39 "internal coordinate moving-atom mask size mismatch");
40 }
41}
42
43void validateGeometryPositions(int n_atoms, const Eigen::VectorXd& positions)
44{
45 if (n_atoms < 0) {
46 throw std::invalid_argument(
47 "internal coordinate atom count is invalid");
48 }
49 if (positions.size() != static_cast<Eigen::Index>(3 * n_atoms) ||
50 !positions.allFinite()) {
51 throw std::invalid_argument(
52 "internal coordinate geometry has invalid shape or values");
53 }
54}
55
56bool atomIsMoving(int atom, const std::vector<char>& moving_atoms)
57{
58 return moving_atoms.empty() ||
59 moving_atoms[static_cast<std::size_t>(atom)] != 0;
60}
61
62Eigen::Vector3d atomPosition(const Eigen::VectorXd& x, int atom)
63{
64 if (atom < 0 || static_cast<Eigen::Index>(3 * atom + 2) >= x.size()) {
65 throw std::invalid_argument(
66 "internal coordinate atom index is invalid");
67 }
68 Eigen::Vector3d out;
69 out << x[3 * atom], x[3 * atom + 1], x[3 * atom + 2];
70 return out;
71}
72
73void addAtomGradient(Eigen::VectorXd& gradient, int atom,
74 const Eigen::Vector3d& value)
75{
76 if (atom < 0 ||
77 static_cast<Eigen::Index>(3 * atom + 2) >= gradient.size()) {
78 throw std::invalid_argument(
79 "internal coordinate atom index is invalid");
80 }
81 gradient.segment<3>(3 * atom) += value;
82}
83
84double primitiveValue(const PrimitiveInternal& primitive,
85 const Eigen::VectorXd& x, const PairBox& box)
86{
87 if (primitive.kind == PrimitiveKind::Bond) {
88 const auto a = atomPosition(x, primitive.atoms[0]);
89 const auto b = atomPosition(x, primitive.atoms[1]);
90 const double r = box.displacement(a, b).norm();
91 if (r <= std::numeric_limits<double>::min()) {
93 "internal coordinate bond has zero length");
94 }
95 return r;
96 }
97 if (primitive.kind == PrimitiveKind::Angle) {
98 const auto a = atomPosition(x, primitive.atoms[0]);
99 const auto b = atomPosition(x, primitive.atoms[1]);
100 const auto c = atomPosition(x, primitive.atoms[2]);
101 const auto u = box.displacement(b, a);
102 const auto v = box.displacement(b, c);
103 const double denom = u.norm() * v.norm();
104 if (denom <= std::numeric_limits<double>::min()) {
106 "internal coordinate angle has zero-length leg");
107 }
108 return std::atan2(u.cross(v).norm(), u.dot(v));
109 }
110 if (primitive.kind == PrimitiveKind::LinearBend) {
111 const auto a = atomPosition(x, primitive.atoms[0]);
112 const auto b = atomPosition(x, primitive.atoms[1]);
113 const auto c = atomPosition(x, primitive.atoms[2]);
114 const auto u = box.displacement(b, a);
115 const auto v = box.displacement(b, c);
116 const double ru = u.norm();
117 const double rv = v.norm();
118 if (ru <= std::numeric_limits<double>::min() ||
119 rv <= std::numeric_limits<double>::min()) {
121 "internal coordinate linear bend has zero-length leg");
122 }
123 return primitive.reference.dot(u / ru + v / rv);
124 }
125
126 const auto a = atomPosition(x, primitive.atoms[0]);
127 const auto b = atomPosition(x, primitive.atoms[1]);
128 const auto c = atomPosition(x, primitive.atoms[2]);
129 const auto d = atomPosition(x, primitive.atoms[3]);
130 const auto dx1 = box.displacement(a, b);
131 const auto dx2 = box.displacement(b, c);
132 const auto dx3 = box.displacement(c, d);
133 const auto n1 = dx1.cross(dx2);
134 const auto n2 = dx2.cross(dx3);
135 const double numer = dx2.dot(n1.cross(n2));
136 const double denom = dx2.norm() * n1.dot(n2);
137 const double norm2 = numer * numer + denom * denom;
138 if (norm2 <= std::numeric_limits<double>::min()) {
140 "internal coordinate dihedral has degenerate plane");
141 }
142 return std::atan2(numer, denom);
143}
144
145void primitiveGradient(const PrimitiveInternal& primitive,
146 const Eigen::VectorXd& x, const PairBox& box,
147 Eigen::VectorXd& gradient)
148{
149 if (gradient.size() != x.size()) {
150 gradient.resize(x.size());
151 }
152 gradient.setZero();
153 if (primitive.kind == PrimitiveKind::Bond) {
154 const int ia = primitive.atoms[0];
155 const int ib = primitive.atoms[1];
156 const Eigen::Vector3d a = atomPosition(x, ia);
157 const Eigen::Vector3d b = atomPosition(x, ib);
158 const Eigen::Vector3d d = box.displacement(a, b);
159 const double r = d.norm();
160 if (r <= std::numeric_limits<double>::min()) {
162 "internal coordinate bond has zero length");
163 }
164 addAtomGradient(gradient, ia, -d / r);
165 addAtomGradient(gradient, ib, d / r);
166 return;
167 }
168
169 if (primitive.kind == PrimitiveKind::Angle) {
170 const int ia = primitive.atoms[0];
171 const int ib = primitive.atoms[1];
172 const int ic = primitive.atoms[2];
173 const Eigen::Vector3d a = atomPosition(x, ia);
174 const Eigen::Vector3d b = atomPosition(x, ib);
175 const Eigen::Vector3d c = atomPosition(x, ic);
176 const Eigen::Vector3d u = box.displacement(b, a);
177 const Eigen::Vector3d v = box.displacement(b, c);
178 const double ru = u.norm();
179 const double rv = v.norm();
180 const double denom = ru * rv;
181 if (denom <= std::numeric_limits<double>::min()) {
183 "internal coordinate angle has zero-length leg");
184 }
185 const Eigen::Vector3d cross = u.cross(v);
186 const double cross_norm = cross.norm();
187 const double sin_theta = cross_norm / denom;
188 const double sin2 = sin_theta * sin_theta;
189 if (angleIsCollinear(sin2)) {
190 // Cone point of the angle. With a bending-plane reference n0
191 // (recorded from a geometry where the triple is bent), the
192 // one-sided limit along the in-plane transverse direction
193 // p = n0 x u_hat is finite: both end atoms bend toward the same
194 // side of the axis, so d theta / d a = -p/|u|,
195 // d theta / d c = -p/|v|, d theta / d b = -(sum).
196 // Without a reference the direction is undefined.
197 if (primitive.reference.squaredNorm() > 0.0) {
198 const Eigen::Vector3d uh = u / ru;
199 Eigen::Vector3d p = primitive.reference.cross(uh);
200 const double pn = p.norm();
201 if (pn > std::numeric_limits<double>::min()) {
202 p /= pn;
203 const Eigen::Vector3d da = -p / ru;
204 const Eigen::Vector3d dc = -p / rv;
205 addAtomGradient(gradient, ia, da);
206 addAtomGradient(gradient, ib, -da - dc);
207 addAtomGradient(gradient, ic, dc);
208 return;
209 }
210 }
212 "internal coordinate angle is collinear");
213 }
214 // Each end-atom derivative is perpendicular to its bond and
215 // has magnitude 1 / bond length, including near-linear bends.
216 const Eigen::Vector3d normal = cross / cross_norm;
217 const Eigen::Vector3d dtheta_du = (u / ru).cross(normal) / ru;
218 const Eigen::Vector3d dtheta_dv = normal.cross(v / rv) / rv;
219 addAtomGradient(gradient, ia, dtheta_du);
220 addAtomGradient(gradient, ib, -dtheta_du - dtheta_dv);
221 addAtomGradient(gradient, ic, dtheta_dv);
222 return;
223 }
224
225 if (primitive.kind == PrimitiveKind::LinearBend) {
226 // d(n . u_hat)/da = (I - u_hat u_hat^T) n / |u|; same for v at c;
227 // atom b carries minus the sum. Smooth for every non-degenerate leg.
228 const int ia = primitive.atoms[0];
229 const int ib = primitive.atoms[1];
230 const int ic = primitive.atoms[2];
231 const Eigen::Vector3d a = atomPosition(x, ia);
232 const Eigen::Vector3d b = atomPosition(x, ib);
233 const Eigen::Vector3d c = atomPosition(x, ic);
234 const Eigen::Vector3d u = box.displacement(b, a);
235 const Eigen::Vector3d v = box.displacement(b, c);
236 const double ru = u.norm();
237 const double rv = v.norm();
238 if (ru <= std::numeric_limits<double>::min() ||
239 rv <= std::numeric_limits<double>::min()) {
241 "internal coordinate linear bend has zero-length leg");
242 }
243 const Eigen::Vector3d uh = u / ru;
244 const Eigen::Vector3d vh = v / rv;
245 const Eigen::Vector3d& n = primitive.reference;
246 const Eigen::Vector3d da = (n - uh.dot(n) * uh) / ru;
247 const Eigen::Vector3d dc = (n - vh.dot(n) * vh) / rv;
248 addAtomGradient(gradient, ia, da);
249 addAtomGradient(gradient, ib, -da - dc);
250 addAtomGradient(gradient, ic, dc);
251 return;
252 }
253
254 const int ia = primitive.atoms[0];
255 const int ib = primitive.atoms[1];
256 const int ic = primitive.atoms[2];
257 const int id = primitive.atoms[3];
258 const Eigen::Vector3d a = atomPosition(x, ia);
259 const Eigen::Vector3d b = atomPosition(x, ib);
260 const Eigen::Vector3d c = atomPosition(x, ic);
261 const Eigen::Vector3d d = atomPosition(x, id);
262 const Eigen::Vector3d dx1 = box.displacement(a, b);
263 const Eigen::Vector3d dx2 = box.displacement(b, c);
264 const Eigen::Vector3d dx3 = box.displacement(c, d);
265 const double dx2_norm = dx2.norm();
266 if (dx2_norm <= std::numeric_limits<double>::min()) {
268 "internal coordinate dihedral has zero central bond");
269 }
270 const Eigen::Vector3d n1 = dx1.cross(dx2);
271 const Eigen::Vector3d n2 = dx2.cross(dx3);
272 const double numer = dx2.dot(n1.cross(n2));
273 const double denom_dihedral = dx2_norm * n1.dot(n2);
274 const double atan_norm2 = numer * numer + denom_dihedral * denom_dihedral;
275 if (atan_norm2 <= std::numeric_limits<double>::min()) {
277 "internal coordinate dihedral has degenerate plane");
278 }
279
280 // Loop invariants: the twelve directional passes below each rebuilt
281 // these from the same unchanged n1, n2, so they carry identical
282 // values every pass.
283 const Eigen::Vector3d n1_cross_n2 = n1.cross(n2);
284 const double n1_dot_n2 = n1.dot(n2);
285 const std::array<int, 4> atoms = {ia, ib, ic, id};
286 for (int local_atom = 0; local_atom < 4; ++local_atom) {
287 for (int dim = 0; dim < 3; ++dim) {
288 Eigen::Vector3d ddx1 = Eigen::Vector3d::Zero();
289 Eigen::Vector3d ddx2 = Eigen::Vector3d::Zero();
290 Eigen::Vector3d ddx3 = Eigen::Vector3d::Zero();
291 Eigen::Vector3d e = Eigen::Vector3d::Zero();
292 e(dim) = 1.0;
293 if (local_atom == 0) {
294 ddx1 -= e;
295 } else if (local_atom == 1) {
296 ddx1 += e;
297 ddx2 -= e;
298 } else if (local_atom == 2) {
299 ddx2 += e;
300 ddx3 -= e;
301 } else {
302 ddx3 += e;
303 }
304
305 const Eigen::Vector3d dn1 = ddx1.cross(dx2) + dx1.cross(ddx2);
306 const Eigen::Vector3d dn2 = ddx2.cross(dx3) + dx2.cross(ddx3);
307 const double dnumer =
308 ddx2.dot(n1_cross_n2) + dx2.dot(dn1.cross(n2) + n1.cross(dn2));
309 const double dnorm_dx2 = dx2.dot(ddx2) / dx2_norm;
310 const double ddenom =
311 dnorm_dx2 * n1_dot_n2 + dx2_norm * (dn1.dot(n2) + n1.dot(dn2));
312 gradient(3 * atoms[static_cast<std::size_t>(local_atom)] + dim) =
313 (denom_dihedral * dnumer - numer * ddenom) / atan_norm2;
314 }
315 }
316}
317
321template <typename Real>
322Real primitiveValueFromLegs(
323 const PrimitiveInternal& primitive,
324 const std::array<Eigen::Matrix<Real, 3, 1>, 3>& legs)
325{
327 using std::sqrt;
328 switch (primitive.kind) {
330 return sqrt(legs[0].dot(legs[0]));
332 const Eigen::Matrix<Real, 3, 1> cross = legs[0].cross(legs[1]);
333 const Real sine = sqrt(cross.dot(cross));
334 const Real cosine = legs[0].dot(legs[1]);
335 return nestedAtan2(sine, cosine);
336 }
338 const Eigen::Matrix<Real, 3, 1> reference =
339 primitive.reference.unaryExpr(
340 [](double v) { return derivatives::lift<Real>(v); });
341 return reference.dot(legs[0] / sqrt(legs[0].dot(legs[0]))) +
342 reference.dot(legs[1] / sqrt(legs[1].dot(legs[1])));
343 }
345 const Eigen::Matrix<Real, 3, 1> n1 = legs[0].cross(legs[1]);
346 const Eigen::Matrix<Real, 3, 1> n2 = legs[1].cross(legs[2]);
347 const Real numer = legs[1].dot(n1.cross(n2));
348 const Real denom = sqrt(legs[1].dot(legs[1])) * n1.dot(n2);
349 return nestedAtan2(numer, denom);
350 }
351 }
352 throw std::logic_error("unknown internal coordinate primitive");
353}
354
359void primitiveDirectionalGradient(const PrimitiveInternal& primitive,
360 const Eigen::VectorXd& x,
361 const Eigen::VectorXd& direction,
362 const PairBox& box, Eigen::VectorXd& out)
363{
364 using Inner = Eigen::AutoDiffScalar<Eigen::Matrix<double, 1, 1>>;
365 using Outer = Eigen::AutoDiffScalar<Eigen::Matrix<Inner, 12, 1>>;
366 const int arity = primitive.arity();
367 std::array<Eigen::Vector3d, 4> atoms;
368 std::array<Eigen::Matrix<Outer, 3, 1>, 4> local;
369 for (int k = 0; k < arity; ++k) {
370 const int atom = primitive.atoms[static_cast<std::size_t>(k)];
371 atoms[static_cast<std::size_t>(k)] = atomPosition(x, atom);
372 for (int dim = 0; dim < 3; ++dim) {
373 Eigen::Matrix<Inner, 12, 1> seed;
374 for (int j = 0; j < 12; ++j)
375 seed(j) = Inner(j == 3 * k + dim ? 1.0 : 0.0,
376 Eigen::Matrix<double, 1, 1>::Zero());
377 local[static_cast<std::size_t>(k)](dim) = Outer(
378 Inner(x(3 * atom + dim), Eigen::Matrix<double, 1, 1>::Constant(
379 direction(3 * atom + dim))),
380 seed);
381 }
382 }
383 // The minimum image is locally constant, so each leg is the plain
384 // difference plus a fixed lattice shift.
385 const auto leg = [&](int from, int to) {
386 const auto f = static_cast<std::size_t>(from);
387 const auto t = static_cast<std::size_t>(to);
388 const Eigen::Vector3d shift =
389 box.displacement(atoms[f], atoms[t]) - (atoms[t] - atoms[f]);
390 Eigen::Matrix<Outer, 3, 1> out = local[t] - local[f];
391 for (int dim = 0; dim < 3; ++dim)
392 out(dim) += derivatives::lift<Outer>(shift(dim));
393 return out;
394 };
395 std::array<Eigen::Matrix<Outer, 3, 1>, 3> legs;
396 switch (primitive.kind) {
398 legs[0] = leg(0, 1);
399 break;
402 legs[0] = leg(1, 0);
403 legs[1] = leg(1, 2);
404 break;
406 legs[0] = leg(0, 1);
407 legs[1] = leg(1, 2);
408 legs[2] = leg(2, 3);
409 break;
410 }
411 const Outer value = primitiveValueFromLegs(primitive, legs);
412 for (int k = 0; k < arity; ++k)
413 for (int dim = 0; dim < 3; ++dim)
414 out(3 * primitive.atoms[static_cast<std::size_t>(k)] + dim) +=
415 value.derivatives()(3 * k + dim).derivatives()(0);
416}
417
418double wrapAngularResidual(double value)
419{
420 if (!std::isfinite(value)) return value;
421 return std::remainder(value, 2.0 * kPi);
422}
423
424std::pair<int, int> normalizedBond(int a, int b)
425{
426 if (a == b) {
427 throw std::invalid_argument(
428 "internal coordinate bond is self-referential");
429 }
430 return (a < b) ? std::make_pair(a, b) : std::make_pair(b, a);
431}
432
433} // namespace
434
436{
439 out.atoms = {a, b, -1, -1};
440 return out;
441}
442
444{
447 out.atoms = {a, b, c, -1};
448 return out;
449}
450
452{
455 out.atoms = {a, b, c, d};
456 return out;
457}
458
460 int a, int b, int c, const Eigen::Vector3d& reference)
461{
464 out.atoms = {a, b, c, -1};
465 out.reference = reference;
466 return out;
467}
468
470{
471 switch (kind) {
473 return 2;
476 return 3;
478 return 4;
479 }
480 return 0;
481}
482
483bool angleIsCollinear(double sin2)
484{
485 // The normalized bending-plane normal carries 1/sin(theta): the plane
486 // is a usable chart direction only while that amplification stays inside
487 // the conditioning bound the chart itself applies to its B-matrix,
488 // kappa_max = 1/sqrt(eps) (the singular-value cutoff of the chart SVD).
489 // 1/sin(theta) <= 1/sqrt(eps) <=> sin^2(theta) >= eps. Below that the
490 // angle is treated as collinear and its smooth replacement (the linear
491 // bend pair) or the limit gradient takes over.
492 constexpr double eps = std::numeric_limits<double>::epsilon();
493 return !(sin2 > eps);
494}
495
496namespace {
497
498bool tripleIsCollinear(const Eigen::VectorXd& x, const PairBox& box, int ia,
499 int ib, int ic, Eigen::Vector3d* axis)
500{
501 const Eigen::Vector3d u =
502 box.displacement(atomPosition(x, ib), atomPosition(x, ia));
503 const Eigen::Vector3d v =
504 box.displacement(atomPosition(x, ib), atomPosition(x, ic));
505 const double denom = u.norm() * v.norm();
506 if (denom <= std::numeric_limits<double>::min()) return false;
507 // The cross product resolves small bends without subtracting two
508 // numbers near one. Topology and gradient evaluation share this test.
509 const double sin_theta = u.cross(v).norm() / denom;
510 if (!angleIsCollinear(sin_theta * sin_theta)) return false;
511 if (axis) {
512 // u and v are antiparallel: u - v is twice the axis.
513 const Eigen::Vector3d d = u / u.norm() - v / v.norm();
514 *axis = d / d.norm();
515 }
516 return true;
517}
518
519} // namespace
520
521std::vector<PrimitiveInternal> resolveCollinearAngles(
522 const std::vector<PrimitiveInternal>& primitives,
523 const Eigen::VectorXd& positions, const std::array<double, 9>& cell)
524{
525 const PairBox box(cell);
526 std::vector<PrimitiveInternal> out;
527 out.reserve(primitives.size() + 4);
528 for (const auto& p: primitives) {
529 if (p.kind == PrimitiveKind::Angle) {
530 Eigen::Vector3d axis;
531 if (!tripleIsCollinear(positions, box, p.atoms[0], p.atoms[1],
532 p.atoms[2], &axis)) {
533 PrimitiveInternal kept = p;
534 const Eigen::Vector3d u =
535 box.displacement(atomPosition(positions, p.atoms[1]),
536 atomPosition(positions, p.atoms[0]));
537 const Eigen::Vector3d v =
538 box.displacement(atomPosition(positions, p.atoms[1]),
539 atomPosition(positions, p.atoms[2]));
540 const Eigen::Vector3d nrm = u.cross(v);
541 const double nn = nrm.norm();
542 if (nn > std::numeric_limits<double>::min())
543 kept.reference = nrm / nn;
544 out.push_back(kept);
545 continue;
546 }
547 // Orthonormal references: axis x (least-aligned Cartesian unit)
548 // and axis x that; both perpendicular to the molecular axis.
549 int least = 0;
550 for (int k = 1; k < 3; ++k) {
551 if (std::abs(axis(k)) < std::abs(axis(least))) least = k;
552 }
553 Eigen::Vector3d e = Eigen::Vector3d::Zero();
554 e(least) = 1.0;
555 Eigen::Vector3d n1 = axis.cross(e);
556 n1 /= n1.norm();
557 const Eigen::Vector3d n2 = axis.cross(n1);
558 out.push_back(PrimitiveInternal::linearBend(p.atoms[0], p.atoms[1],
559 p.atoms[2], n1));
560 out.push_back(PrimitiveInternal::linearBend(p.atoms[0], p.atoms[1],
561 p.atoms[2], n2));
562 continue;
563 }
564 if (p.kind == PrimitiveKind::Dihedral) {
565 if (tripleIsCollinear(positions, box, p.atoms[0], p.atoms[1],
566 p.atoms[2], nullptr) ||
567 tripleIsCollinear(positions, box, p.atoms[1], p.atoms[2],
568 p.atoms[3], nullptr)) {
569 continue;
570 }
571 }
572 out.push_back(p);
573 }
574 return out;
575}
576
577std::vector<PrimitiveInternal> primitiveTopologyFromBondGraph(
578 int n_atoms, const std::vector<std::pair<int, int>>& bonds)
579{
580 if (n_atoms < 0) {
581 throw std::invalid_argument(
582 "internal coordinate atom count is invalid");
583 }
584
585 std::set<std::pair<int, int>> unique_bonds;
586 for (const auto& bond: bonds) {
587 validateAtomIndex(bond.first, n_atoms);
588 validateAtomIndex(bond.second, n_atoms);
589 unique_bonds.insert(normalizedBond(bond.first, bond.second));
590 }
591
592 std::vector<std::vector<int>> neighbours(static_cast<std::size_t>(n_atoms));
593 std::vector<PrimitiveInternal> primitives;
594 primitives.reserve(unique_bonds.size());
595 for (const auto& bond: unique_bonds) {
596 primitives.push_back(PrimitiveInternal::bond(bond.first, bond.second));
597 neighbours[static_cast<std::size_t>(bond.first)].push_back(bond.second);
598 neighbours[static_cast<std::size_t>(bond.second)].push_back(bond.first);
599 }
600 for (auto& atoms: neighbours)
601 std::sort(atoms.begin(), atoms.end());
602
603 for (int center = 0; center < n_atoms; ++center) {
604 const auto& atoms = neighbours[static_cast<std::size_t>(center)];
605 for (std::size_t i = 0; i < atoms.size(); ++i) {
606 for (std::size_t k = i + 1; k < atoms.size(); ++k) {
607 primitives.push_back(
608 PrimitiveInternal::angle(atoms[i], center, atoms[k]));
609 }
610 }
611 }
612
613 std::set<std::array<int, 4>> unique_dihedrals;
614 for (const auto& bond: unique_bonds) {
615 const int b = bond.first;
616 const int c = bond.second;
617 for (const int a: neighbours[static_cast<std::size_t>(b)]) {
618 if (a == c) continue;
619 for (const int d: neighbours[static_cast<std::size_t>(c)]) {
620 if (d == b || d == a) continue;
621 std::array<int, 4> forward = {a, b, c, d};
622 std::array<int, 4> reverse = {d, c, b, a};
623 unique_dihedrals.insert(std::min(forward, reverse));
624 }
625 }
626 }
627 for (const auto& atoms: unique_dihedrals) {
628 primitives.push_back(PrimitiveInternal::dihedral(atoms[0], atoms[1],
629 atoms[2], atoms[3]));
630 }
631
632 return primitives;
633}
634
635namespace {
636
637// Cutoff-free proximity graphs under the minimum-image convention.
638//
639// For a source atom a, every atom c that can block the edge (a, b) satisfies
640// |c - a| < |b - a|: Gabriel needs |c - m| < |d|/2 with m the midpoint of the
641// MIC displacement d, so |c - a| <= |c - m| + |m - a| < |d|; the relative
642// neighbourhood lune needs max(|c - a|, |c - b|) < |d| directly. Hence with
643// the neighbours of a sorted by MIC distance, the blockers of the candidate
644// at rank r are exactly the strictly closer prefix. That prefix scan is the
645// same exact graph as the all-atoms test, cutoff-free and without a k.
646std::vector<std::pair<int, int>> pairwiseBondGraph(
647 int n_atoms, const Eigen::VectorXd& positions,
648 const std::vector<char>& moving_atoms, const std::array<double, 9>& cell,
649 BondGraphKind kind)
650{
651 if (n_atoms < 0 ||
652 positions.size() != static_cast<Eigen::Index>(3 * n_atoms)) {
653 throw std::invalid_argument("bond graph positions have invalid shape");
654 }
655 validateMovingAtoms(n_atoms, moving_atoms);
656 const PairBox box(cell);
657 const auto moving = [&](int atom) {
658 return moving_atoms.empty() ||
659 moving_atoms[static_cast<std::size_t>(atom)] != 0;
660 };
661 struct Neighbour {
662 int atom;
663 double dist2;
664 Eigen::Vector3d displacement;
665 };
666 std::vector<std::pair<int, int>> bonds;
667 std::vector<Neighbour> sorted;
668 sorted.reserve(static_cast<std::size_t>(std::max(0, n_atoms - 1)));
669 for (int a = 0; a < n_atoms; ++a) {
670 const Eigen::Vector3d xa = positions.segment<3>(3 * a);
671 sorted.clear();
672 for (int c = 0; c < n_atoms; ++c) {
673 if (c == a) continue;
674 const Eigen::Vector3d d =
675 box.displacement(xa, positions.segment<3>(3 * c));
676 sorted.push_back({c, d.squaredNorm(), d});
677 }
678 std::stable_sort(sorted.begin(), sorted.end(),
679 [](const Neighbour& l, const Neighbour& r) {
680 return l.dist2 < r.dist2;
681 });
682 for (std::size_t r = 0; r < sorted.size(); ++r) {
683 const Neighbour& cand = sorted[r];
684 const int b = cand.atom;
685 if (b < a) continue; // each unordered pair once
686 if (!moving(a) && !moving(b)) continue;
687 const double dab2 = cand.dist2;
688 bool blocked = false;
689 if (kind == BondGraphKind::Gabriel) {
690 const Eigen::Vector3d midpoint = xa + 0.5 * cand.displacement;
691 const double radius2 = 0.25 * dab2;
692 for (std::size_t q = 0; q < r && !blocked; ++q) {
693 if (!(sorted[q].dist2 < dab2)) break;
694 const Eigen::Vector3d xq =
695 positions.segment<3>(3 * sorted[q].atom);
696 blocked = box.dist2(midpoint, xq) < radius2;
697 }
698 } else {
699 const Eigen::Vector3d xb = xa + cand.displacement;
700 for (std::size_t q = 0; q < r && !blocked; ++q) {
701 if (!(sorted[q].dist2 < dab2)) break;
702 const Eigen::Vector3d xq =
703 positions.segment<3>(3 * sorted[q].atom);
704 blocked =
705 std::max(sorted[q].dist2, box.dist2(xb, xq)) < dab2;
706 }
707 }
708 if (!blocked) bonds.emplace_back(a, b);
709 }
710 }
711 std::sort(bonds.begin(), bonds.end());
712 return bonds;
713}
714
715} // namespace
716
717std::vector<PrimitiveInternal> resolveCollinearAngles(
718 const std::vector<PrimitiveInternal>& primitives,
719 const std::vector<Eigen::VectorXd>& geometries,
720 const std::array<double, 9>& cell)
721{
722 if (geometries.empty()) return primitives;
723 const PairBox box(cell);
724 std::vector<PrimitiveInternal> out;
725 out.reserve(primitives.size() + 4);
726 for (const auto& p: primitives) {
727 if (p.kind == PrimitiveKind::Angle) {
728 bool resolved = false;
729 for (const auto& x: geometries) {
730 Eigen::Vector3d axis;
731 if (tripleIsCollinear(x, box, p.atoms[0], p.atoms[1],
732 p.atoms[2], &axis)) {
733 int least = 0;
734 for (int k = 1; k < 3; ++k) {
735 if (std::abs(axis(k)) < std::abs(axis(least)))
736 least = k;
737 }
738 Eigen::Vector3d e = Eigen::Vector3d::Zero();
739 e(least) = 1.0;
740 Eigen::Vector3d n1 = axis.cross(e);
741 n1 /= n1.norm();
742 const Eigen::Vector3d n2 = axis.cross(n1);
744 p.atoms[0], p.atoms[1], p.atoms[2], n1));
746 p.atoms[0], p.atoms[1], p.atoms[2], n2));
747 resolved = true;
748 break;
749 }
750 }
751 if (!resolved) {
752 // Keep the angle; remember the bending plane of the first
753 // geometry where it is bent, the reference for the limit
754 // gradient should a later query meet the triple collinear.
755 PrimitiveInternal kept = p;
756 for (const auto& x: geometries) {
757 const Eigen::Vector3d u =
758 box.displacement(atomPosition(x, p.atoms[1]),
759 atomPosition(x, p.atoms[0]));
760 const Eigen::Vector3d v =
761 box.displacement(atomPosition(x, p.atoms[1]),
762 atomPosition(x, p.atoms[2]));
763 const Eigen::Vector3d nrm = u.cross(v);
764 const double nn = nrm.norm();
765 if (nn > std::numeric_limits<double>::min()) {
766 kept.reference = nrm / nn;
767 break;
768 }
769 }
770 out.push_back(kept);
771 }
772 continue;
773 }
774 if (p.kind == PrimitiveKind::Dihedral) {
775 bool degenerate = false;
776 for (const auto& x: geometries) {
777 if (tripleIsCollinear(x, box, p.atoms[0], p.atoms[1],
778 p.atoms[2], nullptr) ||
779 tripleIsCollinear(x, box, p.atoms[1], p.atoms[2],
780 p.atoms[3], nullptr)) {
781 degenerate = true;
782 break;
783 }
784 }
785 if (degenerate) continue;
786 }
787 out.push_back(p);
788 }
789 return out;
790}
791
792std::vector<std::pair<int, int>> gabrielBondGraph(
793 int n_atoms, const Eigen::VectorXd& positions,
794 const std::vector<char>& moving_atoms, const std::array<double, 9>& cell)
795{
796 return bondGraph(n_atoms, positions, moving_atoms, BondGraphKind::Gabriel,
797 cell);
798}
799
800std::vector<std::pair<int, int>> relativeNeighborhoodBondGraph(
801 int n_atoms, const Eigen::VectorXd& positions,
802 const std::vector<char>& moving_atoms, const std::array<double, 9>& cell)
803{
804 return bondGraph(n_atoms, positions, moving_atoms,
806}
807
808std::vector<std::pair<int, int>> bondGraph(
809 int n_atoms, const Eigen::VectorXd& positions,
810 const std::vector<char>& moving_atoms, BondGraphKind kind,
811 const std::array<double, 9>& cell)
812{
813 return pairwiseBondGraph(n_atoms, positions, moving_atoms, cell, kind);
814}
815
816std::vector<std::pair<int, int>> unionBondGraph(
817 int n_atoms, const std::vector<Eigen::VectorXd>& geometries,
818 const std::vector<char>& moving_atoms, BondGraphKind kind,
819 const std::array<double, 9>& cell)
820{
821 std::set<std::pair<int, int>> bonds;
822 for (const auto& positions: geometries) {
823 const auto graph =
824 bondGraph(n_atoms, positions, moving_atoms, kind, cell);
825 bonds.insert(graph.begin(), graph.end());
826 }
827 return {bonds.begin(), bonds.end()};
828}
829
830std::vector<PrimitiveInternal> primitiveTopologyFromGeometry(
831 int n_atoms, const Eigen::VectorXd& positions,
832 const std::vector<char>& moving_atoms, BondGraphKind kind,
833 const std::array<double, 9>& cell)
834{
837 n_atoms, bondGraph(n_atoms, positions, moving_atoms, kind, cell)),
838 positions, cell);
839}
840
841int countBonds(const std::vector<PrimitiveInternal>& primitives)
842{
843 return static_cast<int>(std::count_if(
844 primitives.begin(), primitives.end(), [](const PrimitiveInternal& p) {
845 return p.kind == PrimitiveKind::Bond;
846 }));
847}
848
849int countAngles(const std::vector<PrimitiveInternal>& primitives)
850{
851 return static_cast<int>(std::count_if(
852 primitives.begin(), primitives.end(), [](const PrimitiveInternal& p) {
853 return p.kind == PrimitiveKind::Angle;
854 }));
855}
856
857int countDihedrals(const std::vector<PrimitiveInternal>& primitives)
858{
859 return static_cast<int>(std::count_if(
860 primitives.begin(), primitives.end(), [](const PrimitiveInternal& p) {
861 return p.kind == PrimitiveKind::Dihedral;
862 }));
863}
864
866 int n_atoms, std::vector<char> moving_atoms,
867 std::vector<PrimitiveInternal> primitives, std::array<double, 9> cell)
868 : n_atoms_(n_atoms),
869 moving_atoms_(std::move(moving_atoms)),
870 primitives_(std::move(primitives)),
871 active_columns_(),
872 cell_(cell)
873{
874 if (n_atoms_ < 0) {
875 throw std::invalid_argument(
876 "internal coordinate atom count is invalid");
877 }
878 validateMovingAtoms(n_atoms_, moving_atoms_);
879 for (const auto& primitive: primitives_) {
880 for (int i = 0; i < primitive.arity(); ++i) {
881 validateAtomIndex(primitive.atoms[static_cast<std::size_t>(i)],
882 n_atoms_);
883 }
884 }
885
886 active_columns_.reserve(static_cast<std::size_t>(3 * n_atoms_));
887 for (int atom = 0; atom < n_atoms_; ++atom) {
888 const bool moving = moving_atoms_.empty() ||
889 moving_atoms_[static_cast<std::size_t>(atom)] != 0;
890 if (!moving) continue;
891 for (int dim = 0; dim < 3; ++dim) {
892 active_columns_.push_back(3 * atom + dim);
893 }
894 }
895}
896
898 const InternalCoordinateSet& other) const noexcept
899{
900 if (n_atoms_ != other.n_atoms_ || moving_atoms_ != other.moving_atoms_ ||
901 cell_ != other.cell_ || primitives_.size() != other.primitives_.size())
902 return false;
903 for (std::size_t i = 0; i < primitives_.size(); ++i) {
904 const auto& a = primitives_[i];
905 const auto& b = other.primitives_[i];
906 if (a.kind != b.kind || a.atoms != b.atoms ||
907 (a.reference.array() != b.reference.array()).any())
908 return false;
909 }
910 return true;
911}
912
913void InternalCoordinateSet::validatePositions(
914 const Eigen::VectorXd& positions) const
915{
916 if (positions.size() != static_cast<Eigen::Index>(3 * n_atoms_) ||
917 !positions.allFinite()) {
918 throw std::invalid_argument(
919 "internal coordinate positions have invalid shape or values");
920 }
921}
922
924 const Eigen::VectorXd& positions) const
925{
926 validatePositions(positions);
927 const PairBox box(cell_);
928 Eigen::VectorXd out(static_cast<Eigen::Index>(primitives_.size()));
929 for (Eigen::Index row = 0;
930 row < static_cast<Eigen::Index>(primitives_.size()); ++row) {
931 out(row) = primitiveValue(primitives_[static_cast<std::size_t>(row)],
932 positions, box);
933 }
934 return out;
935}
936
938 const Eigen::VectorXd& positions) const
939{
940 validatePositions(positions);
941 Eigen::MatrixXd J(static_cast<Eigen::Index>(primitives_.size()),
942 positions.size());
943 J.setZero();
944 const PairBox box(cell_);
945 Eigen::VectorXd gradient(positions.size());
946 for (Eigen::Index row = 0;
947 row < static_cast<Eigen::Index>(primitives_.size()); ++row) {
948 primitiveGradient(primitives_[static_cast<std::size_t>(row)], positions,
949 box, gradient);
950 J.row(row) = gradient.transpose();
951 }
952 return J;
953}
954
956 const Eigen::VectorXd& positions, const Eigen::VectorXd& direction) const
957{
958 validatePositions(positions);
959 if (direction.size() != positions.size() || !direction.allFinite()) {
960 throw std::invalid_argument(
961 "internal coordinate direction has invalid shape or values");
962 }
963 Eigen::MatrixXd out = Eigen::MatrixXd::Zero(
964 static_cast<Eigen::Index>(primitives_.size()), positions.size());
965 const PairBox box(cell_);
966 Eigen::VectorXd gradient(positions.size()), row_out(positions.size());
967 for (Eigen::Index row = 0;
968 row < static_cast<Eigen::Index>(primitives_.size()); ++row) {
969 const auto& primitive = primitives_[static_cast<std::size_t>(row)];
970 // Validates the geometry the same way the Jacobian does.
971 primitiveGradient(primitive, positions, box, gradient);
972 if (primitive.kind == PrimitiveKind::Angle) {
973 const Eigen::Vector3d b =
974 atomPosition(positions, primitive.atoms[1]);
975 const Eigen::Vector3d u = box.displacement(
976 b, atomPosition(positions, primitive.atoms[0]));
977 const Eigen::Vector3d v = box.displacement(
978 b, atomPosition(positions, primitive.atoms[2]));
979 const double sin_theta = u.cross(v).norm() / (u.norm() * v.norm());
980 if (angleIsCollinear(sin_theta * sin_theta)) {
982 "internal coordinate angle curvature is undefined at "
983 "collinearity");
984 }
985 }
986 row_out.setZero();
987 primitiveDirectionalGradient(primitive, positions, direction, box,
988 row_out);
989 if (!row_out.allFinite()) {
991 "internal coordinate curvature is undefined at this geometry");
992 }
993 out.row(row) = row_out.transpose();
994 }
995 return out;
996}
997
999 const Eigen::VectorXd& positions) const
1000{
1001 validatePositions(positions);
1002 Eigen::MatrixXd J(static_cast<Eigen::Index>(primitives_.size()),
1003 static_cast<Eigen::Index>(active_columns_.size()));
1004 J.setZero();
1005 const PairBox box(cell_);
1006 Eigen::VectorXd full_gradient(positions.size());
1007 for (Eigen::Index row = 0;
1008 row < static_cast<Eigen::Index>(primitives_.size()); ++row) {
1009 primitiveGradient(primitives_[static_cast<std::size_t>(row)], positions,
1010 box, full_gradient);
1011 for (Eigen::Index col = 0;
1012 col < static_cast<Eigen::Index>(active_columns_.size()); ++col) {
1013 J(row, col) =
1014 full_gradient(active_columns_[static_cast<std::size_t>(col)]);
1015 }
1016 }
1017 return J;
1018}
1019
1021 const Eigen::VectorXd& full_step) const
1022{
1023 if (full_step.size() != static_cast<Eigen::Index>(3 * n_atoms_) ||
1024 !full_step.allFinite()) {
1025 throw std::invalid_argument(
1026 "internal coordinate step has invalid shape or values");
1027 }
1028 Eigen::VectorXd step(static_cast<Eigen::Index>(active_columns_.size()));
1029 for (Eigen::Index col = 0;
1030 col < static_cast<Eigen::Index>(active_columns_.size()); ++col) {
1031 step(col) = full_step(active_columns_[static_cast<std::size_t>(col)]);
1032 }
1033 return step;
1034}
1035
1037 const Eigen::VectorXd& positions, const Eigen::VectorXd& direction) const
1038{
1039 validatePositions(positions);
1040 if (direction.size() != positions.size() || !direction.allFinite()) {
1041 throw std::invalid_argument(
1042 "internal coordinate direction has invalid shape or values");
1043 }
1044 const PairBox box(cell_);
1045 Eigen::VectorXd change(static_cast<Eigen::Index>(primitives_.size()));
1046 Eigen::VectorXd gradient(positions.size());
1047 for (Eigen::Index row = 0; row < change.size(); ++row) {
1048 primitiveGradient(primitives_[static_cast<std::size_t>(row)], positions,
1049 box, gradient);
1050 change(row) = gradient.dot(direction);
1051 }
1052 return change;
1053}
1054
1055Eigen::VectorXd InternalCoordinateSet::residualToTarget(
1056 const Eigen::VectorXd& target, const Eigen::VectorXd& current) const
1057{
1058 if (target.size() != current.size() ||
1059 target.size() != static_cast<Eigen::Index>(primitives_.size())) {
1060 throw std::invalid_argument(
1061 "internal coordinate target has invalid shape");
1062 }
1063 Eigen::VectorXd residual = target - current;
1064 for (Eigen::Index row = 0; row < residual.size(); ++row) {
1065 const auto kind = primitives_[static_cast<std::size_t>(row)].kind;
1066 if (kind == PrimitiveKind::Angle || kind == PrimitiveKind::Dihedral) {
1067 residual(row) = wrapAngularResidual(residual(row));
1068 }
1069 }
1070 return residual;
1071}
1072
1073namespace {
1074
1075struct SparseRow {
1076 std::array<Eigen::Index, 12> column{};
1077 std::array<double, 12> value{};
1078 int nnz = 0;
1079};
1080
1081void harvestRow(const PrimitiveInternal& primitive,
1082 const Eigen::VectorXd& gradient,
1083 const std::vector<Eigen::Index>& active_of_full,
1084 bool active_only, SparseRow& row)
1085{
1086 row.nnz = 0;
1087 const int slots = primitive.arity();
1088 for (int k = 0; k < slots; ++k) {
1089 const int atom = primitive.atoms[static_cast<std::size_t>(k)];
1090 if (atom < 0) continue;
1091 for (int dim = 0; dim < 3; ++dim) {
1092 const Eigen::Index full = static_cast<Eigen::Index>(3 * atom + dim);
1093 const double component = gradient(full);
1094 if (component == 0.0) continue;
1095 Eigen::Index column = full;
1096 if (active_only) {
1097 column = active_of_full[static_cast<std::size_t>(full)];
1098 if (column < 0) continue;
1099 }
1100 row.column[static_cast<std::size_t>(row.nnz)] = column;
1101 row.value[static_cast<std::size_t>(row.nnz)] = component;
1102 ++row.nnz;
1103 }
1104 }
1105}
1106
1107double sparseDot(const SparseRow& row, const Eigen::VectorXd& vector)
1108{
1109 double sum = 0.0;
1110 for (int i = 0; i < row.nnz; ++i) {
1111 sum += row.value[static_cast<std::size_t>(i)] *
1112 vector(row.column[static_cast<std::size_t>(i)]);
1113 }
1114 return sum;
1115}
1116
1117using SparseWilsonMatrix = Eigen::SparseMatrix<double>;
1118using SparseWilsonQr =
1119 Eigen::SparseQR<SparseWilsonMatrix, Eigen::COLAMDOrdering<int>>;
1120
1121// Leading right singular vectors of a compact factor, and S^{-1} U^T.
1122// ~threshold~ is the JacobiSVD prescribed threshold: singular values at or
1123// below threshold * sigma_max are dropped. The min-norm solution of
1124// factor * y = rhs is right * (inverse_left * rhs).
1125struct CompactRFactor {
1126 Eigen::MatrixXd right;
1127 Eigen::MatrixXd inverse_left;
1128};
1129
1130double wilsonSvdThreshold(Eigen::Index rows, Eigen::Index cols)
1131{
1132 return std::numeric_limits<double>::epsilon() *
1133 static_cast<double>(std::max(rows, cols));
1134}
1135
1136bool factorCompactR(const Eigen::MatrixXd& factor, double threshold,
1137 CompactRFactor& out, Eigen::VectorXd* singular = nullptr)
1138{
1139 if (factor.size() == 0 || !factor.allFinite()) return false;
1140 Eigen::JacobiSVD<Eigen::MatrixXd> svd(
1141 factor, Eigen::ComputeThinU | Eigen::ComputeThinV);
1142 svd.setThreshold(threshold);
1143 const Eigen::Index rank = svd.rank();
1144 if (rank <= 0) return false;
1145 out.right = svd.matrixV().leftCols(rank);
1146 out.inverse_left = svd.matrixU().leftCols(rank).transpose();
1147 out.inverse_left.array().colwise() /=
1148 svd.singularValues().head(rank).array();
1149 if (singular != nullptr) *singular = svd.singularValues().head(rank);
1150 return out.right.allFinite() && out.inverse_left.allFinite();
1151}
1152
1153// Sparse QR of a Wilson matrix. Pivoting stays at the underflow floor so
1154// the compact R still carries the numerical null columns; the SVD of that
1155// R, not the QR, decides the rank. This is the chart factorisation.
1156bool qrSparseWilson(const SparseWilsonMatrix& wilson, SparseWilsonQr& qr,
1157 Eigen::Index& compact_rows, Eigen::MatrixXd& r)
1158{
1159 qr.setPivotThreshold(std::numeric_limits<double>::min());
1160 qr.compute(wilson);
1161 if (qr.info() != Eigen::Success) return false;
1162 compact_rows = std::min(wilson.rows(), wilson.cols());
1163 r = Eigen::MatrixXd(qr.matrixR().topRows(compact_rows));
1164 return r.size() != 0 && r.allFinite();
1165}
1166
1167// Row space of B in the original column order, and S^{-1} U_R^T from the
1168// compact R. Applying Q^T first gives S^{-1} U^T without forming B^T.
1169bool factorSparseWilson(const SparseWilsonMatrix& wilson, SparseWilsonQr& qr,
1170 Eigen::Index& compact_rows,
1171 Eigen::MatrixXd& tangent_basis,
1172 Eigen::MatrixXd& inverse_left,
1173 Eigen::VectorXd* singular = nullptr)
1174{
1175 Eigen::MatrixXd r;
1176 if (!qrSparseWilson(wilson, qr, compact_rows, r)) return false;
1177 CompactRFactor factor;
1178 if (!factorCompactR(r, wilsonSvdThreshold(wilson.rows(), wilson.cols()),
1179 factor, singular))
1180 return false;
1181 tangent_basis = qr.colsPermutation() * factor.right;
1182 inverse_left = std::move(factor.inverse_left);
1183 return tangent_basis.allFinite() && inverse_left.allFinite();
1184}
1185
1186// Columns of a Wilson matrix at which a left-looking sparse QR of the
1187// Gabriel complex no longer fits the retraction budget. Below this the
1188// row space is the chart factorisation. Above it, B^T B's well-separated
1189// head is already that singular subspace, and the unresolved tail, the
1190// part whose Gram eigenvalues sit at the eigensolver floor, is replaced
1191// by the chart's compact SVD of B restricted to the tail.
1192constexpr Eigen::Index kExactWilsonQrColumns = 160;
1193
1194// Relative singular-value cutoff of the dense retraction reference. On the
1195// Gram it sits at the eigensolver floor and lets rigid modes through; on
1196// the singular values below it is the resolution at which a row is still
1197// invertible without spending a first-order Cartesian move on a
1198// second-order residual.
1199double retractionStepThreshold()
1200{
1201 return std::sqrt(std::numeric_limits<double>::epsilon());
1202}
1203
1204void selectRowSpace(const Eigen::MatrixXd& directions,
1205 const Eigen::VectorXd& singular, double sigma_max,
1206 Eigen::Index rows, Eigen::Index cols,
1207 Eigen::MatrixXd& basis, Eigen::MatrixXd& step_basis)
1208{
1209 const double chart_cut = wilsonSvdThreshold(rows, cols) * sigma_max;
1210 const double step_cut = retractionStepThreshold() * sigma_max;
1211 Eigen::Index chart_rank = 0;
1212 Eigen::Index step_rank = 0;
1213 for (Eigen::Index i = 0; i < singular.size(); ++i) {
1214 if (!(singular(i) > chart_cut)) continue;
1215 ++chart_rank;
1216 if (singular(i) >= step_cut) ++step_rank;
1217 }
1218 basis.resize(directions.rows(), chart_rank);
1219 step_basis.resize(directions.rows(), step_rank);
1220 Eigen::Index chart_col = 0;
1221 Eigen::Index step_col = 0;
1222 for (Eigen::Index i = 0; i < singular.size(); ++i) {
1223 if (!(singular(i) > chart_cut)) continue;
1224 basis.col(chart_col++) = directions.col(i);
1225 if (singular(i) >= step_cut && step_col < step_basis.cols())
1226 step_basis.col(step_col++) = directions.col(i);
1227 }
1228}
1229
1230// Right singular vectors of a wide Wilson matrix. The tail of B^T B is
1231// refined by a Jacobi SVD of B W, the same decomposition the chart applies
1232// to compact R, so a rigid eigenvalue at the Gram floor is measured as a
1233// null singular value and dropped.
1234bool refinedWilsonRowSpace(const SparseWilsonMatrix& wilson,
1235 Eigen::MatrixXd& basis, Eigen::MatrixXd& step_basis)
1236{
1237 const Eigen::Index cols = wilson.cols();
1238 const Eigen::Index rows = wilson.rows();
1239 if (cols <= 0 || rows <= 0) return false;
1240 Eigen::MatrixXd gram = Eigen::MatrixXd::Zero(cols, cols);
1241 std::vector<int> count(static_cast<std::size_t>(rows), 0);
1242 for (int column = 0; column < wilson.outerSize(); ++column) {
1243 for (SparseWilsonMatrix::InnerIterator it(wilson, column); it; ++it) {
1244 if (it.row() >= 0 && it.row() < rows)
1245 ++count[static_cast<std::size_t>(it.row())];
1246 }
1247 }
1248 std::vector<int> start(static_cast<std::size_t>(rows) + 1, 0);
1249 for (Eigen::Index row = 0; row < rows; ++row)
1250 start[static_cast<std::size_t>(row) + 1] =
1251 start[static_cast<std::size_t>(row)] +
1252 count[static_cast<std::size_t>(row)];
1253 const int nnz = start[static_cast<std::size_t>(rows)];
1254 std::vector<int> flat_column(static_cast<std::size_t>(nnz));
1255 std::vector<double> flat_value(static_cast<std::size_t>(nnz));
1256 std::vector<int> cursor = start;
1257 for (int column = 0; column < wilson.outerSize(); ++column) {
1258 for (SparseWilsonMatrix::InnerIterator it(wilson, column); it; ++it) {
1259 if (it.row() < 0 || it.row() >= rows) continue;
1260 const int at = cursor[static_cast<std::size_t>(it.row())]++;
1261 flat_column[static_cast<std::size_t>(at)] = it.col();
1262 flat_value[static_cast<std::size_t>(at)] = it.value();
1263 }
1264 }
1265 for (Eigen::Index row = 0; row < rows; ++row) {
1266 const int begin = start[static_cast<std::size_t>(row)];
1267 const int end = start[static_cast<std::size_t>(row) + 1];
1268 for (int a = begin; a < end; ++a) {
1269 const int ca = flat_column[static_cast<std::size_t>(a)];
1270 const double va = flat_value[static_cast<std::size_t>(a)];
1271 if (ca < 0 || ca >= cols) continue;
1272 for (int b = begin; b < end; ++b) {
1273 const int cb = flat_column[static_cast<std::size_t>(b)];
1274 if (cb < 0 || cb >= cols) continue;
1275 gram(ca, cb) += va * flat_value[static_cast<std::size_t>(b)];
1276 }
1277 }
1278 }
1279 if (!gram.allFinite()) return false;
1280 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver(gram);
1281 if (solver.info() != Eigen::Success) return false;
1282 const Eigen::VectorXd& lambda = solver.eigenvalues();
1283 const double lambda_max = lambda(lambda.size() - 1);
1284 if (!(lambda_max > 0.0) || !std::isfinite(lambda_max)) return false;
1285 // Head eigenvalues are separated from the floor by four orders in the
1286 // singular value, so their eigenvectors are the singular vectors.
1287 const double tail_lambda = 1.0e-4 * lambda_max;
1288 Eigen::Index tail = 0;
1289 while (tail < lambda.size() && lambda(tail) < tail_lambda)
1290 ++tail;
1291 const Eigen::Index head = lambda.size() - tail;
1292 Eigen::MatrixXd directions(cols, lambda.size());
1293 Eigen::VectorXd singular(lambda.size());
1294 if (head > 0) {
1295 directions.rightCols(head) = solver.eigenvectors().rightCols(head);
1296 for (Eigen::Index i = 0; i < head; ++i) {
1297 singular(tail + i) = std::sqrt(std::max(0.0, lambda(tail + i)));
1298 }
1299 }
1300 if (tail > 0) {
1301 const Eigen::MatrixXd tail_vectors =
1302 solver.eigenvectors().leftCols(tail);
1303 Eigen::MatrixXd restricted = Eigen::MatrixXd::Zero(rows, tail);
1304 for (Eigen::Index row = 0; row < rows; ++row) {
1305 const int begin = start[static_cast<std::size_t>(row)];
1306 const int end = start[static_cast<std::size_t>(row) + 1];
1307 for (int a = begin; a < end; ++a) {
1308 const int ca = flat_column[static_cast<std::size_t>(a)];
1309 if (ca < 0 || ca >= cols) continue;
1310 restricted.row(row) += flat_value[static_cast<std::size_t>(a)] *
1311 tail_vectors.row(ca);
1312 }
1313 }
1314 Eigen::JacobiSVD<Eigen::MatrixXd> svd(restricted, Eigen::ComputeThinV);
1315 const Eigen::Index resolved = svd.singularValues().size();
1316 if (resolved <= 0) return false;
1317 // Columns of V that the thin SVD does not report are a null
1318 // complement (more tail directions than rows). Singular value 0
1319 // drops them from the row space.
1320 directions.leftCols(tail).setZero();
1321 directions.leftCols(resolved) =
1322 tail_vectors * svd.matrixV().rowwise().reverse();
1323 singular.head(tail).setZero();
1324 singular.head(resolved) = svd.singularValues().reverse();
1325 }
1326 double sigma_max = std::sqrt(lambda_max);
1327 for (Eigen::Index i = 0; i < singular.size(); ++i)
1328 sigma_max = std::max(sigma_max, singular(i));
1329 if (!(sigma_max > 0.0) || !singular.allFinite() || !directions.allFinite())
1330 return false;
1331 selectRowSpace(directions, singular, sigma_max, rows, cols, basis,
1332 step_basis);
1333 return basis.cols() > 0 && basis.allFinite() && step_basis.allFinite();
1334}
1335
1336// Min-norm solution of N y = g after the row space has already removed
1337// singular values below the retraction cutoff, so N's eigenvalues are not
1338// the rigid-mode floor the Gram cutoff used to keep.
1339bool solveDeflatedNormal(const Eigen::MatrixXd& normal,
1340 const Eigen::VectorXd& rhs, Eigen::VectorXd& solution)
1341{
1342 solution.setZero(rhs.size());
1343 if (normal.rows() == 0 || normal.cols() != normal.rows() ||
1344 rhs.size() != normal.cols() || !normal.allFinite() || !rhs.allFinite())
1345 return false;
1346 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver(normal);
1347 if (solver.info() != Eigen::Success) return false;
1348 const Eigen::VectorXd& lambda = solver.eigenvalues();
1349 if (lambda.size() == 0) return false;
1350 const double lambda_max = lambda(lambda.size() - 1);
1351 if (!(lambda_max > 0.0) || !std::isfinite(lambda_max)) return false;
1352 const double relative = retractionStepThreshold();
1353 const double cutoff = relative * relative * lambda_max;
1354 const Eigen::MatrixXd& vectors = solver.eigenvectors();
1355 bool any = false;
1356 for (Eigen::Index i = 0; i < lambda.size(); ++i) {
1357 if (!(lambda(i) >= cutoff) || !(lambda(i) > 0.0)) continue;
1358 any = true;
1359 solution.noalias() +=
1360 vectors.col(i) * (vectors.col(i).dot(rhs) / lambda(i));
1361 }
1362 return any && solution.allFinite();
1363}
1364
1365// Length used to decide that a Cartesian correction is below coordinate
1366// resolution. x.norm() is not that length: translating a molecule changes
1367// it while every interatomic vector stays put, and a failed line search far
1368// from the origin was then reported as a retraction. The primitives are
1369// functions of those vectors, so the scale is the RMS distance of the atoms
1370// they touch from their centroid. A step much smaller than machine epsilon
1371// times that spread cannot change a primitive at the precision the chart
1372// resolves, and a cluster tighter than one length unit keeps the unit floor
1373// a compact system already used.
1374double translationInvariantCoordinateScale(
1375 const Eigen::VectorXd& positions,
1376 const std::vector<PrimitiveInternal>& primitives,
1377 const std::vector<std::size_t>& rows)
1378{
1379 const Eigen::Index n_atoms = positions.size() / 3;
1380 if (n_atoms <= 0 || rows.empty()) return 1.0;
1381 std::vector<char> used(static_cast<std::size_t>(n_atoms), 0);
1382 int count = 0;
1383 for (const std::size_t row: rows) {
1384 if (row >= primitives.size()) continue;
1385 const PrimitiveInternal& primitive = primitives[row];
1386 const int arity = primitive.arity();
1387 for (int slot = 0; slot < arity; ++slot) {
1388 const int atom = primitive.atoms[static_cast<std::size_t>(slot)];
1389 if (atom < 0 || atom >= n_atoms) continue;
1390 char& mark = used[static_cast<std::size_t>(atom)];
1391 if (mark != 0) continue;
1392 mark = 1;
1393 ++count;
1394 }
1395 }
1396 if (count <= 0) return 1.0;
1397 Eigen::Vector3d centroid = Eigen::Vector3d::Zero();
1398 for (Eigen::Index atom = 0; atom < n_atoms; ++atom) {
1399 if (used[static_cast<std::size_t>(atom)] == 0) continue;
1400 centroid += positions.segment<3>(3 * atom);
1401 }
1402 centroid /= static_cast<double>(count);
1403 double sum_sq = 0.0;
1404 for (Eigen::Index atom = 0; atom < n_atoms; ++atom) {
1405 if (used[static_cast<std::size_t>(atom)] == 0) continue;
1406 sum_sq += (positions.segment<3>(3 * atom) - centroid).squaredNorm();
1407 }
1408 const double rms = std::sqrt(sum_sq / static_cast<double>(count));
1409 return std::max(1.0, rms);
1410}
1411
1412} // namespace
1413
1416 const Eigen::VectorXd& positions,
1417 const Eigen::VectorXd& cartesian_step) const
1418{
1419 validatePositions(positions);
1420 RetractionReport report;
1421 if (cartesian_step.size() != positions.size() ||
1422 !cartesian_step.allFinite()) {
1423 throw std::invalid_argument(
1424 "internal coordinate retraction step has invalid shape or values");
1425 }
1426
1427 const Eigen::VectorXd active_step = activeStep(cartesian_step);
1428 const PairBox box(cell_);
1429 std::vector<Eigen::Index> active_of_full(
1430 static_cast<std::size_t>(positions.size()), -1);
1431 for (Eigen::Index col = 0;
1432 col < static_cast<Eigen::Index>(active_columns_.size()); ++col) {
1433 const Eigen::Index full =
1434 active_columns_[static_cast<std::size_t>(col)];
1435 if (full >= 0 && static_cast<std::size_t>(full) < active_of_full.size())
1436 active_of_full[static_cast<std::size_t>(full)] = col;
1437 }
1438
1439 std::vector<std::size_t> regular_rows;
1440 std::vector<double> target_values;
1441 bool target_in_domain = true;
1442 const Eigen::Index n_active =
1443 static_cast<Eigen::Index>(active_columns_.size());
1444 std::vector<Eigen::Triplet<double>> anchor_entries;
1445 anchor_entries.reserve(12 * primitives_.size());
1446 Eigen::VectorXd full_gradient(positions.size());
1447 SparseRow sparse;
1448 for (std::size_t row = 0; row < primitives_.size(); ++row) {
1449 try {
1450 const double value =
1451 primitiveValue(primitives_[row], positions, box);
1452 primitiveGradient(primitives_[row], positions, box, full_gradient);
1453 harvestRow(primitives_[row], full_gradient, active_of_full, true,
1454 sparse);
1455 ++report.wilson_rows_evaluated;
1456 regular_rows.push_back(row);
1457 const double target = value + sparseDot(sparse, active_step);
1458 target_values.push_back(target);
1459 const Eigen::Index subset_row =
1460 static_cast<Eigen::Index>(regular_rows.size() - 1);
1461 for (int i = 0; i < sparse.nnz; ++i) {
1462 anchor_entries.emplace_back(
1463 subset_row, sparse.column[static_cast<std::size_t>(i)],
1464 sparse.value[static_cast<std::size_t>(i)]);
1465 }
1466 if (primitives_[row].kind == PrimitiveKind::Angle &&
1467 (target < 0.0 || target > kPi))
1468 target_in_domain = false;
1469 } catch (const std::invalid_argument&) {
1470 // A primitive that cannot be evaluated at these positions (a
1471 // degenerate angle, say) contributes no row: it is left out of
1472 // regular_rows and target_values rather than aborting the build.
1473 }
1474 }
1475
1476 Eigen::VectorXd x = positions;
1477 for (Eigen::Index col = 0; col < n_active; ++col) {
1478 const Eigen::Index full_col =
1479 active_columns_[static_cast<std::size_t>(col)];
1480 x(full_col) += cartesian_step(full_col);
1481 }
1482 // A valence-angle target outside [0, pi] has no Cartesian inverse.
1483 // Crossing the cone point is valid atomic motion, so this chart-domain
1484 // case retains the requested Cartesian step with frozen atoms fixed
1485 // and reports that status. An empty primitive set is a failure: the
1486 // Cartesian trial is not returned in its place.
1487 if (!target_in_domain) {
1488 report.positions = x;
1489 report.residual = std::numeric_limits<double>::infinity();
1491 return report;
1492 }
1493 if (regular_rows.empty()) {
1495 return report;
1496 }
1497
1498 Eigen::VectorXd target(static_cast<Eigen::Index>(target_values.size()));
1499 for (Eigen::Index row = 0; row < target.size(); ++row) {
1500 target(row) = target_values[static_cast<std::size_t>(row)];
1501 }
1502 const auto subsetValues = [&](const Eigen::VectorXd& pos,
1503 Eigen::VectorXd& out) {
1504 out.resize(static_cast<Eigen::Index>(regular_rows.size()));
1505 for (Eigen::Index row = 0; row < out.size(); ++row) {
1506 const std::size_t primitive_row =
1507 regular_rows[static_cast<std::size_t>(row)];
1508 try {
1509 out(row) = primitiveValue(primitives_[primitive_row], pos, box);
1510 } catch (const std::invalid_argument&) {
1511 return false;
1512 }
1513 }
1514 return true;
1515 };
1516 const auto subsetResidual = [&](const Eigen::VectorXd& current) {
1517 Eigen::VectorXd residual = target - current;
1518 for (Eigen::Index row = 0; row < residual.size(); ++row) {
1519 const auto kind =
1520 primitives_[regular_rows[static_cast<std::size_t>(row)]].kind;
1521 if (kind == PrimitiveKind::Angle ||
1522 kind == PrimitiveKind::Dihedral) {
1523 residual(row) = wrapAngularResidual(residual(row));
1524 }
1525 }
1526 return residual;
1527 };
1528
1529 Eigen::VectorXd best = x;
1530 Eigen::VectorXd current_values;
1531 if (!subsetValues(x, current_values)) {
1533 return report;
1534 }
1535 double best_residual = subsetResidual(current_values).norm();
1536 const double residual_tol =
1537 std::numeric_limits<double>::epsilon() * std::max(1.0, target.norm()) *
1538 std::max<double>(
1539 1.0, static_cast<double>(target.size() + active_columns_.size()));
1540 auto fail = [&]() {
1541 report.positions.resize(0);
1542 report.residual = best_residual;
1544 return report;
1545 };
1546 auto finish = [&](const Eigen::VectorXd& retracted) {
1547 // An accepted residual can sit on a singular primitive gradient
1548 // (a valence angle on its cone has a value and no derivative).
1549 // That geometry is Failed, not a retraction.
1550 for (const std::size_t row: regular_rows) {
1551 // The recheck is a Wilson evaluation of the accepted geometry,
1552 // so it counts with the anchor pass and the iteration passes.
1553 ++report.wilson_rows_evaluated;
1554 try {
1555 primitiveGradient(primitives_[row], retracted, box,
1556 full_gradient);
1557 } catch (const std::invalid_argument&) {
1558 return fail();
1559 }
1560 }
1561 report.positions = retracted;
1562 report.residual = best_residual;
1564 return report;
1565 };
1566 if (best_residual <= residual_tol) return finish(best);
1567
1568 // Corrections lie in the anchor Jacobian's row space. Its nullspace
1569 // contains allowed Cartesian motion that the primitives cannot resolve
1570 // to first order; fitting their nonlinear residual must preserve it.
1571 // The row space is the chart factorisation: a sparse QR of B and the
1572 // SVD of compact R when that QR fits, and the same SVD on the
1573 // unresolved tail of B^T B when it does not. Either way a rigid-body
1574 // eigenvalue at the Gram floor is a null singular value and is dropped.
1575 // Rows between that floor and the retraction cutoff stay in the reported
1576 // rank, but inverting them replaces a second-order residual with a
1577 // first-order Cartesian move, so the step uses the resolved rows only.
1578 Eigen::MatrixXd correction_basis;
1579 Eigen::MatrixXd step_basis;
1580 {
1581 SparseWilsonMatrix anchor_wilson(
1582 static_cast<Eigen::Index>(regular_rows.size()), n_active);
1583 anchor_wilson.setFromTriplets(anchor_entries.begin(),
1584 anchor_entries.end());
1585 if (n_active == 0) return fail();
1586 if (n_active <= kExactWilsonQrColumns) {
1587 SparseWilsonQr anchor_qr;
1588 Eigen::Index anchor_compact = 0;
1589 Eigen::MatrixXd anchor_inverse;
1590 Eigen::VectorXd anchor_sigma;
1591 if (!factorSparseWilson(anchor_wilson, anchor_qr, anchor_compact,
1592 correction_basis, anchor_inverse,
1593 &anchor_sigma)) {
1594 return fail();
1595 }
1596 const double sigma_max =
1597 anchor_sigma.size() == 0 ? 0.0 : anchor_sigma.maxCoeff();
1598 Eigen::MatrixXd chart_basis;
1599 selectRowSpace(correction_basis, anchor_sigma, sigma_max,
1600 anchor_wilson.rows(), anchor_wilson.cols(),
1601 chart_basis, step_basis);
1602 correction_basis = std::move(chart_basis);
1603 } else if (!refinedWilsonRowSpace(anchor_wilson, correction_basis,
1604 step_basis)) {
1605 return fail();
1606 }
1607 }
1608 report.anchor_rank = correction_basis.cols();
1609 if (step_basis.cols() <= 0) return fail();
1610
1611 const int max_steps = std::max<int>(1, static_cast<int>(n_active));
1612 const double eps = std::numeric_limits<double>::epsilon();
1613 bool any_accepted = false;
1614 // current_values contains the primitives at the accepted geometry x.
1615 for (int iter = 0; iter < max_steps; ++iter) {
1616 report.iterations = iter + 1;
1617 const Eigen::VectorXd residual = subsetResidual(current_values);
1618 if (residual.norm() <= residual_tol) return finish(x);
1619 // J and J^T residual from one sparse pass. The Gauss-Newton step is
1620 // the min-norm solution of J V y = residual. V is the resolved part
1621 // of the anchor row space. The same sparse QR and compact-R SVD
1622 // produce the step when V is narrow enough; a wide V is already
1623 // deflated, so the normal matrix is factored directly.
1624 const bool wide_step = step_basis.cols() > kExactWilsonQrColumns;
1625 std::vector<Eigen::Triplet<double>> entries;
1626 Eigen::MatrixXd jtj;
1627 if (!wide_step)
1628 entries.reserve(static_cast<std::size_t>(residual.size()) * 12);
1629 else
1630 jtj = Eigen::MatrixXd::Zero(n_active, n_active);
1631 Eigen::VectorXd jtr = Eigen::VectorXd::Zero(n_active);
1632 bool rows_defined = true;
1633 for (Eigen::Index row = 0; row < residual.size(); ++row) {
1634 const std::size_t primitive_row =
1635 regular_rows[static_cast<std::size_t>(row)];
1636 try {
1637 primitiveGradient(primitives_[primitive_row], x, box,
1638 full_gradient);
1639 } catch (const std::invalid_argument&) {
1640 rows_defined = false;
1641 break;
1642 }
1643 harvestRow(primitives_[primitive_row], full_gradient,
1644 active_of_full, true, sparse);
1645 ++report.wilson_rows_evaluated;
1646 for (int i = 0; i < sparse.nnz; ++i) {
1647 const Eigen::Index column =
1648 sparse.column[static_cast<std::size_t>(i)];
1649 const double value = sparse.value[static_cast<std::size_t>(i)];
1650 if (!wide_step)
1651 entries.emplace_back(row, column, value);
1652 else {
1653 for (int j = 0; j < sparse.nnz; ++j) {
1654 jtj(column,
1655 sparse.column[static_cast<std::size_t>(j)]) +=
1656 value * sparse.value[static_cast<std::size_t>(j)];
1657 }
1658 }
1659 jtr(column) += value * residual(row);
1660 }
1661 }
1662 // An undefined or vanishing primitive gradient is not a retracted
1663 // point, including when an earlier iterate had already been accepted.
1664 if (!rows_defined || !jtr.allFinite()) return fail();
1665 Eigen::VectorXd coefficients;
1666 if (!wide_step) {
1667 SparseWilsonMatrix wilson(residual.size(), n_active);
1668 wilson.setFromTriplets(entries.begin(), entries.end());
1669 SparseWilsonQr qr;
1670 Eigen::Index compact_rows = 0;
1671 Eigen::MatrixXd r_factor;
1672 if (!qrSparseWilson(wilson, qr, compact_rows, r_factor))
1673 return fail();
1674 const Eigen::MatrixXd permuted_basis =
1675 qr.colsPermutation().transpose() * step_basis;
1676 const Eigen::MatrixXd projected_r = r_factor * permuted_basis;
1677 if (!projected_r.allFinite()) return fail();
1678 const double jacobian_norm = projected_r.norm();
1679 if (!(jacobian_norm > 0.0)) return fail();
1680 const Eigen::VectorXd projected = step_basis.transpose() * jtr;
1681 if (!projected.allFinite()) return fail();
1682 // First-order stationarity of the least-squares objective: the
1683 // residual is orthogonal to the allowed correction derivatives
1684 // up to the resolution of the product. A redundant target need
1685 // not have a zero residual at this fixed point.
1686 if (projected.norm() <= eps * jacobian_norm * residual.norm()) {
1687 return finish(best);
1688 }
1689 CompactRFactor reduced;
1690 if (!factorCompactR(projected_r, retractionStepThreshold(),
1691 reduced)) {
1692 return any_accepted ? finish(best) : fail();
1693 }
1694 const Eigen::VectorXd qt = qr.matrixQ().adjoint() * residual;
1695 if (qt.size() < compact_rows ||
1696 !qt.head(compact_rows).allFinite()) {
1697 return any_accepted ? finish(best) : fail();
1698 }
1699 coefficients =
1700 reduced.right * (reduced.inverse_left * qt.head(compact_rows));
1701 } else {
1702 if (!jtj.allFinite()) return fail();
1703 const Eigen::MatrixXd normal =
1704 step_basis.transpose() * jtj * step_basis;
1705 const Eigen::VectorXd projected = step_basis.transpose() * jtr;
1706 double gram_trace = 0.0;
1707 for (Eigen::Index i = 0; i < normal.rows(); ++i)
1708 gram_trace += normal(i, i);
1709 const double jacobian_norm = std::sqrt(std::max(0.0, gram_trace));
1710 if (!normal.allFinite() || !projected.allFinite() ||
1711 !(jacobian_norm > 0.0)) {
1712 return fail();
1713 }
1714 if (projected.norm() <= eps * jacobian_norm * residual.norm()) {
1715 return finish(best);
1716 }
1717 if (!solveDeflatedNormal(normal, projected, coefficients)) {
1718 return any_accepted ? finish(best) : fail();
1719 }
1720 }
1721 const Eigen::VectorXd delta_active = step_basis * coefficients;
1722 if (delta_active.size() != n_active || !delta_active.allFinite() ||
1723 !(delta_active.norm() > 0.0)) {
1724 return any_accepted ? finish(best) : fail();
1725 }
1726 // A correction below the resolution of the interatomic vectors
1727 // does not move the geometry. That is not a retraction unless a
1728 // step was already accepted or the constraint residual itself is
1729 // within tolerance.
1730 const double coordinate_scale =
1731 translationInvariantCoordinateScale(x, primitives_, regular_rows);
1732 const double delta_norm = delta_active.norm();
1733 if (delta_norm <= eps * coordinate_scale) {
1734 if (any_accepted || residual.norm() <= residual_tol)
1735 return finish(best);
1736 return fail();
1737 }
1738 const double residual_before = best_residual;
1739
1740 bool accepted = false;
1741 double alpha = 1.0;
1742 for (int ls = 0; ls < std::numeric_limits<double>::digits; ++ls) {
1743 // Further halving would not change the stored coordinates.
1744 if (alpha * delta_norm <= eps * coordinate_scale) break;
1745 Eigen::VectorXd trial = x;
1746 for (Eigen::Index col = 0; col < delta_active.size(); ++col) {
1747 trial(active_columns_[static_cast<std::size_t>(col)]) +=
1748 alpha * delta_active(col);
1749 }
1750 if (!trial.allFinite()) {
1751 alpha *= 0.5;
1752 continue;
1753 }
1754 Eigen::VectorXd trial_values;
1755 if (!subsetValues(trial, trial_values)) {
1756 alpha *= 0.5;
1757 continue;
1758 }
1759 const double trial_residual = subsetResidual(trial_values).norm();
1760 if (std::isfinite(trial_residual) &&
1761 trial_residual < best_residual) {
1762 x = trial;
1763 best = trial;
1764 best_residual = trial_residual;
1765 current_values = trial_values;
1766 accepted = true;
1767 any_accepted = true;
1768 break;
1769 }
1770 alpha *= 0.5;
1771 }
1772 if (!accepted) {
1773 if (any_accepted || best_residual <= residual_tol)
1774 return finish(best);
1775 return fail();
1776 }
1777 if (best_residual <= residual_tol) return finish(best);
1778 // Stationarity: a decrease below the resolution of the residual is
1779 // the least-squares floor of an inconsistent (redundant) target.
1780 if (residual_before - best_residual <= eps * residual_before) {
1781 return finish(best);
1782 }
1783 }
1784 return any_accepted ? finish(best) : fail();
1785}
1786
1787Eigen::VectorXd sellaInternalTrust(const InternalCoordinateSet& coordinates)
1788{
1789 const auto& primitives = coordinates.primitives();
1790 Eigen::VectorXd trust(static_cast<Eigen::Index>(primitives.size()));
1791 for (std::size_t i = 0; i < primitives.size(); ++i) {
1792 switch (primitives[i].kind) {
1794 trust(static_cast<Eigen::Index>(i)) = 0.3;
1795 break;
1799 trust(static_cast<Eigen::Index>(i)) = 0.2;
1800 break;
1801 }
1802 }
1803 return trust;
1804}
1805
1807 const InternalCoordinateSet& coordinates, const Eigen::VectorXd& positions,
1808 const Eigen::VectorXd& cartesian_step,
1809 const Eigen::VectorXd& internal_trust_per_primitive)
1810{
1811 if (cartesian_step.size() != positions.size() ||
1812 !cartesian_step.allFinite() || !positions.allFinite()) {
1813 return cartesian_step;
1814 }
1815 const Eigen::VectorXd trust = internal_trust_per_primitive.size() > 0
1816 ? internal_trust_per_primitive
1817 : sellaInternalTrust(coordinates);
1818 if (trust.size() == 0 || trust.maxCoeff() <= 0.0) return cartesian_step;
1819 const Eigen::VectorXd ds =
1820 coordinates.linearizedChange(positions, cartesian_step);
1821 if (ds.size() == 0) return cartesian_step;
1822 double worst_ratio = 1.0;
1823 for (Eigen::Index k = 0; k < ds.size(); ++k) {
1824 const double radius = k < trust.size() ? trust(k) : 0.0;
1825 if (!(radius > 0.0)) continue;
1826 const double change = std::abs(ds(k));
1827 if (std::isfinite(change) && change / radius > worst_ratio)
1828 worst_ratio = change / radius;
1829 }
1830 if (worst_ratio > 1.0) return cartesian_step / worst_ratio;
1831 return cartesian_step;
1832}
1833
1835 const InternalCoordinateSet& coordinates, const Eigen::VectorXd& positions,
1836 const Eigen::VectorXd& cartesian_step,
1837 const Eigen::VectorXd& internal_trust_per_primitive)
1838{
1839 const Eigen::VectorXd scaled = scaleCartesianStepToInternalTrust(
1840 coordinates, positions, cartesian_step, internal_trust_per_primitive);
1841 const Eigen::VectorXd retracted =
1842 coordinates.retractLinearized(positions, scaled);
1843 if (retracted.size() != positions.size() || !retracted.allFinite()) {
1845 "internal coordinate retraction failed");
1846 }
1847 return retracted;
1848}
1849
1851 Eigen::VectorXd anchor, const Eigen::MatrixXd& constraint_jacobian)
1852 : anchor_(std::move(anchor))
1853{
1854 if (anchor_.size() == 0 || !anchor_.allFinite() ||
1855 constraint_jacobian.cols() != anchor_.size() ||
1856 !constraint_jacobian.allFinite())
1857 throw std::invalid_argument(
1858 "affine chart has invalid anchor or constraints");
1859 tangent_basis_ = constraintFreeBasis(constraint_jacobian);
1860 tangent_projector_.noalias() = tangent_basis_ * tangent_basis_.transpose();
1861}
1862
1863void AffineCoordinateChart::validatePositions(
1864 const Eigen::VectorXd& positions) const
1865{
1866 if (positions.size() != anchor_.size() || !positions.allFinite())
1867 throw std::invalid_argument(
1868 "affine chart positions have invalid shape or values");
1869}
1870
1872 const Eigen::VectorXd& positions) const
1873{
1874 validatePositions(positions);
1875 return tangent_basis_.transpose() * (positions - anchor_);
1876}
1877
1879 const Eigen::VectorXd& positions) const
1880{
1881 validatePositions(positions);
1882 return tangent_basis_.transpose();
1883}
1884
1886 const Eigen::VectorXd& positions, const Eigen::VectorXd& direction) const
1887{
1888 validatePositions(positions);
1889 if (direction.size() != positions.size())
1890 throw std::invalid_argument(
1891 "affine coordinate direction has invalid shape");
1892 return Eigen::MatrixXd::Zero(tangent_basis_.cols(), positions.size());
1893}
1894
1896 std::shared_ptr<const InternalCoordinateSet> internal_coordinates,
1897 Eigen::VectorXd anchor_positions)
1898 : internal_coordinates_(std::move(internal_coordinates)),
1899 anchor_positions_(std::move(anchor_positions))
1900{
1901 if (!internal_coordinates_) {
1902 throw std::invalid_argument(
1903 "internal coordinate chart requires a coordinate set");
1904 }
1905 {
1906 // A topology built without positions may carry valence angles that
1907 // are collinear at this anchor; the chart takes the smooth linear
1908 // bend pair for those (and drops the undefined dihedrals).
1909 if (anchor_positions_.size() !=
1910 static_cast<Eigen::Index>(3 *
1911 internal_coordinates_->numAtoms()) ||
1912 !anchor_positions_.allFinite()) {
1913 throw std::invalid_argument(
1914 "internal coordinate chart anchor has invalid shape or values");
1915 }
1916 std::vector<PrimitiveInternal> resolved = resolveCollinearAngles(
1917 internal_coordinates_->primitives(), anchor_positions_,
1918 internal_coordinates_->cell());
1919 bool changed =
1920 resolved.size() != internal_coordinates_->primitives().size();
1921 for (std::size_t i = 0; !changed && i < resolved.size(); ++i) {
1922 changed =
1923 resolved[i].kind != internal_coordinates_->primitives()[i].kind;
1924 }
1925 if (changed) {
1926 internal_coordinates_ =
1927 std::make_shared<const InternalCoordinateSet>(
1928 internal_coordinates_->numAtoms(),
1929 internal_coordinates_->movingAtoms(), std::move(resolved),
1930 internal_coordinates_->cell());
1931 }
1932 }
1933
1934 anchor_internal_values_ = internal_coordinates_->values(anchor_positions_);
1935 if (!anchor_internal_values_.allFinite()) return;
1936 const Eigen::Index n = anchor_positions_.size();
1937 const auto& primitives = internal_coordinates_->primitives();
1938 if (n == 0 || primitives.empty()) return;
1939 const PairBox box(internal_coordinates_->cell());
1940 Eigen::VectorXd gradient(n);
1941 std::vector<Eigen::Index> unused;
1942 SparseRow sparse;
1943 std::vector<Eigen::Triplet<double>> entries;
1944 entries.reserve(12 * primitives.size());
1945 for (Eigen::Index row = 0;
1946 row < static_cast<Eigen::Index>(primitives.size()); ++row) {
1947 const auto& primitive = primitives[static_cast<std::size_t>(row)];
1948 primitiveGradient(primitive, anchor_positions_, box, gradient);
1949 harvestRow(primitive, gradient, unused, false, sparse);
1950 for (int i = 0; i < sparse.nnz; ++i) {
1951 entries.emplace_back(row,
1952 sparse.column[static_cast<std::size_t>(i)],
1953 sparse.value[static_cast<std::size_t>(i)]);
1954 }
1955 }
1956
1957 // Sparse QR applies orthogonal transformations directly to B, so it
1958 // does not square B's condition number. Only the compact R factor is
1959 // dense for the final SVD. The rank cutoff is machine epsilon times
1960 // max(m, n), matching constraintFreeBasis and the dense SVD in the
1961 // chart parity sweep. Eigen's own default is epsilon times the
1962 // diagonal size min(m, n); the wider cutoff is the one those dense
1963 // comparisons use, and it drops roundoff singular values of a
1964 // primitive-redundant Wilson matrix. Retraction uses this same
1965 // factorisation for its row space and Gauss-Newton steps.
1966 SparseWilsonMatrix wilson(static_cast<Eigen::Index>(primitives.size()), n);
1967 wilson.setFromTriplets(entries.begin(), entries.end());
1968 if (!factorSparseWilson(wilson, anchor_qr_, compact_qr_rows_,
1969 tangent_basis_, inverse_r_left_)) {
1970 tangent_basis_.resize(0, 0);
1971 inverse_r_left_.resize(0, 0);
1972 return;
1973 }
1974 tangent_projector_.noalias() = tangent_basis_ * tangent_basis_.transpose();
1975}
1976
1978 const Eigen::VectorXd& positions) const
1979{
1980 if (!valid()) return Eigen::VectorXd{};
1981 Eigen::VectorXd delta =
1982 internal_coordinates_->values(positions) - anchor_internal_values_;
1983 const auto& primitives = internal_coordinates_->primitives();
1984 for (Eigen::Index i = 0; i < delta.size(); ++i) {
1985 if (primitives[static_cast<std::size_t>(i)].kind ==
1987 delta(i) = std::remainder(delta(i), 2.0 * kPi);
1988 }
1989 }
1990 const Eigen::VectorXd qt_delta = anchor_qr_.matrixQ().adjoint() * delta;
1991 return inverse_r_left_ * qt_delta.head(compact_qr_rows_);
1992}
1993
1995 const Eigen::VectorXd& positions) const
1996{
1997 if (!valid()) return Eigen::MatrixXd{};
1998 if (positions.size() != anchor_positions_.size() || !positions.allFinite())
1999 throw std::invalid_argument(
2000 "internal coordinate chart positions have invalid shape or values");
2001 const Eigen::Index n = anchor_positions_.size();
2002 const PairBox box(internal_coordinates_->cell());
2003 std::vector<Eigen::Triplet<double>> entries;
2004 entries.reserve(12 * internal_coordinates_->primitives().size());
2005 Eigen::VectorXd gradient_query(n);
2006 std::vector<Eigen::Index> unused;
2007 SparseRow right;
2008 const auto& primitives = internal_coordinates_->primitives();
2009 for (Eigen::Index row = 0;
2010 row < static_cast<Eigen::Index>(primitives.size()); ++row) {
2011 const auto& primitive = primitives[static_cast<std::size_t>(row)];
2012 primitiveGradient(primitive, positions, box, gradient_query);
2013 harvestRow(primitive, gradient_query, unused, false, right);
2014 for (int i = 0; i < right.nnz; ++i) {
2015 entries.emplace_back(row, right.column[static_cast<std::size_t>(i)],
2016 right.value[static_cast<std::size_t>(i)]);
2017 }
2018 }
2019 SparseWilsonMatrix wilson(static_cast<Eigen::Index>(primitives.size()), n);
2020 wilson.setFromTriplets(entries.begin(), entries.end());
2021 Eigen::MatrixXd qt_wilson(compact_qr_rows_, n);
2022 for (Eigen::Index column = 0; column < n; ++column) {
2023 const Eigen::VectorXd dense_column(wilson.col(column));
2024 const Eigen::VectorXd transformed =
2025 anchor_qr_.matrixQ().adjoint() * dense_column;
2026 qt_wilson.col(column) = transformed.head(compact_qr_rows_);
2027 }
2028 return inverse_r_left_ * qt_wilson;
2029}
2030
2032 const Eigen::VectorXd& positions, const Eigen::VectorXd& direction) const
2033{
2034 if (!valid()) return Eigen::MatrixXd{};
2035 const Eigen::MatrixXd wilson_derivative =
2036 internal_coordinates_->directionalJacobian(positions, direction);
2037 Eigen::MatrixXd qt_derivative(compact_qr_rows_, wilson_derivative.cols());
2038 for (Eigen::Index column = 0; column < wilson_derivative.cols(); ++column) {
2039 const Eigen::VectorXd transformed =
2040 anchor_qr_.matrixQ().adjoint() * wilson_derivative.col(column);
2041 qt_derivative.col(column) = transformed.head(compact_qr_rows_);
2042 }
2043 return inverse_r_left_ * qt_derivative;
2044}
2045
2046Eigen::MatrixXd constraintFreeBasis(const Eigen::MatrixXd& constraint_jacobian)
2047{
2048 if (constraint_jacobian.cols() == 0) return Eigen::MatrixXd();
2049 if (constraint_jacobian.rows() == 0) {
2050 return Eigen::MatrixXd::Identity(constraint_jacobian.cols(),
2051 constraint_jacobian.cols());
2052 }
2053 Eigen::JacobiSVD<Eigen::MatrixXd> svd(constraint_jacobian,
2054 Eigen::ComputeFullV);
2055 const Eigen::VectorXd singular = svd.singularValues();
2056 int rank = 0;
2057 if (singular.size() > 0) {
2058 const double sigma_max = singular.cwiseAbs().maxCoeff();
2059 const double cutoff =
2060 std::numeric_limits<double>::epsilon() *
2061 static_cast<double>(std::max(constraint_jacobian.rows(),
2062 constraint_jacobian.cols())) *
2063 sigma_max;
2064 for (Eigen::Index i = 0; i < singular.size(); ++i) {
2065 if (singular(i) > cutoff) ++rank;
2066 }
2067 }
2068 return svd.matrixV().rightCols(
2069 static_cast<Eigen::Index>(constraint_jacobian.cols() - rank));
2070}
2071
2072} // namespace geometry
2073} // namespace gpr
@ x
Definition Enums.h:28
Eigen::VectorXd coordinates(const Eigen::VectorXd &positions) const override
Eigen::MatrixXd jacobian(const Eigen::VectorXd &positions) const override
Eigen::MatrixXd directionalJacobian(const Eigen::VectorXd &positions, const Eigen::VectorXd &direction) const override
AffineCoordinateChart(Eigen::VectorXd anchor, const Eigen::MatrixXd &constraint_jacobian)
const Eigen::VectorXd & anchor() const noexcept override
Eigen::MatrixXd jacobian(const Eigen::VectorXd &positions) const override
InternalCoordinateChart(std::shared_ptr< const InternalCoordinateSet > internal_coordinates, Eigen::VectorXd anchor_positions)
Eigen::VectorXd coordinates(const Eigen::VectorXd &positions) const override
Eigen::MatrixXd directionalJacobian(const Eigen::VectorXd &positions, const Eigen::VectorXd &direction) const override
const std::vector< PrimitiveInternal > & primitives() const
RetractionReport retractLinearizedReport(const Eigen::VectorXd &positions, const Eigen::VectorXd &cartesian_step) const
Eigen::VectorXd values(const Eigen::VectorXd &positions) const
Eigen::MatrixXd activeJacobian(const Eigen::VectorXd &positions) const
const std::array< double, 9 > & cell() const noexcept
Eigen::MatrixXd directionalJacobian(const Eigen::VectorXd &positions, const Eigen::VectorXd &direction) const
Eigen::VectorXd linearizedChange(const Eigen::VectorXd &positions, const Eigen::VectorXd &direction) const
Eigen::MatrixXd jacobian(const Eigen::VectorXd &positions) const
Eigen::VectorXd activeStep(const Eigen::VectorXd &full_step) const
InternalCoordinateSet(int n_atoms, std::vector< char > moving_atoms, std::vector< PrimitiveInternal > primitives, std::array< double, 9 > cell={})
Eigen::VectorXd retractLinearized(const Eigen::VectorXd &positions, const Eigen::VectorXd &cartesian_step) const
bool hasSameDefinition(const InternalCoordinateSet &other) const noexcept
void displacement(const double p[3], const double q[3], double dr[3]) const
Displacement from p to q. Cartesian q - p when the cell is zero.
Definition MinImage.h:210
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
Eigen::Vector3d at(const FieldMatrixd &mat, Index_t i)
double nestedAtan2(double y, double x)
T lift(const Value &value)
DoubleDouble sqrt(DoubleDouble a)
Eigen::VectorXd scaleCartesianStepToInternalTrust(const InternalCoordinateSet &coordinates, const Eigen::VectorXd &positions, const Eigen::VectorXd &cartesian_step, const Eigen::VectorXd &internal_trust_per_primitive)
std::vector< std::pair< int, int > > bondGraph(int n_atoms, const Eigen::VectorXd &positions, const std::vector< char > &moving_atoms, BondGraphKind kind, const std::array< double, 9 > &cell)
int countDihedrals(const std::vector< PrimitiveInternal > &primitives)
Eigen::MatrixXd constraintFreeBasis(const Eigen::MatrixXd &constraint_jacobian)
std::vector< PrimitiveInternal > primitiveTopologyFromBondGraph(int n_atoms, const std::vector< std::pair< int, int > > &bonds)
Eigen::VectorXd retractRestrictedStep(const InternalCoordinateSet &coordinates, const Eigen::VectorXd &positions, const Eigen::VectorXd &cartesian_step, const Eigen::VectorXd &internal_trust_per_primitive)
std::vector< PrimitiveInternal > primitiveTopologyFromGeometry(int n_atoms, const Eigen::VectorXd &positions, const std::vector< char > &moving_atoms, BondGraphKind kind, const std::array< double, 9 > &cell)
bool angleIsCollinear(double sin2)
std::vector< std::pair< int, int > > gabrielBondGraph(int n_atoms, const Eigen::VectorXd &positions, const std::vector< char > &moving_atoms, const std::array< double, 9 > &cell)
int countBonds(const std::vector< PrimitiveInternal > &primitives)
std::vector< std::pair< int, int > > relativeNeighborhoodBondGraph(int n_atoms, const Eigen::VectorXd &positions, const std::vector< char > &moving_atoms, const std::array< double, 9 > &cell)
Eigen::VectorXd sellaInternalTrust(const InternalCoordinateSet &coordinates)
std::vector< std::pair< int, int > > unionBondGraph(int n_atoms, const std::vector< Eigen::VectorXd > &geometries, const std::vector< char > &moving_atoms, BondGraphKind kind, const std::array< double, 9 > &cell)
int countAngles(const std::vector< PrimitiveInternal > &primitives)
std::vector< PrimitiveInternal > resolveCollinearAngles(const std::vector< PrimitiveInternal > &primitives, const Eigen::VectorXd &positions, const std::array< double, 9 > &cell)
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
bool resolved(Dual value, Dual error, const BridgeResidualOptions &options)
STL namespace.
static PrimitiveInternal angle(int a, int b, int c)
static PrimitiveInternal dihedral(int a, int b, int c, int d)
static PrimitiveInternal bond(int a, int b)
Eigen::Vector3d reference
Reference direction of a LinearBend; unused by the other kinds.
static PrimitiveInternal linearBend(int a, int b, int c, const Eigen::Vector3d &reference)