38Vector3d exactMeanForce(
const AtomMatrix &forces) {
39 const auto n =
static_cast<std::size_t
>(forces.rows());
40 const double inv = 1.0 /
static_cast<double>(forces.rows());
42 for (
int axis = 0; axis < 3; ++axis) {
43 const auto column = forces.col(axis);
46 column.data(), n,
static_cast<std::size_t
>(column.innerStride())) *
64 Eigen::Matrix<std::int64_t, Eigen::Dynamic, 1>
atomIndex;
83 structComp{params.structure_comparison_options()},
97 ownedPotential = std::move(
pot);
98 if (ownedPotential && ownedPotential->requiresIsolatedMoleculeLayout()) {
99 usePeriodicBoundaries =
false;
122void checkAtom(
long nAtoms,
long indexAtom,
const char *fn) {
123 if (indexAtom < 0 || indexAtom >= nAtoms) {
124 throw std::out_of_range(std::string(fn) +
": atom index out of range");
127void checkAxis(
int axis,
const char *fn) {
128 if (axis < 0 || axis > 2) {
129 throw std::out_of_range(std::string(fn) +
": axis out of range");
140 if (
this == &matter) {
154 impl_->cellInverse = matter.
impl_->cellInverse;
199 :
impl_{std::make_unique<Impl>()} {
200 operator=(std::move(other));
204 if (
this == &other) {
219 impl_->positions = std::move(other.impl_->positions);
220 impl_->velocities = std::move(other.impl_->velocities);
221 impl_->forces = std::move(other.impl_->forces);
222 impl_->biasForces = std::move(other.impl_->biasForces);
224 other.biasPotential =
nullptr;
225 impl_->masses = std::move(other.impl_->masses);
226 impl_->atomicNrs = std::move(other.impl_->atomicNrs);
227 impl_->isFixed = std::move(other.impl_->isFixed);
228 impl_->atomIndex = std::move(other.impl_->atomIndex);
230 impl_->freeMask = std::move(other.impl_->freeMask);
231 impl_->maskedForces = std::move(other.impl_->maskedForces);
235 impl_->cell = std::move(other.impl_->cell);
236 impl_->cellInverse = std::move(other.impl_->cellInverse);
237 impl_->stress = other.impl_->stress;
238 impl_->haveStress = other.impl_->haveStress;
248 other.recomputePotential =
true;
249 other.recomputeFreeMask =
true;
250 other.recomputeMaskedForces =
true;
257 if (
structComp.check_rotation && indistinguishable) {
260 }
else if (indistinguishable) {
278 throw std::invalid_argument(
"Matter::distanceTo: size mismatch");
280 return pbc(
impl_->positions - matter.
impl_->positions).norm();
286 double max_distance = 0.0;
290 for (i = 0; i <
nAtoms; i++) {
291 max_distance = std::max(diff.row(i).norm(), max_distance);
299 throw std::invalid_argument(
"Matter::resize: negative atom count");
303 const bool keepAtomIds =
304 (length ==
nAtoms &&
impl_->atomIndex.size() == length &&
309 impl_->positions.resize(length, 3);
310 impl_->positions.setZero();
312 impl_->velocities.resize(length, 3);
313 impl_->velocities.setZero();
315 impl_->biasForces.resize(length, 3);
316 impl_->biasForces.setZero();
318 impl_->forces.resize(length, 3);
319 impl_->forces.setZero();
321 impl_->masses.resize(length);
322 impl_->masses.setZero();
324 impl_->atomicNrs.resize(length);
325 impl_->atomicNrs.setZero();
327 impl_->isFixed.resize(length, 3);
328 impl_->isFixed.setZero();
331 impl_->atomIndex.resize(length);
333 for (
long i = 0; i < length; i++) {
334 impl_->atomIndex(i) =
static_cast<std::int64_t
>(i);
348 impl_->cell = newCell;
355 checkAtom(
nAtoms, indexAtom,
"Matter::getPosition");
356 checkAxis(axis,
"Matter::getPosition");
357 return impl_->positions(indexAtom, axis);
361 checkAtom(
nAtoms, indexAtom,
"Matter::setPosition");
362 checkAxis(axis,
"Matter::setPosition");
363 impl_->positions(indexAtom, axis) = position;
372 checkAtom(
nAtoms, indexAtom,
"Matter::setVelocity");
373 checkAxis(axis,
"Matter::setVelocity");
374 impl_->velocities(indexAtom, axis) = vel;
397 VectorXi ret(
static_cast<Eigen::Index
>(
freeIndices.size()));
405 std::string prefixMovie, std::string prefixCheckpoint,
406 bool retainMovieFrames) {
407 if (retainMovieFrames) {
411 *
this, *
parameters, quiet, writeMovie, checkpoint, prefixMovie,
412 prefixCheckpoint, retainMovieFrames ? &
movie_frames_ :
nullptr);
421 if (pos.rows() !=
nAtoms) {
422 throw std::invalid_argument(
"Matter::setPositions: row count mismatch");
424 impl_->positions = pos;
490 return impl_->maskedForces;
495 return impl_->forces;
507 ret.row(
static_cast<long>(j)) = allForces.row(
freeIndices[j]);
519 checkAtom(
nAtoms, index1,
"Matter::distance");
520 checkAtom(
nAtoms, index2,
"Matter::distance");
521 return pbc(
impl_->positions.row(index1) -
impl_->positions.row(index2))
528 checkAtom(
nAtoms, index1,
"Matter::pdistance");
529 checkAtom(
nAtoms, index2,
"Matter::pdistance");
530 checkAxis(axis,
"Matter::pdistance");
531 Matrix<double, 1, 3> ret;
534 impl_->positions(index1, axis) -
impl_->positions(index2, axis);
542 checkAtom(
nAtoms, index,
"Matter::distance");
543 checkAtom(matter.
nAtoms, index,
"Matter::distance");
549 checkAtom(
nAtoms, indexAtom,
"Matter::getMass");
550 return (
impl_->masses[indexAtom]);
554 checkAtom(
nAtoms, indexAtom,
"Matter::setMass");
555 impl_->masses[indexAtom] = mass;
559 if (massesIn.size() !=
nAtoms) {
560 throw std::invalid_argument(
"Matter::setMasses: size mismatch");
562 impl_->masses = massesIn;
566 return (
impl_->atomicNrs[indexAtom]);
570 impl_->atomicNrs[indexAtom] = atomicNr;
576 checkAtom(
nAtoms, indexAtom,
"Matter::getFixed");
577 return (
impl_->isFixed(indexAtom, 0) > 0.5 &&
578 impl_->isFixed(indexAtom, 1) > 0.5 &&
579 impl_->isFixed(indexAtom, 2) > 0.5)
585 checkAtom(
nAtoms, indexAtom,
"Matter::getFixed");
586 checkAxis(axis,
"Matter::getFixed");
587 return impl_->isFixed(indexAtom, axis) > 0.5 ? 1 : 0;
591 checkAtom(
nAtoms, indexAtom,
"Matter::getFixedMask");
592 return {
impl_->isFixed(indexAtom, 0) > 0.5,
593 impl_->isFixed(indexAtom, 1) > 0.5,
594 impl_->isFixed(indexAtom, 2) > 0.5};
598 checkAtom(
nAtoms, indexAtom,
"Matter::setFixed");
599 const double v = isFixed_passed ? 1.0 : 0.0;
600 impl_->isFixed(indexAtom, 0) = v;
601 impl_->isFixed(indexAtom, 1) = v;
602 impl_->isFixed(indexAtom, 2) = v;
608 checkAtom(
nAtoms, indexAtom,
"Matter::setFixed");
609 checkAxis(axis,
"Matter::setFixed");
610 impl_->isFixed(indexAtom, axis) = isFixed_passed ? 1.0 : 0.0;
616 checkAtom(
nAtoms, indexAtom,
"Matter::setFixedMask");
617 impl_->isFixed(indexAtom, 0) = mask[0] ? 1.0 : 0.0;
618 impl_->isFixed(indexAtom, 1) = mask[1] ? 1.0 : 0.0;
619 impl_->isFixed(indexAtom, 2) = mask[2] ? 1.0 : 0.0;
635 Eigen::VectorXd speed2 = vfree.rowwise().squaredNorm();
636 return 0.5 * (
impl_->masses.array() * speed2.array()).sum();
645 for (
long i = 0; i <
nAtoms; ++i) {
669 throw std::runtime_error(
670 "Potential requires an isolated (non-periodic) molecular layout "
671 "(NWChem/ORCA-class). Disable periodic boundaries before optimizing; "
672 "PBC wraps can tear non-centered molecules (issue #188).");
677 const unsigned long long pe =
699 throw std::runtime_error(
700 "Matter::computePotential called without a potential");
705 auto surrogatePotential =
707 auto [freePE, freeForces, vari] = surrogatePotential->
get_ef_var(
711 impl_->haveStress =
false;
712 for (
long idx{0}, jdx{0}; idx <
nAtoms; idx++) {
714 impl_->forces.row(idx) = freeForces.row(jdx);
723 const auto n =
static_cast<size_t>(
nAtoms);
731 std::span<const double>(
impl_->positions.data(), n * 3),
732 std::span<const int>(
impl_->atomicNrs.data(), n),
734 &var, std::span<const double>(force_cell.data(), 9));
740 throw std::runtime_error(
741 "Potential returned non-finite energy or forces");
750 const Vector3d tempForce = exactMeanForce(
impl_->forces);
751 for (
long int i = 0; i <
nAtoms; i++) {
752 impl_->forces.row(i) -= tempForce.transpose();
765 if (std::abs(
impl_->cell.determinant()) < 1e-30) {
773 if (rows.rows() !=
nAtoms) {
774 throw std::invalid_argument(
775 "Matter::maxFreeAtomForce: row count does not match atom count");
789 if (atmnrs.size() != this->nAtoms) {
790 throw std::invalid_argument(
791 "Vector of atomic numbers not equal to the number of atoms");
793 this->
impl_->atomicNrs = atmnrs;
802 impl_->freeMask = 1.0 -
impl_->isFixed.array();
805 for (
long i = 0; i <
nAtoms; i++) {
806 if (
impl_->freeMask.row(i).sum() > 0.5) {
812 return impl_->freeMask;
830 impl_->haveStress =
false;
839 auto invMass =
impl_->masses.array().inverse();
840 ret.col(0).array() *= invMass;
841 ret.col(1).array() *= invMass;
842 ret.col(2).array() *= invMass;
847 return impl_->masses;
862 "Disabled PBC for isolated-molecule potential (NWChem/ORCA-class); "
863 "re-enabling PBC will throw (issue #188)");
873 impl_->haveStress =
false;
881 const Vector3d tempForce = exactMeanForce(
impl_->forces);
882 for (
long int i = 0; i <
nAtoms; i++) {
883 impl_->forces.row(i) -= tempForce.transpose();
900 impl_->haveStress =
false;
908 if (threads &&
livePotential()->isSharedInstanceThreadSafe() &&
914 impl_->haveStress =
impl_->stress.allFinite();
915 }
catch (
const std::logic_error &) {
916 impl_->haveStress =
false;
922 throw std::logic_error(
923 "Matter::cauchyStress requires a potential that reports stress");
927 return impl_->stress;
932 if (!sigma.allFinite()) {
933 throw std::runtime_error(
"Potential returned a non-finite stress tensor");
960 return impl_->atomIndex(atom);
964 impl_->atomIndex(atom) = index;
969 impl_->forces = fileForces;
970 impl_->haveStress =
false;
982 std::vector<const Potential *> seen;
983 seen.reserve(systems.size());
984 for (
Matter *m : systems) {
985 const Potential *p = m->getPotential().get();
989 if (std::find(seen.begin(), seen.end(), p) == seen.end()) {
999 bool threads, std::span<const long> owners) {
1000 std::vector<Matter *> dirty;
1001 std::vector<long> dirtyOwners;
1002 for (
size_t i = 0; i < systems.size(); ++i) {
1006 dirtyOwners.push_back(i < owners.size() ? owners[i] : -1);
1009 if (dirty.empty()) {
1012 if (dirty.size() == 1 || !
pot.supportsBatchEvaluation()) {
1015 dirty[static_cast<size_t>(i - 1)]->getForcesRaw();
1019 for (
Matter *m : dirty) {
1024 const long n = dirty.size();
1025 const long atoms = dirty.front()->numberOfAtoms();
1026 std::vector<VectorXi> nrs(n);
1027 std::vector<Matrix3d> boxes(n);
1028 std::vector<const double *> posPtr, boxPtr;
1029 std::vector<const int *> nrsPtr;
1030 std::vector<double *> frcPtr;
1031 for (
long j = 0; j < n; ++j) {
1034 throw std::invalid_argument(
1035 "evaluateTogether: systems differ in atom count");
1042 : Matrix3d::Zero().eval();
1044 for (
long j = 0; j < n; ++j) {
1045 posPtr.push_back(dirty[j]->getPositions().data());
1046 nrsPtr.push_back(nrs[j].data());
1047 frcPtr.push_back(dirty[j]->forcesData());
1048 boxPtr.push_back(boxes[j].data());
1050 std::vector<double> energies(n), variances(n);
1051 if (owners.empty()) {
1052 pot.forceBatch(n, atoms, posPtr.data(), nrsPtr.data(), frcPtr.data(),
1053 energies.data(), variances.data(), boxPtr.data());
1055 pot.forceBatchOwned(n, atoms, posPtr.data(), nrsPtr.data(), frcPtr.data(),
1056 energies.data(), variances.data(), boxPtr.data(),
1057 dirtyOwners.data());
1059 for (
long j = 0; j < n; ++j) {
1060 dirty[j]->setComputedPotential(energies[j], variances[j]);
Eigen::Matrix< double, 3, 3, eOnStorageOrder > Matrix3d
Eigen::Matrix< double, Eigen::Dynamic, 3, eOnStorageOrder > AtomMatrix
#define EONC_LOG_WARNING(...)
Functionality relying on the conjugate gradients algorithm.
void applyPeriodicBoundary()
void setBiasPotential(BondBoost *bondBoost)
double getKineticEnergy() const
bool getWriteConForces() const noexcept
Parameters.main_options().writeConForces for this Matter.
VectorXi getAtomicNrs() const
void setComputedPotential(double energy, double variance)
Set energy/variance from external batched evaluation and mark forces as up-to-date (recomputePotentia...
void setForces(const AtomMatrix &f)
void setFixed(long int atom, int isFixed)
Broadcast a whole-atom flag onto all three axes.
std::shared_ptr< Potential > getPotential()
BondBoost * getBiasPotential() const
The bias potential added to this Matter's forces, or nullptr.
double maxFreeAtomForce(const AtomMatrix &rows) const
Max per-atom Euclidean norm of rows.
void setFixedMask(long int atom, std::array< bool, 3 > mask)
void setPosition(long int atom, int axis, double position)
PbcConvention pbcConvention
const AtomMatrix & getPositions() const
bool relax(bool quiet=false, bool writeMovie=false, bool checkpoint=false, std::string prefixMovie=std::string(), std::string prefixCheckpoint=std::string(), bool retainMovieFrames=false)
double distanceTo(const Matter &matter)
VectorXd getForcesFreeV() const
void setPositions(const AtomMatrix &pos)
void setAtomicNr(long int atom, long atomicNr)
double pdistance(long index1, long index2, int axis) const
AtomMatrix getForcesFree() const
const Matter & operator=(const Matter &matter)
std::vector< readcon::ConFrame > movie_frames_
bool compare(const Matter &matter, bool indistinguishable=false)
void setPositionsV(const VectorXd &pos)
void setCell(const Matrix3d &newCell)
std::vector< int > freeIndices
AtomMatrix getFree() const
bool getPeriodic() const noexcept
void setVelocity(long int atom, int axis, double velocity)
void computePotential() const
void setPotential(std::shared_ptr< Potential > pot)
void setPositionsFreeV(const VectorXd &pos)
bool recomputeMaskedForces
std::unique_ptr< Potential > ownedPotential
const Parameters * parameters
long int numberOfAtoms() const
Matrix3d cauchyStress()
Cauchy stress in eV/Angstrom^3.
AtomMatrix pbc(const AtomMatrix &diff) const
std::shared_ptr< Potential > potential
long getForceCalls() const
VectorXd getPositionsFreeV() const
BondBoost * biasPotential
void setAtomicNrs(const VectorXi &atmnrs)
AtomMatrix getVelocities() const
void setVelocities(const AtomMatrix &v)
double getMechanicalEnergy() const
void setAtomIndex(long int atom, std::int64_t index)
double perAtomNorm(const Matter &matter)
const AtomMatrix & getForcesRaw() const
void resize(long int nAtoms)
VectorXd pbcV(const VectorXd &diff) const
AtomMatrix getPositionsFree() const
double getPosition(long int atom, int axis) const
size_t getPotentialCalls() const
unsigned long long cachedHostEpoch_
std::shared_ptr< bool > writeConForces_
VectorXi getAtomicNrsFree() const
void restoreFileForces(const AtomMatrix &fileForces, bool trustEnergy, double energy)
Write .con forces without the fixed-atom mask setForces applies.
Eigen::Matrix< double, Eigen::Dynamic, 1 > getMasses() const
long int numberOfFixedAtoms() const
std::unique_ptr< Impl > impl_
unsigned long long cachedPotEpoch_
double distance(long index1, long index2) const
double getMass(long int atom) const
unsigned long long surfaceEpoch_
void setMasses(const VectorXd &massesIn)
void setMass(long int atom, double mass)
double getPotentialEnergy() const
AtomMatrix getAccelerations()
void stampSurfaceEpoch() const
double * forcesData()
Mutable access to force storage for batched potential evaluation.
bool needsForceUpdate() const
Whether forces need recomputation (positions or surface epoch changed).
AtomMatrix getBiasForces()
std::array< std::string, 5 > headerCon
bool holdsExclusivePotential() const
True while no copy has shared the Potential from an exclusive handoff.
StructureComparisonOptions structComp
bool usePeriodicBoundaries
long int numberOfFreeAtoms() const
VectorXd getFreeV() const
Matter(std::shared_ptr< Potential > pot, const Parameters ¶ms)
CancelToken cancel_token_
long getAtomicNr(long int atom) const
double getEnergyVariance() const
AtomMatrix getPositionsCopy() const
void shareOwnedPotential() const
std::array< bool, 3 > getFixedMask(long int atom) const
Per-axis CON column-4 mask (bit0=x, bit1=y, bit2=z).
void setBiasForces(const AtomMatrix &bf)
void setPositionsFree(const AtomMatrix &pos)
std::vector< long > fileToMatter
std::int64_t getAtomIndex(long int atom) const
.con column-5 index (pre-grouping); public for I/O / bindings.
void assertIsolatedMoleculeLayoutSafe() const
Throw if pot forbids PBC (isolated molecular QM backends, issue #188).
VectorXd getPositionsV() const
void assignKeepingBias(const Matter &other)
Copy another structure in and keep this Matter's own bias potential.
const AtomMatrix & getForces() const
int getFixed(long int atom) const
1 if every Cartesian axis of the atom is fixed, else 0.
Potential * livePotential() const
void setSurfaceEpoch(unsigned long long epoch)
Host surface generation.
VectorXd getForcesV() const
void captureStress() const
double maxForce(void) const
std::atomic< size_t > forceCallCounter
virtual unsigned long long surfaceEpoch() const noexcept
Host-visible surface generation.
virtual void force(long nAtoms, const double *positions, const int *atomicNrs, double *forces, double *energy, double *variance, const double *box)=0
virtual bool forwardsStoredCell() const noexcept
A host that owns the cell reads the stored matrix.
virtual Matrix3d cauchyStress() const
Cauchy stress in eV/Angstrom^3.
void recordForceCall() noexcept
Charge one evaluated geometry to this potential and its owning registry.
virtual void setFixedMask(long nAtoms, const double *isFixed)
Optional frozen-atom mask (nAtoms*3, 1.0 = fixed).
std::tuple< double, AtomMatrix, double > get_ef_var(const AtomMatrix pos, const VectorXi atmnrs, const Matrix3d box)
double sumStrided(const double *x, std::size_t n, std::size_t stride)
Same sum for x[i * stride].
bool rotationMatch(const Matter &m1, const Matter &m2, const double max_diff)
bool identical(const Matter &m1, const Matter &m2, const double distanceDifference)
bool sortedR(const Matter &m1, const Matter &m2, const double distanceDifference)
void translationRemove(Matter &m1, const AtomMatrix r1)
bool relaxMatter(Matter &matter, const Parameters ¶ms, bool quiet=false, bool writeMovie=false, bool checkpoint=false, std::string prefixMovie=std::string(), std::string prefixCheckpoint=std::string(), std::vector< readcon::ConFrame > *outFrames=nullptr)
AtomMatrix apply(const AtomMatrix &diff, const Matrix3d &cell, const Matrix3d &cellInverse)
AtomMatrix applyPositions(const AtomMatrix &coords, const Matrix3d &cell, const Matrix3d &cellInverse, PbcConvention convention)
VectorXd applyV(const VectorXd &diffVector, const Matrix3d &cell, const Matrix3d &cellInverse)
RAII resource manager for the ARTn C library with global synchronization.
bool potAllowsSharedInstance(const P &p) noexcept
void forEachImage(long n, Work &&work)
void evaluateTogether(Potential &pot, std::span< Matter *const > systems, bool threads, std::span< const long > owners)
Evaluates every system that needs a force update.
double maxFreeAtomForceNorm(const double *forces, const double *fixed, long nAtoms)
Max Euclidean norm over N x 3 row-major force rows.
bool canComputeConcurrently(std::span< Matter *const > systems)
True when the systems can compute on separate threads at once: every potential instance that two of t...
Eigen::Matrix< std::int64_t, Eigen::Dynamic, 1 > atomIndex