Loading...
Searching...
No Matches
aux Namespace Reference

Namespaces

namespace  distance

Classes

struct  AtomSignature
class  AuxiliaryFunctionality
 Some auxiliary functions. More...
struct  ChainRealignStats
class  Distance
 Methods to calculate distances between atoms. More...
struct  EndpointAlignResult
class  Gradient
 Methods to calculate gradients (derivatives) with respect to different directions. More...
struct  InverseDistanceCache
 Methods to calculate distances between atoms. More...
struct  LebedevNode
struct  OracleOrientation
class  ProblemSetUp
 Set up the GP-dimer problem. More...

Functions

ChainRealignStats realignChainToPredecessors (gpr::neb::NEBPath &path, const std::vector< int > &atomic_numbers, std::vector< std::vector< uint64_t > > *image_ids, double kmax_factor)
std::pair< gpr::Coord, gpr::FieldMatrixIdx > get_canonical_configuration (const gpr::Coord &x_in, const gpr::FieldMatrixIdx &types_in)
double solve_assignment_problem (const Eigen::MatrixXd &cost_matrix)
 Solves the assignment problem using the Hungarian algorithm.
std::vector< int > solve_assignment_indices (const Eigen::MatrixXd &cost_matrix)
 Like solve_assignment_problem, but returns the optimal assignment.
double calculate_aligned_rmsd (const gpr::Coord &P, const gpr::Coord &Q)
const double * farFieldCentre (const gpr::AtomsConfiguration &conf, Eigen::Index atom)
void farFieldDifference (const gpr::geometry::PairBox &box, const double centre[3], const double left[3], const double right[3], double delta[3])
void addFarSource (double tensor[3][3], const double r[3], double weight)
double farQuadratic (const double tensor[3][3], const double delta[3])
void farContract (const double tensor[3][3], const double delta[3], double out[3])
bool farFromCentre (const gpr::geometry::PairBox &box, const double centre[3], const double frozen[3], double radius)
EndpointAlignResult alignProductToReactant (const Eigen::VectorXd &reactant_positions, const Eigen::VectorXd &product_positions, const std::vector< int > &reactant_types, const std::vector< int > &product_types, double kmax_factor)
EndpointAlignResult alignProductToReactantMinDist (const Eigen::VectorXd &reactant_positions, const Eigen::VectorXd &product_positions, const std::vector< int > &reactant_types, const std::vector< int > &product_types)
Eigen::VectorXd unwrapEndpointsMinimumImage (const Eigen::VectorXd &reactant_positions, const Eigen::VectorXd &product_positions, const std::array< double, 9 > &cell)
EndpointAlignResult alignProductPeriodicMinImage (const Eigen::VectorXd &reactant_positions, const Eigen::VectorXd &product_positions, const std::vector< int > &reactant_types, const std::vector< int > &product_types, const std::array< double, 9 > &cell)
Eigen::VectorXd kabschAlignProductToReactant (const Eigen::VectorXd &reactant_positions, const Eigen::VectorXd &product_positions)
double rigidAlignedRmsd (const Eigen::VectorXd &reference, const Eigen::VectorXd &mobile)
void lebedevAddOrbit (std::vector< LebedevNode > &nodes, double x, double y, double z, double weight)
std::vector< LebedevNode > lebedevLaikovGrid (int order)
 order is 6, 14, or 26. Any other value throws.
double lebedevWeightSum (int order)
Eigen::Matrix3d lebedevNodeRotation (const LebedevNode &node)
 Proper rotation taking e_z to the node. Identity for the north pole.
OracleOrientation orientGeometryForOracle (const Eigen::VectorXd &positions, const Eigen::VectorXd &reference, const std::vector< int > &types, bool align, double kmax_factor)
void pullForcesToCallerFrame (double *forces, long n_atoms, const Eigen::Matrix3d &rotation)
template<class Eval>
void averageOverLebedev (long n_atoms, const double *positions, int order, Eval eval, double *energy, double *forces, double *energy_noise, double *force_noise)

Function Documentation

◆ addFarSource()

void aux::addFarSource ( double tensor[3][3],
const double r[3],
double weight )
inline

Definition at line 49 of file FarField.h.

50{
51 const double r2 = r[0] * r[0] + r[1] * r[1] + r[2] * r[2];
52 if (!(r2 > 0.0)) return;
53 const double scale = weight / (r2 * r2 * r2);
54 for (int a = 0; a < 3; ++a) {
55 for (int b = 0; b < 3; ++b)
56 tensor[a][b] += scale * r[a] * r[b];
57 }
58}

◆ alignProductPeriodicMinImage()

EndpointAlignResult aux::alignProductPeriodicMinImage ( const Eigen::VectorXd & reactant_positions,
const Eigen::VectorXd & product_positions,
const std::vector< int > & reactant_types,
const std::vector< int > & product_types,
const std::array< double, 9 > & cell )

Same correspondence as alignProductToReactantMinDist, with minimum-image distances and no rigid rotation. aligned is the unwrapped product.

Definition at line 387 of file IRAAlign.cpp.

