Loading...
Searching...
No Matches
eonc::helpers Namespace Reference

Namespaces

namespace  create
namespace  eigen
namespace  neb_paths
namespace  surrogate

Functions

std::string get_value_from_env_or_param (const char *env_variable, const std::string &param_value, const std::string &default_value, const std::string &warning_message, const bool is_mandatory)
std::unique_ptr< Job > makeJob (std::unique_ptr< Parameters > params, Runtime &runtime)
 Borrow: caller keeps Runtime alive.
std::unique_ptr< Job > makeJob (std::unique_ptr< Parameters > params, std::unique_ptr< Runtime > runtime)
 Own the unique_ptr Runtime.
std::unique_ptr< Job > makeJob (std::unique_ptr< Parameters > params, Runtime &&runtime)
 Own the rvalue Runtime.
std::unique_ptr< Job > makeJob (std::unique_ptr< Parameters > params)
 One-shot: Job owns a default Runtime.
std::unique_ptr< Potential > makePotential (const Parameters &params)
 Exclusive ownership.
std::shared_ptr< Potential > makeImagePotential (const Potential &pot, const Parameters &params)
 A separate instance of pot for one image of a band, dimer or pair of minimizations: a clone when the backend can clone, else a new instance built from params.
std::unique_ptr< Potential > makePotential (PotType ptype, const Parameters &params, Runtime &runtime)
std::unique_ptr< Potential > makePotential (PotType ptype, const Parameters &params)
template<typename T>
std::vector< T > get_val_from_string (std::string_view line, std::optional< size_t > nelements=std::nullopt)
 Parse a string into values.
template std::vector< size_t > get_val_from_string (std::string_view, std::optional< size_t >)
std::vector< std::string > get_split_strings (std::string_view line)
 Split a string into constituent strings.
bool isNumber (std::string_view token)
 Figure out if a string has a number in it.
template<typename Writer>
bool atomicWriteFile (const std::string &path, Writer writer)
gpr::InputParameters eon_parameters_to_gpr (const Parameters &parameters)
 Create a parameters object for gpr_dimer.
gpr::AtomsConfiguration eon_matter_to_atmconf (Matter *matter)
 Create a configuration of atoms for gpr_dimer.
gpr::Observation eon_matter_to_init_obs (Matter *matter)
 Create an initial Observation object for gpr_dimer.
AtomMatrix makeOrthogonal (const AtomMatrix v1, const AtomMatrix v2)
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)
void getTime (double *real, double *user, double *sys)
bool existsFile (std::string filename)
std::optional< std::string > enterJobDirectory (std::string_view jobPath)
 Enter jobPath as the working directory.
bool stageReturnLog (std::string_view logHome, std::string_view name)
 Copy name from logHome into the current directory when that file is not already this directory's copy.
std::string getRelevantFile (std::string filename)
VectorXd loadMasses (std::string filename, int nAtoms)
AtomMatrix loadMode (FILE *modeFile, int nAtoms)
AtomMatrix loadMode (std::string filename, int nAtoms)
bool loadOrSynthesizeDisplacement (Matter &target, const Matter &initial, const std::string &displacementPath, const std::string &modePath, double scale)
bool applyClientDisplacement (Matter &target, const Matter &initial, const Parameters &params, AtomMatrix *modeOut)
void saveMode (FILE *modeFile, std::shared_ptr< Matter > matter, AtomMatrix mode)
 Write a mode; constrained axes are emitted as 0.
void saveMode (const std::string &filename, std::shared_ptr< Matter > matter, AtomMatrix mode)
std::vector< int > split_string_int (std::string s, std::string delim)
std::optional< std::string_view > convergenceMetricLabel (std::string_view metric)
 Display label for a force-convergence metric, or nullopt when the name is none of the four the optimizer-driven searches understand (norm, rms, max_atom, max_component).
void requireKnownConvergenceMetric (std::string_view metric, std::string_view context)
 Throws std::invalid_argument naming context when metric is unrecognized.
template<typename T>
bool eigenEquality (const Eigen::MatrixBase< T > &lhs, const Eigen::MatrixBase< T > &rhs, const double threshold=1e-4)
 Check two eigen objects for equality.
std::shared_ptr< Potential > sharePotential (std::unique_ptr< Potential > pot)
 Multi-owner boundary: one instance observed by several Matters, images, or a binding.

Variables

constexpr double pi = 3.14159265358979323846

Function Documentation

◆ applyClientDisplacement()

bool eonc::helpers::applyClientDisplacement ( Matter & target,
const Matter & initial,
const Parameters & params,
AtomMatrix * modeOut )

Definition at line 247 of file HelperFunctions.cpp.

250 {
251 using namespace eonc::EpiCenters;
252 const auto &opt = params.saddle_search_options();
253 const std::string &dtype = opt.displace_type;
254 if (dtype == DISP_LOAD) {
255 return false;
256 }
257
258 long epicenter = -1;
259 const double cutoff = params.structure_comparison_options().neighbor_cutoff;
260 if (dtype == DISP_LISTED_ATOMS) {
261 epicenter = listedAtomEpiCenter(&initial, opt.displace_atom_list);
262 } else if (dtype == DISP_RANDOM) {
263 epicenter = randomFreeAtomEpiCenter(&initial);
264 } else if (dtype == DISP_LAST_ATOM) {
265 epicenter = lastAtom(&initial);
266 } else if (dtype == DISP_MIN_COORDINATED) {
267 epicenter = minCoordinatedEpiCenter(&initial, cutoff);
268 } else if (dtype == DISP_NOT_FCC_OR_HCP) {
269 epicenter = cnaEpiCenter(&initial, cutoff);
270 } else {
271 return false;
272 }
273
274 target = initial;
275 const long n = initial.numberOfAtoms();
276 const double radius = opt.displace_radius;
277 const double mag = opt.displace_magnitude;
278 AtomMatrix pos = initial.getPositionsCopy();
279 AtomMatrix mode = AtomMatrix::Zero(n, 3);
280 for (long i = 0; i < n; ++i) {
281 if (initial.getFixed(i)) {
282 continue;
283 }
284 const double dist = (i == epicenter) ? 0.0 : initial.distance(epicenter, i);
285 if (dist <= radius) {
286 for (int a = 0; a < 3; ++a) {
287 mode(i, a) = eonc::rng::gaussRandom(0.0, mag);
288 }
289 }
290 }
291 const double norm = mode.norm();
292 if (norm > 0.0) {
293 pos += mode;
294 mode /= norm;
295 } else if (epicenter >= 0 && epicenter < n && !initial.getFixed(epicenter)) {
296 mode(epicenter, 0) = 1.0;
297 pos(epicenter, 0) += mag;
298 }
299 target.setPositions(pos);
300 if (modeOut != nullptr) {
301 *modeOut = std::move(mode);
302 }
303 return true;
304}
Eigen::Matrix< double, Eigen::Dynamic, 3, eOnStorageOrder > AtomMatrix
Definition Eigen.h:37
void setPositions(const AtomMatrix &pos)
Definition Matter.cpp:420
long int numberOfAtoms() const
Definition Matter.cpp:343
AtomMatrix getPositionsCopy() const
Definition Matter.cpp:380
int getFixed(long int atom) const
1 if every Cartesian axis of the atom is fixed, else 0.
Definition Matter.cpp:575
const saddle_search_options_t & saddle_search_options() const
const structure_comparison_options_t & structure_comparison_options() const
const char DISP_RANDOM[]
Definition EpiCenters.h:24
long lastAtom(const Matter *matter)
const char DISP_LISTED_ATOMS[]
Definition EpiCenters.h:25
long cnaEpiCenter(const Matter *matter, double neighborCutoff)
const char DISP_LOAD[]
Definition EpiCenters.h:20
long randomFreeAtomEpiCenter(const Matter *matter)
long listedAtomEpiCenter(const Matter *matter, const std::vector< long > &atomList)
long minCoordinatedEpiCenter(const Matter *matter, double neighborCutoff)
double norm(const Eigen::MatrixBase< A > &x)
sqrt of the correctly rounded squared norm; IEEE sqrt is itself correctly rounded,...
double gaussRandom(double avg, double std)

