Loading...
Searching...
No Matches
aux::Distance Class Reference

Methods to calculate distances between atoms. More...

#include <gpr/auxiliary/Distance.h>

Public Member Functions

 Distance ()
virtual ~Distance ()
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 and C'.
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.
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 function 'gpcf_matern32at'.
double range_at (const gpr::Coord &positions, const gpr::AtomsConfiguration &conf_info, const gpr::FieldMatrixd &lengthscale)
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.
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.
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 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_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_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).
bool hasCachedDistances () const
void clearCache ()
void setFarFieldRadius (double radius)
double farFieldRadius () const
void setRadialFarFieldList (bool enabled)
bool radialFarFieldList () const
std::uint64_t radialListEntries () const
bool selectsRadialFarField (const gpr::AtomsConfiguration &conf) const

Detailed Description

Methods to calculate distances between atoms.

Definition at line 154 of file Distance.h.

Constructor & Destructor Documentation

◆ Distance()

aux::Distance::Distance ( )

Definition at line 295 of file Distance.cpp.

295{ }

◆ ~Distance()

aux::Distance::~Distance ( )
virtual

Definition at line 297 of file Distance.cpp.

297{ }

Member Function Documentation

◆ cacheInverseDistances()

void aux::Distance::cacheInverseDistances ( const gpr::Coord & x1,
const gpr::Coord & x2,
const gpr::AtomsConfiguration & conf_info )

Pre-compute and cache raw inverse distances for given positions.

Call this once when positions are set (before an optimization loop). Subsequent calls to dist_at_cached() will reuse the cached 1/r values and only apply the lengthscale weighting.

Definition at line 1085 of file Distance.cpp.

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}
Eigen::Vector3d at(const FieldMatrixd &mat, Index_t i)
uint32_t Index_t
Definition Macros.h:17
AtomsPositionAndType atoms_froz_active
Info on active frozen atoms.
Definition Structures.h:841
AtomsPositionAndType atoms_mov
Info on moving atoms.
Definition Structures.h:844

◆ clearCache()

void aux::Distance::clearCache ( )
inline

Definition at line 354 of file Distance.h.

355 {
356 cache_.clear();
357 }

◆ dist_at()

void aux::Distance::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 function 'gpcf_matern32at'.

The distance between configurations C and C' is based on the changes of the inter-atomic distances:

dist(C,C') = sqrt(2 SUM_{i<j}{[(1/r_ij-1/r_ij')/l_ij]^2}), where r_ij and r_ij' are the distances between atoms i and j in configurations C and C', respectively, and l_ij is the lengthscale of the corresponding atom pair type.

The input vectors x1 and x2 are assumed to be row vectors including the gpr::Coordinates of the moving atoms: [x_1,y_1,z_1,x_2,y_2,z_2,...].

The parameter 'conf_info' is a structure array including necessary information about the configurations: conf_info.conf_fro: gpr::Coordinates of active frozen atoms (N_fro x 3) conf_info.atomtype_mov: atomtype indices for moving atoms (1 x N_mov) conf_info.atomtype_fro: atomtype indices for active frozen atoms (1 x N_fro) Atomtypes must be indexed as 1,2,...,n_at (may include also inactive atomtypes). conf_info.pairtype: pairtype indices for pairs of atomtypes (n_at x n_at) conf_info.n_pt: number of active pairtypes Active pairtypes are indexed as 0,1,2,...,n_pt-1. Inactive pairtypes are given index -1.

Parameters
x1gpr::Coordinates of the moving atoms in configurations C (n1 x 3*N_mov)
x2gpr::Coordinates of the moving atoms in configurations C' (n2 x 3*N_mov)
conf_infostructure array including information about the configurations necessary for the GP model
lengthscalelengthscales for different atom pair types (1 x n_pt)
distmatrix including the distances between configurations C and C' (n1 x n2)
take_sqrtReturn distances when true and squared distances otherwise
Note
x2-dependent inverse distances are pre-computed before the x1 loop to avoid redundant coordinate extractions. Frozen atom positions are cached outside the (n, m) inner loops. The final element-wise sqrt uses a vectorised Eigen ArrayXd map.

