Loading...
Searching...
No Matches
Matter.cpp
Go to the documentation of this file.
1/*
2** This file is part of eOn.
3**
4** SPDX-License-Identifier: BSD-3-Clause
5**
6** Copyright (c) 2010--present, eOn Development Team
7** All rights reserved.
8**
9** Repo:
10** https://github.com/TheochemUI/eOn
11*/
12#include "eon/Matter.h"
13#include "eon/BaseStructures.h"
14#include "eon/BondBoost.h"
15#include "eon/ExactReduction.h"
16#include "eon/ForceNorm.h"
18#include "eon/HelperFunctions.h"
19#include "eon/Parameters.h"
20#include "eon/PotCapabilities.h"
22
23#include "ForEachImage.h"
24#include "eon/EonLogger.h"
25#include <algorithm>
26#include <cmath>
27#include <memory>
28#include <span>
29#include <stdexcept>
30#include <string>
31#include <vector>
32
33namespace eonc {
34namespace {
35
36// Eigen's column sum follows the packet width, so the mean subtracted here
37// differed between x86 and NEON and the minimizer took another path.
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());
41 Vector3d mean;
42 for (int axis = 0; axis < 3; ++axis) {
43 const auto column = forces.col(axis);
44 mean[axis] =
46 column.data(), n, static_cast<std::size_t>(column.innerStride())) *
47 inv;
48 }
49 return mean;
50}
51
52} // namespace
53
55 AtomMatrix positions{AtomMatrix::Zero(0, 3)};
56 AtomMatrix velocities{AtomMatrix::Zero(0, 3)};
57 mutable AtomMatrix forces{AtomMatrix::Zero(0, 3)};
58 AtomMatrix biasForces{AtomMatrix::Zero(0, 3)};
59 VectorXd masses{VectorXd::Zero(0)};
60 VectorXi atomicNrs{VectorXi::Zero(0)};
61 // Nx3; 1.0 if that axis is fixed, 0.0 if free.
62 AtomMatrix isFixed{AtomMatrix::Zero(0, 3)};
63 // Original atom index from .con column 5.
64 Eigen::Matrix<std::int64_t, Eigen::Dynamic, 1> atomIndex;
65 mutable AtomMatrix freeMask; // Nx3; 1.0 free, 0.0 fixed
66 mutable AtomMatrix maskedForces; // forces with fixed atoms zeroed
67 Matrix3d cell{Matrix3d::Zero()};
68 Matrix3d cellInverse{Matrix3d::Zero()};
69 // Cauchy stress the potential reported with the cached evaluation.
70 Matrix3d stress{Matrix3d::Zero()};
71 bool haveStress{false};
72};
73
74Matter::~Matter() = default;
75
76Matter::Matter(std::shared_ptr<Potential> pot, const Parameters &params)
77 : potential{pot},
78 usePeriodicBoundaries{!(pot && pot->requiresIsolatedMoleculeLayout())},
81 forceCalls{0},
82 removeNetForce{params.main_options().removeNetForce},
83 structComp{params.structure_comparison_options()},
84 writeConForces_{params.main_options().writeConForces.share()},
85 parameters{&params},
86 nAtoms{0},
87 impl_{std::make_unique<Impl>()},
88 biasPotential{nullptr},
89 energyVariance{0.0},
90 potentialEnergy{0.0},
93 cachedPotEpoch_{0} {}
94
95Matter::Matter(std::unique_ptr<Potential> pot, const Parameters &params)
96 : Matter(std::shared_ptr<Potential>{}, params) {
97 ownedPotential = std::move(pot);
98 if (ownedPotential && ownedPotential->requiresIsolatedMoleculeLayout()) {
99 usePeriodicBoundaries = false;
100 }
101}
102
104 return ownedPotential ? ownedPotential.get() : potential.get();
105}
106
108 if (ownedPotential) {
109 potential = std::shared_ptr<Potential>(std::move(ownedPotential));
110 }
111}
112
114 return static_cast<bool>(ownedPotential);
115}
116
117bool Matter::getWriteConForces() const noexcept {
119}
120
121namespace {
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");
125 }
126}
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");
130 }
131}
132} // namespace
133
134Matter::Matter(const Matter &matter)
135 : impl_{std::make_unique<Impl>()} {
136 operator=(matter);
137}
138
139const Matter &Matter::operator=(const Matter &matter) {
140 if (this == &matter) {
141 return *this;
142 }
143 nAtoms = matter.nAtoms;
144 resize(nAtoms);
145
146 impl_->positions = matter.impl_->positions;
147 impl_->forces = matter.impl_->forces;
148 impl_->masses = matter.impl_->masses;
149 impl_->atomicNrs = matter.impl_->atomicNrs;
150 impl_->isFixed = matter.impl_->isFixed;
151 impl_->atomIndex = matter.impl_->atomIndex;
152 fileToMatter = matter.fileToMatter;
153 impl_->cell = matter.impl_->cell;
154 impl_->cellInverse = matter.impl_->cellInverse;
155 impl_->stress = matter.impl_->stress;
156 impl_->haveStress = matter.impl_->haveStress;
157 impl_->velocities = matter.impl_->velocities;
158
160 structComp = matter.structComp;
162 parameters = matter.parameters;
163
166
167 matter.shareOwnedPotential();
168 ownedPotential.reset();
169 potential = matter.potential;
172 forceCalls = matter.forceCalls;
177 // Both caches describe the forces this object held before the assignment.
178 // resize() above already raises them; state it here alongside the members
179 // this function owns.
180 recomputeFreeMask = true;
182
183 // A BondBoost binds to one Matter (BondBoost.h:32 takes a Matter *), so a
184 // copy cannot share the source's: boosting through it would drive the
185 // original. The copy starts without one and re-establishes it through
186 // setBiasPotential. biasForces is zeroed by the resize above, which is the
187 // state that matches having no bias potential.
188 biasPotential = nullptr;
189
190 headerCon = matter.headerCon;
192 // ConFrame is move-only; copy does not retain movie trajectory.
193 movie_frames_.clear();
194
195 return *this;
196}
197
198Matter::Matter(Matter &&other) noexcept
199 : impl_{std::make_unique<Impl>()} {
200 operator=(std::move(other));
201}
202
203Matter &Matter::operator=(Matter &&other) noexcept {
204 if (this == &other) {
205 return *this;
206 }
207 ownedPotential = std::move(other.ownedPotential);
208 potential = std::move(other.potential);
209 usePeriodicBoundaries = other.usePeriodicBoundaries;
210 pbcConvention = other.pbcConvention;
211 recomputePotential = other.recomputePotential;
212 forceCalls = other.forceCalls;
213 headerCon = std::move(other.headerCon);
214 removeNetForce = other.removeNetForce;
215 structComp = other.structComp;
216 writeConForces_ = other.writeConForces_;
217 parameters = other.parameters;
218 nAtoms = other.nAtoms;
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);
223 biasPotential = other.biasPotential;
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);
229 fileToMatter = std::move(other.fileToMatter);
230 impl_->freeMask = std::move(other.impl_->freeMask);
231 impl_->maskedForces = std::move(other.impl_->maskedForces);
232 freeIndices = std::move(other.freeIndices);
233 recomputeFreeMask = other.recomputeFreeMask;
234 recomputeMaskedForces = other.recomputeMaskedForces;
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;
239 energyVariance = other.energyVariance;
240 movie_frames_ = std::move(other.movie_frames_);
241 potentialEnergy = other.potentialEnergy;
242 cancel_token_ = std::move(other.cancel_token_);
243 surfaceEpoch_ = other.surfaceEpoch_;
244 cachedHostEpoch_ = other.cachedHostEpoch_;
245 cachedPotEpoch_ = other.cachedPotEpoch_;
246
247 other.nAtoms = 0;
248 other.recomputePotential = true;
249 other.recomputeFreeMask = true;
250 other.recomputeMaskedForces = true;
251 return *this;
252}
253
254bool Matter::compare(const Matter &matter, bool indistinguishable) {
255 if (nAtoms != matter.numberOfAtoms())
256 return false;
257 if (structComp.check_rotation && indistinguishable) {
258 return eonc::geometry::sortedR(*this, matter,
259 structComp.distance_difference);
260 } else if (indistinguishable) {
261 if (this->numberOfFixedAtoms() == 0 and structComp.remove_translation)
263 return eonc::geometry::identical(*this, matter,
264 structComp.distance_difference);
265 } else if (structComp.check_rotation) {
266 return eonc::geometry::rotationMatch(*this, matter,
267 structComp.distance_difference);
268 } else {
269 if (this->numberOfFixedAtoms() == 0 and structComp.remove_translation)
271 return (structComp.distance_difference) > perAtomNorm(matter);
272 }
273}
274
275// Returns the distance to the given matter object.
276double Matter::distanceTo(const Matter &matter) {
277 if (matter.numberOfAtoms() != nAtoms) {
278 throw std::invalid_argument("Matter::distanceTo: size mismatch");
279 }
280 return pbc(impl_->positions - matter.impl_->positions).norm();
281}
282
283// Returns the maximum distance between two atoms in the Matter objects.
284double Matter::perAtomNorm(const Matter &matter) {
285 long i = 0;
286 double max_distance = 0.0;
287
288 if (matter.numberOfAtoms() == nAtoms) {
289 AtomMatrix diff = pbc(impl_->positions - matter.impl_->positions);
290 for (i = 0; i < nAtoms; i++) {
291 max_distance = std::max(diff.row(i).norm(), max_distance);
292 }
293 }
294 return max_distance;
295}
296
297void Matter::resize(const long int length) {
298 if (length < 0) {
299 throw std::invalid_argument("Matter::resize: negative atom count");
300 }
301 // Same-N resize still zeros coordinates. Keep .con column-5 ids and
302 // the file-order map so a later matter2con does not stamp 1..N.
303 const bool keepAtomIds =
304 (length == nAtoms && impl_->atomIndex.size() == length &&
305 fileToMatter.size() == static_cast<size_t>(length));
306 // Zero is a real size: leaving nAtoms at the old value there sends
307 // setMasses and every other nAtoms loop off the end of an empty array.
308 nAtoms = length;
309 impl_->positions.resize(length, 3);
310 impl_->positions.setZero();
311
312 impl_->velocities.resize(length, 3);
313 impl_->velocities.setZero();
314
315 impl_->biasForces.resize(length, 3);
316 impl_->biasForces.setZero();
317
318 impl_->forces.resize(length, 3);
319 impl_->forces.setZero();
320
321 impl_->masses.resize(length);
322 impl_->masses.setZero();
323
324 impl_->atomicNrs.resize(length);
325 impl_->atomicNrs.setZero();
326
327 impl_->isFixed.resize(length, 3);
328 impl_->isFixed.setZero();
329
330 if (!keepAtomIds) {
331 impl_->atomIndex.resize(length);
332 fileToMatter.resize(static_cast<size_t>(length));
333 for (long i = 0; i < length; i++) {
334 impl_->atomIndex(i) = static_cast<std::int64_t>(i); // default: sequential
335 fileToMatter[static_cast<size_t>(i)] = i;
336 }
337 }
338 recomputePotential = true;
340 recomputeFreeMask = true;
341}
342
343long int Matter::numberOfAtoms() const { return (nAtoms); }
344
345Matrix3d Matter::getCell() const { return impl_->cell; }
346
347void Matter::setCell(const Matrix3d &newCell) {
348 impl_->cell = newCell;
349 impl_->cellInverse = impl_->cell.inverse();
350 recomputePotential = true;
352}
353
354double Matter::getPosition(long int indexAtom, int axis) const {
355 checkAtom(nAtoms, indexAtom, "Matter::getPosition");
356 checkAxis(axis, "Matter::getPosition");
357 return impl_->positions(indexAtom, axis);
358}
359
360void Matter::setPosition(long int indexAtom, int axis, double position) {
361 checkAtom(nAtoms, indexAtom, "Matter::setPosition");
362 checkAxis(axis, "Matter::setPosition");
363 impl_->positions(indexAtom, axis) = position;
366 }
367 recomputePotential = true;
369}
370
371void Matter::setVelocity(long int indexAtom, int axis, double vel) {
372 checkAtom(nAtoms, indexAtom, "Matter::setVelocity");
373 checkAxis(axis, "Matter::setVelocity");
374 impl_->velocities(indexAtom, axis) = vel;
375}
376
377// return coordinates of atoms by const reference (zero-copy)
378const AtomMatrix &Matter::getPositions() const { return impl_->positions; }
379// return a modifiable copy of positions
380AtomMatrix Matter::getPositionsCopy() const { return impl_->positions; }
381
382VectorXd Matter::getPositionsV() const {
383 return VectorXd::Map(impl_->positions.data(), 3 * numberOfAtoms());
384}
385
387 getFree(); // ensure freeIndices is up to date
388 AtomMatrix ret(static_cast<long>(freeIndices.size()), 3);
389 for (size_t j = 0; j < freeIndices.size(); j++) {
390 ret.row(static_cast<long>(j)) = impl_->positions.row(freeIndices[j]);
391 }
392 return ret;
393}
394
395VectorXi Matter::getAtomicNrsFree() const {
396 getFree();
397 VectorXi ret(static_cast<Eigen::Index>(freeIndices.size()));
398 for (size_t j = 0; j < freeIndices.size(); j++) {
399 ret[static_cast<Eigen::Index>(j)] = impl_->atomicNrs[freeIndices[j]];
400 }
401 return ret;
402}
403
404bool Matter::relax(bool quiet, bool writeMovie, bool checkpoint,
405 std::string prefixMovie, std::string prefixCheckpoint,
406 bool retainMovieFrames) {
407 if (retainMovieFrames) {
408 movie_frames_.clear();
409 }
411 *this, *parameters, quiet, writeMovie, checkpoint, prefixMovie,
412 prefixCheckpoint, retainMovieFrames ? &movie_frames_ : nullptr);
413}
414
416 return VectorXd::Map(getPositionsFree().data(), 3 * numberOfFreeAtoms());
417}
418
419// update Matter with the new positions of the free atoms given in array 'pos'
421 if (pos.rows() != nAtoms) {
422 throw std::invalid_argument("Matter::setPositions: row count mismatch");
423 }
424 impl_->positions = pos;
427 }
428 recomputePotential = true;
430}
431
432// Same but takes vector instead of n x 3 matrix
433void Matter::setPositionsV(const VectorXd &pos) {
434 setPositions(AtomMatrix::Map(pos.data(), numberOfAtoms(), 3));
435}
436
438 getFree(); // ensure freeIndices is up to date
439 for (size_t j = 0; j < freeIndices.size(); j++) {
440 impl_->positions.row(freeIndices[j]) = pos.row(static_cast<long>(j));
441 }
442 // Optimizers write free-atom coords only (TIP4P/SPCE and any PBC pot).
443 // Match setPositions: wrap the full configuration when PBC is on (#171).
446 }
447 recomputePotential = true;
449}
450
451void Matter::setPositionsFreeV(const VectorXd &pos) {
452 setPositionsFree(AtomMatrix::Map(pos.data(), numberOfFreeAtoms(), 3));
453}
454
456 if (biasPotential != nullptr) {
457 // Evaluate the current bias only. The MD job advances the bond-boost
458 // schedule once per step via BondBoost::advance().
459 biasPotential->boost();
460 }
461 return impl_->biasForces.array() * getFree().array();
462}
463
465 biasPotential = bondBoost;
466}
467
469
471 BondBoost *keep = biasPotential;
472 *this = other;
473 biasPotential = keep;
474}
475
477 impl_->biasForces = bf.array() * getFree().array();
478}
479// Return forces with fixed atoms zeroed (cached).
480// Note: not thread-safe. Concurrent reads on the same Matter instance
481// may race on the mutable maskedForces/recomputeMaskedForces members.
485 // Use the cached freeMask (Nx3, 1.0 for free / 0.0 for fixed) to zero
486 // fixed-atom forces in a single vectorized Eigen operation.
487 impl_->maskedForces = impl_->forces.array() * getFree().array();
488 recomputeMaskedForces = false;
489 }
490 return impl_->maskedForces;
491}
492
495 return impl_->forces;
496}
497
498VectorXd Matter::getForcesV() const {
499 return VectorXd::Map(getForces().data(), 3 * numberOfAtoms());
500}
501
503 AtomMatrix allForces = getForces();
504 getFree(); // ensure freeIndices is up to date (mutable cache)
505 AtomMatrix ret(static_cast<long>(freeIndices.size()), 3);
506 for (size_t j = 0; j < freeIndices.size(); j++) {
507 ret.row(static_cast<long>(j)) = allForces.row(freeIndices[j]);
508 }
509 return ret;
510}
511
512VectorXd Matter::getForcesFreeV() const {
513 AtomMatrix freeForces = getForcesFree();
514 return VectorXd::Map(freeForces.data(), 3 * numberOfFreeAtoms());
515}
516
517// return distance between the atoms with index1 and index2
518double Matter::distance(long index1, long index2) const {
519 checkAtom(nAtoms, index1, "Matter::distance");
520 checkAtom(nAtoms, index2, "Matter::distance");
521 return pbc(impl_->positions.row(index1) - impl_->positions.row(index2))
522 .norm();
523}
524
525// return projected distance between the atoms with index1 and index2 on asix
526// (0-x,1-y,2-z)
527double Matter::pdistance(long index1, long index2, int axis) const {
528 checkAtom(nAtoms, index1, "Matter::pdistance");
529 checkAtom(nAtoms, index2, "Matter::pdistance");
530 checkAxis(axis, "Matter::pdistance");
531 Matrix<double, 1, 3> ret;
532 ret.setZero();
533 ret(0, axis) =
534 impl_->positions(index1, axis) - impl_->positions(index2, axis);
535 ret = pbc(ret);
536 return ret(0, axis);
537}
538
539// return the distance atom with index has moved between the current Matter
540// object and the Matter object passed as argument
541double Matter::distance(const Matter &matter, long index) const {
542 checkAtom(nAtoms, index, "Matter::distance");
543 checkAtom(matter.nAtoms, index, "Matter::distance");
544 return pbc(impl_->positions.row(index) - matter.getPositions().row(index))
545 .norm();
546}
547
548double Matter::getMass(long int indexAtom) const {
549 checkAtom(nAtoms, indexAtom, "Matter::getMass");
550 return (impl_->masses[indexAtom]);
551}
552
553void Matter::setMass(long int indexAtom, double mass) {
554 checkAtom(nAtoms, indexAtom, "Matter::setMass");
555 impl_->masses[indexAtom] = mass;
556}
557
558void Matter::setMasses(const VectorXd &massesIn) {
559 if (massesIn.size() != nAtoms) {
560 throw std::invalid_argument("Matter::setMasses: size mismatch");
561 }
562 impl_->masses = massesIn;
563}
564
565long Matter::getAtomicNr(long int indexAtom) const {
566 return (impl_->atomicNrs[indexAtom]);
567}
568
569void Matter::setAtomicNr(long int indexAtom, long atomicNr) {
570 impl_->atomicNrs[indexAtom] = atomicNr;
571 recomputePotential = true;
573}
574
575int Matter::getFixed(long int indexAtom) const {
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)
580 ? 1
581 : 0;
582}
583
584int Matter::getFixed(long int indexAtom, int axis) const {
585 checkAtom(nAtoms, indexAtom, "Matter::getFixed");
586 checkAxis(axis, "Matter::getFixed");
587 return impl_->isFixed(indexAtom, axis) > 0.5 ? 1 : 0;
588}
589
590std::array<bool, 3> Matter::getFixedMask(long int indexAtom) const {
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};
595}
596
597void Matter::setFixed(long int indexAtom, int isFixed_passed) {
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;
603 recomputeFreeMask = true;
605}
606
607void Matter::setFixed(long int indexAtom, int axis, int isFixed_passed) {
608 checkAtom(nAtoms, indexAtom, "Matter::setFixed");
609 checkAxis(axis, "Matter::setFixed");
610 impl_->isFixed(indexAtom, axis) = isFixed_passed ? 1.0 : 0.0;
611 recomputeFreeMask = true;
613}
614
615void Matter::setFixedMask(long int indexAtom, std::array<bool, 3> mask) {
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;
620 recomputeFreeMask = true;
622}
623
625 if (nAtoms > 0) {
627 return potentialEnergy;
628 } else
629 return 0.0;
630}
631
633 // 0.5 * sum(mass_i * |v_i,free|^2); a constrained axis does not contribute.
634 AtomMatrix vfree = impl_->velocities.array() * getFree().array();
635 Eigen::VectorXd speed2 = vfree.rowwise().squaredNorm();
636 return 0.5 * (impl_->masses.array() * speed2.array()).sum();
637}
638
642
644 long n = 0;
645 for (long i = 0; i < nAtoms; ++i) {
646 if (getFixed(i)) {
647 ++n;
648 }
649 }
650 return n;
651}
652
654 return nAtoms - numberOfFixedAtoms();
655}
656
657long Matter::getForceCalls() const { return (forceCalls); }
658
660 forceCalls = 0;
661 return;
662}
663
665 if (!livePotential() || !livePotential()->requiresIsolatedMoleculeLayout()) {
666 return;
667 }
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).");
673 }
674}
675
676bool Matter::epochDirty() const {
677 const unsigned long long pe =
680}
681
686
687void Matter::setSurfaceEpoch(unsigned long long epoch) {
688 if (epoch != surfaceEpoch_) {
689 surfaceEpoch_ = epoch;
690 recomputePotential = true;
692 }
693}
694
696 cancel_token_.poll("force");
698 if (!livePotential()) {
699 throw std::runtime_error(
700 "Matter::computePotential called without a potential");
701 }
703 if (livePotential()->isSurrogate()) {
704 // Surrogate potential case: uses free-atom subset interface
705 auto surrogatePotential =
706 static_cast<SurrogatePotential *>(livePotential());
707 auto [freePE, freeForces, vari] = surrogatePotential->get_ef_var(
708 this->getPositionsFree(), this->getAtomicNrsFree(), impl_->cell);
709 this->potentialEnergy = freePE;
710 this->energyVariance = vari;
711 impl_->haveStress = false;
712 for (long idx{0}, jdx{0}; idx < nAtoms; idx++) {
713 if (!getFixed(idx)) {
714 impl_->forces.row(idx) = freeForces.row(jdx);
715 jdx++;
716 }
717 }
718 } else {
719 // Hot path: call force() directly into member storage.
720 // No intermediate allocation, no tuple, no copy.
721 double var{0};
722 livePotential()->setFixedMask(nAtoms, impl_->isFixed.data());
723 const auto n = static_cast<size_t>(nAtoms);
724 // Isolated molecules still store a box for I/O. Pots that infer PBC
725 // from a non-zero cell (GFN2) must see a zero box here.
726 const Matrix3d force_cell =
728 ? impl_->cell
729 : Matrix3d::Zero();
731 std::span<const double>(impl_->positions.data(), n * 3),
732 std::span<const int>(impl_->atomicNrs.data(), n),
733 std::span<double>(impl_->forces.data(), n * 3), &potentialEnergy,
734 &var, std::span<const double>(force_cell.data(), 9));
735 this->energyVariance = var;
738 }
739 if (!std::isfinite(potentialEnergy) || !impl_->forces.allFinite()) {
740 throw std::runtime_error(
741 "Potential returned non-finite energy or forces");
742 }
744 recomputePotential = false;
746
747 // One free atom: subtracting the mean force is identically zero,
748 // and NEB would then report immediate GOOD.
749 if (impl_->isFixed.maxCoeff() < 0.5 && removeNetForce && nAtoms > 1) {
750 const Vector3d tempForce = exactMeanForce(impl_->forces);
751 for (long int i = 0; i < nAtoms; i++) {
752 impl_->forces.row(i) -= tempForce.transpose();
753 }
754 }
755 }
756}
757
758// Transform coordinates into the cell using the selected PBC convention (#176).
759// Legacy selects fractional [0,1); MinimumImage selects fractional [-0.5,0.5).
760// Closest-image displacement vectors use the independent Euclidean operation.
763 // Unset / singular cell (default after Matter construct is Zero) — do not
764 // wipe coordinates; callers set the cell before wrapping makes sense.
765 if (std::abs(impl_->cell.determinant()) < 1e-30) {
766 return;
767 }
768 impl_->positions = eonc::pbc::applyPositions(
769 impl_->positions, impl_->cell, impl_->cellInverse, pbcConvention);
770}
771
772double Matter::maxFreeAtomForce(const AtomMatrix &rows) const {
773 if (rows.rows() != nAtoms) {
774 throw std::invalid_argument(
775 "Matter::maxFreeAtomForce: row count does not match atom count");
776 }
777 return maxFreeAtomForceNorm(rows.data(), impl_->isFixed.data(), nAtoms);
778}
779
780double Matter::maxForce() const {
781 // Ensures that the forces are up to date
783 return maxFreeAtomForce(getForces());
784}
785
786VectorXi Matter::getAtomicNrs() const { return this->impl_->atomicNrs; }
787
788void Matter::setAtomicNrs(const VectorXi &atmnrs) {
789 if (atmnrs.size() != this->nAtoms) {
790 throw std::invalid_argument(
791 "Vector of atomic numbers not equal to the number of atoms");
792 } else {
793 this->impl_->atomicNrs = atmnrs;
794 recomputePotential = true;
796 }
797}
798
800 if (recomputeFreeMask) {
801 impl_->freeMask.resize(nAtoms, 3);
802 impl_->freeMask = 1.0 - impl_->isFixed.array();
803 freeIndices.clear();
804 freeIndices.reserve(static_cast<size_t>(nAtoms));
805 for (long i = 0; i < nAtoms; i++) {
806 if (impl_->freeMask.row(i).sum() > 0.5) {
807 freeIndices.push_back(static_cast<int>(i));
808 }
809 }
810 recomputeFreeMask = false;
811 }
812 return impl_->freeMask;
813}
814
815VectorXd Matter::getFreeV() const {
816 return VectorXd::Map(getFree().data(), 3 * numberOfAtoms());
817}
818
820 return impl_->velocities.array() * getFree().array();
821}
822
824 impl_->velocities = v.array() * getFree().array();
825}
826
828 impl_->forces = f.array() * getFree().array();
829 impl_->maskedForces = impl_->forces;
830 impl_->haveStress = false;
831 recomputeMaskedForces = false;
832 recomputePotential = false;
833}
834
837 AtomMatrix ret = totF.array() * getFree().array();
838 // Single reciprocal mass computation, replicated across 3 columns
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;
843 return ret;
844}
845
846Matrix<double, Eigen::Dynamic, 1> Matter::getMasses() const {
847 return impl_->masses;
848}
849
850void Matter::setPotential(std::shared_ptr<Potential> pot) {
851 ownedPotential.reset();
852 this->potential = std::move(pot);
853 // Molecular QM backends (NWChem/ORCA) must not use PBC wraps (#188). Auto-off
854 // with a hard fail if code later forces PBC while this pot is attached.
855 if (livePotential() && livePotential()->requiresIsolatedMoleculeLayout() &&
857 usePeriodicBoundaries = false;
858 // Use EONC_LOG_* (not bare QUILL_LOG_* with eonc::log::get() as arg): the
859 // quill macros expand logger->… and choke on a call expression as the first
860 // macro argument on some GCC versions (CI: expected primary-expression).
862 "Disabled PBC for isolated-molecule potential (NWChem/ORCA-class); "
863 "re-enabling PBC will throw (issue #188)");
864 }
865 recomputePotential = true;
867}
868
869void Matter::setComputedPotential(double energy, double variance) {
870 potentialEnergy = energy;
871 energyVariance = variance;
872 // A batch leaves at most the last system's stress on the potential.
873 impl_->haveStress = false;
874 recomputePotential = false;
877 forceCalls++;
878
879 // Apply the same net force removal as computePotential()
880 if (impl_->isFixed.maxCoeff() < 0.5 && removeNetForce && nAtoms > 1) {
881 const Vector3d tempForce = exactMeanForce(impl_->forces);
882 for (long int i = 0; i < nAtoms; i++) {
883 impl_->forces.row(i) -= tempForce.transpose();
884 }
885 }
886}
887
889 return this->livePotential()->forceCallCounter;
890}
891
893 if (nAtoms > 0) {
895 }
896 return this->energyVariance;
897}
898
900 impl_->haveStress = false;
901 if (!livePotential()->computesStress()) {
902 return;
903 }
904 // A potential instance holds the stress of its own last call. With
905 // [Main] parallel on, a thread-safe shared instance can serve another
906 // image between that call and this read, so it is not read here.
907 const bool threads = parameters && parameters->main_options().parallel;
908 if (threads && livePotential()->isSharedInstanceThreadSafe() &&
909 !livePotential()->needsPerImageInstance()) {
910 return;
911 }
912 try {
913 impl_->stress = livePotential()->cauchyStress();
914 impl_->haveStress = impl_->stress.allFinite();
915 } catch (const std::logic_error &) {
916 impl_->haveStress = false;
917 }
918}
919
921 if (!livePotential() || !livePotential()->computesStress()) {
922 throw std::logic_error(
923 "Matter::cauchyStress requires a potential that reports stress");
924 }
925 // The stress that came with the cached evaluation describes this image.
926 if (!recomputePotential && impl_->haveStress) {
927 return impl_->stress;
928 }
929 recomputePotential = true;
932 if (!sigma.allFinite()) {
933 throw std::runtime_error("Potential returned a non-finite stress tensor");
934 }
935 return sigma;
936}
937
938std::shared_ptr<Potential> Matter::getPotential() {
940 return potential;
941}
942
945 return diff;
946 }
947 return eonc::pbc::apply(diff, impl_->cell, impl_->cellInverse);
948}
949
950VectorXd Matter::pbcV(const VectorXd &diff) const {
952 return diff;
953 }
954 return eonc::pbc::applyV(diff, impl_->cell, impl_->cellInverse);
955}
956
957double *Matter::forcesData() { return impl_->forces.data(); }
958
959std::int64_t Matter::getAtomIndex(long int atom) const {
960 return impl_->atomIndex(atom);
961}
962
963void Matter::setAtomIndex(long int atom, std::int64_t index) {
964 impl_->atomIndex(atom) = index;
965}
966
967void Matter::restoreFileForces(const AtomMatrix &fileForces, bool trustEnergy,
968 double energy) {
969 impl_->forces = fileForces;
970 impl_->haveStress = false;
972 if (trustEnergy) {
973 potentialEnergy = energy;
974 energyVariance = 0.0;
975 recomputePotential = false;
976 } else {
977 recomputePotential = true;
978 }
979}
980
981bool canComputeConcurrently(std::span<Matter *const> systems) {
982 std::vector<const Potential *> seen;
983 seen.reserve(systems.size());
984 for (Matter *m : systems) {
985 const Potential *p = m->getPotential().get();
986 if (p == nullptr) {
987 return false;
988 }
989 if (std::find(seen.begin(), seen.end(), p) == seen.end()) {
990 seen.push_back(p);
991 } else if (!eonc::potAllowsSharedInstance(*p)) {
992 return false;
993 }
994 }
995 return true;
996}
997
998void evaluateTogether(Potential &pot, std::span<Matter *const> systems,
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) {
1003 Matter *m = systems[i];
1004 if (m != nullptr && m->needsForceUpdate()) {
1005 dirty.push_back(m);
1006 dirtyOwners.push_back(i < owners.size() ? owners[i] : -1);
1007 }
1008 }
1009 if (dirty.empty()) {
1010 return;
1011 }
1012 if (dirty.size() == 1 || !pot.supportsBatchEvaluation()) {
1013 if (threads && dirty.size() > 1 && canComputeConcurrently(dirty)) {
1014 eonc::forEachImage(static_cast<long>(dirty.size()), [&dirty](long i) {
1015 dirty[static_cast<size_t>(i - 1)]->getForcesRaw();
1016 });
1017 return;
1018 }
1019 for (Matter *m : dirty) {
1020 m->getForcesRaw();
1021 }
1022 return;
1023 }
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) {
1032 Matter *m = dirty[j];
1033 if (m->numberOfAtoms() != atoms) {
1034 throw std::invalid_argument(
1035 "evaluateTogether: systems differ in atom count");
1036 }
1037 nrs[j] = m->getAtomicNrs();
1038 // A non-periodic system hands the potential a zero box, as
1039 // computePotential does. A host that owns the cell still sees it.
1040 boxes[j] = (m->getPeriodic() || pot.forwardsStoredCell())
1041 ? m->getCell()
1042 : Matrix3d::Zero().eval();
1043 }
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());
1049 }
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());
1054 } else {
1055 pot.forceBatchOwned(n, atoms, posPtr.data(), nrsPtr.data(), frcPtr.data(),
1056 energies.data(), variances.data(), boxPtr.data(),
1057 dirtyOwners.data());
1058 }
1059 for (long j = 0; j < n; ++j) {
1060 dirty[j]->setComputedPotential(energies[j], variances[j]);
1061 }
1062}
1063
1064} // namespace eonc
Eigen::Matrix< double, 3, 3, eOnStorageOrder > Matrix3d
Definition Eigen.h:35
Eigen::Matrix< double, Eigen::Dynamic, 3, eOnStorageOrder > AtomMatrix
Definition Eigen.h:37
#define EONC_LOG_WARNING(...)
Definition EonLogger.h:322
Functionality relying on the conjugate gradients algorithm.
Definition BondBoost.h:25
double potentialEnergy
Definition Matter.h:414
void applyPeriodicBoundary()
Definition Matter.cpp:761
void setBiasPotential(BondBoost *bondBoost)
Definition Matter.cpp:464
double getKineticEnergy() const
Definition Matter.cpp:632
void resetForceCalls()
Definition Matter.cpp:659
bool getWriteConForces() const noexcept
Parameters.main_options().writeConForces for this Matter.
Definition Matter.cpp:117
VectorXi getAtomicNrs() const
Definition Matter.cpp:786
bool recomputeFreeMask
Definition Matter.h:410
void setComputedPotential(double energy, double variance)
Set energy/variance from external batched evaluation and mark forces as up-to-date (recomputePotentia...
Definition Matter.cpp:869
void setForces(const AtomMatrix &f)
Definition Matter.cpp:827
void setFixed(long int atom, int isFixed)
Broadcast a whole-atom flag onto all three axes.
Definition Matter.cpp:597
std::shared_ptr< Potential > getPotential()
Definition Matter.cpp:938
BondBoost * getBiasPotential() const
The bias potential added to this Matter's forces, or nullptr.
Definition Matter.cpp:468
double maxFreeAtomForce(const AtomMatrix &rows) const
Max per-atom Euclidean norm of rows.
Definition Matter.cpp:772
void setFixedMask(long int atom, std::array< bool, 3 > mask)
Definition Matter.cpp:615
void setPosition(long int atom, int axis, double position)
Definition Matter.cpp:360
PbcConvention pbcConvention
Definition Matter.h:374
const AtomMatrix & getPositions() const
Definition Matter.cpp:378
bool relax(bool quiet=false, bool writeMovie=false, bool checkpoint=false, std::string prefixMovie=std::string(), std::string prefixCheckpoint=std::string(), bool retainMovieFrames=false)
Definition Matter.cpp:404
double distanceTo(const Matter &matter)
Definition Matter.cpp:276
VectorXd getForcesFreeV() const
Definition Matter.cpp:512
void setPositions(const AtomMatrix &pos)
Definition Matter.cpp:420
void setAtomicNr(long int atom, long atomicNr)
Definition Matter.cpp:569
double pdistance(long index1, long index2, int axis) const
Definition Matter.cpp:527
AtomMatrix getForcesFree() const
Definition Matter.cpp:502
const Matter & operator=(const Matter &matter)
Definition Matter.cpp:139
std::vector< readcon::ConFrame > movie_frames_
Definition Matter.h:413
bool compare(const Matter &matter, bool indistinguishable=false)
Definition Matter.cpp:254
void setPositionsV(const VectorXd &pos)
Definition Matter.cpp:433
void setCell(const Matrix3d &newCell)
Definition Matter.cpp:347
std::vector< int > freeIndices
Definition Matter.h:409
AtomMatrix getFree() const
Definition Matter.cpp:799
bool getPeriodic() const noexcept
Definition Matter.h:338
void setVelocity(long int atom, int axis, double velocity)
Definition Matter.cpp:371
void computePotential() const
Definition Matter.cpp:695
void setPotential(std::shared_ptr< Potential > pot)
Definition Matter.cpp:850
void setPositionsFreeV(const VectorXd &pos)
Definition Matter.cpp:451
bool recomputeMaskedForces
Definition Matter.h:411
Matrix3d getCell() const
Definition Matter.cpp:345
std::unique_ptr< Potential > ownedPotential
Definition Matter.h:367
const Parameters * parameters
Definition Matter.h:398
bool removeNetForce
Definition Matter.h:392
long nAtoms
Definition Matter.h:399
long int numberOfAtoms() const
Definition Matter.cpp:343
Matrix3d cauchyStress()
Cauchy stress in eV/Angstrom^3.
Definition Matter.cpp:920
AtomMatrix pbc(const AtomMatrix &diff) const
Definition Matter.cpp:943
std::shared_ptr< Potential > potential
Definition Matter.h:369
long getForceCalls() const
Definition Matter.cpp:657
VectorXd getPositionsFreeV() const
Definition Matter.cpp:415
BondBoost * biasPotential
Definition Matter.h:404
void setAtomicNrs(const VectorXi &atmnrs)
Definition Matter.cpp:788
AtomMatrix getVelocities() const
Definition Matter.cpp:819
void setVelocities(const AtomMatrix &v)
Definition Matter.cpp:823
double getMechanicalEnergy() const
Definition Matter.cpp:639
void setAtomIndex(long int atom, std::int64_t index)
Definition Matter.cpp:963
double perAtomNorm(const Matter &matter)
Definition Matter.cpp:284
const AtomMatrix & getForcesRaw() const
Definition Matter.cpp:493
long forceCalls
Definition Matter.h:378
void resize(long int nAtoms)
Definition Matter.cpp:297
VectorXd pbcV(const VectorXd &diff) const
Definition Matter.cpp:950
AtomMatrix getPositionsFree() const
Definition Matter.cpp:386
double getPosition(long int atom, int axis) const
Definition Matter.cpp:354
size_t getPotentialCalls() const
Definition Matter.cpp:888
unsigned long long cachedHostEpoch_
Definition Matter.h:416
std::shared_ptr< bool > writeConForces_
Definition Matter.h:396
VectorXi getAtomicNrsFree() const
Definition Matter.cpp:395
void restoreFileForces(const AtomMatrix &fileForces, bool trustEnergy, double energy)
Write .con forces without the fixed-atom mask setForces applies.
Definition Matter.cpp:967
Eigen::Matrix< double, Eigen::Dynamic, 1 > getMasses() const
Definition Matter.cpp:846
long int numberOfFixedAtoms() const
Definition Matter.cpp:643
std::unique_ptr< Impl > impl_
Definition Matter.h:403
unsigned long long cachedPotEpoch_
Definition Matter.h:417
double distance(long index1, long index2) const
Definition Matter.cpp:518
double getMass(long int atom) const
Definition Matter.cpp:548
bool recomputePotential
Definition Matter.h:375
unsigned long long surfaceEpoch_
Definition Matter.h:415
void setMasses(const VectorXd &massesIn)
Definition Matter.cpp:558
void setMass(long int atom, double mass)
Definition Matter.cpp:553
double getPotentialEnergy() const
Definition Matter.cpp:624
AtomMatrix getAccelerations()
Definition Matter.cpp:835
void stampSurfaceEpoch() const
Definition Matter.cpp:682
double * forcesData()
Mutable access to force storage for batched potential evaluation.
Definition Matter.cpp:957
bool needsForceUpdate() const
Whether forces need recomputation (positions or surface epoch changed).
Definition Matter.h:220
AtomMatrix getBiasForces()
Definition Matter.cpp:455
std::array< std::string, 5 > headerCon
Definition Matter.h:381
bool holdsExclusivePotential() const
True while no copy has shared the Potential from an exclusive handoff.
Definition Matter.cpp:113
StructureComparisonOptions structComp
Definition Matter.h:393
bool usePeriodicBoundaries
Definition Matter.h:370
long int numberOfFreeAtoms() const
Definition Matter.cpp:653
VectorXd getFreeV() const
Definition Matter.cpp:815
Matter(std::shared_ptr< Potential > pot, const Parameters &params)
Definition Matter.cpp:76
CancelToken cancel_token_
Definition Matter.h:418
long getAtomicNr(long int atom) const
Definition Matter.cpp:565
double getEnergyVariance() const
Definition Matter.cpp:892
AtomMatrix getPositionsCopy() const
Definition Matter.cpp:380
void shareOwnedPotential() const
Definition Matter.cpp:107
std::array< bool, 3 > getFixedMask(long int atom) const
Per-axis CON column-4 mask (bit0=x, bit1=y, bit2=z).
Definition Matter.cpp:590
void setBiasForces(const AtomMatrix &bf)
Definition Matter.cpp:476
void setPositionsFree(const AtomMatrix &pos)
Definition Matter.cpp:437
std::vector< long > fileToMatter
Definition Matter.h:405
std::int64_t getAtomIndex(long int atom) const
.con column-5 index (pre-grouping); public for I/O / bindings.
Definition Matter.cpp:959
void assertIsolatedMoleculeLayoutSafe() const
Throw if pot forbids PBC (isolated molecular QM backends, issue #188).
Definition Matter.cpp:664
VectorXd getPositionsV() const
Definition Matter.cpp:382
void assignKeepingBias(const Matter &other)
Copy another structure in and keep this Matter's own bias potential.
Definition Matter.cpp:470
const AtomMatrix & getForces() const
Definition Matter.cpp:482
double energyVariance
Definition Matter.h:412
bool epochDirty() const
Definition Matter.cpp:676
int getFixed(long int atom) const
1 if every Cartesian axis of the atom is fixed, else 0.
Definition Matter.cpp:575
Potential * livePotential() const
Definition Matter.cpp:103
void setSurfaceEpoch(unsigned long long epoch)
Host surface generation.
Definition Matter.cpp:687
VectorXd getForcesV() const
Definition Matter.cpp:498
void captureStress() const
Definition Matter.cpp:899
double maxForce(void) const
Definition Matter.cpp:780
std::atomic< size_t > forceCallCounter
Definition Potential.h:57
virtual unsigned long long surfaceEpoch() const noexcept
Host-visible surface generation.
Definition Potential.h:124
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.
Definition Potential.h:202
virtual Matrix3d cauchyStress() const
Cauchy stress in eV/Angstrom^3.
Definition Potential.h:212
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).
Definition Potential.h:110
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 &params, 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)
Definition Matter.h:46
AtomMatrix applyPositions(const AtomMatrix &coords, const Matrix3d &cell, const Matrix3d &cellInverse, PbcConvention convention)
Definition Matter.h:66
VectorXd applyV(const VectorXd &diffVector, const Matrix3d &cell, const Matrix3d &cellInverse)
Definition Matter.h:77
RAII resource manager for the ARTn C library with global synchronization.
bool potAllowsSharedInstance(const P &p) noexcept
PbcConvention
Definition Matter.h:38
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.
Definition Matter.cpp:998
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...
Definition Matter.cpp:981
AtomMatrix positions
Definition Matter.cpp:55
AtomMatrix isFixed
Definition Matter.cpp:62
Matrix3d cellInverse
Definition Matter.cpp:68
AtomMatrix velocities
Definition Matter.cpp:56
AtomMatrix forces
Definition Matter.cpp:57
Matrix3d stress
Definition Matter.cpp:70
AtomMatrix maskedForces
Definition Matter.cpp:66
VectorXd masses
Definition Matter.cpp:59
Eigen::Matrix< std::int64_t, Eigen::Dynamic, 1 > atomIndex
Definition Matter.cpp:64
AtomMatrix freeMask
Definition Matter.cpp:65
VectorXi atomicNrs
Definition Matter.cpp:60
AtomMatrix biasForces
Definition Matter.cpp:58