Loading...
Searching...
No Matches
Distance.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/*
6 * Distance.cpp
7 *
8 * Created on: 30 Jun 2020
9 * Author: Maxim Masterov
10 * Company: SURFSara
11 */
12
13#include "Distance.h"
14
15#include "FarField.h"
16#include "IRAAlign.h"
17#include "MinImage.h"
18#include "PairCutoff.h"
19#ifdef USE_HIGHWAY
20#include "DistanceHwy.h"
21#endif
22
23#include <algorithm>
24#include <array>
25#include <cfloat>
26#include <cmath>
27#include <limits>
28#include <map>
29#include <stdexcept>
30#include <vector>
31
33
34#ifdef USE_OPENMP
35#include <omp.h>
36#endif
37
38#ifdef USE_HIGHS
39#include "Highs.h"
40#endif
41
42namespace aux {
43
44std::pair<gpr::Coord, gpr::FieldMatrixIdx> get_canonical_configuration(
45 const gpr::Coord& x_in, const gpr::FieldMatrixIdx& types_in)
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}
100
101namespace {
102
103// Kuhn-Munkres maximum-weight matching on the negated costs, i.e. the
104// minimum-cost assignment. Returns xy[i] = column matched to row i, or an
105// empty vector when the input is not a finite square matrix or no perfect
106// matching was reached.
107//
108// Tightness is tested against a tolerance scaled by the largest magnitude in
109// the matrix. An absolute tolerance silently misses tight edges once the costs
110// are large, and a missed tight edge makes the slack `delta` come out at zero,
111// which leaves the augmenting loop spinning without ever changing the
112// potentials.
113std::vector<int> hungarian_assignment(const Eigen::MatrixXd& cost_matrix)
114{
115 const int n = static_cast<int>(cost_matrix.rows());
116 if (n == 0) return {};
117 if (cost_matrix.cols() != n || !cost_matrix.allFinite()) return {};
118
119 const Eigen::MatrixXd costs = -cost_matrix;
120 const double scale = std::max(1.0, cost_matrix.cwiseAbs().maxCoeff());
121 const double tight_tol = scale * 1e-9;
122
123 Eigen::VectorXd lx = costs.rowwise().maxCoeff();
124 Eigen::VectorXd ly = Eigen::VectorXd::Zero(n);
125 std::vector<int> xy(n, -1);
126 std::vector<int> yx(n, -1);
127 std::vector<bool> S(n), T(n);
128
129 auto match = [&](int u, auto& self) -> bool {
130 S[u] = true;
131 for (int v = 0; v < n; ++v) {
132 if (!T[v] && std::abs(lx(u) + ly(v) - costs(u, v)) < tight_tol) {
133 T[v] = true;
134 if (yx[v] == -1 || self(yx[v], self)) {
135 yx[v] = u;
136 xy[u] = v;
137 return true;
138 }
139 }
140 }
141 return false;
142 };
143
144 for (int i = 0; i < n; ++i) {
145 // Each pass either augments or relaxes the potentials by delta > 0,
146 // which admits at least one new tight edge, so n rounds suffice. The
147 // bound guards against a non-positive delta arising from rounding; it
148 // is not part of the algorithm.
149 for (int pass = 0; pass <= n; ++pass) {
150 std::fill(S.begin(), S.end(), false);
151 std::fill(T.begin(), T.end(), false);
152 if (match(i, match)) break;
153
154 double delta = std::numeric_limits<double>::max();
155 for (int u = 0; u < n; ++u) {
156 if (!S[u]) continue;
157 for (int v = 0; v < n; ++v) {
158 if (!T[v])
159 delta = std::min(delta, lx(u) + ly(v) - costs(u, v));
160 }
161 }
162 if (!(delta > 0.0) || delta == std::numeric_limits<double>::max()) {
163 return {};
164 }
165
166 for (int j = 0; j < n; ++j) {
167 if (S[j]) lx(j) -= delta;
168 if (T[j]) ly(j) += delta;
169 }
170 }
171 if (xy[i] == -1) return {};
172 }
173
174 return xy;
175}
176
177} // namespace
178
179double solve_assignment_problem(const Eigen::MatrixXd& cost_matrix)
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}
192
193std::vector<int> solve_assignment_indices(const Eigen::MatrixXd& cost_matrix)
194{
195 return hungarian_assignment(cost_matrix);
196}
197
198#ifdef USE_HIGHS
199// NOTE(rg):: Weirdly this is slower and spikier than the basic implementation
200// above
201double solve_assignment_problem_highs(const Eigen::MatrixXd& cost_matrix)
202{
203 const int n = cost_matrix.rows();
204 if (n == 0) return 0.0;
205 if (cost_matrix.cols() != n || !cost_matrix.allFinite()) {
206 return std::numeric_limits<double>::infinity();
207 }
208
209 // 1. Create a HiGHS instance
210 Highs highs;
211 highs.setOptionValue("output_flag", false); // Suppress solver output
212
213 // 2. Define the LP model
214 HighsModel model;
215 model.lp_.num_col_ = n * n; // n*n variables x_ij
216 model.lp_.num_row_ = 2 * n; // 2*n constraints
217
218 // 3. Define the objective function (costs)
219 // The variables are flattened: x_00, x_01, ..., x_0(n-1), x_10, ...
220 model.lp_.col_cost_.resize(n * n);
221 for (int i = 0; i < n; ++i) {
222 for (int j = 0; j < n; ++j) {
223 model.lp_.col_cost_[i * n + j] = cost_matrix(i, j);
224 }
225 }
226
227 // 4. Define variable bounds (0 <= x_ij <= 1)
228 model.lp_.col_lower_.assign(n * n, 0.0);
229 model.lp_.col_upper_.assign(n * n, 1.0);
230
231 // 5. Define the constraints
232 // All constraint right-hand-sides are 1.
233 model.lp_.row_lower_.assign(2 * n, 1.0);
234 model.lp_.row_upper_.assign(2 * n, 1.0);
235
236 // The constraint matrix A is very sparse. We define it in column-major
237 // format. Each variable x_ij appears in exactly two constraints: row i and
238 // row n+j.
239 model.lp_.a_matrix_.start_.resize(n * n + 1);
240 model.lp_.a_matrix_.index_.resize(2 * n * n);
241 model.lp_.a_matrix_.value_.resize(2 * n * n);
242
243 int nz = 0; // Non-zero counter
244 for (int i = 0; i < n; ++i) {
245 for (int j = 0; j < n; ++j) {
246 int var_idx = i * n + j;
247 model.lp_.a_matrix_.start_[var_idx] = nz;
248
249 // Entry for the "sum over j" constraint (row i)
250 model.lp_.a_matrix_.index_[nz] = i;
251 model.lp_.a_matrix_.value_[nz] = 1.0;
252 nz++;
253
254 // Entry for the "sum over i" constraint (row n+j)
255 model.lp_.a_matrix_.index_[nz] = n + j;
256 model.lp_.a_matrix_.value_[nz] = 1.0;
257 nz++;
258 }
259 }
260 model.lp_.a_matrix_.start_[n * n] = nz;
261 model.lp_.a_matrix_.format_ = MatrixFormat::kColwise; // Specify format
262
263 // 6. Solve the model
264 highs.passModel(model);
265 HighsStatus status = highs.run();
266
267 // kOk only says the run did not error; an iteration or time limit also
268 // reports kOk while leaving a non-optimal objective behind. Require an
269 // optimal model status before trusting the value.
270 if (status != HighsStatus::kOk ||
271 highs.getModelStatus() != HighsModelStatus::kOptimal) {
272 // Infinity, matching solve_assignment_problem's failure value.
273 // Returning DBL_MAX instead made an unsolved assignment arrive at
274 // dist_emd as a huge but finite distance, which propagates as data.
275 return std::numeric_limits<double>::infinity();
276 }
277
278 // 7. Return the optimal objective value
279 return highs.getInfo().objective_function_value;
280}
281#endif
282
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}
294
296
298
300{
301 if (!(radius >= 0.0) || !std::isfinite(radius)) {
302 throw std::invalid_argument(
303 "far-field radius must be finite and non-negative");
304 }
305 far_field_radius_ = radius;
306 clearCache();
307}
308
309void Distance::inverseDistancesToPoint(const double* data, Eigen::Index cols,
310 Eigen::Index off, double fx, double fy,
311 double fz, Eigen::Index n, double* out,
312 const gpr::geometry::PairBox& box)
313{
314 const double from[3] = {fx, fy, fz};
315#ifdef USE_HIGHWAY
316 if (n >= kReciprocalSqrtVectorThreshold) {
317 for (Eigen::Index i = 0; i < n; ++i) {
318 const double* p = data + i * cols + off;
319 double dr[3];
320 box.displacement(from, p, dr);
321 out[i] = dr[0] * dr[0] + dr[1] * dr[1] + dr[2] * dr[2];
322 }
323 gpr::hwy_kernels::recip_sqrt_inplace(out, static_cast<int64_t>(n));
324 return;
325 }
326#endif
327 // Fused: staging r^2 into the buffer and inverting it in a second pass
328 // only pays once the inversion is vectorised. Below the threshold the
329 // extra traversal and the call are pure cost.
330 for (Eigen::Index i = 0; i < n; ++i) {
331 const double* p = data + i * cols + off;
332 double dr[3];
333 box.displacement(from, p, dr);
334 out[i] = 1.0 / std::sqrt(dr[0] * dr[0] + dr[1] * dr[1] + dr[2] * dr[2]);
335 }
336}
337
338void Distance::inverseDistancesBetween(const double* data, Eigen::Index cols,
339 Eigen::Index off_a, Eigen::Index off_b,
340 Eigen::Index n, double* out,
341 const gpr::geometry::PairBox& box)
342{
343#ifdef USE_HIGHWAY
344 if (n >= kReciprocalSqrtVectorThreshold) {
345 for (Eigen::Index i = 0; i < n; ++i) {
346 const double* pa = data + i * cols + off_a;
347 const double* pb = data + i * cols + off_b;
348 double dr[3];
349 box.displacement(pb, pa, dr);
350 out[i] = dr[0] * dr[0] + dr[1] * dr[1] + dr[2] * dr[2];
351 }
352 gpr::hwy_kernels::recip_sqrt_inplace(out, static_cast<int64_t>(n));
353 return;
354 }
355#endif
356 for (Eigen::Index i = 0; i < n; ++i) {
357 const double* pa = data + i * cols + off_a;
358 const double* pb = data + i * cols + off_b;
359 double dr[3];
360 box.displacement(pb, pa, dr);
361 out[i] = 1.0 / std::sqrt(dr[0] * dr[0] + dr[1] * dr[1] + dr[2] * dr[2]);
362 }
363}
364
365void Distance::reciprocalSqrtInPlace(double* r2, Eigen::Index count)
366{
367#ifdef USE_HIGHWAY
368 // Below a couple of vectors' worth the cross-TU dynamic dispatch costs
369 // more than the vector arithmetic saves: measured, batches this small
370 // regressed dist_at by around 30% on the no-frozen-atom fixtures while
371 // the large ones gained 20-28%. The same threshold idiom guards the
372 // accumulate kernel (n2 >= 8). Both arms are the same arithmetic, so the
373 // branch cannot change a result.
374 if (count >= kReciprocalSqrtVectorThreshold) {
375 gpr::hwy_kernels::recip_sqrt_inplace(r2, static_cast<int64_t>(count));
376 return;
377 }
378#endif
379 for (Eigen::Index i = 0; i < count; ++i) {
380 r2[i] = 1.0 / std::sqrt(r2[i]);
381 }
382}
383
384void Distance::buildInverseSquaredLengthscales(
385 const gpr::FieldMatrixd& lengthscale, gpr::Index_t n_pt,
387{
388 const Eigen::Index n_given = lengthscale.size();
389 if (n_given == 1) {
390 // Scalar (non-ARD) lengthscale: one value shared by every registered
391 // pairtype. Read through the flat pointer so a row- or column-vector
392 // lengthscale behaves the same.
393 const double l = *lengthscale.data();
394 const double inv_sq = 1. / (l * l);
395 s2.resize(1, static_cast<Eigen::Index>(n_pt));
396 s2.setConstant(inv_sq);
397 return;
398 }
399 s2.resize(1, n_given);
400 for (Eigen::Index n = 0; n < n_given; ++n) {
401 const double l = *(lengthscale.data() + n);
402 *(s2.data() + n) = 1. / (l * l);
403 }
404}
405
410void Distance::dist_rmsd(const gpr::Coord& x1, const gpr::Coord& x2,
411 const gpr::AtomsConfiguration& conf_info,
412 gpr::FieldMatrixd& dist)
413{
414 Eigen::Index n1 = x1.rows(); // Number of configurations in x1
415 Eigen::Index n2 = x2.rows(); // Number of configurations in x2
416 Eigen::Index num_cols = x1.cols();
417
418 // Basic check for consistent atom numbers
419 if (num_cols != x2.cols()) {
420 // Or throw an exception for a more robust error handling
421 dist.resize(0, 0);
422 return;
423 }
424
425 dist.resize(n1, n2);
426 const gpr::FieldMatrixIdx& types = conf_info.atoms_mov.type;
427
428 // The canonical form of each x2 row does not depend on n; canonicalising
429 // inside the n loop repeated the whole O(N^2 log N) signature sort n1
430 // times.
431 std::vector<gpr::Coord> x2_canonical(static_cast<std::size_t>(n2));
432 for (Eigen::Index m = 0; m < n2; ++m) {
433 gpr::Coord q;
434 q.resize(1, num_cols);
435 for (Eigen::Index k = 0; k < num_cols; ++k) {
436 q(0, k) = x2(m, k);
437 }
438 x2_canonical[static_cast<std::size_t>(m)] =
439 get_canonical_configuration(q, types).first;
440 }
441
442 for (Eigen::Index n = 0; n < n1; ++n) {
443 // Manually extract the n-th configuration (row) from x1 into a new
444 // single-row Coord object 'p'.
445 gpr::Coord p;
446 p.resize(1, num_cols);
447 for (Eigen::Index k = 0; k < num_cols; ++k) {
448 p(0, k) = x1(n, k);
449 }
450
451 auto p_canonical_pair = get_canonical_configuration(p, types);
452
453 for (Eigen::Index m = 0; m < n2; ++m) {
454 // Calculate the aligned RMSD and store it in the distance matrix.
455 dist(n, m) = calculate_aligned_rmsd(
456 p_canonical_pair.first,
457 x2_canonical[static_cast<std::size_t>(m)]);
458 }
459 }
460}
461
463 const gpr::AtomsConfiguration& conf_info,
464 gpr::FieldMatrixd& dist)
465{
466 Eigen::Index n1 = x1.rows();
467 Eigen::Index n2 = x2.rows();
468 Eigen::Index N_mov = x1.cols() / 3;
469 Eigen::Index N_fro = conf_info.atoms_froz_active.positions.cols() / 3;
470
471 dist.resize(n1, n2);
472 dist.setZero();
473 const gpr::geometry::PairBox box(conf_info.cell);
474
475 // Distances between moving atoms
476 if (N_mov > 1) {
477 for (Eigen::Index i = 0; i < N_mov - 1; ++i) {
478 for (Eigen::Index j = i + 1; j < N_mov; ++j) {
479 for (Eigen::Index n = 0; n < n1; ++n) {
480 double r_ij_1 = box.displacement(gpr::coord::at(x1, n, i),
481 gpr::coord::at(x1, n, j))
482 .norm();
483 for (Eigen::Index m = 0; m < n2; ++m) {
484 double r_ij_2 =
485 box.displacement(gpr::coord::at(x2, m, i),
486 gpr::coord::at(x2, m, j))
487 .norm();
488 // Coincident atoms make the ratio 0/0 or x/0. The
489 // resulting NaN loses the `tmp > dist` comparison
490 // silently and a wrong finite distance is kept, so
491 // saturate to infinity instead.
492 const double tmp =
493 (r_ij_1 > 0. && r_ij_2 > 0.)
494 ? std::fabs(std::log(r_ij_2 / r_ij_1))
495 : std::numeric_limits<double>::infinity();
496 if (tmp > dist(n, m)) dist(n, m) = tmp;
497 }
498 }
499 }
500 }
501 }
502
503 // Distances from moving atoms to active frozen atoms
504 if (N_fro > 0) {
505 for (Eigen::Index j = 0; j < N_mov; ++j) {
506 for (Eigen::Index i = 0; i < N_fro; ++i) {
507 Eigen::Vector3d froz_pos =
509 for (Eigen::Index n = 0; n < n1; ++n) {
510 double r_ij_1 =
511 box.displacement(froz_pos, gpr::coord::at(x1, n, j))
512 .norm();
513 for (Eigen::Index m = 0; m < n2; ++m) {
514 double r_ij_2 =
515 box.displacement(froz_pos, gpr::coord::at(x2, m, j))
516 .norm();
517 // Coincident atoms make the ratio 0/0 or x/0. The
518 // resulting NaN loses the `tmp > dist` comparison
519 // silently and a wrong finite distance is kept, so
520 // saturate to infinity instead.
521 const double tmp =
522 (r_ij_1 > 0. && r_ij_2 > 0.)
523 ? std::fabs(std::log(r_ij_2 / r_ij_1))
524 : std::numeric_limits<double>::infinity();
525 if (tmp > dist(n, m)) dist(n, m) = tmp;
526 }
527 }
528 }
529 }
530 }
531}
532
533double Distance::range_at(const gpr::Coord& positions,
534 const gpr::AtomsConfiguration& conf_info,
535 const gpr::FieldMatrixd& lengthscale)
536{
537 const Eigen::Index dimensions = 3 * conf_info.atoms_mov.type.size();
538 if (positions.cols() < dimensions)
539 throw std::invalid_argument(
540 "distance range requires all moving coordinates");
541 if (positions.rows() == 0) return 0.0;
542 if (!positions.leftCols(dimensions).allFinite())
543 return std::numeric_limits<double>::quiet_NaN();
544
545 std::map<std::vector<double>, Eigen::Index> seen;
546 gpr::Coord unique(positions.rows(), dimensions);
547 Eigen::Index count = 0;
548 for (Eigen::Index row = 0; row < positions.rows(); ++row) {
549 std::vector<double> key(static_cast<std::size_t>(dimensions));
550 for (Eigen::Index column = 0; column < dimensions; ++column)
551 key[static_cast<std::size_t>(column)] = positions(row, column);
552 if (seen.emplace(std::move(key), count).second)
553 unique.row(count++) = positions.row(row).head(dimensions);
554 }
555 unique.conservativeResize(count, Eigen::NoChange);
556 gpr::FieldMatrixd distances;
557 dist_at(unique, unique, conf_info, lengthscale, distances);
558 return distances.size() == 0 ? 0.0 : distances.maxCoeff();
559}
560
561namespace {
562
563void addFarDipole(const double* x1, Eigen::Index x1_cols, Eigen::Index n1,
564 const double* x2, Eigen::Index x2_cols, Eigen::Index n2,
565 Eigen::Index atom, const double* frozen,
566 Eigen::Index n_frozen, const gpr::AtomsConfiguration& conf,
567 const gpr::FieldMatrixd& s2,
568 const gpr::geometry::PairBox& box, double radius, double sign,
569 gpr::FieldMatrixd* total,
570 std::vector<gpr::FieldMatrixd>* per_type)
571{
572 if (!(radius > 0.0) || n1 == 0 || n_frozen == 0) return;
573 const double* centre = farFieldCentre(conf, atom);
574 const Eigen::Index n_pt = s2.cols();
575 std::vector<std::array<double, 9>> tensor(static_cast<std::size_t>(n_pt));
576 bool any = false;
577 for (Eigen::Index i = 0; i < n_frozen; ++i) {
578 const double* source = frozen + 3 * i;
579 if (!farFromCentre(box, centre, source, radius)) continue;
580 const gpr::Index_t pt = conf.pairtype(conf.atoms_froz_active.type(0, i),
581 conf.atoms_mov.type(0, atom));
582 if (pt == static_cast<gpr::Index_t>(EMPTY) ||
583 static_cast<Eigen::Index>(pt) >= n_pt)
584 continue;
585 double r[3];
586 box.displacement(source, centre, r);
587 const double two_s2 = 2.0 * s2(0, static_cast<Eigen::Index>(pt));
588 double block[3][3];
589 for (int a = 0; a < 9; ++a)
590 block[a / 3][a % 3] = tensor[static_cast<std::size_t>(pt)][a];
591 addFarSource(block, r, two_s2);
592 for (int a = 0; a < 9; ++a)
593 tensor[static_cast<std::size_t>(pt)][a] = block[a / 3][a % 3];
594 any = true;
595 }
596 if (!any) return;
597 for (Eigen::Index n = 0; n < n1; ++n) {
598 const double* left = x1 + n * x1_cols + 3 * atom;
599 for (Eigen::Index m = 0; m < n2; ++m) {
600 const double* right = x2 + m * x2_cols + 3 * atom;
601 double delta[3];
602 farFieldDifference(box, centre, left, right, delta);
603 for (Eigen::Index pt = 0; pt < n_pt; ++pt) {
604 const auto& stored = tensor[static_cast<std::size_t>(pt)];
605 double block[3][3];
606 for (int a = 0; a < 9; ++a)
607 block[a / 3][a % 3] = stored[a];
608 const double quad = sign * farQuadratic(block, delta);
609 if (quad == 0.0) continue;
610 if (total != nullptr) (*total)(n, m) += quad;
611 if (per_type != nullptr)
612 (*per_type)[static_cast<std::size_t>(pt)](n, m) += quad;
613 }
614 }
615 }
616}
617
618} // namespace
619
620void Distance::dist_at(const gpr::Coord& x1, const gpr::Coord& x2,
621 const gpr::AtomsConfiguration& conf_info,
622 const gpr::FieldMatrixd& lengthscale,
623 gpr::FieldMatrixd& dist, bool take_sqrt)
624{
625 // A pair cutoff uses the radial assembly. A far-field radius uses
626 // the radial list only when that list was requested. The direct
627 // loop, including the dipole outside the radius, is the default.
628 if (selectsRadialFarField(conf_info)) {
629 if (radial_far_field_list_) ++radial_list_entries_;
630 dist = gpr::FieldMatrixd::Zero(x1.rows(), x2.rows());
631 for (const auto& part: gpr::radialPairSquaredDistances(
632 x1, x2, conf_info, lengthscale, far_field_radius_))
633 dist += part;
634 if (take_sqrt) dist = dist.array().sqrt().matrix();
635 return;
636 }
637 // Cell construction is shared by every pair in this distance batch.
638 const gpr::geometry::PairBox box(conf_info.cell);
639 Eigen::Index n1 = x1.rows();
640 Eigen::Index n2 = x2.rows();
641 Eigen::Index N_mov = conf_info.atoms_mov.type.size();
642 Eigen::Index N_fro = conf_info.atoms_froz_active.type.size();
644
645 dist.resize(n1, n2);
646 dist.setZero();
647
648 buildInverseSquaredLengthscales(lengthscale, conf_info.n_pt, s2);
649
650 // Replace gpr::coord::at(x, row, col) chains -- which return
651 // Eigen::Vector3d by value and run through Eigen's expression
652 // templates -- with raw pointer arithmetic. The Eigen .norm()
653 // expression chain is the hot path here: cachegrind on a dense
654 // molecular fixture attributes 19.4 % of all instructions to
655 // Distance.cpp, with the bulk in EigenHelpers.h +
656 // DenseCoeffsBase.h indexing
657 // overhead. Direct pointer access skips the Vector3d construction
658 // and operator- expression-template machinery; the math is
659 // identical (dx=p2j[0]-p2i[0]; dy=...; dz=...; norm = sqrt(dx*dx +
660 // dy*dy + dz*dz)). Storage layout: gpr::coord uses row-major-of-
661 // packed-3D (mat.data() + row * mat.cols() + 3 * col gives the
662 // Vector3d start, mirroring gpr::coord::at(mat, row, col)).
663 const double* const x1_data = x1.data();
664 const Eigen::Index x1_cols = x1.cols();
665 const double* const x2_data = x2.data();
666 const Eigen::Index x2_cols = x2.cols();
667
668 // Distances between moving atoms
669 if (N_mov > 1) {
670 scratch_invr2_.assign(n2, 0.0);
671 auto& invr2 = scratch_invr2_;
672 for (Eigen::Index j = 0; j < N_mov - 1; ++j) {
673 for (Eigen::Index i = j + 1; i < N_mov; ++i) {
674 const gpr::Index_t pt =
675 conf_info.pairtype(conf_info.atoms_mov.type(0, i),
676 conf_info.atoms_mov.type(0, j));
677 if (!isActivePairtype(pt, s2.cols())) continue;
678 double s2_val = s2(0, pt);
679 double two_s2 = 2. * s2_val;
680 const Eigen::Index x2_off_j = 3 * j;
681 const Eigen::Index x2_off_i = 3 * i;
682 // Accumulate r^2 first, then invert the whole batch in one
683 // vectorised pass. The reciprocal square root is the expensive
684 // part of this assembly and was being evaluated one element at
685 // a time; the r^2 arithmetic is cheap and tolerates the
686 // strided loads. Bit-identical: sqrt and divide are correctly
687 // rounded under IEEE-754.
688 inverseDistancesBetween(x2_data, x2_cols, x2_off_j, x2_off_i,
689 n2, invr2.data(), box);
690 const Eigen::Index x1_off_j = 3 * j;
691 const Eigen::Index x1_off_i = 3 * i;
692 // Same batching for x1: r^2 in a cheap strided pass, then one
693 // vectorised reciprocal-sqrt, so the accumulation loop below
694 // only reads a value.
695 scratch_invr1_.resize(static_cast<std::size_t>(n1));
696 inverseDistancesBetween(x1_data, x1_cols, x1_off_j, x1_off_i,
697 n1, scratch_invr1_.data(), box);
698 const double* const invr1 = scratch_invr1_.data();
699#ifdef USE_OPENMP
700#pragma omp parallel for schedule(static) if (n1 >= 4096 && \
701 omp_get_max_threads() > 1)
702#endif
703 for (Eigen::Index n = 0; n < n1; ++n) {
704 const double invr_ij_1 = invr1[n];
705#ifdef USE_HIGHWAY
706 if (n2 >= 8) {
707 gpr::hwy_kernels::accumulate_invr_diff_sq(
708 dist.data() + n * n2, invr2.data(), invr_ij_1,
709 two_s2, n2);
710 } else {
711#endif
712 for (Eigen::Index m = 0; m < n2; ++m) {
713 double invr_diff = invr_ij_1 - invr2[m];
714 dist(n, m) += two_s2 * invr_diff * invr_diff;
715 }
716#ifdef USE_HIGHWAY
717 }
718#endif
719 }
720 }
721 }
722 }
723
724 // Distances from moving atoms to active frozen atoms
725 if (N_fro > 0) {
726 scratch_invr2_.assign(n2, 0.0);
727 auto& invr2 = scratch_invr2_;
728 const double* const froz_data =
729 conf_info.atoms_froz_active.positions.data();
730 for (Eigen::Index j = 0; j < N_mov; ++j) {
731 for (Eigen::Index i = 0; i < N_fro; ++i) {
732 // Frozen position is taken from atoms_froz_active.positions
733 // at row 0, column i. gpr::coord::at(mat, 0, i) maps to
734 // mat.data() + 3 * i (row-major-packed-3D, row=0).
735 const double* froz_pos = froz_data + 3 * i;
736 const double fx = froz_pos[0];
737 const double fy = froz_pos[1];
738 const double fz = froz_pos[2];
739 const gpr::Index_t pt =
740 conf_info.pairtype(conf_info.atoms_froz_active.type(0, i),
741 conf_info.atoms_mov.type(0, j));
742 if (!isActivePairtype(pt, s2.cols())) continue;
743 if (far_field_radius_ > 0.0 && n1 > 0 &&
744 farFromCentre(box, farFieldCentre(conf_info, j), froz_pos,
745 far_field_radius_))
746 continue;
747 double s2_val = s2(0, pt);
748 double two_s2 = 2. * s2_val;
749 const Eigen::Index x2_off_j = 3 * j;
750 // r^2 first, then one vectorised reciprocal-sqrt pass; see
751 // the moving-moving block above.
752 inverseDistancesToPoint(x2_data, x2_cols, x2_off_j, fx, fy, fz,
753 n2, invr2.data(), box);
754 const Eigen::Index x1_off_j = 3 * j;
755 // r^2 then one vectorised pass; see the moving-moving block.
756 scratch_invr1_.resize(static_cast<std::size_t>(n1));
757 inverseDistancesToPoint(x1_data, x1_cols, x1_off_j, fx, fy, fz,
758 n1, scratch_invr1_.data(), box);
759 const double* const invr1 = scratch_invr1_.data();
760#ifdef USE_OPENMP
761#pragma omp parallel for schedule(static) if (n1 >= 4096 && \
762 omp_get_max_threads() > 1)
763#endif
764 for (Eigen::Index n = 0; n < n1; ++n) {
765 const double invr_ij_1 = invr1[n];
766#ifdef USE_HIGHWAY
767 if (n2 >= 8) {
768 gpr::hwy_kernels::accumulate_invr_diff_sq(
769 dist.data() + n * n2, invr2.data(), invr_ij_1,
770 two_s2, n2);
771 } else {
772#endif
773 for (Eigen::Index m = 0; m < n2; ++m) {
774 double invr_diff = invr_ij_1 - invr2[m];
775 dist(n, m) += two_s2 * invr_diff * invr_diff;
776 }
777#ifdef USE_HIGHWAY
778 }
779#endif
780 }
781 }
782 if (far_field_radius_ > 0.0) {
783 addFarDipole(x1_data, x1_cols, n1, x2_data, x2_cols, n2, j,
784 froz_data, N_fro, conf_info, s2, box,
785 far_field_radius_, 1.0, &dist, nullptr);
786 }
787 }
788 }
789
790 if (take_sqrt) {
791 Eigen::Map<Eigen::ArrayXd>(dist.data(), dist.size()) =
792 Eigen::Map<Eigen::ArrayXd>(dist.data(), dist.size()).sqrt();
793 }
794}
795
797 const gpr::AtomsConfiguration& conf_info,
798 const gpr::FieldMatrixd& lengthscale,
799 std::vector<gpr::FieldMatrixd>& dist)
800{
801 if (selectsRadialFarField(conf_info)) {
802 if (radial_far_field_list_) ++radial_list_entries_;
803 dist = gpr::radialPairSquaredDistances(x1, x2, conf_info, lengthscale,
804 far_field_radius_);
805 for (auto& part: dist)
806 part = -part;
807 return;
808 }
809 const gpr::geometry::PairBox box(conf_info.cell);
810 Eigen::Index n1 = x1.rows();
811 Eigen::Index n2 = x2.rows();
812 Eigen::Index N_mov = conf_info.atoms_mov.type.size();
813 Eigen::Index N_fro = conf_info.atoms_froz_active.type.size();
815
816 buildInverseSquaredLengthscales(lengthscale, conf_info.n_pt, s2);
817
818 // One output block per lengthscale. Sizing by s2 rather than by n_pt keeps
819 // dist[pt] in range when an ARD lengthscale disagrees with conf_info.n_pt;
820 // the isActivePairtype bound below indexes both.
821 dist.resize(static_cast<std::size_t>(s2.cols()));
822 for (std::size_t n = 0; n < dist.size(); ++n) {
823 dist[n].resize(n1, n2);
824 dist[n].setZero();
825 }
826
827 const double* const x1_data = x1.data();
828 const Eigen::Index x1_cols = x1.cols();
829 const double* const x2_data = x2.data();
830 const Eigen::Index x2_cols = x2.cols();
831
832 // Distances between moving atoms
833 if (N_mov > 1) {
834 scratch_invr2_.assign(n2, 0.0);
835 auto& invr2 = scratch_invr2_;
836 for (Eigen::Index j = 0; j < N_mov - 1; ++j) {
837 for (Eigen::Index i = j + 1; i < N_mov; ++i) {
838 gpr::Index_t pt =
839 conf_info.pairtype(conf_info.atoms_mov.type(0, i),
840 conf_info.atoms_mov.type(0, j));
841 if (!isActivePairtype(pt, s2.cols())) continue;
842 double s2_val = s2(0, pt);
843 double two_s2 = 2. * s2_val;
844 const Eigen::Index x2_off_j = 3 * j;
845 const Eigen::Index x2_off_i = 3 * i;
846 // Accumulate r^2 first, then invert the whole batch in one
847 // vectorised pass. The reciprocal square root is the expensive
848 // part of this assembly and was being evaluated one element at
849 // a time; the r^2 arithmetic is cheap and tolerates the
850 // strided loads. Bit-identical: sqrt and divide are correctly
851 // rounded under IEEE-754.
852 inverseDistancesBetween(x2_data, x2_cols, x2_off_j, x2_off_i,
853 n2, invr2.data(), box);
854 const Eigen::Index x1_off_j = 3 * j;
855 const Eigen::Index x1_off_i = 3 * i;
856 // Same batching for x1: r^2 in a cheap strided pass, then one
857 // vectorised reciprocal-sqrt, so the accumulation loop below
858 // only reads a value.
859 scratch_invr1_.resize(static_cast<std::size_t>(n1));
860 inverseDistancesBetween(x1_data, x1_cols, x1_off_j, x1_off_i,
861 n1, scratch_invr1_.data(), box);
862 const double* const invr1 = scratch_invr1_.data();
863#ifdef USE_OPENMP
864#pragma omp parallel for schedule(static) if (n1 >= 4096 && \
865 omp_get_max_threads() > 1)
866#endif
867 for (Eigen::Index n = 0; n < n1; ++n) {
868 const double invr_ij_1 = invr1[n];
869#ifdef USE_HIGHWAY
870 if (n2 >= 8) {
871 gpr::hwy_kernels::accumulate_invr_diff_sq(
872 dist[pt].data() + n * n2, invr2.data(), invr_ij_1,
873 -two_s2, n2);
874 } else {
875#endif
876 for (Eigen::Index m = 0; m < n2; ++m) {
877 double invr_diff = invr_ij_1 - invr2[m];
878 dist[pt](n, m) -= two_s2 * invr_diff * invr_diff;
879 }
880#ifdef USE_HIGHWAY
881 }
882#endif
883 }
884 }
885 }
886 }
887
888 // Distances from moving atoms to active frozen atoms
889 if (N_fro > 0) {
890 scratch_invr2_.assign(n2, 0.0);
891 auto& invr2 = scratch_invr2_;
892 const double* const froz_data =
893 conf_info.atoms_froz_active.positions.data();
894 for (Eigen::Index j = 0; j < N_mov; ++j) {
895 for (Eigen::Index i = 0; i < N_fro; ++i) {
896 const double* froz_pos = froz_data + 3 * i;
897 const double fx = froz_pos[0];
898 const double fy = froz_pos[1];
899 const double fz = froz_pos[2];
900 gpr::Index_t pt =
901 conf_info.pairtype(conf_info.atoms_froz_active.type(0, i),
902 conf_info.atoms_mov.type(0, j));
903 if (!isActivePairtype(pt, s2.cols())) continue;
904 if (far_field_radius_ > 0.0 && n1 > 0 &&
905 farFromCentre(box, farFieldCentre(conf_info, j), froz_pos,
906 far_field_radius_))
907 continue;
908 double s2_val = s2(0, pt);
909 double two_s2 = 2. * s2_val;
910 const Eigen::Index x2_off_j = 3 * j;
911 // r^2 first, then one vectorised reciprocal-sqrt pass; see
912 // the moving-moving block above.
913 inverseDistancesToPoint(x2_data, x2_cols, x2_off_j, fx, fy, fz,
914 n2, invr2.data(), box);
915 const Eigen::Index x1_off_j = 3 * j;
916 // r^2 then one vectorised pass; see the moving-moving block.
917 scratch_invr1_.resize(static_cast<std::size_t>(n1));
918 inverseDistancesToPoint(x1_data, x1_cols, x1_off_j, fx, fy, fz,
919 n1, scratch_invr1_.data(), box);
920 const double* const invr1 = scratch_invr1_.data();
921#ifdef USE_OPENMP
922#pragma omp parallel for schedule(static) if (n1 >= 4096 && \
923 omp_get_max_threads() > 1)
924#endif
925 for (Eigen::Index n = 0; n < n1; ++n) {
926 const double invr_ij_1 = invr1[n];
927#ifdef USE_HIGHWAY
928 if (n2 >= 8) {
929 gpr::hwy_kernels::accumulate_invr_diff_sq(
930 dist[pt].data() + n * n2, invr2.data(), invr_ij_1,
931 -two_s2, n2);
932 } else {
933#endif
934 for (Eigen::Index m = 0; m < n2; ++m) {
935 double invr_diff = invr_ij_1 - invr2[m];
936 dist[pt](n, m) -= two_s2 * invr_diff * invr_diff;
937 }
938#ifdef USE_HIGHWAY
939 }
940#endif
941 }
942 }
943 if (far_field_radius_ > 0.0) {
944 addFarDipole(x1_data, x1_cols, n1, x2_data, x2_cols, n2, j,
945 froz_data, N_fro, conf_info, s2, box,
946 far_field_radius_, -1.0, nullptr, &dist);
947 }
948 }
949 }
950
951 // for(Eigen::Index n = 0; n < n1; ++n) {
952 // for(Eigen::Index m = 0; m < n2; ++m) {
953 // dist(n, m) = sqrt(dist(n, m));
954 // }
955 // }
956}
957
959 const gpr::AtomsConfiguration& conf_info,
960 gpr::FieldMatrixd& dist)
961{
962 // Use clearer variable names and correct size calculations
963 const auto num_configs = x.rows();
964 const auto num_moving_atoms = x.cols() / 3;
965 const auto& frozen_pos = conf_info.atoms_froz_active.positions;
966 const auto num_frozen_atoms = frozen_pos.cols() / 3;
967
968 // Handle the edge case of no moving atoms
969 if (num_moving_atoms == 0) {
970 dist.resize(0, 0);
971 return;
972 }
973
974 dist.resize(num_configs, num_moving_atoms);
975 dist.setConstant(DBL_MAX);
976 const gpr::geometry::PairBox box(conf_info.cell);
977
978 // Loop over configurations first to improve memory access patterns
979 // (cache-friendlier)
980 for (Eigen::Index n = 0; n < num_configs; ++n) {
981 // --- Distances between moving atoms for configuration 'n' ---
982 if (num_moving_atoms > 1) {
983 for (Eigen::Index i = 0; i < num_moving_atoms - 1; ++i) {
984 for (Eigen::Index j = i + 1; j < num_moving_atoms; ++j) {
985 const double r_ij =
986 box.displacement(gpr::coord::at(x, n, i),
987 gpr::coord::at(x, n, j))
988 .norm();
989
990 // Update the minimum distance for both atoms in the pair
991 // Use std::min for clarity and correctness.
992 dist(n, i) = std::min(dist(n, i), r_ij);
993 dist(n, j) = std::min(dist(n, j), r_ij);
994 }
995 }
996 }
997
998 // --- Distances from moving to frozen atoms for configuration 'n' ---
999 if (num_frozen_atoms > 0) {
1000 for (Eigen::Index j = 0; j < num_moving_atoms;
1001 ++j) { // For each moving atom
1002 for (Eigen::Index i = 0; i < num_frozen_atoms;
1003 ++i) { // Check against each frozen atom
1004 const double r_ij =
1005 box.displacement(gpr::coord::at(frozen_pos, 0, i),
1006 gpr::coord::at(x, n, j))
1007 .norm();
1008
1009 // Update the minimum distance ONLY for the current moving
1010 // atom 'j'
1011 dist(n, j) = std::min(dist(n, j), r_ij);
1012 }
1013 }
1014 }
1015 }
1016}
1017
1018void Distance::dist_emd(const gpr::Coord& x1, const gpr::Coord& x2,
1019 const gpr::AtomsConfiguration& conf_info,
1020 gpr::FieldMatrixd& dist)
1021{
1022 Eigen::Index n1 = x1.rows(); // Number of configurations in x1
1023 Eigen::Index n2 = x2.rows(); // Number of configurations in x2
1024 Eigen::Index num_atoms = x1.cols() / 3;
1025
1026 if (num_atoms != x2.cols() / 3) {
1027 dist.resize(0, 0);
1028 return;
1029 }
1030
1031 dist.resize(n1, n2);
1032 const gpr::FieldMatrixIdx& types = conf_info.atoms_mov.type;
1033
1034 // Group atom indices by type
1035 std::map<gpr::Index_t, std::vector<gpr::Index_t>> indices_by_type;
1036 for (Eigen::Index i = 0; i < types.size(); ++i) {
1037 indices_by_type[types(0, i)].push_back(i);
1038 }
1039
1040 for (Eigen::Index n = 0; n < n1; ++n) {
1041 for (Eigen::Index m = 0; m < n2; ++m) {
1042 double max_of_avg_type_emds = 0.0;
1043 double total_emd_for_type = 0.0;
1044
1045 // Calculate EMD for each atom type separately
1046 for (auto const& [type, indices]: indices_by_type) {
1047 int num_type_atoms = indices.size();
1048 if (num_type_atoms == 0) continue;
1049
1050 // Build the cost matrix for this type
1051 Eigen::MatrixXd cost_matrix(num_type_atoms, num_type_atoms);
1052 for (int i = 0; i < num_type_atoms; ++i) {
1053 for (int j = 0; j < num_type_atoms; ++j) {
1054 gpr::Index_t atom_idx1 = indices[i];
1055 gpr::Index_t atom_idx2 = indices[j];
1056 cost_matrix(i, j) = (gpr::coord::at(x1, n, atom_idx1) -
1057 gpr::coord::at(x2, m, atom_idx2))
1058 .norm();
1059 }
1060 }
1061
1062 // Solve the assignment problem for this atom type
1063#ifdef USE_HIGHS
1064 total_emd_for_type =
1065 solve_assignment_problem_highs(cost_matrix);
1066#else
1067 total_emd_for_type = solve_assignment_problem(cost_matrix);
1068#endif
1069 // Calculate the AVERAGE displacement for THIS type
1070 double avg_emd_for_type = total_emd_for_type / num_type_atoms;
1071
1072 // Keep track of the MAXIMUM average we've seen
1073 if (avg_emd_for_type > max_of_avg_type_emds) {
1074 max_of_avg_type_emds = avg_emd_for_type;
1075 }
1076 }
1077
1078 // NOTE(rg): This is now INTENSIVE, so on average no atom group
1079 // should move more than this amount
1080 dist(n, m) = max_of_avg_type_emds;
1081 }
1082 }
1083}
1084
1086 const gpr::AtomsConfiguration& conf_info)
1087{
1088 cache_.clear();
1089 if (conf_info.pair_cutoff > 0.0) return;
1090 cache_.x1_cached = x1;
1091 cache_.x2_cached = x2;
1092 for (int i = 0; i < 9; ++i)
1093 cache_.cell_cached[i] = conf_info.cell[i];
1094 cache_.n1 = x1.rows();
1095 cache_.n2 = x2.rows();
1096 cache_.n_mov = conf_info.atoms_mov.type.size();
1097 cache_.n_fro = conf_info.atoms_froz_active.type.size();
1098 const gpr::geometry::PairBox box(conf_info.cell);
1099
1100 Eigen::Index N_mov = cache_.n_mov;
1101 Eigen::Index N_fro = cache_.n_fro;
1102 Eigen::Index n1 = cache_.n1;
1103 Eigen::Index n2 = cache_.n2;
1104
1105 // Moving-moving pairs
1106 if (N_mov > 1) {
1107 for (Eigen::Index j = 0; j < N_mov - 1; ++j) {
1108 for (Eigen::Index i = j + 1; i < N_mov; ++i) {
1109 gpr::Index_t pt =
1110 conf_info.pairtype(conf_info.atoms_mov.type(0, i),
1111 conf_info.atoms_mov.type(0, j));
1112 if (!isActivePairtype(
1113 pt, static_cast<Eigen::Index>(conf_info.n_pt)))
1114 continue;
1115 cache_.pair_types.push_back(pt);
1116
1117 std::vector<double> ir1(n1), ir2(n2);
1118 for (Eigen::Index n = 0; n < n1; ++n) {
1119 ir1[n] = 1.0 / box.displacement(gpr::coord::at(x1, n, i),
1120 gpr::coord::at(x1, n, j))
1121 .norm();
1122 }
1123 for (Eigen::Index m = 0; m < n2; ++m) {
1124 ir2[m] = 1.0 / box.displacement(gpr::coord::at(x2, m, i),
1125 gpr::coord::at(x2, m, j))
1126 .norm();
1127 }
1128 cache_.invr_x1.push_back(std::move(ir1));
1129 cache_.invr_x2.push_back(std::move(ir2));
1130 }
1131 }
1132 }
1133
1134 // Moving-frozen pairs
1135 if (N_fro > 0) {
1136 for (Eigen::Index j = 0; j < N_mov; ++j) {
1137 for (Eigen::Index i = 0; i < N_fro; ++i) {
1138 Eigen::Vector3d froz_pos =
1140 gpr::Index_t pt =
1141 conf_info.pairtype(conf_info.atoms_froz_active.type(0, i),
1142 conf_info.atoms_mov.type(0, j));
1143 if (!isActivePairtype(
1144 pt, static_cast<Eigen::Index>(conf_info.n_pt)))
1145 continue;
1146 cache_.pair_types.push_back(pt);
1147
1148 std::vector<double> ir1(n1), ir2(n2);
1149 for (Eigen::Index n = 0; n < n1; ++n) {
1150 ir1[n] = 1.0 / box.displacement(froz_pos,
1151 gpr::coord::at(x1, n, j))
1152 .norm();
1153 }
1154 for (Eigen::Index m = 0; m < n2; ++m) {
1155 ir2[m] = 1.0 / box.displacement(froz_pos,
1156 gpr::coord::at(x2, m, j))
1157 .norm();
1158 }
1159 cache_.invr_x1.push_back(std::move(ir1));
1160 cache_.invr_x2.push_back(std::move(ir2));
1161 }
1162 }
1163 }
1164
1165 cache_.valid = true;
1166}
1167
1168void Distance::accumulateCachedSquaredDistances(
1169 const gpr::AtomsConfiguration& conf_info,
1170 const gpr::FieldMatrixd& lengthscale, gpr::FieldMatrixd& dist)
1171{
1172 const Eigen::Index n1 = cache_.n1;
1173 const Eigen::Index n2 = cache_.n2;
1174
1175 dist.resize(n1, n2);
1176 dist.setZero();
1177
1179 buildInverseSquaredLengthscales(lengthscale, conf_info.n_pt, s2);
1180
1181 // Accumulate from cached inverse distances. The cache was filled against
1182 // conf_info.n_pt; an ARD lengthscale can be shorter, so bound against s2
1183 // here too rather than indexing it blind.
1184 for (std::size_t p = 0; p < cache_.pair_types.size(); ++p) {
1185 const gpr::Index_t pt = cache_.pair_types[p];
1186 if (!isActivePairtype(pt, s2.cols())) continue;
1187 const double two_s2 = 2.0 * s2(0, pt);
1188 const double* ir1 = cache_.invr_x1[p].data();
1189 const double* ir2 = cache_.invr_x2[p].data();
1190
1191#ifdef USE_OPENMP
1192#pragma omp parallel for schedule(static) if (n1 >= 4096 && \
1193 omp_get_max_threads() > 1)
1194#endif
1195 for (Eigen::Index n = 0; n < n1; ++n) {
1196 const double invr_ij_1 = ir1[n];
1197#ifdef USE_HIGHWAY
1198 if (n2 >= 8) {
1199 gpr::hwy_kernels::accumulate_invr_diff_sq(
1200 dist.data() + n * n2, ir2, invr_ij_1, two_s2, n2);
1201 } else {
1202#endif
1203 for (Eigen::Index m = 0; m < n2; ++m) {
1204 const double invr_diff = invr_ij_1 - ir2[m];
1205 dist(n, m) += two_s2 * invr_diff * invr_diff;
1206 }
1207#ifdef USE_HIGHWAY
1208 }
1209#endif
1210 }
1211 }
1212}
1213
1215 const gpr::AtomsConfiguration& conf_info,
1216 const gpr::FieldMatrixd& lengthscale,
1217 gpr::FieldMatrixd& dist)
1218{
1219 if (far_field_radius_ > 0.0 || conf_info.pair_cutoff > 0.0 ||
1220 !cache_.matches(x1, x2, conf_info.cell)) {
1221 dist_at(x1, x2, conf_info, lengthscale, dist);
1222 return;
1223 }
1224
1225 accumulateCachedSquaredDistances(conf_info, lengthscale, dist);
1226 Eigen::Map<Eigen::ArrayXd>(dist.data(), dist.size()) =
1227 Eigen::Map<Eigen::ArrayXd>(dist.data(), dist.size()).sqrt();
1228}
1229
1231 const gpr::AtomsConfiguration& conf_info,
1232 const gpr::FieldMatrixd& lengthscale,
1233 gpr::FieldMatrixd& dist_sq)
1234{
1235 if (far_field_radius_ > 0.0 || conf_info.pair_cutoff > 0.0 ||
1236 !cache_.matches(x1, x2, conf_info.cell)) {
1237 dist_at(x1, x2, conf_info, lengthscale, dist_sq, /*take_sqrt=*/false);
1238 return;
1239 }
1240
1241 // No sqrt -- returns squared distances
1242 accumulateCachedSquaredDistances(conf_info, lengthscale, dist_sq);
1243}
1244} /* namespace aux */
@ x
Definition Enums.h:28
#define EMPTY
Definition Macros.h:39
void dist_at_cached_sq(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, const gpr::FieldMatrixd &lengthscale, gpr::FieldMatrixd &dist_sq)
Like dist_at_cached but returns SQUARED distances (skips final sqrt).
void dist_at_cached(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, const gpr::FieldMatrixd &lengthscale, gpr::FieldMatrixd &dist)
Compute dist_at using cached inverse distances.
void dist_at_vec(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, const gpr::FieldMatrixd &lengthscale, std::vector< gpr::FieldMatrixd > &dist)
Similar to dist_at but calculates vector of distances for every pair of moving and frozen atoms.
Definition Distance.cpp:796
void cacheInverseDistances(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info)
Pre-compute and cache raw inverse distances for given positions.
void dist_at(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, const gpr::FieldMatrixd &lengthscale, gpr::FieldMatrixd &dist, bool take_sqrt=true)
Give the distance between two atomic configurations as defined in the special GPstuff covariance func...
Definition Distance.cpp:620
bool selectsRadialFarField(const gpr::AtomsConfiguration &conf) const
Definition Distance.h:391
virtual ~Distance()
Definition Distance.cpp:297
void dist_max1Dlog(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, gpr::FieldMatrixd &dist)
Give the maximum difference in the logarithmic inter-atomic distances between atomic configurations C...
Definition Distance.cpp:462
void clearCache()
Definition Distance.h:354
void mindist_interatomic(const gpr::Coord &x, const gpr::AtomsConfiguration &conf_info, gpr::FieldMatrixd &dist)
Give the distance from each moving atom to its nearest neighbour atom in configuration C.
Definition Distance.cpp:958
void dist_emd(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, gpr::FieldMatrixd &dist)
Calculates the Earth Mover's Distance between sets of configurations.
void setFarFieldRadius(double radius)
Definition Distance.cpp:299
double range_at(const gpr::Coord &positions, const gpr::AtomsConfiguration &conf_info, const gpr::FieldMatrixd &lengthscale)
Definition Distance.cpp:533
void dist_rmsd(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, gpr::FieldMatrixd &dist)
Calculates the aligned Root Mean Square Deviation (RMSD) between sets of configurations.
Definition Distance.cpp:410
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
int status
bool farFromCentre(const gpr::geometry::PairBox &box, const double centre[3], const double frozen[3], double radius)
Definition FarField.h:81
std::vector< int > solve_assignment_indices(const Eigen::MatrixXd &cost_matrix)
Like solve_assignment_problem, but returns the optimal assignment.
Definition Distance.cpp:193
double solve_assignment_problem(const Eigen::MatrixXd &cost_matrix)
Solves the assignment problem using the Hungarian algorithm.
Definition Distance.cpp:179
std::pair< gpr::Coord, gpr::FieldMatrixIdx > get_canonical_configuration(const gpr::Coord &x_in, const gpr::FieldMatrixIdx &types_in)
Definition Distance.cpp:44
double farQuadratic(const double tensor[3][3], const double delta[3])
Definition FarField.h:60
void farFieldDifference(const gpr::geometry::PairBox &box, const double centre[3], const double left[3], const double right[3], double delta[3])
Definition FarField.h:36
double calculate_aligned_rmsd(const gpr::Coord &P, const gpr::Coord &Q)
Definition Distance.cpp:283
void addFarSource(double tensor[3][3], const double r[3], double weight)
Definition FarField.h:49
const double * farFieldCentre(const gpr::AtomsConfiguration &conf, Eigen::Index atom)
Definition FarField.h:15
double rigidAlignedRmsd(const Eigen::VectorXd &reference, const Eigen::VectorXd &mobile)
Eigen::Vector3d at(const FieldMatrixd &mat, Index_t i)
void set(FieldMatrixd &mat, Index_t i, const Eigen::Vector3d &vec)
std::vector< FieldMatrixd > radialPairSquaredDistances(const Coord &left, const Coord &right, const AtomsConfiguration &configuration, const FieldMatrixd &lengths, double far_radius)
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
Eigen::Matrix< double, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixd
Definition Macros.h:25
std::vector< std::vector< double > > invr_x1
Definition Distance.h:105
std::vector< std::vector< double > > invr_x2
Definition Distance.h:106
std::vector< gpr::Index_t > pair_types
Definition Distance.h:107
Stores configurations of all atoms in the system.
Definition Structures.h:832
AtomsPositionAndType atoms_froz_active
Info on active frozen atoms.
Definition Structures.h:841
AtomsPositionAndType atoms_mov
Info on moving atoms.
Definition Structures.h:844