◆ atomicWriteFile()

template<typename Writer>
bool eonc::helpers::atomicWriteFile ( const std::string & path,
Writer writer )

Definition at line 26 of file AtomicFile.h.

26 {
27 std::string pattern = path + ".tmp.XXXXXX";
28 std::vector<char> name(pattern.begin(), pattern.end());
29 name.push_back('\0');
30#ifdef _WIN32
31 if (_mktemp_s(name.data(), name.size()) != 0) {
32 return false;
33 }
34 int fd = _open(name.data(), _O_CREAT | _O_EXCL | _O_WRONLY | _O_BINARY,
35 _S_IREAD | _S_IWRITE);
36#else
37 int fd = mkstemp(name.data());
38#endif
39 if (fd < 0) {
40 return false;
41 }
42#ifdef _WIN32
43 FILE *file = _fdopen(fd, "wb");
44#else
45 FILE *file = fdopen(fd, "wb");
46#endif
47 if (!file) {
48#ifdef _WIN32
49 _close(fd);
50#else
51 close(fd);
52#endif
53 std::remove(name.data());
54 return false;
55 }
56 bool ok = false;
57 try {
58 ok = writer(file) && !std::ferror(file) && std::fflush(file) == 0;
59 } catch (...) {
60 std::fclose(file);
61 std::remove(name.data());
62 throw;
63 }
64#ifdef _WIN32
65 if (ok) {
66 ok = _commit(fd) == 0;
67 }
68#else
69 if (ok) {
70 ok = fsync(fd) == 0;
71 }
72#endif
73 if (std::fclose(file) != 0) {
74 ok = false;
75 }
76 if (ok) {
77#ifdef _WIN32
78 ok = MoveFileExA(name.data(), path.c_str(),
79 MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) != 0;
80#else
81 ok = std::rename(name.data(), path.c_str()) == 0;
82#endif
83 }
84 if (!ok) {
85 std::remove(name.data());
86 }
87 return ok;
88}

◆ convergenceMetricLabel()

std::optional< std::string_view > eonc::helpers::convergenceMetricLabel ( std::string_view metric)

Display label for a force-convergence metric, or nullopt when the name is none of the four the optimizer-driven searches understand (norm, rms, max_atom, max_component).

Single source of the accepted spellings.

Definition at line 356 of file HelperFunctions.cpp.

356 {
357 if (metric == "max_atom") {
358 return "Max atom force";
359 }
360 if (metric == "max_component") {
361 return "Max force comp";
362 }
363 if (metric == "norm") {
364 return "||Force||";
365 }
366 if (metric == "rms") {
367 return "RMS force";
368 }
369 return std::nullopt;
370}

◆ eigenEquality()

template<typename T>
bool eonc::helpers::eigenEquality ( const Eigen::MatrixBase< T > & lhs,
const Eigen::MatrixBase< T > & rhs,
const double threshold = 1e-4 )

Check two eigen objects for equality.

Parameters
lhsleft-hand matrix
rhsright-hand matrix
thresholdabsolute tolerance passed to Eigen isApprox

Definition at line 28 of file MatrixHelpers.hpp.

30 {
31 return lhs.isApprox(rhs, threshold);
32}

◆ enterJobDirectory()

std::optional< std::string > eonc::helpers::enterJobDirectory ( std::string_view jobPath)

Enter jobPath as the working directory.

Returns nullopt on success. On failure the working directory is unchanged and the string is the filesystem error, so the caller must not run the job or report the path as finished.

Definition at line 81 of file HelperFunctions.cpp.

81 {
82 try {
83 std::filesystem::current_path(std::filesystem::path{jobPath});
84 } catch (const std::filesystem::filesystem_error &err) {
85 return std::string{err.what()};
86 }
87 return std::nullopt;
88}

◆ eon_matter_to_atmconf()

gpr::AtomsConfiguration eonc::helpers::eon_matter_to_atmconf ( Matter * matter)

Create a configuration of atoms for gpr_dimer.

Parameters
mattereOn Matter object

Remember that the atom type in eOn is the real atomic number, while in GPR Dimer it is a set of values from 0 to n-1 so this is eOn

False "atomtype" for GPR Dimer

Is a fixed atom Use eOn's atomtype as a key for the GPR's fake atomtype

Is moving

Special case when there's only one atom type, we can now just use the set function of the Field. Essentially now we only have one atom type

End case where we have both nonzero moving and nonzero frozen atoms

Now we will consider the case when everything is moving Everything is almost exactly the same, only we don't have frozen atoms

Special case when there's only one atom type, we can now just use the set function of the Field. Essentially now we only have one atom type

Definition at line 112 of file GPRHelpers.cpp.

