38#include <sys/resource.h>
45 return v1 -
matDot(v1, v2) * eonc::safemath::safe_normalized(v2);
49 using namespace std::chrono;
50 auto now = steady_clock::now();
52 *real = duration<double>(now.time_since_epoch()).count();
61 struct rusage r_usage;
62 if (getrusage(RUSAGE_SELF, &r_usage) != 0) {
66 *user =
static_cast<double>(r_usage.ru_utime.tv_sec) +
67 static_cast<double>(r_usage.ru_utime.tv_usec) / 1e6;
70 *sys =
static_cast<double>(r_usage.ru_stime.tv_sec) +
71 static_cast<double>(r_usage.ru_stime.tv_usec) / 1e6;
77 return std::filesystem::exists(filename);
80std::optional<std::string>
83 std::filesystem::current_path(std::filesystem::path{jobPath});
84 }
catch (
const std::filesystem::filesystem_error &err) {
85 return std::string{err.what()};
91 std::string_view name) {
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) {
98 const fs::path dest{std::string{name}};
100 const bool destFile = fs::is_regular_file(dest, ec);
101 if (logHome.empty()) {
104 const fs::path src = fs::path{std::string{logHome}} / dest.filename();
106 if (!fs::is_regular_file(src, ec)) {
110 if (destFile && fs::equivalent(src, dest, ec)) {
114 fs::copy_file(src, dest, fs::copy_options::overwrite_existing, ec);
116 EONC_LOG_ERROR(
"stageReturnLog: cannot copy {} to {}: {}", src.string(),
117 dest.string(), ec.message());
118 return fs::is_regular_file(dest);
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;
131 return filenameRelevant;
133 filenameRelevant = prefix +
"_in" + postfix;
135 return filenameRelevant;
141 std::ifstream massFile(filename.c_str());
142 if (!massFile.is_open()) {
144 throw std::runtime_error(std::format(
"cannot open {}", filename));
147 VectorXd masses(nAtoms);
148 for (
int i = 0; i < nAtoms; i++) {
150 if (!(massFile >> mass)) {
152 throw std::runtime_error(
153 std::format(
"{} ended after {} of {} masses", filename, i, nAtoms));
165 mode.resize(nAtoms, 3);
167 for (
int i = 0; i < nAtoms; i++) {
168 if (fscanf(modeFile,
"%lf %lf %lf", &mode(i, 0), &mode(i, 1),
171 throw std::runtime_error(
172 std::format(
"mode file ended after {} of {} atoms", i, nAtoms));
180 auto closer = [](
FILE *f) {
184 std::unique_ptr<
FILE,
decltype(closer)> modeFile(
185 std::fopen(filename.c_str(),
"rb"), closer);
188 throw std::runtime_error(std::format(
"cannot open {}", filename));
190 return loadMode(modeFile.get(), nAtoms);
194 Matter &target,
const Matter &initial,
const std::string &displacementPath,
195 const std::string &modePath,
double scale) {
208 std::vector<long> fileMap(
static_cast<size_t>(n));
209 for (
long i = 0; i < n; i++) {
211 pos.row(i) = initPos.row(i);
214 fileMap[
static_cast<size_t>(i)] = initial.
mapFileRow(i);
225 const double norm = mode.norm();
229 mode *= (scale / norm);
235 for (
long i = 0; i < n; i++) {
237 pos.row(i) = initPos.row(i);
241 EONC_LOG_INFO(
"Synthesized displacement from pos.con + scale {:.6g} * unit "
242 "mode in {} (missing {})",
243 scale, modePath, displacementPath);
276 const double radius = opt.displace_radius;
277 const double mag = opt.displace_magnitude;
280 for (
long i = 0; i < n; ++i) {
284 const double dist = (i == epicenter) ? 0.0 : initial.
distance(epicenter, i);
285 if (dist <= radius) {
286 for (
int a = 0; a < 3; ++a) {
291 const double norm = mode.norm();
295 }
else if (epicenter >= 0 && epicenter < n && !initial.
getFixed(epicenter)) {
296 mode(epicenter, 0) = 1.0;
297 pos(epicenter, 0) += mag;
300 if (modeOut !=
nullptr) {
301 *modeOut = std::move(mode);
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));
318 std::shared_ptr<Matter> matter,
AtomMatrix mode) {
319 std::ofstream out(filename);
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));
332 std::vector<int> list;
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()) {
342 list.push_back(std::stoi(token));
343 }
catch (
const std::exception &) {
347 if (end == std::string::npos)
350 end = s.find_first_of(delim, start);
355std::optional<std::string_view>
357 if (metric ==
"max_atom") {
358 return "Max atom force";
360 if (metric ==
"max_component") {
361 return "Max force comp";
363 if (metric ==
"norm") {
366 if (metric ==
"rms") {
373 std::string_view context) {
377 throw std::invalid_argument(
378 std::format(
"{} unknown convergence_metric: {}", context, metric));
390 params.optimizer_options().convergence_metric,
"[Matter]");
392 ~MatterObjectiveFunction() =
default;
394 VectorXd getGradient(
bool fdstep =
false) {
401 return getConvergence() < params.optimizer_options().converged_force;
403 double getConvergence() {
404 if (params.optimizer_options().convergence_metric ==
"norm") {
406 }
else if (params.optimizer_options().convergence_metric ==
"rms") {
408 const auto n = f.size();
411 }
else if (params.optimizer_options().convergence_metric ==
"max_atom") {
413 }
else if (params.optimizer_options().convergence_metric ==
415 return m_matter.
getForces().cwiseAbs().maxCoeff();
418 params.optimizer_options().convergence_metric);
419 throw std::invalid_argument(
420 std::format(
"[Matter] unknown convergence_metric: {}",
421 params.optimizer_options().convergence_metric));
424 VectorXd difference(
const VectorXd &a,
const VectorXd &b) {
425 return m_matter.
pbcV(a - b);
427 VectorXd getMasses()
const override {
429 const auto mask = m_matter.
getFree();
433 if (mask.row(i).sum() > 0.5) {
439 bool getPeriodic()
const override {
return m_matter.
getPeriodic(); }
440 void minimumImage(Eigen::Ref<Eigen::Vector3d> dr)
const override {
442 m.row(0) = dr.transpose();
444 dr = m.row(0).transpose();
450 bool quiet,
bool writeMovie,
bool checkpoint,
451 std::string prefixMovie,
452 std::string prefixCheckpoint,
453 std::vector<readcon::ConFrame> *outFrames) {
455 auto objf = std::make_shared<MatterObjectiveFunction>(matter, params);
459 std::ostringstream min;
461 std::string minDatFilename = prefixMovie +
".dat";
462 auto write_movie_frame = [&](uint64_t frameIndex,
bool append,
467 metadata.
scalars.push_back({
"step_size", stepSize});
468 metadata.
scalars.push_back({
"convergence", objf->getConvergence()});
474 QUILL_LOG_WARNING(m_log,
"Failed to write movie frame {}", min.str());
479 std::ofstream minDat(minDatFilename,
480 append ? (std::ios::binary | std::ios::app)
484 minDat <<
"iteration\tstep_size\tconvergence\tenergy\n";
486 minDat << std::format(
"{}\t{:.5e}\t{:.5e}\t{:.6f}\n", frameIndex,
487 stepSize, objf->getConvergence(),
492 if (writeMovie || outFrames) {
493 write_movie_frame(0,
false, 0.0);
498 QUILL_LOG_DEBUG(m_log,
"{} {:10s} {:14s} {:18s} {:13s}\n",
"[Matter]",
502 QUILL_LOG_DEBUG(m_log,
"{} {:10} {:14.5e} {:18.5e} {:13.5f}\n",
503 "[Matter]", iteration, 0.0, objf->getConvergence(),
507 while (!objf->isConverged() &&
520 QUILL_LOG_DEBUG(m_log,
"{} {:10} {:14.5e} {:18.5e} {:13.5f}",
521 "[Matter]", iteration, stepSize, objf->getConvergence(),
525 if (writeMovie || outFrames) {
526 write_movie_frame(
static_cast<uint64_t
>(iteration),
true, stepSize);
530 std::ostringstream chk;
531 chk << prefixCheckpoint <<
"_cp";
533 QUILL_LOG_WARNING(m_log,
"Failed to write checkpoint {}", chk.str());
538 if (iteration == 0) {
540 QUILL_LOG_DEBUG(m_log,
"{} {:10} {:14.5e} {:18.5e} {:13.5f}",
541 "[Matter]", iteration, 0.0, objf->getConvergence(),
545 return objf->isConverged();
double matDot(const AtomMatrix &a, const AtomMatrix &b)
SIMD-optimized dot product for contiguous Eigen matrices.
Eigen::Matrix< double, Eigen::Dynamic, 3, eOnStorageOrder > AtomMatrix
#define EONC_LOG_ERROR(...)
#define EONC_LOG_WARNING(...)
#define EONC_LOG_INFO(...)
#define EONC_LOG_CRITICAL(...)
The optimizer class is used to serve as an abstract class for all optimizers, as well as to call an o...
void pollCancel(const char *site) const
const AtomMatrix & getPositions() const
VectorXd getForcesFreeV() const
void setPositions(const AtomMatrix &pos)
AtomMatrix getFree() const
bool getPeriodic() const noexcept
void setPositionsFreeV(const VectorXd &pos)
long int numberOfAtoms() const
AtomMatrix pbc(const AtomMatrix &diff) const
VectorXd getPositionsFreeV() const
void setAtomIndex(long int atom, std::int64_t index)
VectorXd pbcV(const VectorXd &diff) const
Eigen::Matrix< double, Eigen::Dynamic, 1 > getMasses() const
double distance(long index1, long index2) const
double getPotentialEnergy() const
long mapFileRow(long file_row) const
Map a CON file-order row onto the Matter row after matter_order.
long int numberOfFreeAtoms() const
AtomMatrix getPositionsCopy() const
std::int64_t getAtomIndex(long int atom) const
.con column-5 index (pre-grouping); public for I/O / bindings.
const AtomMatrix & getForces() const
void setFileToMatter(std::vector< long > map)
io::IoStatus matter2con(std::string filename, bool append=false, const io::ConFrameMetadata *metadata=nullptr)
int getFixed(long int atom) const
1 if every Cartesian axis of the atom is fixed, else 0.
io::IoStatus con2matter(std::string filename)
double maxForce(void) const
const saddle_search_options_t & saddle_search_options() const
const debug_options_t & debug_options() const
const structure_comparison_options_t & structure_comparison_options() const
const optimizer_options_t & optimizer_options() const
long lastAtom(const Matter *matter)
const char DISP_LISTED_ATOMS[]
const char DISP_NOT_FCC_OR_HCP[]
const char DISP_MIN_COORDINATED[]
long cnaEpiCenter(const Matter *matter, double neighborCutoff)
const char DISP_LAST_ATOM[]
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 maxAtomMotion(const AtomMatrix v1)
std::unique_ptr< Optimizer > mkOptim(std::shared_ptr< ObjectiveFunction > a_objf, OptType a_otype, const Parameters &a_params)
VectorXd loadMasses(std::string filename, int nAtoms)
bool applyClientDisplacement(Matter &target, const Matter &initial, const Parameters ¶ms, AtomMatrix *modeOut)
bool relaxMatter(Matter &matter, const Parameters ¶ms, bool quiet=false, bool writeMovie=false, bool checkpoint=false, std::string prefixMovie=std::string(), std::string prefixCheckpoint=std::string(), std::vector< readcon::ConFrame > *outFrames=nullptr)
std::string getRelevantFile(std::string filename)
bool loadOrSynthesizeDisplacement(Matter &target, const Matter &initial, const std::string &displacementPath, const std::string &modePath, double scale)
AtomMatrix loadMode(FILE *modeFile, int nAtoms)
void saveMode(FILE *modeFile, std::shared_ptr< Matter > matter, AtomMatrix mode)
Write a mode; constrained axes are emitted as 0.
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...
std::vector< int > split_string_int(std::string s, std::string delim)
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...
void requireKnownConvergenceMetric(std::string_view metric, std::string_view context)
Throws std::invalid_argument naming context when metric is unrecognized.
std::optional< std::string > enterJobDirectory(std::string_view jobPath)
Enter jobPath as the working directory.
void getTime(double *real, double *user, double *sys)
AtomMatrix makeOrthogonal(const AtomMatrix v1, const AtomMatrix v2)
bool existsFile(std::string filename)
readcon::ConFrame matterToConFrame(Matter &m, const ConFrameMetadata *metadata)
Build a single stamped ConFrame from Matter (same builder as matter2con).
constexpr bool io_ok(IoStatus s) noexcept
double gaussRandom(double avg, double std)
RAII resource manager for the ARTn C library with global synchronization.
bool write_deprecated_outs
RAII helper for class-scoped logging.
std::string convergence_metric_label
std::string displace_type