Definition at line 620 of file Distance.cpp.

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}
bool selectsRadialFarField(const gpr::AtomsConfiguration &conf) const
Definition Distance.h:391
bool farFromCentre(const gpr::geometry::PairBox &box, const double centre[3], const double frozen[3], double radius)
Definition FarField.h:81
const double * farFieldCentre(const gpr::AtomsConfiguration &conf, Eigen::Index atom)
Definition FarField.h:15
std::vector< FieldMatrixd > radialPairSquaredDistances(const Coord &left, const Coord &right, const AtomsConfiguration &configuration, const FieldMatrixd &lengths, double far_radius)
Eigen::Matrix< double, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixd
Definition Macros.h:25

◆ dist_at_cached()

void aux::Distance::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.

Requires a prior call to cacheInverseDistances() with the same positions. Only recomputes the lengthscale-weighted sum. Falls back to dist_at() if cache is invalid.

Definition at line 1214 of file Distance.cpp.

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}
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

◆ dist_at_cached_sq()

void aux::Distance::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).

The SexpatCF covariance kernels take these to avoid the sqrt + square roundtrip.

Definition at line 1230 of file Distance.cpp.

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}

◆ dist_at_vec()

void aux::Distance::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.

Note
Same pre-computation optimisations as dist_at: x2 inverse distances are computed once per atom pair, frozen positions are cached outside inner loops.
Parameters
x1First set of configurations, with moving coordinates in each row.
x2Second set of configurations, with frozen coordinates in each row.
conf_infoAtom counts and pair-type metadata for the structures.
lengthscaleLength scale associated with each pair type.
distOutput distance matrices organized by pair type.

Definition at line 796 of file Distance.cpp.

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}

◆ dist_emd()

void aux::Distance::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.

This method is fully permutation-invariant without needing a canonicalization step. It solves the assignment problem for each atom type to find the minimum "work" required to transform one configuration into another.

Definition at line 1018 of file Distance.cpp.

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}
double solve_assignment_problem(const Eigen::MatrixXd &cost_matrix)
Solves the assignment problem using the Hungarian algorithm.
Definition Distance.cpp:179
Eigen::Matrix< Index_t, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixIdx
Definition Macros.h:29

◆ dist_max1Dlog()

void aux::Distance::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 and C'.

It returns the maximum absolute logarithmic change in any interatomic distance. For atoms i,j this is abs(log(r_ij'/r_ij)), where r_ij and r_ij' are their distances in configurations C and C'.

The input vectors x1 and x2 are assumed to be row vectors including the gpr::Coordinates of the moving atoms: [x_1,y_1,z_1,x_2,y_2,z_2,...].

Parameters
x1gpr::Coordinates of the moving atoms in configurations C (n1 x 3*N_mov)
x2gpr::Coordinates of the moving atoms in configurations C' (n2 x 3*N_mov)
conf_infoStructure array including information about the configurations necessary for the GP model
  • conf_info.conf_fro: gpr::Coordinates of active frozen atoms (N_fro x 3)
  • conf_info.atomtype_mov: atomtype indices for moving atoms (1 x N_mov)
  • conf_info.atomtype_fro: pairtype indices for active frozen atoms (1 x N_fro)
  • conf_info.pairtype: pairtype indices for pairs of atomtypes (n_at x n_at)
  • conf_info.n_pt: number of active pairtypes
distMatrix including the "distances" from configurations C to configurations C' (n1 x n2)

Definition at line 462 of file Distance.cpp.

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}

◆ dist_rmsd()

void aux::Distance::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 at line 410 of file Distance.cpp.

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}
std::pair< gpr::Coord, gpr::FieldMatrixIdx > get_canonical_configuration(const gpr::Coord &x_in, const gpr::FieldMatrixIdx &types_in)
Definition Distance.cpp:44
double calculate_aligned_rmsd(const gpr::Coord &P, const gpr::Coord &Q)
Definition Distance.cpp:283
FieldMatrixd Coord
Definition Macros.h:35