112 {
113 if (!matter) {
114 throw std::invalid_argument("eon_matter_to_atmconf: null Matter");
115 }
116 gpr::AtomsConfiguration atoms_config;
117 aux::ProblemSetUp problem_setup;
118 gpr::Index_t number_of_mov_atoms;
119 gpr::Index_t number_of_fro_atoms;
120 std::set<int> unique_atomtypes;
121 gpr::Index_t n_at;
122 std::vector<int> atomnrs;
123 std::unordered_map<int, int>
124 atype_to_gprd_atype;
127 int fake_atype;
128
129 atoms_config.clear();
130 // gpr_optim stores positions as row-major 1×(3N), matching AtomMatrix flat
131 // layout.
132 copyAtomMatrixToCoord(matter->getPositions(), atoms_config.positions);
133 const auto nAtoms = matter->numberOfAtoms();
134 atoms_config.is_frozen.resize(1, nAtoms);
135 atoms_config.id.resize(1, nAtoms);
136 atoms_config.atomicNrs.resize(1, nAtoms);
137 for (auto i = 0; i < nAtoms; i++) {
138 atomnrs.push_back(matter->getAtomicNr(i));
139 // Field matrices are 1×N; use (0, i). getFixed is bool → MOVING/FROZEN.
140 atoms_config.atomicNrs(0, i) = matter->getAtomicNr(i);
141 atoms_config.is_frozen(0, i) =
142 matter->getFixed(i) ? FROZEN_ATOM : MOVING_ATOM;
143 atoms_config.id(0, i) = static_cast<gpr::Index_t>(i + 1);
144 }
145
146 unique_atomtypes = std::set<int>(atomnrs.begin(), atomnrs.end());
147 n_at = unique_atomtypes.size();
148 fake_atype = 0;
149 for (auto uatom : unique_atomtypes) {
150 atype_to_gprd_atype.insert(
151 std::pair<int, int>(static_cast<int>(uatom), fake_atype));
152 fake_atype++;
153 }
154
155 number_of_mov_atoms = atoms_config.countMovingAtoms();
156 number_of_fro_atoms =
157 static_cast<gpr::Index_t>(atoms_config.is_frozen.size()) -
158 number_of_mov_atoms;
159
160 if (number_of_fro_atoms > 0 && number_of_mov_atoms > 0) {
161 // Resize structures for moving and frozen atoms
162 atoms_config.atoms_mov.resize(number_of_mov_atoms);
163 atoms_config.atoms_froz_inactive.resize(number_of_fro_atoms);
164
165 // Dense GPR types from the Z→0..n-1 map.
166 if (atype_to_gprd_atype.size() > 1) {
167 int mov_counter = 0;
168 int froz_inactive_counter = 0;
169 for (auto i = 0; i < nAtoms; i++) {
170 if (matter->getFixed(i)) {
173 atoms_config.atoms_froz_inactive.type(0, froz_inactive_counter) =
174 atype_to_gprd_atype.at(atomnrs[i]);
175 froz_inactive_counter++;
176 } else {
178 atoms_config.atoms_mov.type(0, mov_counter) =
179 atype_to_gprd_atype.at(atomnrs[i]);
180 mov_counter++;
181 }
182 }
183 }
186 else if (atype_to_gprd_atype.size() == 1) {
187 atoms_config.atoms_mov.type.setConstant(
188 atype_to_gprd_atype.at(atomnrs[0]));
189 atoms_config.atoms_froz_inactive.type.setConstant(
190 atype_to_gprd_atype.at(atomnrs[0]));
191 }
192 // Assign moving and frozen atoms and list all frozen atoms as inactive
193 gpr::Index_t counter_f = 0, counter_m = 0;
194 for (gpr::Index_t n = 0;
195 n < static_cast<gpr::Index_t>(atoms_config.is_frozen.size()); ++n) {
196 if (atoms_config.is_frozen(0, n) == MOVING_ATOM)
197 gpr::coord::set(atoms_config.atoms_mov.positions, 0, counter_m++,
198 gpr::coord::at(atoms_config.positions, n));
199 else
200 gpr::coord::set(atoms_config.atoms_froz_inactive.positions, 0,
201 counter_f++, gpr::coord::at(atoms_config.positions, n));
202 }
204 } else {
205 if (number_of_mov_atoms == 0) {
206 throw std::runtime_error("eon_matter_to_atmconf: no moving atoms");
207 }
210 atoms_config.atoms_mov.resize(number_of_mov_atoms);
211
212 // Dense GPR types from the Z→0..n-1 map.
213 if (atype_to_gprd_atype.size() > 1) {
214 int mov_counter = 0;
215 for (auto i = 0; i < nAtoms; i++) {
216 atoms_config.atoms_mov.type(0, mov_counter) =
217 atype_to_gprd_atype.at(atomnrs[i]);
218 mov_counter++;
219 }
220 }
223 else if (atype_to_gprd_atype.size() == 1) {
224 atoms_config.atoms_mov.type.setConstant(
225 atype_to_gprd_atype.at(atomnrs[0]));
226 }
227 }
228 // Pairtype indices for pairs of atomtypes (n_at x n_at)
229 // Active pairtypes are indexed as 0,1,...,n_pt-1. Inactive pairtypes are
230 // given index EMPTY.
231 atoms_config.pairtype.resize(n_at, n_at);
232 atoms_config.pairtype.setConstant(EMPTY);
233
234 // Set pairtype indices for moving+moving atom pairs (and update number of
235 // active pairtypes)
236 problem_setup.setPairtypeForMovingAtoms(
237 atoms_config.atoms_mov.type, atoms_config.n_pt, atoms_config.pairtype);
238
239 return atoms_config;
240}
const AtomMatrix & getPositions() const
Definition Matter.cpp:378
long getAtomicNr(long int atom) const
Definition Matter.cpp:565

◆ eon_matter_to_init_obs()

gpr::Observation eonc::helpers::eon_matter_to_init_obs ( Matter * matter)

Create an initial Observation object for gpr_dimer.

Note that this is essentially only for the setup, and it does not actually append or handle the Observation structure other than for initialization of atomic gp dimer

Parameters
mattereOn Matter object

Definition at line 242 of file GPRHelpers.cpp.

242 {
243 gpr::Observation o;
244 o.clear();
245 copyAtomMatrixToCoord(matter->getPositions(), o.R);
246 // Forces as negative gradients; same N×3 → 1×(3N) packing as positions.
247 AtomMatrix neg_forces = -matter->getForces();
248 copyAtomMatrixToCoord(neg_forces, o.G);
249 o.E.resize(1, 1);
250 o.E(0, 0) = matter->getPotentialEnergy();
251 return o;
252}
double getPotentialEnergy() const
Definition Matter.cpp:624
const AtomMatrix & getForces() const
Definition Matter.cpp:482

◆ eon_parameters_to_gpr()

gpr::InputParameters eonc::helpers::eon_parameters_to_gpr ( const Parameters & parameters)

Create a parameters object for gpr_dimer.

TODO: Get the cell size from a Matter object

Parameters
parameterseOn parameters

Definition at line 26 of file GPRHelpers.cpp.

26 {
27 gpr::InputParameters p;
28 // Problem parameters
29 p.actdist_fro.value = parameters.gpr_dimer_options().active_radius;
30 p.dimer_sep.value = parameters.gpr_dimer_options().dimer_sep;
31 p.method_rot.value = parameters.gpr_dimer_options().rot_opt_method;
32 p.method_trans.value = parameters.gpr_dimer_options().trans_opt_method;
33 p.param_trans.value[0] = parameters.gpr_dimer_options().conv_step;
34 p.param_trans.value[1] = parameters.gpr_dimer_options().max_step;
35 // Saddle point convergence parameter
36 p.T_dimer.value = parameters.saddle_search_options().converged_force;
37 p.T_anglerot_init.value = parameters.gpr_dimer_options().converged_angle;
38 // ---
39 p.initrot_nogp.value = parameters.gpr_dimer_options().init_rot_gp;
40 p.num_iter_initrot.value = parameters.gpr_dimer_options().init_rotations_max;
41 // unused except in the capnp for now
42 // p.inittrans_nogp.value = parameters.gpr_dimer_options().init_trans_gp;
43 p.T_anglerot_gp.value = parameters.gpr_dimer_options().relax_conv_angle;
44 p.num_iter_rot_gp.value = parameters.gpr_dimer_options().relax_rotations_max;
45 p.divisor_T_dimer_gp.value =
47 p.disp_max.value = parameters.gpr_dimer_options().midpoint_max_disp;
48 p.ratio_at_limit.value = parameters.gpr_dimer_options().ratio_at_limit;
49 p.num_bigiter.value = parameters.gpr_dimer_options().max_outer_iterations;
50 p.num_iter.value = parameters.gpr_dimer_options().max_inner_iterations;
51 p.islarge_num_iter.value = parameters.gpr_dimer_options().many_iterations;
52 // GPR Parameters
53 p.gp_sigma2.value = parameters.gpr_dimer_options().gpr_params.sigma2;
54 p.jitter_sigma2.value =
56 p.sigma2.value = parameters.gpr_dimer_options().gpr_params.noise_sigma2;
57 p.prior_mu.value = parameters.gpr_dimer_options().gpr_params.prior_mu;
58 p.prior_nu.value = parameters.gpr_dimer_options().gpr_params.prior_nu;
59 p.prior_s2.value = parameters.gpr_dimer_options().gpr_params.prior_sigma2;
60 // gpr_optim enables the check only when this string equals "true".
61 // A bool assigns as one char, so the flag never turns on.
62 p.check_derivative.value =
64 : "false";
65 p.max_iter.value = parameters.gpr_dimer_options().opt_params.max_iterations;
66 p.tolerance_func.value = parameters.gpr_dimer_options().opt_params.tol_func;
67 p.tolerance_sol.value = parameters.gpr_dimer_options().opt_params.tol_sol;
68 p.lambda_limit.value = parameters.gpr_dimer_options().opt_params.lambda_limit;
69 p.lambda.value = parameters.gpr_dimer_options().opt_params.lambda_init;
70 // Prune
71 p.use_prune.value = parameters.gpr_dimer_options().prune_params.use_prune;
72 p.start_prune_at.value = parameters.gpr_dimer_options().prune_params.begin;
73 p.nprune_vals.value = parameters.gpr_dimer_options().prune_params.n_vals;
74 p.prune_threshold.value =
76 // Debugging
77 p.report_level.value =
79 p.debug_level.value = parameters.gpr_dimer_options().debug_params.debug_level;
80 p.debug_output_dir.value =
82 p.debug_output_file_R.value =
84 p.debug_output_file_E.value =
86 p.debug_output_file_G.value =
88 p.debug_output_file_extension.value =
90 p.debug_offset_from_mid_point.value =
92 p.debug_dy.value = parameters.gpr_dimer_options().debug_params.dy;
93 p.debug_dz.value = parameters.gpr_dimer_options().debug_params.dz;
94 return p;
95}
const gpr_dimer_options_t & gpr_dimer_options() const
struct eonc::gpr_dimer_options_t::prune_params_t prune_params
struct eonc::gpr_dimer_options_t::gpr_params_t gpr_params
struct eonc::gpr_dimer_options_t::debug_params_t debug_params
struct eonc::gpr_dimer_options_t::opt_params_t opt_params

◆ existsFile()

bool eonc::helpers::existsFile ( std::string filename)

Definition at line 76 of file HelperFunctions.cpp.

76 {
77 return std::filesystem::exists(filename);
78}

◆ get_split_strings()

std::vector< std::string > eonc::helpers::get_split_strings ( std::string_view line)

Split a string into constituent strings.

Based on https://www.fluentcpp.com/2017/04/21/how-to-split-a-string-in-c/

Parameters
lineA thing to be parsed

Definition at line 46 of file StringHelpers.cc.

46 {
47 std::istringstream ss{std::string{line}};
48 std::vector<std::string> split_strings{std::istream_iterator<std::string>{ss},
49 std::istream_iterator<std::string>()};
50 return split_strings;
51}

◆ get_val_from_string() [1/2]

template<typename T>
std::vector< T > eonc::helpers::get_val_from_string ( std::string_view line,
std::optional< size_t > nelements = std::nullopt )

Parse a string into values.

Parameters
linetext to parse
nelementsexpected count, when set

Definition at line 9 of file StringHelpers.cc.

10 {
11 assert(not line.empty());
12 std::vector<T> retval;
13 const bool b_isunsigned{std::is_unsigned<T>::value};
14 auto elements{get_split_strings(line)};
15 if (nelements.has_value()) {
16 // Used to truncate if the number of elements is given
17 assert(nelements > 0);
18 elements.resize(nelements.value());
19 }
20 // If it is unsigned then use long double else T
21 for (typename std::conditional<b_isunsigned, long double, T>::type tmp;
22 auto elem : elements) {
23 if (not isNumber(elem)) {
24 continue;
25 }
26 std::istringstream ss{
27 elem}; // instead of {ss.str(elem); ss >> tmp; ss.clear();}
28 ss >> tmp;
29 if (b_isunsigned and tmp < 0) {
30 std::cerr << "Can't represent negative numbers with an unsigned type, "
31 "bailing on "
32 << tmp << "\n";
33 assert(tmp > 0);
34 }
35 retval.push_back(tmp);
36 }
37 return retval;
38}
bool isNumber(std::string_view token)
Figure out if a string has a number in it.
std::vector< std::string > get_split_strings(std::string_view line)
Split a string into constituent strings.

◆ get_val_from_string() [2/2]

template std::vector< size_t > eonc::helpers::get_val_from_string ( std::string_view ,
std::optional< size_t >  )

◆ get_value_from_env_or_param()

std::string eonc::helpers::get_value_from_env_or_param ( const char * env_variable,
const std::string & param_value,
const std::string & default_value,
const std::string & warning_message,
const bool is_mandatory )
nodiscard

Definition at line 7 of file EnvHelpers.cc.

11 {
12 const char *env_value = std::getenv(env_variable);
13 if (env_value != nullptr) {
14 return std::string(env_value);
15 }
16
17 if (!param_value.empty()) {
18 return param_value;
19 }
20
21 if (is_mandatory) {
22 throw std::runtime_error(
23 "Environment variable " + std::string(env_variable) +
24 " is not set and no parameter value provided. Please set it in the "
25 "configuration or as an environment variable.\n");
26 }
27
28 if (!default_value.empty() && !warning_message.empty()) {
29 EONC_LOG_WARNING("{}", warning_message);
30 }
31
32 return default_value;
33}
#define EONC_LOG_WARNING(...)
Definition EonLogger.h:322

◆ getRelevantFile()

std::string eonc::helpers::getRelevantFile ( std::string filename)

Definition at line 123 of file HelperFunctions.cpp.

123 {
124 const auto dot = filename.rfind('.');
125 const std::string prefix =
126 (dot == std::string::npos) ? filename : filename.substr(0, dot);
127 const std::string postfix =
128 (dot == std::string::npos) ? std::string{} : filename.substr(dot);
129 std::string filenameRelevant = prefix + "_cp" + postfix;
130 if (existsFile(filenameRelevant)) {
131 return filenameRelevant;
132 }
133 filenameRelevant = prefix + "_in" + postfix;
134 if (existsFile(filenameRelevant)) {
135 return filenameRelevant;
136 }
137 return filename;
138}
bool existsFile(std::string filename)

◆ getTime()

void eonc::helpers::getTime ( double * real,
double * user,
double * sys )

Definition at line 48 of file HelperFunctions.cpp.

48 {
49 using namespace std::chrono;
50 auto now = steady_clock::now();
51 if (real) {
52 *real = duration<double>(now.time_since_epoch()).count();
53 }
54
55#ifdef _WIN32
56 if (user)
57 *user = 0.0;
58 if (sys)
59 *sys = 0.0;
60#else
61 struct rusage r_usage;
62 if (getrusage(RUSAGE_SELF, &r_usage) != 0) {
63 EONC_LOG_WARNING("problem getting usage info: {}", strerror(errno));
64 }
65 if (user) {
66 *user = static_cast<double>(r_usage.ru_utime.tv_sec) +
67 static_cast<double>(r_usage.ru_utime.tv_usec) / 1e6;
68 }
69 if (sys) {
70 *sys = static_cast<double>(r_usage.ru_stime.tv_sec) +
71 static_cast<double>(r_usage.ru_stime.tv_usec) / 1e6;
72 }
73#endif
74}

◆ isNumber()

bool eonc::helpers::isNumber ( std::string_view token)

Figure out if a string has a number in it.

Based on

Definition at line 53 of file StringHelpers.cc.

53 {
54 return std::regex_match(
55 std::string{token},
56 std::regex(("((\\+|-)?[[:digit:]]+)(\\.(([[:digit:]]+)?))?")));
57}

◆ loadMasses()

VectorXd eonc::helpers::loadMasses ( std::string filename,
int nAtoms )

Definition at line 140 of file HelperFunctions.cpp.

140 {
141 std::ifstream massFile(filename.c_str());
142 if (!massFile.is_open()) {
143 EONC_LOG_CRITICAL("File {} was not found", filename);
144 throw std::runtime_error(std::format("cannot open {}", filename));
145 }
146
147 VectorXd masses(nAtoms);
148 for (int i = 0; i < nAtoms; i++) {
149 double mass;
150 if (!(massFile >> mass)) {
151 EONC_LOG_CRITICAL("Error reading {}", filename);
152 throw std::runtime_error(
153 std::format("{} ended after {} of {} masses", filename, i, nAtoms));
154 }
155 masses(i) = mass;
156 }
157
158 massFile.close();
159
160 return masses;
161}
#define EONC_LOG_CRITICAL(...)
Definition EonLogger.h:334

◆ loadMode() [1/2]

AtomMatrix eonc::helpers::loadMode ( FILE * modeFile,
int nAtoms )

Definition at line 163 of file HelperFunctions.cpp.

163 {
164 AtomMatrix mode;
165 mode.resize(nAtoms, 3);
166 mode.setZero();
167 for (int i = 0; i < nAtoms; i++) {
168 if (fscanf(modeFile, "%lf %lf %lf", &mode(i, 0), &mode(i, 1),
169 &mode(i, 2)) != 3) {
170 EONC_LOG_CRITICAL("Mode file ended after {} of {} atoms", i, nAtoms);
171 throw std::runtime_error(
172 std::format("mode file ended after {} of {} atoms", i, nAtoms));
173 }
174 }
175 return mode;
176}

◆ loadMode() [2/2]

AtomMatrix eonc::helpers::loadMode ( std::string filename,
int nAtoms )

Definition at line 178 of file HelperFunctions.cpp.

178 {
179 // Unique FILE* with RAII cleanup
180 auto closer = [](FILE *f) {
181 if (f)
182 std::fclose(f);
183 };
184 std::unique_ptr<FILE, decltype(closer)> modeFile(
185 std::fopen(filename.c_str(), "rb"), closer);
186 if (!modeFile) {
187 EONC_LOG_CRITICAL("File {} was not found", filename);
188 throw std::runtime_error(std::format("cannot open {}", filename));
189 }
190 return loadMode(modeFile.get(), nAtoms);
191}
AtomMatrix loadMode(FILE *modeFile, int nAtoms)

◆ loadOrSynthesizeDisplacement()

bool eonc::helpers::loadOrSynthesizeDisplacement ( Matter & target,
const Matter & initial,
const std::string & displacementPath,
const std::string & modePath,
double scale )

Definition at line 193 of file HelperFunctions.cpp.

195 {
196 if (eonc::io::io_ok(target.con2matter(displacementPath))) {
197 if (target.numberOfAtoms() != initial.numberOfAtoms()) {
198 EONC_LOG_ERROR("{} holds {} atoms, the initial structure has {}",
199 displacementPath, target.numberOfAtoms(),
200 initial.numberOfAtoms());
201 return false;
202 }
203 // displacement.con may carry stale fixed-atom coordinates from a prior run.
204 // It also usually has sequential column-5 ids; keep the reactant's.
205 const AtomMatrix &initPos = initial.getPositions();
206 AtomMatrix pos = target.getPositionsCopy();
207 const long n = initial.numberOfAtoms();
208 std::vector<long> fileMap(static_cast<size_t>(n));
209 for (long i = 0; i < n; i++) {
210 if (initial.getFixed(i)) {
211 pos.row(i) = initPos.row(i);
212 }
213 target.setAtomIndex(i, initial.getAtomIndex(i));
214 fileMap[static_cast<size_t>(i)] = initial.mapFileRow(i);
215 }
216 target.setFileToMatter(std::move(fileMap));
217 target.setPositions(pos);
218 return true;
219 }
220 if (!existsFile(modePath)) {
221 return false;
222 }
223 AtomMatrix mode =
224 loadMode(modePath, static_cast<int>(initial.numberOfAtoms()));
225 const double norm = mode.norm();
226 if (!(norm > 0.0)) {
227 return false;
228 }
229 mode *= (scale / norm);
230 target = initial;
231 AtomMatrix pos = initial.getPositionsCopy();
232 pos += mode;
233 const AtomMatrix &initPos = initial.getPositions();
234 const long n = initial.numberOfAtoms();
235 for (long i = 0; i < n; i++) {
236 if (initial.getFixed(i)) {
237 pos.row(i) = initPos.row(i);
238 }
239 }
240 target.setPositions(pos);
241 EONC_LOG_INFO("Synthesized displacement from pos.con + scale {:.6g} * unit "
242 "mode in {} (missing {})",
243 scale, modePath, displacementPath);
244 return true;
245}
#define EONC_LOG_ERROR(...)
Definition EonLogger.h:328
#define EONC_LOG_INFO(...)
Definition EonLogger.h:316
void setAtomIndex(long int atom, std::int64_t index)
Definition Matter.cpp:963
long mapFileRow(long file_row) const
Map a CON file-order row onto the Matter row after matter_order.
Definition Matter.h:318
std::int64_t getAtomIndex(long int atom) const
.con column-5 index (pre-grouping); public for I/O / bindings.
Definition Matter.cpp:959
void setFileToMatter(std::vector< long > map)
Definition Matter.h:325
io::IoStatus con2matter(std::string filename)
Definition Matter.h:281
constexpr bool io_ok(IoStatus s) noexcept
Definition ConFileIO.h:38

◆ makeImagePotential()

std::shared_ptr< Potential > eonc::helpers::makeImagePotential ( const Potential & pot,
const Parameters & params )
nodiscard

A separate instance of pot for one image of a band, dimer or pair of minimizations: a clone when the backend can clone, else a new instance built from params.

It charges its force calls to the registry that counts pot's, so a job's force-call total includes every image.

Definition at line 271 of file Potential.cpp.

272 {
273 PotentialConstructionScope scope(pot.registry());
274 if (auto cloned = pot.clonePotential()) {
275 return cloned;
276 }
277 return sharePotential(makePotential(params));
278}
RAII: Potential default construction records on this registry instead of PotRegistry::get().
Definition Potential.h:33
std::unique_ptr< Potential > makePotential(const Parameters &params)
Exclusive ownership.
std::shared_ptr< Potential > sharePotential(std::unique_ptr< Potential > pot)
Multi-owner boundary: one instance observed by several Matters, images, or a binding.
Definition Potential.h:292

◆ makeJob() [1/4]

std::unique_ptr< Job > eonc::helpers::makeJob ( std::unique_ptr< Parameters > params)

One-shot: Job owns a default Runtime.

Definition at line 65 of file JobRegistry.cpp.

65 {
66 return makeJob(std::move(params), std::make_unique<Runtime>());
67}
std::unique_ptr< Job > makeJob(std::unique_ptr< Parameters > params, Runtime &runtime)
Borrow: caller keeps Runtime alive.

◆ makeJob() [2/4]

std::unique_ptr< Job > eonc::helpers::makeJob ( std::unique_ptr< Parameters > params,
Runtime && runtime )

Own the rvalue Runtime.

Definition at line 59 of file JobRegistry.cpp.

60 {
61 return makeJob(std::move(params),
62 std::make_unique<Runtime>(std::move(runtime)));
63}

◆ makeJob() [3/4]

std::unique_ptr< Job > eonc::helpers::makeJob ( std::unique_ptr< Parameters > params,
Runtime & runtime )

Borrow: caller keeps Runtime alive.

Definition at line 43 of file JobRegistry.cpp.

44 {
45 return makeJobFromFactory(std::move(params), runtime);
46}

◆ makeJob() [4/4]

std::unique_ptr< Job > eonc::helpers::makeJob ( std::unique_ptr< Parameters > params,
std::unique_ptr< Runtime > runtime )

Own the unique_ptr Runtime.

Definition at line 48 of file JobRegistry.cpp.

49 {
50 if (!runtime) {
51 throw std::logic_error("makeJob: null Runtime");
52 }
53 Runtime &ref = *runtime;
54 auto job = makeJobFromFactory(std::move(params), ref);
55 job->adoptRuntime(std::move(runtime));
56 return job;
57}
Move-only composition root for process resources (dlopen loaders and the potential registry).
Definition Runtime.h:27

◆ makeOrthogonal()

AtomMatrix eonc::helpers::makeOrthogonal ( const AtomMatrix v1,
const AtomMatrix v2 )

Definition at line 43 of file HelperFunctions.cpp.

44 {
45 return v1 - matDot(v1, v2) * eonc::safemath::safe_normalized(v2);
46}
double matDot(const AtomMatrix &a, const AtomMatrix &b)
SIMD-optimized dot product for contiguous Eigen matrices.
Definition Eigen.h:50

◆ makePotential() [1/3]

std::unique_ptr< Potential > eonc::helpers::makePotential ( const Parameters & params)
nodiscard

Exclusive ownership.

Share only at a multi-owner boundary via sharePotential().

Definition at line 268 of file Potential.cpp.

268 {
269 return makePotential(params.potential_options().potential, params);
270}
const potential_options_t & potential_options() const

◆ makePotential() [2/3]

std::unique_ptr< Potential > eonc::helpers::makePotential ( PotType ptype,
const Parameters & params )
nodiscard

Definition at line 285 of file Potential.cpp.

286 {
287 // Inject config-file path before any potential constructor runs.
288 // Called on every code path including Job::Job which uses this overload.
291 switch (ptype) {
292 // TODO: Every potential must know their own type
293 case PotType::EMT: {
295 PotType::EMT, params,
296 rgpot::EMTConfig{.rasmussen = params.potential_options().EMTRasmussen});
297 break;
298 }
299 case PotType::EXT_POT: {
300 return (std::make_unique<ExtPot>(params));
301 break;
302 }
303 case PotType::LJ: {
305 pair_config<rgpot::LJConfig>(params));
306 break;
307 }
308 case PotType::LJCLUSTER: {
310 PotType::LJCLUSTER, params,
311 pair_config<rgpot::LJClusterConfig>(params));
312 break;
313 }
314 case PotType::MORSE_PT: {
316 pair_config<rgpot::MorseConfig>(params));
317 break;
318 }
319#ifdef CUH2_POT
320 case PotType::CUH2: {
322 break;
323 }
324#endif
325#ifdef WITH_WATER
326 case PotType::TIP4P: {
328 rgpot::WaterConfig{});
329 break;
330 }
331 case PotType::SPCE: {
333 rgpot::WaterConfig{});
334 break;
335 }
336 case PotType::TIP4P_PT: {
338 rgpot::WaterConfig{});
339 break;
340 }
341#endif
342#ifdef WITH_FORTRAN
343 case PotType::TIP4P_H: {
345 params);
346 break;
347 }
348#endif
349 // Fortran potentials: always available, loaded at runtime via dlopen
350 case PotType::EAM_AL: {
352 params);
353 break;
354 }
355 case PotType::EDIP: {
357 break;
358 }
359 case PotType::FEHE: {
361 break;
362 }
363 case PotType::LENOSKY_SI: {
365 params);
366 break;
367 }
368 case PotType::SW_SI: {
370 break;
371 }
372 case PotType::TERSOFF_SI: {
374 params);
375 break;
376 }
377#ifndef _WIN32
378#ifdef WITH_VASP
379 case PotType::VASP: {
380 return (std::make_unique<VASP>(params));
381 break;
382 }
383#endif
384#endif
385 case PotType::LAMMPS: {
386 return std::make_unique<LAMMPSPot>(params);
387 }
388#ifdef EONMPI
389 case PotType::MPI: {
390 return (std::make_unique<MPIPot>(params));
391 break;
392 }
393#endif
394#ifdef EMBED_PYTHON
395#ifdef WITH_ASE_POT
396 case PotType::ASE_POT: {
397 return (std::make_unique<ASE>(params));
398 break;
399 }
400#endif
401#endif
402#ifdef WITH_AMS
403 case PotType::AMS: {
404 return (std::make_unique<AMS>(params));
405 break;
406 }
407 case PotType::AMS_IO: {
408 return (std::make_unique<AMS_IO>(params));
409 break;
410 }
411#endif
412#ifdef WITH_CATLEARN
413 case PotType::CatLearn: {
414 return (std::make_unique<CatLearnPot>(params));
415 break;
416 }
417#endif
418// TODO: Handle Fortran interaction
419#ifdef WITH_XTB
420 case PotType::XTB: {
421 const auto &o = params.xtb_options();
422 rgpot::GFNMethod method = rgpot::GFNMethod::GFN2xTB;
423 if (o.paramset == "GFNFF") {
424 method = rgpot::GFNMethod::GFNFF;
425 } else if (o.paramset == "GFN0xTB") {
426 method = rgpot::GFNMethod::GFN0xTB;
427 } else if (o.paramset == "GFN1xTB") {
428 method = rgpot::GFNMethod::GFN1xTB;
429 } else if (o.paramset == "GFN2xTB") {
430 method = rgpot::GFNMethod::GFN2xTB;
431 } else {
432 throw std::runtime_error(
433 "Parameter set for XTB must be one of GFNFF, GFN0xTB, GFN1xTB or "
434 "GFN2xTB.\n");
435 }
437 PotType::XTB, params,
438 rgpot::XTBConfig{
439 .method = method,
440 .accuracy = o.acc,
441 .electronic_temperature = o.elec_temperature,
442 .max_iterations = static_cast<int>(o.maxiter),
443 .charge = o.charge,
444 .uhf = o.uhf,
445 });
446 break;
447 }
448#endif
449#ifdef WITH_ASE_ORCA
450 case PotType::ASE_ORCA: {
451 return (std::make_unique<ASEOrcaPot>(params));
452 break;
453 }
454#endif
455#ifdef WITH_ASE_NWCHEM
456 case PotType::ASE_NWCHEM: {
457 return (std::make_unique<ASENwchemPot>(params));
458 break;
459 }
460#endif
461#ifdef WITH_METATOMIC
462 case PotType::METATOMIC: {
463 return (std::make_unique<MetatomicPotential>(params));
464 break;
465 }
466#endif
467#ifdef RGPOT_HAS_DFTD3
468 case PotType::DFTD3: {
469 rgpot::D3Damping damp = rgpot::D3Damping::BJ;
470 std::string dname = params.dftd_options().d3_damping;
471 for (char &c : dname) {
472 c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
473 }
474 if (dname == "zero") {
475 damp = rgpot::D3Damping::Zero;
476 }
478 PotType::DFTD3, params,
479 rgpot::D3Config{.damping = damp,
480 .functional = params.dftd_options().functional,
481 .atm = params.dftd_options().atm});
482 break;
483 }
484#endif
485#ifdef RGPOT_HAS_DFTD4
486 case PotType::DFTD4: {
488 PotType::DFTD4, params,
489 rgpot::D4Config{.functional = params.dftd_options().functional,
490 .charge = params.dftd_options().d4_charge,
491 .atm = params.dftd_options().atm});
492 break;
493 }
494#endif
495 case PotType::ZBL: {
497 PotType::ZBL, params,
498 rgpot::ZBLConfig{
499 .cut_inner = params.zbl_options().cut_inner,
500 .cut_global = params.zbl_options().cut_global,
501 });
502 break;
503 }
504#ifndef IS_WINDOWS
506 return (std::make_unique<SocketNWChemPot>(params));
507 break;
508 }
509#endif
510#ifdef WITH_RGPOT
511 case PotType::RGPOT: {
512 return (std::make_unique<RgpotPot>(params));
513 break;
514 }
515#endif
516 case PotType::MOPAC: {
518 PotType::MOPAC, params,
519 rgpot::MOPACPot::Config{
520 .charge = params.mopac_options().charge,
521 .spin = params.mopac_options().spin,
522 .model = params.mopac_options().model,
523 .engine_path = params.mopac_options().engine_path,
524 });
525 break;
526 }
527#ifdef RGPOT_HAS_EXPR
528 case PotType::EXPR: {
529 if (params.expr_options().expression.empty()) {
530 throw std::runtime_error(
531 "ExprPot needs [ExprPot] expression, e.g. 0.5*lj + d3");
532 }
533 rgpot::ExprPot expr(params.expr_options().expression,
534 parse_expr_terms(params));
535 return std::make_unique<RgpotAdapter<rgpot::ExprPot>>(PotType::EXPR, params,
536 std::move(expr));
537 break;
538 }
539#endif
540 default:
541 EONC_LOG_ERROR("No known potential could be constructed from {}",
542 magic_enum::enum_name(ptype));
543 eonc::log::get()->flush_log();
544 throw std::runtime_error("Terminating");
545 break;
546 }
547}
std::unique_ptr< eonc::Potential > makeRgpotDefault(eonc::PotType ptype, const eonc::Parameters &params)
Factory arm helper for kernels whose parameters are fixed tabulated data with no eOn-side configurati...
std::unique_ptr< eonc::Potential > makeRgpot(eonc::PotType ptype, const eonc::Parameters &params, const Cfg &cfg)
Factory arm helper: construct the kernel from its config and wrap it.
const expr_options_t & expr_options() const
const xtb_options_t & xtb_options() const
const zbl_options_t & zbl_options() const
const mopac_options_t & mopac_options() const
const dftd_options_t & dftd_options() const
void add_config_paths(const std::string &colon_paths) override
Inject search paths from the eOn config file.
static PluginLoader & instance()
Thread-safe singleton accessor (Meyer's pattern).
quill::Logger * get() noexcept
Get or create the default "combi" logger.
Definition EonLogger.h:111

◆ makePotential() [3/3]

std::unique_ptr< Potential > eonc::helpers::makePotential ( PotType ptype,
const Parameters & params,
Runtime & runtime )
nodiscard

Definition at line 280 of file Potential.cpp.

280 {
281 PotentialConstructionScope scope(runtime.pots());
283 return makePotential(ptype, params);
284}
PotRegistry & pots() noexcept
Definition Runtime.cpp:33
PluginLoader & plugins() noexcept
Definition Runtime.cpp:39

◆ relaxMatter()

bool eonc::helpers::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 )

Definition at line 449 of file HelperFunctions.cpp.