392{
394 const Eigen::Index n = reactant_positions.size();
395 const int nat = static_cast<int>(n / 3);
396 if (n == 0 || n != product_positions.size() || n % 3 != 0 ||
397 static_cast<int>(reactant_types.size()) != nat ||
398 static_cast<int>(product_types.size()) != nat ||
399 !gpr::geometry::cellIsMicLattice(cell.data())) {
400 res.error = -2;
401 return res;
402 }
403 res.available = true;
404 const gpr::geometry::PairBox box(cell);
405 Eigen::Map<const Eigen::Matrix<double, 3, Eigen::Dynamic>> react(
406 reactant_positions.data(), 3, nat);
407 Eigen::Map<const Eigen::Matrix<double, 3, Eigen::Dynamic>> prod(
408 product_positions.data(), 3, nat);
409
410 auto mic_norm = [&](int i, int j) {
411 return box.displacement(react.col(i), prod.col(j)).norm();
412 };
413 Eigen::MatrixXd cost(nat, nat);
414 double max_dist = 0.0;
415 for (int i = 0; i < nat; ++i)
416 for (int j = 0; j < nat; ++j)
417 max_dist = std::max(max_dist, mic_norm(i, j));
418 const double type_penalty = (max_dist + 1.0) * (nat + 1);
419 for (int i = 0; i < nat; ++i) {
420 for (int j = 0; j < nat; ++j) {
421 double d = mic_norm(i, j);
422 if (reactant_types[static_cast<std::size_t>(i)] !=
423 product_types[static_cast<std::size_t>(j)])
424 d += type_penalty;
425 cost(i, j) = d;
426 }
427 }
428 const std::vector<int> perm = aux::solve_assignment_indices(cost);
429 if (static_cast<int>(perm.size()) != nat) {
430 res.error = -4;
431 return res;
432 }
433 for (int i = 0; i < nat; ++i) {
434 const int p = perm[static_cast<std::size_t>(i)];
435 if (p < 0 || p >= nat ||
436 product_types[static_cast<std::size_t>(p)] !=
437 reactant_types[static_cast<std::size_t>(i)]) {
438 res.error = -3;
439 return res;
440 }
441 }
442 res.applied = true;
443 res.method = "periodic_min_image";
444 res.permutation.assign(perm.begin(), perm.end());
445
446 bool perm_identity = true;
447 for (int i = 0; i < nat; ++i)
448 if (perm[static_cast<std::size_t>(i)] != i) {
449 perm_identity = false;
450 break;
451 }
452
453 auto bonds_of = [&](const Eigen::VectorXd& flat,
454 const std::vector<int>& types) {
455 BondSet bonds;
456 Eigen::Map<const Eigen::Matrix<double, 3, Eigen::Dynamic>> P(
457 flat.data(), 3, nat);
458 for (int i = 0; i < nat; ++i) {
459 for (int j = i + 1; j < nat; ++j) {
460 const double cutoff = kCovalentBondTolerance *
462 types[static_cast<std::size_t>(i)]) +
464 types[static_cast<std::size_t>(j)]));
465 if (box.displacement(P.col(i), P.col(j)).norm() < cutoff)
466 bonds.emplace(i, j);
467 }
468 }
469 return bonds;
470 };
471
472 if (!perm_identity) {
473 Eigen::VectorXd prod_swapped(n);
474 for (int i = 0; i < nat; ++i)
475 prod_swapped.segment<3>(3 * i) = product_positions.segment<3>(
476 3 * perm[static_cast<std::size_t>(i)]);
477 const BondSet react_bonds =
478 bonds_of(reactant_positions, reactant_types);
479 const BondSet identity_bonds =
480 bonds_of(product_positions, product_types);
481 const BondSet assigned_bonds = bonds_of(prod_swapped, reactant_types);
483 bondChangeCount(react_bonds, identity_bonds);
485 bondChangeCount(react_bonds, assigned_bonds);
486 BondSet permuted_react_bonds;
487 for (const auto& bond: react_bonds) {
488 const int a = perm[static_cast<std::size_t>(bond.first)];
489 const int b = perm[static_cast<std::size_t>(bond.second)];
490 permuted_react_bonds.insert({std::min(a, b), std::max(a, b)});
491 }
492 const bool endpoint_symmetry = assigned_bonds == identity_bonds ||
493 permuted_react_bonds == react_bonds;
494 if (product_types == reactant_types && !endpoint_symmetry) {
495 std::iota(res.permutation.begin(), res.permutation.end(), 0);
496 perm_identity = true;
497 res.bond_graph_kept_identity = true;
498 }
499 }
500
501 Eigen::VectorXd chosen = product_positions;
502 if (!perm_identity) {
503 for (int i = 0; i < nat; ++i)
504 chosen.segment<3>(3 * i) = product_positions.segment<3>(
505 3 * res.permutation[static_cast<std::size_t>(i)]);
506 }
507 const Eigen::VectorXd unwrapped =
508 unwrapEndpointsMinimumImage(reactant_positions, chosen, cell);
509 double hd = 0.0;
510 for (int i = 0; i < nat; ++i)
511 hd = std::max(hd, (react.col(i) - unwrapped.segment<3>(3 * i)).norm());
512 res.hausdorff = hd;
513 if (perm_identity &&
514 (unwrapped - product_positions).cwiseAbs().maxCoeff() < 1e-9) {
515 res.identity = true;
516 } else {
517 res.aligned = unwrapped;
518 }
519 return res;
520}
std::vector< int > solve_assignment_indices(const Eigen::MatrixXd &cost_matrix)
Like solve_assignment_problem, but returns the optimal assignment.
Definition Distance.cpp:193
Eigen::VectorXd unwrapEndpointsMinimumImage(const Eigen::VectorXd &reactant_positions, const Eigen::VectorXd &product_positions, const std::array< double, 9 > &cell)
Definition IRAAlign.cpp:367
bool cellIsMicLattice(const double cell[9]) noexcept
Nonzero ASE 3x3 that is not the 25 A vacuum convention.
Definition MinImage.h:56
double cordero_radius_angstrom(int Z) noexcept
Convert one Cordero entry to Angstrom (kernel length-scale unit).
Eigen::VectorXd aligned
Definition IRAAlign.h:33
const char * method
"ira_match" or "cshda_svd"
Definition IRAAlign.h:38
int error
0 on success; libira cerr or local code
Definition IRAAlign.h:30
bool available
built with WITH_IRA and libira linked
Definition IRAAlign.h:24
std::vector< int > permutation
Definition IRAAlign.h:31
double hausdorff
Hausdorff distance after alignment.
Definition IRAAlign.h:29
bool applied
libira_match succeeded (error == 0)
Definition IRAAlign.h:25

◆ alignProductToReactant()

EndpointAlignResult aux::alignProductToReactant ( const Eigen::VectorXd & reactant_positions,
const Eigen::VectorXd & product_positions,
const std::vector< int > & reactant_types,
const std::vector< int > & product_types,
double kmax_factor = 1.8 )

Match the product endpoint onto the reactant frame.

Coordinates are flat 3N arrays (xyzxyz), which is exactly the Fortran-side (3, nat) column-major layout libira expects. Types are atomic numbers per endpoint in that endpoint's own file order. kmax_factor is libira_match's km_factor (must exceed 1.0; the IRA examples and eOn's tests use values in [1.0, 10.0], default 1.8).

When the assignment comes back as the identity (permutation[i] == i, rotation within 1e-9 of I, translation within 1e-9 of 0) the result sets identity=true and leaves aligned empty: consistently ordered inputs pass through without picking up floating-point noise from the rotation product.

Collinear molecules (e.g. HCN) have no IRA rotation basis, so libira_match reports "no basis could be found"; the helper then falls back to libira_cshda_svd (geometric-center CShDA assignment + single-shot SVD), which resolves permutations and translations in an already rotation-consistent frame – exactly the scrambled-order endpoint case.

Definition at line 63 of file IRAAlign.cpp.

68{
70#ifdef WITH_IRA
71 res.available = true;
72 const int nat = static_cast<int>(reactant_types.size());
73 if (static_cast<int>(product_types.size()) != nat ||
74 reactant_positions.size() != 3 * nat ||
75 product_positions.size() != 3 * nat || nat == 0) {
76 res.error = -2; // shape mismatch; not a libira failure
77 return res;
78 }
79
80 // libira takes non-const pointers; work on copies. The flat xyzxyz
81 // layout is the (3, nat) column-major array Fortran expects.
82 std::vector<int> typ1(reactant_types), typ2(product_types);
83 std::vector<double> c1(reactant_positions.data(),
84 reactant_positions.data() + 3 * nat);
85 std::vector<double> c2(product_positions.data(),
86 product_positions.data() + 3 * nat);
87
88 // Candidate central atoms: -1 in slot 0 means "use the geometric
89 // center as origin", the equal-atom-count convention eOn's
90 // IRACompare::match uses (indices are F-style otherwise).
91 std::vector<int> cand1(static_cast<size_t>(nat), 0);
92 std::vector<int> cand2(static_cast<size_t>(nat), 0);
93 cand1[0] = -1;
94 cand2[0] = -1;
95
96 std::vector<double> rmat_buf(9, 0.0);
97 std::vector<double> tr_buf(3, 0.0);
98 std::vector<int> perm_buf(static_cast<size_t>(nat), 0);
99 double hd = 0.0;
100 int ierr = 0;
101 double* rmat = rmat_buf.data();
102 double* tr = tr_buf.data();
103 int* perm = perm_buf.data();
104
105 libira_match(nat, typ1.data(), c1.data(), cand1.data(), nat, typ2.data(),
106 c2.data(), cand2.data(), kmax_factor, &rmat, &tr, &perm, &hd,
107 &ierr);
108 res.method = "ira_match";
109
110 if (ierr != 0) {
111 // Collinear structures (no IRA rotation basis) land here.
112 // CShDA on geometric-center-recentered coordinates + a
113 // single-shot SVD resolves permutation + translation for
114 // endpoints that already share a rotational frame.
115 std::vector<double> dists_buf(static_cast<size_t>(nat), 0.0);
116 double* dists = dists_buf.data();
117 int svd_err = 0;
118 libira_cshda_svd(nat, typ1.data(), c1.data(), nat, typ2.data(),
119 c2.data(), /*dthr=*/999.9, /*recenter=*/1, &perm,
120 &dists, &rmat, &tr, &svd_err);
121 if (svd_err == 0) {
122 ierr = 0;
123 hd = 0.0;
124 for (int i = 0; i < nat; ++i)
125 hd = std::max(hd, dists[i]);
126 res.method = "cshda_svd";
127 }
128 if (dists != dists_buf.data()) std::free(dists);
129 }
130
131 res.error = ierr;
132 if (ierr == 0) {
133 res.hausdorff = hd;
134 res.permutation.assign(perm, perm + nat);
135
136 // Type consistency: the assignment must map like onto like.
137 for (int i = 0; i < nat; ++i) {
138 const int p = res.permutation[static_cast<size_t>(i)];
139 if (p < 0 || p >= nat ||
140 typ2[static_cast<size_t>(p)] != typ1[static_cast<size_t>(i)]) {
141 res.error = -3;
142 break;
143 }
144 }
145 }
146
147 if (res.error == 0) {
148 res.applied = true;
149 for (int k = 0; k < 9; ++k)
150 res.rotation[static_cast<size_t>(k)] = rmat[k];
151 for (int d = 0; d < 3; ++d)
152 res.translation[static_cast<size_t>(d)] = tr[d];
153
154 // Identity gate: consistently ordered inputs must pass through
155 // bit-equal, so detect the identity assignment and skip the
156 // floating-point transform entirely. The returned rmat is in C
157 // row-major order (rmat[3*i + j] = R(i, j)) after libira's
158 // final transpose; the SVD rotation carries ~1e-15 noise for
159 // identical structures, hence the 1e-9 gate.
160 bool perm_identity = true;
161 for (int i = 0; i < nat; ++i) {
162 if (res.permutation[static_cast<size_t>(i)] != i) {
163 perm_identity = false;
164 break;
165 }
166 }
167 double dev = 0.0;
168 for (int i = 0; i < 3; ++i) {
169 for (int j = 0; j < 3; ++j) {
170 const double ident = (i == j) ? 1.0 : 0.0;
171 dev = std::max(dev, std::fabs(rmat[3 * i + j] - ident));
172 }
173 dev = std::max(dev, std::fabs(tr[i]));
174 }
175
176 if (perm_identity && dev < 1e-9) {
177 res.identity = true;
178 } else {
179 // Apply the match exactly as documented by libira_match:
180 // coords2_new(:, i) = R * coords2(:, perm(i)) + tr
181 res.aligned.resize(3 * nat);
182 for (int i = 0; i < nat; ++i) {
183 const int p = res.permutation[static_cast<size_t>(i)];
184 for (int d = 0; d < 3; ++d) {
185 res.aligned[3 * i + d] = rmat[3 * d + 0] * c2[3 * p + 0] +
186 rmat[3 * d + 1] * c2[3 * p + 1] +
187 rmat[3 * d + 2] * c2[3 * p + 2] +
188 tr[d];
189 }
190 }
191 }
192 }
193
194 // libira's wrapper fills the caller buffers in place, but guard the
195 // reallocation path the same way eOn does: replacement buffers come
196 // from c_malloc on the Fortran side, so std::free matches.
197 if (rmat != rmat_buf.data()) std::free(rmat);
198 if (tr != tr_buf.data()) std::free(tr);
199 if (perm != perm_buf.data()) std::free(perm);
200#else
201 (void)reactant_positions;
202 (void)product_positions;
203 (void)reactant_types;
204 (void)product_types;
205 (void)kmax_factor;
206 res.error = -1;
207#endif
208 return res;
209}
std::array< double, 3 > translation
Definition IRAAlign.h:37
std::array< double, 9 > rotation
row-major R
Definition IRAAlign.h:35

◆ alignProductToReactantMinDist()

EndpointAlignResult aux::alignProductToReactantMinDist ( const Eigen::VectorXd & reactant_positions,
const Eigen::VectorXd & product_positions,
const std::vector< int > & reactant_types,
const std::vector< int > & product_types )

Endpoint correspondence by minimum total displacement, computed consistently.

Anchors the rigid alignment to the IDENTITY atom correspondence (a Kabsch rotation over the input pairing), then solves the type-constrained minimum-total-distance assignment (Hungarian) in that fixed frame. Decoupling the rotation from the permutation is what makes the result consistent: a free-rotation RMSD/Hausdorff search (IRA) co-optimises both and shuffles a reaction's equivalent atoms into a lower-score but chemically wrong reordering. Minimising total distance in the identity-anchored frame re-pairs atoms that are closer to a different partner; the re-pairing is kept only when the permutation maps the covalent bond graph (Cordero radii, 1.2 tolerance) of the reactant or of the product onto itself, so equivalent atoms of an endpoint may be renamed while the reaction stays that of the supplied ordering. Endpoints that do not list the same elements in the same order have no supplied correspondence and take the assignment.

Needs no IRA: pure Eigen Kabsch + Hungarian, so it is always available and deterministic. Returns identity=true for a bit-equal pass-through.

Definition at line 211 of file IRAAlign.cpp.

216{
218 const Eigen::Index n = reactant_positions.size();
219 const int nat = static_cast<int>(n / 3);
220 if (n == 0 || n != product_positions.size() || n % 3 != 0 ||
221 static_cast<int>(reactant_types.size()) != nat ||
222 static_cast<int>(product_types.size()) != nat) {
223 res.error = -2; // shape mismatch
224 return res;
225 }
226 res.available = true;
227
228 // Anchor the rigid frame to the IDENTITY correspondence: the input
229 // ordering is the authoritative chemical pairing, so the Kabsch rotation
230 // is computed over the identity pairing. This removes a spurious frame
231 // difference (mis-framed endpoints like collinear HCN or the spread-vs-
232 // compact 03_h2co frames) WITHOUT coupling the rotation to the
233 // permutation. That coupling is exactly what lets a free-rotation
234 // RMSD/Hausdorff search (IRA) shuffle a reaction's equivalent atoms into
235 // a lower-score but chemically wrong reordering.
236 const Eigen::VectorXd aligned_id =
237 kabschAlignProductToReactant(reactant_positions, product_positions);
238
239 Eigen::Map<const Eigen::Matrix<double, 3, Eigen::Dynamic>> react(
240 reactant_positions.data(), 3, nat);
241 Eigen::Map<const Eigen::Matrix<double, 3, Eigen::Dynamic>> prod_id(
242 aligned_id.data(), 3, nat);
243
244 // Type-constrained minimum-total-distance assignment in the fixed
245 // identity-anchored frame. A type mismatch is penalised above any
246 // feasible same-type total, so the Hungarian only pairs like with like.
247 Eigen::MatrixXd cost(nat, nat);
248 double max_dist = 0.0;
249 for (int i = 0; i < nat; ++i)
250 for (int j = 0; j < nat; ++j)
251 max_dist =
252 std::max(max_dist, (react.col(i) - prod_id.col(j)).norm());
253 const double type_penalty = (max_dist + 1.0) * (nat + 1);
254 for (int i = 0; i < nat; ++i) {
255 for (int j = 0; j < nat; ++j) {
256 double d = (react.col(i) - prod_id.col(j)).norm();
257 if (reactant_types[i] != product_types[j]) d += type_penalty;
258 cost(i, j) = d;
259 }
260 }
261
262 const std::vector<int> perm = aux::solve_assignment_indices(cost);
263 if (static_cast<int>(perm.size()) != nat) {
264 res.error = -4; // solver failure
265 return res;
266 }
267 for (int i = 0; i < nat; ++i) {
268 if (perm[static_cast<size_t>(i)] < 0 ||
269 perm[static_cast<size_t>(i)] >= nat ||
270 product_types[static_cast<size_t>(perm[static_cast<size_t>(i)])] !=
271 reactant_types[static_cast<size_t>(i)]) {
272 res.error = -3; // assignment crossed atom types
273 return res;
274 }
275 }
276 res.applied = true;
277 res.permutation.assign(perm.begin(), perm.end());
278
279 bool perm_identity = true;
280 for (int i = 0; i < nat; ++i)
281 if (perm[static_cast<size_t>(i)] != i) {
282 perm_identity = false;
283 break;
284 }
285 if (!perm_identity) {
286 // A shorter total displacement is a valid re-pairing only when it
287 // is the same reaction: the supplied correspondence states which
288 // bonds form and which break, and minimum total distance across a
289 // rearrangement swaps like atoms between partners into another
290 // reaction (a proton relay through a second water becomes the
291 // direct four-centre transfer, with fewer bond changes and a
292 // higher barrier). Two correspondences describe one reaction when
293 // they differ by a symmetry of an endpoint: the re-pairing stands
294 // when the permutation maps the reactant's bond graph onto itself
295 // (it renames equivalent reactant atoms, two carboxylate oxygens
296 // or the hydrogens of a methyl group) or the product's. When the
297 // two endpoints do not list the same elements in the same order
298 // the input ordering is no correspondence and the assignment is
299 // taken.
300 Eigen::VectorXd prod_swapped(n);
301 for (int i = 0; i < nat; ++i)
302 for (int d = 0; d < 3; ++d)
303 prod_swapped[3 * i + d] =
304 product_positions[3 * perm[static_cast<size_t>(i)] + d];
305 const BondSet react_bonds = covalentBonds(react, reactant_types);
306 const BondSet identity_bonds = covalentBonds(
307 PosMap(product_positions.data(), 3, nat), product_types);
308 const BondSet assigned_bonds =
309 covalentBonds(PosMap(prod_swapped.data(), 3, nat), reactant_types);
311 bondChangeCount(react_bonds, identity_bonds);
313 bondChangeCount(react_bonds, assigned_bonds);
314 BondSet permuted_react_bonds;
315 for (const auto& bond: react_bonds) {
316 const int a = perm[static_cast<size_t>(bond.first)];
317 const int b = perm[static_cast<size_t>(bond.second)];
318 permuted_react_bonds.insert({std::min(a, b), std::max(a, b)});
319 }
320 const bool endpoint_symmetry = assigned_bonds == identity_bonds ||
321 permuted_react_bonds == react_bonds;
322 if (product_types == reactant_types && !endpoint_symmetry) {
323 std::iota(res.permutation.begin(), res.permutation.end(), 0);
324 perm_identity = true;
325 res.bond_graph_kept_identity = true;
326 }
327 }
328
329 if (perm_identity) {
330 // Identity correspondence: keep the rigid reframe. A true no-op
331 // (already a common frame) passes the product through bit-equal.
332 res.method = "kabsch_identity";
333 const double dev =
334 (aligned_id - product_positions).cwiseAbs().maxCoeff();
335 if (dev < 1e-9) {
336 res.identity = true;
337 } else {
338 res.aligned = aligned_id;
339 }
340 double hd = 0.0;
341 for (int i = 0; i < nat; ++i)
342 hd = std::max(hd, (react.col(i) - prod_id.col(i)).norm());
343 res.hausdorff = hd;
344 } else {
345 // Genuine re-pairing (scrambled input ordering): permute the product
346 // then refine the rigid rotation once for the chosen pairing. The
347 // assignment is not reopened, so there is no rotation/permutation
348 // coupling.
349 Eigen::VectorXd prod_perm(n);
350 for (int i = 0; i < nat; ++i)
351 for (int d = 0; d < 3; ++d)
352 prod_perm[3 * i + d] =
353 product_positions[3 * perm[static_cast<size_t>(i)] + d];
354 res.aligned =
355 kabschAlignProductToReactant(reactant_positions, prod_perm);
356 res.method = "kabsch_hungarian";
357 Eigen::Map<const Eigen::Matrix<double, 3, Eigen::Dynamic>> pa(
358 res.aligned.data(), 3, nat);
359 double hd = 0.0;
360 for (int i = 0; i < nat; ++i)
361 hd = std::max(hd, (react.col(i) - pa.col(i)).norm());
362 res.hausdorff = hd;
363 }
364 return res;
365}
Eigen::VectorXd kabschAlignProductToReactant(const Eigen::VectorXd &reactant_positions, const Eigen::VectorXd &product_positions)

◆ averageOverLebedev()

template<class Eval>
void aux::averageOverLebedev ( long n_atoms,
const double * positions,
int order,
Eval eval,
double * energy,
double * forces,
double * energy_noise,
double * force_noise )
inline

Weighted mean of evaluations at the Lebedev node rotations. eval(pos, forces, energy, energy_noise, force_noise) sees one rotated copy; forces it writes are in that copy's frame.

Definition at line 251 of file LebedevLaikov.h.

254{
255 const std::vector<LebedevNode> nodes = lebedevLaikovGrid(order);
256 const Eigen::Index n3 = 3 * n_atoms;
257 Eigen::Map<const Eigen::Matrix<double, 3, Eigen::Dynamic>> cloud(
258 positions, 3, n_atoms);
259 const Eigen::Vector3d centroid = cloud.rowwise().mean();
260 Eigen::VectorXd force_acc = Eigen::VectorXd::Zero(n3);
261 Eigen::VectorXd force_i(n3);
262 Eigen::VectorXd rotated(n3);
263 double energy_acc = 0.0;
264 double energy_noise_acc = 0.0;
265 double force_noise_acc = 0.0;
266 for (const LebedevNode& node: nodes) {
267 const bool north = std::fabs(node.x) < 1.0e-15 &&
268 std::fabs(node.y) < 1.0e-15 && node.z > 0.0;
269 const double* sample = positions;
270 const Eigen::Matrix3d rotation = lebedevNodeRotation(node);
271 if (!north) {
272 Eigen::Map<Eigen::Matrix<double, 3, Eigen::Dynamic>> out(
273 rotated.data(), 3, n_atoms);
274 out =
275 (rotation * (cloud.colwise() - centroid)).colwise() + centroid;
276 sample = rotated.data();
277 }
278 double sample_energy = 0.0;
279 double sample_energy_noise = 0.0;
280 double sample_force_noise = 0.0;
281 force_i.setZero();
282 eval(sample, force_i.data(), &sample_energy, &sample_energy_noise,
283 &sample_force_noise);
284 if (!north) {
285 Eigen::Map<Eigen::Matrix<double, 3, Eigen::Dynamic>> mapped(
286 force_i.data(), 3, n_atoms);
287 const Eigen::Matrix<double, 3, Eigen::Dynamic> pulled =
288 rotation.transpose() * mapped;
289 mapped = pulled;
290 }
291 force_acc += node.weight * force_i;
292 energy_acc += node.weight * sample_energy;
293 energy_noise_acc += node.weight * sample_energy_noise;
294 force_noise_acc += node.weight * sample_force_noise;
295 }
296 if (energy) *energy = energy_acc;
297 if (energy_noise) *energy_noise = energy_noise_acc;
298 if (force_noise) *force_noise = force_noise_acc;
299 if (forces) {
300 Eigen::Map<Eigen::VectorXd>(forces, n3) = force_acc;
301 }
302}
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
Eigen::Matrix3d lebedevNodeRotation(const LebedevNode &node)
Proper rotation taking e_z to the node. Identity for the north pole.
std::vector< LebedevNode > lebedevLaikovGrid(int order)
order is 6, 14, or 26. Any other value throws.

◆ calculate_aligned_rmsd()

double aux::calculate_aligned_rmsd ( const gpr::Coord & P,
const gpr::Coord & Q )

Definition at line 283 of file Distance.cpp.

284{
285 // P and Q are single configurations, 1 x 3N rows.
286 if (P.cols() != Q.cols() || P.rows() < 1 || Q.rows() < 1) {
287 // Structures must have the same number of atoms.
288 return std::numeric_limits<double>::max();
289 }
290 const Eigen::VectorXd p = P.row(0).transpose();
291 const Eigen::VectorXd q = Q.row(0).transpose();
292 return rigidAlignedRmsd(q, p);
293}
double rigidAlignedRmsd(const Eigen::VectorXd &reference, const Eigen::VectorXd &mobile)

◆ farContract()

void aux::farContract ( const double tensor[3][3],
const double delta[3],
double out[3] )
inline

Definition at line 71 of file FarField.h.

73{
74 for (int a = 0; a < 3; ++a) {
75 out[a] = tensor[a][0] * delta[0] + tensor[a][1] * delta[1] +
76 tensor[a][2] * delta[2];
77 }
78}

◆ farFieldCentre()

const double * aux::farFieldCentre ( const gpr::AtomsConfiguration & conf,
Eigen::Index atom )
inline

Definition at line 15 of file FarField.h.

17{
18 const auto& reference = conf.atoms_mov.positions;
19 if (reference.rows() != 1 ||
20 reference.cols() != 3 * conf.atoms_mov.type.size() || atom < 0 ||
21 atom >= conf.atoms_mov.type.size())
22 throw std::invalid_argument(
23 "far-field kernel requires fixed reference positions for every "
24 "moving atom");
25 const double* centre = reference.data() + 3 * atom;
26 for (int d = 0; d < 3; ++d)
27 if (!std::isfinite(centre[d]))
28 throw std::invalid_argument("far-field reference must be finite");
29 return centre;
30}
AtomsPositionAndType atoms_mov
Info on moving atoms.
Definition Structures.h:844

◆ farFieldDifference()

void aux::farFieldDifference ( const gpr::geometry::PairBox & box,
const double centre[3],
const double left[3],
const double right[3],
double delta[3] )
inline

Definition at line 36 of file FarField.h.

39{
40 double a[3], b[3];
41 box.displacement(centre, left, a);
42 box.displacement(centre, right, b);
43 for (int d = 0; d < 3; ++d)
44 delta[d] = a[d] - b[d];
45}
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

◆ farFromCentre()

bool aux::farFromCentre ( const gpr::geometry::PairBox & box,
const double centre[3],
const double frozen[3],
double radius )
inline

Definition at line 81 of file FarField.h.

84{
85 double r[3];
86 box.displacement(frozen, centre, r);
87 const double r2 = r[0] * r[0] + r[1] * r[1] + r[2] * r[2];
88 return r2 >= radius * radius;
89}

◆ farQuadratic()

double aux::farQuadratic ( const double tensor[3][3],
const double delta[3] )
inline

Definition at line 60 of file FarField.h.

61{
62 double contracted[3] = {0.0, 0.0, 0.0};
63 for (int a = 0; a < 3; ++a) {
64 contracted[a] = tensor[a][0] * delta[0] + tensor[a][1] * delta[1] +
65 tensor[a][2] * delta[2];
66 }
67 return delta[0] * contracted[0] + delta[1] * contracted[1] +
68 delta[2] * contracted[2];
69}

◆ get_canonical_configuration()

std::pair< gpr::Coord, gpr::FieldMatrixIdx > aux::get_canonical_configuration ( const gpr::Coord & x_in,
const gpr::FieldMatrixIdx & types_in )

Definition at line 44 of file Distance.cpp.

46{
47 const Eigen::Index num_atoms = types_in.size();
48 if (num_atoms == 0) {
49 return {gpr::Coord(), gpr::FieldMatrixIdx()};
50 }
51
52 std::vector<AtomSignature> atom_signatures(num_atoms);
53
54 // For each atom, compute its signature
55 for (Eigen::Index i = 0; i < num_atoms; ++i) {
56 atom_signatures[i].original_index = i;
57 atom_signatures[i].type = types_in(0, i);
58
59 // The signature is the vector of inverse distances to all other atoms
60 for (Eigen::Index j = 0; j < num_atoms; ++j) {
61 if (i == j) continue;
62 double r_ij =
63 (gpr::coord::at(x_in, 0, i) - gpr::coord::at(x_in, 0, j))
64 .norm();
65 // Coincident atoms would divide by zero. Record infinity rather
66 // than dropping the entry: dropping made the signature shorter for
67 // exactly those atoms, and operator< compares the vectors
68 // lexicographically, so an atom's rank depended on how many
69 // near-coincident neighbours it had rather than on its geometry.
70 // Every atom now contributes num_atoms - 1 entries, so the
71 // canonical order is well defined for degenerate input too. No
72 // physically valid configuration reaches this branch -- nuclei do
73 // not sit 1e-9 apart -- so the ordering is unchanged in practice.
74 atom_signatures[i].signature_vec.push_back(
75 r_ij > 1e-9 ? 1.0 / r_ij
76 : std::numeric_limits<double>::infinity());
77 }
78 // Sort the signature vector itself to make it invariant to the ordering
79 // of other atoms
80 std::sort(atom_signatures[i].signature_vec.begin(),
81 atom_signatures[i].signature_vec.end());
82 }
83
84 // Sort the atoms based on their type and signature
85 std::sort(atom_signatures.begin(), atom_signatures.end());
86
87 // Create the new canonical configuration based on the sorted order
88 gpr::Coord x_canonical;
89 x_canonical.resize(1, num_atoms * 3);
90 gpr::FieldMatrixIdx types_canonical(1, num_atoms);
91
92 for (Eigen::Index i = 0; i < num_atoms; ++i) {
93 gpr::Index_t old_index = atom_signatures[i].original_index;
94 gpr::coord::set(x_canonical, 0, i, gpr::coord::at(x_in, 0, old_index));
95 types_canonical(0, i) = types_in(0, old_index);
96 }
97
98 return {x_canonical, types_canonical};
99}
Eigen::Vector3d at(const FieldMatrixd &mat, Index_t i)
void set(FieldMatrixd &mat, Index_t i, const Eigen::Vector3d &vec)
Eigen::Matrix< Index_t, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixIdx
Definition Macros.h:29
FieldMatrixd Coord
Definition Macros.h:35
uint32_t Index_t
Definition Macros.h:17

◆ kabschAlignProductToReactant()

Eigen::VectorXd aux::kabschAlignProductToReactant ( const Eigen::VectorXd & reactant_positions,
const Eigen::VectorXd & product_positions )

Rigid (rotation + translation) alignment of the product endpoint onto the reactant frame using the identity atom correspondence (rgmin's rgmin_rigid_align, the Horn quaternion solution of the Wahba problem, over flat 3N xyzxyz coordinates).

Unlike alignProductToReactant this never permutes atoms. A reaction whose endpoints are written in a rotated or translated frame (e.g. a .con where the heavy atoms appear swapped end-to-end, as in the HCN / HNC isomerisation) still interpolates physically because the rigid transform removes the spurious frame difference; at the same time the input atom identities are preserved, so a reaction whose endpoints share an atom-type multiset (the migrating vs spectator hydrogens of a tautomerisation) is never re-indexed into a different reaction. Rigid motion is an energy-invariant symmetry operation, so the product's internal geometry is unchanged.

Returns the flat 3N aligned product. On a size mismatch or an empty / non-multiple-of-three input the product is returned unchanged.

Definition at line 34 of file KabschAlign.cpp.

37{
38 Eigen::VectorXd aligned = product_positions;
39 double rmsd = 0.0;
40 if (!rigidAlign(reactant_positions, aligned, rmsd))
41 return product_positions;
42 return aligned;
43}

◆ lebedevAddOrbit()

void aux::lebedevAddOrbit ( std::vector< LebedevNode > & nodes,
double x,
double y,
double z,
double weight )
inline

Definition at line 44 of file LebedevLaikov.h.

46{
47 std::array<double, 3> coords{x, y, z};
48 std::sort(coords.begin(), coords.end());
49 std::set<std::array<long, 3>> seen;
50 do {
51 for (int signs = 0; signs < 8; ++signs) {
52 const double sx = (signs & 1) ? -coords[0] : coords[0];
53 const double sy = (signs & 2) ? -coords[1] : coords[1];
54 const double sz = (signs & 4) ? -coords[2] : coords[2];
55 const std::array<long, 3> key{std::lround(sx * 1.0e8),
56 std::lround(sy * 1.0e8),
57 std::lround(sz * 1.0e8)};
58 if (!seen.insert(key).second) continue;
59 nodes.push_back(LebedevNode{sx, sy, sz, weight});
60 }
61 } while (std::next_permutation(coords.begin(), coords.end()));
62}
@ z
Definition Enums.h:28
@ x
Definition Enums.h:28
@ y
Definition Enums.h:28
constexpr std::array< Real, 8 > nodes

◆ lebedevLaikovGrid()

std::vector< LebedevNode > aux::lebedevLaikovGrid ( int order)
inline

order is 6, 14, or 26. Any other value throws.

Definition at line 65 of file LebedevLaikov.h.

66{
67 std::vector<LebedevNode> nodes;
68 const double inv_sqrt2 = 1.0 / std::sqrt(2.0);
69 const double inv_sqrt3 = 1.0 / std::sqrt(3.0);
70 if (order == 6) {
71 lebedevAddOrbit(nodes, 1.0, 0.0, 0.0, 1.0 / 6.0);
72 } else if (order == 14) {
73 // 6·(1/15) + 8·(3/40) = 1.
74 lebedevAddOrbit(nodes, 1.0, 0.0, 0.0, 1.0 / 15.0);
75 lebedevAddOrbit(nodes, inv_sqrt3, inv_sqrt3, inv_sqrt3, 3.0 / 40.0);
76 } else if (order == 26) {
77 // 6·(1/21) + 12·(4/105) + 8·(9/280) = 1.
78 lebedevAddOrbit(nodes, 1.0, 0.0, 0.0, 1.0 / 21.0);
79 lebedevAddOrbit(nodes, inv_sqrt2, inv_sqrt2, 0.0, 4.0 / 105.0);
80 lebedevAddOrbit(nodes, inv_sqrt3, inv_sqrt3, inv_sqrt3, 9.0 / 280.0);
81 } else {
82 throw std::invalid_argument(
83 "Lebedev-Laikov order must be 6, 14, or 26");
84 }
85 return nodes;
86}
void lebedevAddOrbit(std::vector< LebedevNode > &nodes, double x, double y, double z, double weight)

◆ lebedevNodeRotation()

Eigen::Matrix3d aux::lebedevNodeRotation ( const LebedevNode & node)
inline

Proper rotation taking e_z to the node. Identity for the north pole.

Definition at line 97 of file LebedevLaikov.h.

98{
99 const Eigen::Vector3d n(node.x, node.y, node.z);
100 const Eigen::Vector3d ez(0.0, 0.0, 1.0);
101 const double cosine = n.dot(ez);
102 if (cosine > 1.0 - 1.0e-14) return Eigen::Matrix3d::Identity();
103 if (cosine < -1.0 + 1.0e-14) {
104 Eigen::Matrix3d half_turn = Eigen::Matrix3d::Identity();
105 half_turn(1, 1) = -1.0;
106 half_turn(2, 2) = -1.0;
107 return half_turn;
108 }
109 const Eigen::Vector3d crossed = ez.cross(n);
110 const double sine = crossed.norm();
111 const Eigen::Vector3d axis = crossed / sine;
112 Eigen::Matrix3d skew = Eigen::Matrix3d::Zero();
113 skew(0, 1) = -axis.z();
114 skew(0, 2) = axis.y();
115 skew(1, 0) = axis.z();
116 skew(1, 2) = -axis.x();
117 skew(2, 0) = -axis.y();
118 skew(2, 1) = axis.x();
119 return Eigen::Matrix3d::Identity() + skew * sine +
120 skew * skew * (1.0 - cosine);
121}

◆ lebedevWeightSum()

double aux::lebedevWeightSum ( int order)
inline

Definition at line 88 of file LebedevLaikov.h.

89{
90 double sum = 0.0;
91 for (const LebedevNode& node: lebedevLaikovGrid(order))
92 sum += node.weight;
93 return sum;
94}

◆ orientGeometryForOracle()

OracleOrientation aux::orientGeometryForOracle ( const Eigen::VectorXd & positions,
const Eigen::VectorXd & reference,
const std::vector< int > & types,
bool align,
double kmax_factor )
inline

Rigid frame for one oracle energy evaluation.

When align is false the returned coordinates are positions unchanged (a rotated copy of an identical geometry stays rotated). When align is true, IRA matches positions onto reference. A non-identity atom permutation is rejected and the identity-paired Kabsch rotation is used instead, so a reacting image is never reindexed. An identity match returns positions bit-equal.

Definition at line 204 of file LebedevLaikov.h.

207{
209 out.positions = positions;
210 if (!align) return out;
211 const int nat = static_cast<int>(types.size());
212 if (nat <= 0 || positions.size() != 3L * nat ||
213 reference.size() != positions.size()) {
214 return out;
215 }
216 const EndpointAlignResult matched =
217 alignProductToReactant(reference, positions, types, types, kmax_factor);
218 if (matched.applied && matched.identity) return out;
219 if (matched.applied &&
220 detail::permutationIsIdentity(matched.permutation, nat) &&
221 matched.aligned.size() == positions.size()) {
222 out.positions = matched.aligned;
223 out.passthrough = false;
224 for (int i = 0; i < 3; ++i) {
225 for (int j = 0; j < 3; ++j) {
226 out.rotation(i, j) =
227 matched.rotation[static_cast<size_t>(3 * i + j)];
228 }
229 out.translation[i] = matched.translation[static_cast<size_t>(i)];
230 }
231 return out;
232 }
233 return detail::kabschOrientation(reference, positions);
234}
EndpointAlignResult alignProductToReactant(const Eigen::VectorXd &reactant_positions, const Eigen::VectorXd &product_positions, const std::vector< int > &reactant_types, const std::vector< int > &product_types, double kmax_factor)
Definition IRAAlign.cpp:63

◆ pullForcesToCallerFrame()

void aux::pullForcesToCallerFrame ( double * forces,
long n_atoms,
const Eigen::Matrix3d & rotation )
inline

Definition at line 236 of file LebedevLaikov.h.

238{
239 if (!forces || n_atoms <= 0) return;
240 Eigen::Map<Eigen::Matrix<double, 3, Eigen::Dynamic>> mapped(forces, 3,
241 n_atoms);
242 const Eigen::Matrix<double, 3, Eigen::Dynamic> pulled =
243 rotation.transpose() * mapped;
244 mapped = pulled;
245}

◆ realignChainToPredecessors()

ChainRealignStats aux::realignChainToPredecessors ( gpr::neb::NEBPath & path,
const std::vector< int > & atomic_numbers,
std::vector< std::vector< uint64_t > > * image_ids,
double kmax_factor = 1.8 )

IRA-align every interior image of path onto its predecessor.

Sequential sweep i = 1 .. numImages()-2: image i is matched onto the already-processed image i-1, so frames compose along the chain. Endpoints stay untouched (they are fixed by the NEB and the product endpoint already went through the startup endpoint assignment). Identity assignments are skipped entirely (bit-equal no-op), so a drift-free chain passes through unchanged.

For a non-identity assignment the image positions become R * x[perm] + t, the stored gradient (if evaluated) co-rotates as R * g[perm] (gradients are covariant under rigid motion and follow their atoms under permutation; the energy is invariant), and the per-image id row in image_ids (when non-null and sized to the path) is permuted alongside so write-out restores the original atom identities.

Definition at line 12 of file ChainRealign.cpp.

15{
17 const int n = path.numImages();
18 const int nat = static_cast<int>(atomic_numbers.size());
19 const bool track_ids =
20 image_ids != nullptr && static_cast<int>(image_ids->size()) == n;
21
22 for (int i = 1; i <= n - 2; ++i) {
23 const auto& ref = path.image(i - 1).positions;
24 auto& im = path.image(i);
25 const auto match = alignProductToReactant(
26 ref, im.positions, atomic_numbers, atomic_numbers, kmax_factor);
27 if (!match.available) return stats; // built without IRA
28 if (!match.applied) {
29 ++stats.images_failed;
30 continue; // leave the image untouched
31 }
32 if (match.identity) continue; // bit-equal pass-through
33
34 im.positions = match.aligned;
35
36 // Gradients are covariant under the rigid motion and follow
37 // their atoms under the permutation: g'_slot = R * g[perm].
38 // The energy is invariant.
39 if (im.evaluated && im.gradient.size() == 3 * nat) {
40 Eigen::VectorXd g_new(3 * nat);
41 const auto& R = match.rotation; // row-major
42 for (int a = 0; a < nat; ++a) {
43 const int p = match.permutation[static_cast<size_t>(a)];
44 for (int d = 0; d < 3; ++d) {
45 g_new[3 * a + d] = R[static_cast<size_t>(3 * d + 0)] *
46 im.gradient[3 * p + 0] +
47 R[static_cast<size_t>(3 * d + 1)] *
48 im.gradient[3 * p + 1] +
49 R[static_cast<size_t>(3 * d + 2)] *
50 im.gradient[3 * p + 2];
51 }
52 }
53 im.gradient = g_new;
54 }
55
56 if (track_ids) {
57 auto& ids = (*image_ids)[static_cast<size_t>(i)];
58 if (static_cast<int>(ids.size()) == nat) {
59 std::vector<uint64_t> permuted(static_cast<size_t>(nat));
60 for (int a = 0; a < nat; ++a)
61 permuted[static_cast<size_t>(a)] = ids[static_cast<size_t>(
62 match.permutation[static_cast<size_t>(a)])];
63 ids = std::move(permuted);
64 }
65 }
66 ++stats.images_realigned;
67 }
68 return stats;
69}
int numImages() const
Definition NEBPath.h:338
Image & image(int i)
Access image i.
Definition NEBPath.h:329
int images_failed
libira errors (image left untouched)
int images_realigned
non-identity assignments applied
Eigen::VectorXd positions
Definition NEBPath.h:40

◆ rigidAlignedRmsd()

double aux::rigidAlignedRmsd ( const Eigen::VectorXd & reference,
const Eigen::VectorXd & mobile )

RMSD after the same rigid alignment, sqrt(sum_i norm(R m_i + t - r_i)^2 / n_atoms) in the given atom order. NaN on a size mismatch, an empty or non-multiple-of-three input, or a non-finite coordinate.

Definition at line 45 of file KabschAlign.cpp.

47{
48 Eigen::VectorXd aligned = mobile;
49 double rmsd = std::numeric_limits<double>::quiet_NaN();
50 if (!reference.allFinite() || !mobile.allFinite() ||
51 !rigidAlign(reference, aligned, rmsd))
52 return std::numeric_limits<double>::quiet_NaN();
53 return rmsd;
54}

◆ solve_assignment_indices()

std::vector< int > aux::solve_assignment_indices ( const Eigen::MatrixXd & cost_matrix)

Like solve_assignment_problem, but returns the optimal assignment.

Parameters
cost_matrixA square matrix where cost_matrix(i, j) is the cost of assigning worker i to job j.
Returns
result[i] = column (job) assigned to row (worker) i. Empty on an empty or non-square / non-finite cost matrix.

Definition at line 193 of file Distance.cpp.

194{
195 return hungarian_assignment(cost_matrix);
196}

◆ solve_assignment_problem()

double aux::solve_assignment_problem ( const Eigen::MatrixXd & cost_matrix)

Solves the assignment problem using the Hungarian algorithm.

Given a cost matrix, this function finds the minimum cost assignment of workers to jobs, which is equivalent to finding the minimum total distance when pairing atoms of the same type.

Parameters
cost_matrixA square matrix where cost_matrix(i, j) is the cost of assigning worker i to job j.
Returns
The minimum total cost of the optimal assignment.

Definition at line 179 of file Distance.cpp.

180{
181 const int n = static_cast<int>(cost_matrix.rows());
182 if (n == 0) return 0.0;
183
184 const std::vector<int> xy = hungarian_assignment(cost_matrix);
185 if (xy.empty()) return std::numeric_limits<double>::infinity();
186
187 double min_cost = 0.0;
188 for (int i = 0; i < n; ++i)
189 min_cost += cost_matrix(i, xy[i]);
190 return min_cost;
191}

◆ unwrapEndpointsMinimumImage()

Eigen::VectorXd aux::unwrapEndpointsMinimumImage ( const Eigen::VectorXd & reactant_positions,
const Eigen::VectorXd & product_positions,
const std::array< double, 9 > & cell )

Place each product atom on the minimum image relative to the reactant atom in the same slot. No rotation and no permutation: a periodic cell is not free to rotate, and a fixed atom stays on its site.

Definition at line 367 of file IRAAlign.cpp.

370{
371 const Eigen::Index n = reactant_positions.size();
372 if (n == 0 || n != product_positions.size() || n % 3 != 0 ||
373 !gpr::geometry::cellIsMicLattice(cell.data())) {
374 return product_positions;
375 }
376 const int nat = static_cast<int>(n / 3);
377 const gpr::geometry::PairBox box(cell);
378 Eigen::VectorXd unwrapped(n);
379 for (int i = 0; i < nat; ++i) {
380 const Eigen::Vector3d from = reactant_positions.segment<3>(3 * i);
381 const Eigen::Vector3d to = product_positions.segment<3>(3 * i);
382 unwrapped.segment<3>(3 * i) = from + box.displacement(from, to);
383 }
384 return unwrapped;
385}