◆ farFieldRadius()

double aux::Distance::farFieldRadius ( ) const
inlinenodiscard

Definition at line 363 of file Distance.h.

364 {
365 return far_field_radius_;
366 }

◆ hasCachedDistances()

bool aux::Distance::hasCachedDistances ( ) const
inline

Definition at line 350 of file Distance.h.

351 {
352 return cache_.valid;
353 }

◆ mindist_interatomic()

void aux::Distance::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.

The input vectors in x are assumed to be row vectors including the gpr::Coordinates of the moving atoms: [x_1,y_1,z_1,x_2,y_2,z_2,...].

Parameters
xgpr::Coordinates of the moving atoms in configurations C (n x 3*N_mov)
conf_infostructure array including information about the configurations necessary for the GP model
  • conf_info.conf_fro: gpr::Coordinates of active frozen atoms (N_fro x 3)
  • conf_info.atomtype_mov: atomtype indices for moving atoms (1 x N_mov)
  • conf_info.atomtype_fro: pairtype indices for active frozen atoms (1 x N_fro)
  • conf_info.pairtype: pairtype indices for pairs of atomtypes (n_at x n_at)
  • conf_info.n_pt: number of active pairtypes
distmatrix including the minimum interatomic distances for each moving atom in configurations C (n x N_mov)

Definition at line 958 of file Distance.cpp.

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}
@ x
Definition Enums.h:28

◆ radialFarFieldList()

bool aux::Distance::radialFarFieldList ( ) const
inlinenodiscard

Definition at line 377 of file Distance.h.

378 {
379 return radial_far_field_list_;
380 }

◆ radialListEntries()

std::uint64_t aux::Distance::radialListEntries ( ) const
inlinenodiscard

Entries to the radial-list branch of dist_at and dist_at_vec. Stays zero while the direct loop is selected.

Definition at line 384 of file Distance.h.

385 {
386 return radial_list_entries_;
387 }

◆ range_at()

double aux::Distance::range_at ( const gpr::Coord & positions,
const gpr::AtomsConfiguration & conf_info,
const gpr::FieldMatrixd & lengthscale )

Maximum pair-feature distance over the distinct coordinate rows. Observation/channel tags after the moving coordinates are ignored. Repeated energy and gradient rows do not enlarge the geometry work.

Definition at line 533 of file Distance.cpp.

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}

◆ selectsRadialFarField()

bool aux::Distance::selectsRadialFarField ( const gpr::AtomsConfiguration & conf) const
inlinenodiscard

True when this call uses the radial assembly. A pair cutoff always does. A far-field radius does only after setRadialFarFieldList(true).

Definition at line 391 of file Distance.h.

393 {
394 if (conf.pair_cutoff > 0.0) return true;
395 return far_field_radius_ > 0.0 && radial_far_field_list_;
396 }

◆ setFarFieldRadius()

void aux::Distance::setFarFieldRadius ( double radius)

Moving-frozen pairs at or beyond radius from atoms_mov.positions use the dipole tensor about that fixed model reference. Query coordinates use its local minimum-image chart. Zero keeps every pair exact.

Definition at line 299 of file Distance.cpp.

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}
void clearCache()
Definition Distance.h:354

◆ setRadialFarFieldList()

void aux::Distance::setRadialFarFieldList ( bool enabled)
inline

The radial far-field list is opt-in. The direct loop is the default at every size. The list is slower than that loop at every size measured in docs/verification/far-field-ladder.txt, from 63 through 32000 atoms. Nothing above 32000 atoms was measured.

Definition at line 372 of file Distance.h.

373 {
374 radial_far_field_list_ = enabled;
375 clearCache();
376 }

The documentation for this class was generated from the following files: