Loading...
Searching...
No Matches
IRAAlign.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
5#include "IRAAlign.h"
6
7#include <algorithm>
8#include <cmath>
9#include <cstdlib>
10#include <numeric>
11#include <set>
12#include <utility>
13
15#include "Distance.h"
16#include "MinImage.h"
17
18#ifdef WITH_IRA
19extern "C" {
20#include "iralib_interf.h"
21}
22#endif
23
24namespace {
25using PosMap = Eigen::Map<const Eigen::Matrix<double, 3, Eigen::Dynamic>>;
26using BondSet = std::set<std::pair<int, int>>;
27
28// Covalent bond graph from Cordero radii: a pair is bonded when its
29// distance lies below kCovalentBondTolerance times the radius sum, the
30// tolerance pymatgen's CovalentBondNN and RDKit's xyz2mol apply.
31constexpr double kCovalentBondTolerance = 1.2;
32
33BondSet covalentBonds(const PosMap& P, const std::vector<int>& types)
34{
35 BondSet bonds;
36 const int nat = static_cast<int>(P.cols());
37 for (int i = 0; i < nat; ++i) {
38 for (int j = i + 1; j < nat; ++j) {
39 const double cutoff =
40 kCovalentBondTolerance * (gpr::priors::cordero_radius_angstrom(
41 types[static_cast<size_t>(i)]) +
43 types[static_cast<size_t>(j)]));
44 if ((P.col(i) - P.col(j)).norm() < cutoff) bonds.emplace(i, j);
45 }
46 }
47 return bonds;
48}
49
50int bondChangeCount(const BondSet& a, const BondSet& b)
51{
52 int n = 0;
53 for (const auto& e: a)
54 n += b.count(e) == 0;
55 for (const auto& e: b)
56 n += a.count(e) == 0;
57 return n;
58}
59} // namespace
60
61namespace aux {
62
64 const Eigen::VectorXd& reactant_positions,
65 const Eigen::VectorXd& product_positions,
66 const std::vector<int>& reactant_types,
67 const std::vector<int>& product_types, double kmax_factor)
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}
210
212 const Eigen::VectorXd& reactant_positions,
213 const Eigen::VectorXd& product_positions,
214 const std::vector<int>& reactant_types,
215 const std::vector<int>& product_types)
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}
366
368 const Eigen::VectorXd& reactant_positions,
369 const Eigen::VectorXd& product_positions, const std::array<double, 9>& cell)
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}
386
388 const Eigen::VectorXd& reactant_positions,
389 const Eigen::VectorXd& product_positions,
390 const std::vector<int>& reactant_types,
391 const std::vector<int>& product_types, const std::array<double, 9>& cell)
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}
521
522} // namespace aux
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
Eigen::VectorXd kabschAlignProductToReactant(const Eigen::VectorXd &reactant_positions, const Eigen::VectorXd &product_positions)
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)
Definition IRAAlign.cpp:387
std::vector< int > solve_assignment_indices(const Eigen::MatrixXd &cost_matrix)
Like solve_assignment_problem, but returns the optimal assignment.
Definition Distance.cpp:193
EndpointAlignResult alignProductToReactantMinDist(const Eigen::VectorXd &reactant_positions, const Eigen::VectorXd &product_positions, const std::vector< int > &reactant_types, const std::vector< int > &product_types)
Definition IRAAlign.cpp:211
Eigen::VectorXd unwrapEndpointsMinimumImage(const Eigen::VectorXd &reactant_positions, const Eigen::VectorXd &product_positions, const std::array< double, 9 > &cell)
Definition IRAAlign.cpp:367
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
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
std::array< double, 3 > translation
Definition IRAAlign.h:37
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
std::array< double, 9 > rotation
row-major R
Definition IRAAlign.h:35
bool applied
libira_match succeeded (error == 0)
Definition IRAAlign.h:25