453 {
454 eonc::log::Scoped m_log;
455 auto objf = std::make_shared<MatterObjectiveFunction>(matter, params);
457 objf, params.optimizer_options().method, params);
458
459 std::ostringstream min;
460 min << prefixMovie;
461 std::string minDatFilename = prefixMovie + ".dat";
462 auto write_movie_frame = [&](uint64_t frameIndex, bool append,
463 double stepSize) {
465 metadata.frame_index = frameIndex;
466 metadata.energy = matter.getPotentialEnergy();
467 metadata.scalars.push_back({"step_size", stepSize});
468 metadata.scalars.push_back({"convergence", objf->getConvergence()});
469 if (outFrames) {
470 outFrames->push_back(eonc::io::matterToConFrame(matter, &metadata));
471 }
472 if (writeMovie) {
473 if (!eonc::io::io_ok(matter.matter2con(min.str(), append, &metadata))) {
474 QUILL_LOG_WARNING(m_log, "Failed to write movie frame {}", min.str());
475 }
476 }
477
479 std::ofstream minDat(minDatFilename,
480 append ? (std::ios::binary | std::ios::app)
481 : std::ios::binary);
482 if (minDat) {
483 if (!append) {
484 minDat << "iteration\tstep_size\tconvergence\tenergy\n";
485 }
486 minDat << std::format("{}\t{:.5e}\t{:.5e}\t{:.6f}\n", frameIndex,
487 stepSize, objf->getConvergence(),
488 matter.getPotentialEnergy());
489 }
490 }
491 };
492 if (writeMovie || outFrames) {
493 write_movie_frame(0, false, 0.0);
494 }
495
496 int iteration = 0;
497 if (!quiet) {
498 QUILL_LOG_DEBUG(m_log, "{} {:10s} {:14s} {:18s} {:13s}\n", "[Matter]",
499 "Iter", "Step size",
501 "Energy");
502 QUILL_LOG_DEBUG(m_log, "{} {:10} {:14.5e} {:18.5e} {:13.5f}\n",
503 "[Matter]", iteration, 0.0, objf->getConvergence(),
504 matter.getPotentialEnergy());
505 }
506
507 while (!objf->isConverged() &&
508 iteration < params.optimizer_options().max_iterations) {
509 matter.pollCancel("relax");
510
511 AtomMatrix pos = matter.getPositions();
512
513 optim->step(params.optimizer_options().max_move);
514 iteration++;
515
516 double stepSize =
517 eonc::geometry::maxAtomMotion(matter.pbc(matter.getPositions() - pos));
518
519 if (!quiet) {
520 QUILL_LOG_DEBUG(m_log, "{} {:10} {:14.5e} {:18.5e} {:13.5f}",
521 "[Matter]", iteration, stepSize, objf->getConvergence(),
522 matter.getPotentialEnergy());
523 }
524
525 if (writeMovie || outFrames) {
526 write_movie_frame(static_cast<uint64_t>(iteration), true, stepSize);
527 }
528
529 if (checkpoint) {
530 std::ostringstream chk;
531 chk << prefixCheckpoint << "_cp";
532 if (!eonc::io::io_ok(matter.matter2con(chk.str(), false))) {
533 QUILL_LOG_WARNING(m_log, "Failed to write checkpoint {}", chk.str());
534 }
535 }
536 }
537
538 if (iteration == 0) {
539 if (!quiet) {
540 QUILL_LOG_DEBUG(m_log, "{} {:10} {:14.5e} {:18.5e} {:13.5f}",
541 "[Matter]", iteration, 0.0, objf->getConvergence(),
542 matter.getPotentialEnergy());
543 }
544 }
545 return objf->isConverged();
546}
void pollCancel(const char *site) const
Definition Matter.h:349
AtomMatrix pbc(const AtomMatrix &diff) const
Definition Matter.cpp:943
io::IoStatus matter2con(std::string filename, bool append=false, const io::ConFrameMetadata *metadata=nullptr)
Definition Matter.h:293
const debug_options_t & debug_options() const
const optimizer_options_t & optimizer_options() const
double maxAtomMotion(const AtomMatrix v1)
std::unique_ptr< Optimizer > mkOptim(std::shared_ptr< ObjectiveFunction > a_objf, OptType a_otype, const Parameters &a_params)
Definition Optimizer.cpp:55
readcon::ConFrame matterToConFrame(Matter &m, const ConFrameMetadata *metadata)
Build a single stamped ConFrame from Matter (same builder as matter2con).
std::optional< uint64_t > frame_index
Definition ConFileIO.h:72
std::vector< ConMetadataValue > scalars
Definition ConFileIO.h:79
std::optional< double > energy
Definition ConFileIO.h:73
RAII helper for class-scoped logging.
Definition EonLogger.h:238

◆ requireKnownConvergenceMetric()

void eonc::helpers::requireKnownConvergenceMetric ( std::string_view metric,
std::string_view context )

Throws std::invalid_argument naming context when metric is unrecognized.

Call at construction: the metric is compared once per optimizer step, and a typo should not surface on iteration 4000.

Definition at line 372 of file HelperFunctions.cpp.

373 {
374 if (convergenceMetricLabel(metric)) {
375 return;
376 }
377 throw std::invalid_argument(
378 std::format("{} unknown convergence_metric: {}", context, metric));
379}
std::optional< std::string_view > convergenceMetricLabel(std::string_view metric)
Display label for a force-convergence metric, or nullopt when the name is none of the four the optimi...

◆ saveMode() [1/2]

void eonc::helpers::saveMode ( const std::string & filename,
std::shared_ptr< Matter > matter,
AtomMatrix mode )

Definition at line 317 of file HelperFunctions.cpp.

318 {
319 std::ofstream out(filename);
320 if (!out)
321 return;
322 const AtomMatrix free = matter->getFree();
323 long const nAtoms = matter->numberOfAtoms();
324 for (long i = 0; i < nAtoms; ++i) {
325 out << std::format("{:.17g}\t{:.17g}\t{:.17g}\n", free(i, 0) * mode(i, 0),
326 free(i, 1) * mode(i, 1), free(i, 2) * mode(i, 2));
327 }
328}

◆ saveMode() [2/2]

void eonc::helpers::saveMode ( FILE * modeFile,
std::shared_ptr< Matter > matter,
AtomMatrix mode )

Write a mode; constrained axes are emitted as 0.

Definition at line 306 of file HelperFunctions.cpp.

307 {
308 const AtomMatrix free = matter->getFree();
309 long const nAtoms = matter->numberOfAtoms();
310 for (long i = 0; i < nAtoms; ++i) {
311 fprintf(modeFile, "%.17g\t%.17g\t%.17g\n", free(i, 0) * mode(i, 0),
312 free(i, 1) * mode(i, 1), free(i, 2) * mode(i, 2));
313 }
314 return;
315}

◆ sharePotential()

std::shared_ptr< Potential > eonc::helpers::sharePotential ( std::unique_ptr< Potential > pot)
inlinenodiscard

Multi-owner boundary: one instance observed by several Matters, images, or a binding.

Definition at line 292 of file Potential.h.

292 {
293 return std::shared_ptr<Potential>(std::move(pot));
294}

◆ split_string_int()

std::vector< int > eonc::helpers::split_string_int ( std::string s,
std::string delim )

Definition at line 330 of file HelperFunctions.cpp.

331 {
332 std::vector<int> list;
333 if (s.empty())
334 return list;
335
336 size_t start = 0;
337 size_t end = s.find_first_of(delim);
338 while (start < s.size()) {
339 auto token = s.substr(start, end - start);
340 if (!token.empty()) {
341 try {
342 list.push_back(std::stoi(token));
343 } catch (const std::exception &) {
344 return {}; // Parse error
345 }
346 }
347 if (end == std::string::npos)
348 break;
349 start = end + 1;
350 end = s.find_first_of(delim, start);
351 }
352 return list;
353}

◆ stageReturnLog()

bool eonc::helpers::stageReturnLog ( std::string_view logHome,
std::string_view name )

Copy name from logHome into the current directory when that file is not already this directory's copy.

True only when a regular file of that name is then present.

Definition at line 90 of file HelperFunctions.cpp.

91 {
92 namespace fs = std::filesystem;
93 if (name.empty() || name == "." || name == ".." ||
94 name.find('/') != std::string_view::npos ||
95 name.find('\\') != std::string_view::npos) {
96 return false;
97 }
98 const fs::path dest{std::string{name}};
99 std::error_code ec;
100 const bool destFile = fs::is_regular_file(dest, ec);
101 if (logHome.empty()) {
102 return destFile;
103 }
104 const fs::path src = fs::path{std::string{logHome}} / dest.filename();
105 ec.clear();
106 if (!fs::is_regular_file(src, ec)) {
107 return destFile;
108 }
109 ec.clear();
110 if (destFile && fs::equivalent(src, dest, ec)) {
111 return true;
112 }
113 ec.clear();
114 fs::copy_file(src, dest, fs::copy_options::overwrite_existing, ec);
115 if (ec) {
116 EONC_LOG_ERROR("stageReturnLog: cannot copy {} to {}: {}", src.string(),
117 dest.string(), ec.message());
118 return fs::is_regular_file(dest);
119 }
120 return true;
121}

Variable Documentation

◆ pi

double eonc::helpers::pi = 3.14159265358979323846
inlineconstexpr

Definition at line 29 of file HelperFunctions.h.