Loading...
Searching...
No Matches
GlobalOptimizationJob.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*/
13#include "eon/EonLogger.h"
14
15#include "eon/Dynamics.h"
16#include "eon/HelperFunctions.h"
17#include <format>
18#include <memory>
19#include <stdexcept>
20
21#include <algorithm>
22#include <cmath>
23
24namespace eonc {
25
26std::vector<std::string> GlobalOptimizationJob::run() {
27 std::string reactant_passed =
28 eonc::helpers::getRelevantFile(params.main_options().conFilename);
29 std::vector<std::string> returnFiles;
30 auto matter_cur = std::make_unique<Matter>(pot, params);
31 auto matter_hop = std::make_unique<Matter>(pot, params);
32 if (!eonc::io::io_ok(matter_cur->con2matter(reactant_passed))) {
33 QUILL_LOG_CRITICAL(log, "Failed to load {}", reactant_passed);
34 throw std::runtime_error("failed to load " + reactant_passed);
35 }
36 bool converged;
37 long nstep = params.global_optimization_options().steps;
38 AtomMatrix rat_t(matter_cur->numberOfAtoms(), 3);
39 QUILL_LOG_DEBUG(log, "\nBeginning minima hopping of {}",
40 reactant_passed.c_str());
41 QUILL_LOG_TRACE_L1(log, "fcalls= {}", matter_cur->getForceCalls());
42 QUILL_LOG_TRACE_L1(log, "epot= {:24.15E}", matter_cur->getPotentialEnergy());
43 converged =
44 matter_cur->relax(false, params.debug_options().write_movies,
45 params.main_options().checkpoint, "min", "matter_cur");
46 QUILL_LOG_DEBUG(log, "converged {}", (converged) ? "TRUE" : "FALSE");
47 earr.push_back(matter_cur->getPotentialEnergy());
48 *matter_hop = *matter_cur;
50 for (long istep = 1; istep <= nstep; istep++) {
51 // hoppingStep attempts to hop into a new state followed by a minimization
52 hoppingStep(istep, *matter_cur, *matter_hop);
53 // decisionStep decides to accept or reject this step if it escaped
54 decisionStep(*matter_cur, *matter_hop);
55 // analyzing what happened in this step if it escaped
56 analyze(*matter_cur, *matter_hop);
57 // reporting useful information about this hop
58 report(*matter_hop);
59 if (matter_cur->getPotentialEnergy() <
60 params.global_optimization_options().target_energy)
61 break;
62 }
63 for (size_t i = 0; i < earr.size(); i++) {
64 double earrim1;
65 if (i == 0) {
66 earrim1 = earr[0];
67 } else {
68 earrim1 = earr[i - 1];
69 }
70 earrfile << std::format("{:5} {:15.5f} {:15.5f} {:15.5f} ", i + 1,
71 earr[i], earr[i] - earr[0], earr[i] - earrim1);
72 }
73 return returnFiles;
74} // end of GlobalOptimizationJob::run
75
76void GlobalOptimizationJob::analyze(Matter &matter_cur, Matter &matter_hop) {
77 if (escapeResult == "failure") {
78 hoppingResult = "same";
79 return;
80 }
81 double epot = matter_hop.getPotentialEnergy();
82 size_t jlo = hunt(epot);
83 QUILL_LOG_TRACE_L1(log, "REZA: {}", jlo);
84 if (std::abs(epot - earr[jlo]) <
85 params.structure_comparison_options().energy_difference) {
86 hoppingResult = "already_visited";
87 } else {
88 hoppingResult = "new";
89 }
90 if (decisionResult == "accepted") {
91 double epot_hop = matter_hop.getPotentialEnergy();
92 matter_cur = matter_hop;
93 size_t jlo = hunt(matter_hop.getPotentialEnergy());
94 if (hoppingResult == "new" && jlo == 0 && epot_hop < earr[0]) {
95 QUILL_LOG_DEBUG(log,
96 "new lowest: nlmin, epot_hop, dE {:7d} {:15.5f} {:10.5f}",
97 1, epot_hop, epot_hop - earr[0]);
98 }
99 insert(matter_cur);
100 } else if (decisionResult == "rejected") {
101 } else {
102 if (quill::Logger *trace = eonc::log::traceback()) {
103 log = trace;
104 QUILL_LOG_CRITICAL(
105 log,
106 "ERROR: new minimum is neither accepted nor rejected: client stops.");
107 }
108 throw std::runtime_error(
109 "[Global Optimization] new minimum is neither accepted nor rejected");
110 }
111}
112
114 Matter &matter_hop) {
115 double epot, epot_hop;
116 epot = matter_cur.getPotentialEnergy();
117 epot_hop = matter_hop.getPotentialEnergy();
118 if (std::abs(epot_hop - epot) <
119 params.structure_comparison_options().energy_difference) {
120 escapeResult = "failure";
121 } else {
122 escapeResult = "success";
123 }
124}
125
127 if (firstStep) {
128 firstStep = false;
129 return;
130 }
131 if (hoppingResult == "same") {
132 ekin *= beta1;
133 } else if (hoppingResult == "already_visited") {
134 ekin *= beta2;
135 } else if (hoppingResult == "new") {
136 ekin *= beta3;
137 } else {
138 if (quill::Logger *trace = eonc::log::traceback()) {
139 log = trace;
140 QUILL_LOG_CRITICAL(log,
141 "ERROR: client does not know what to do with ekin.");
142 QUILL_LOG_CRITICAL(log, "ERROR: client stops in applyMoveFeedbackMD.");
143 }
144 throw std::runtime_error(std::format(
145 "[Global Optimization] unknown hoppingResult: {}", hoppingResult));
146 }
147}
148
150 if (decisionResult == "accepted") {
151 ediff *= alpha1;
152 } else {
153 ediff *= alpha2;
154 }
155}
156
158 char C1, C2;
159 double ekin_p;
160 if (hoppingResult == "same") {
161 C1 = 'S';
162 C2 = '-';
163 ekin_p = ekin * beta1;
164 } else if (hoppingResult == "already_visited") {
165 C1 = 'O';
166 ekin_p = ekin * beta2;
167 } else if (hoppingResult == "new") {
168 C1 = 'N';
169 ekin_p = ekin * beta3;
170 } else {
171 C1 = '-';
172 ekin_p = ekin;
173 }
174 if (decisionResult == "accepted") {
175 C2 = 'A';
176 } else if (decisionResult == "rejected") {
177 C2 = 'R';
178 } else {
179 C2 = '-';
180 }
181 double epot_hop = matter_hop.getPotentialEnergy();
182 double temp = (2.0 * ekin_p / params.constants().kB);
183 double dt = params.dynamics_options().time_step;
184 monfile << std::format(
185 "{:15.5f} {:15.5f} {:11} {:12.2f} {}{} {:5} {:5}", epot_hop,
186 ediff, static_cast<size_t>(temp), dt, C1, C2, fcallsMove, fcallsRelax);
187}
188
190 Matter &matter_hop) {
191 decisionResult = "unknown";
192 examineEscape(matter_cur, matter_hop);
193 if (escapeResult == "failure") {
194 return;
195 }
196 if (params.global_optimization_options().decision_method == "npew") {
197 acceptRejectNPEW(matter_cur, matter_hop);
198 } else if (params.global_optimization_options().decision_method ==
199 "boltzmann") {
200 acceptRejectBoltzmann(matter_cur, matter_hop);
201 } else {
203 QUILL_LOG_CRITICAL(
204 log, "ERROR: accept/reject method not specified. client stops.");
205 throw std::invalid_argument(
206 std::format("[Global Optimization] unknown decision_method: {}",
207 params.global_optimization_options().decision_method));
208 }
210}
211
212// NPEW: non-probablistic energy window (used in minima hopping method)
214 Matter &matter_hop) {
215 if (matter_hop.getPotentialEnergy() <
216 matter_cur.getPotentialEnergy() + ediff) {
217 decisionResult = "accepted";
218 } else {
219 decisionResult = "rejected";
220 }
221}
222
224 Matter &matter_hop) {
225 double eTrial = matter_hop.getPotentialEnergy();
226 double eCurrent = matter_cur.getPotentialEnergy();
227
228 double deltaE = eTrial - eCurrent;
229 const double kB = params.constants().kB;
230 const double T = params.main_options().temperature;
231
232 double p;
233 if (deltaE <= 0.0) {
234 p = 1.0;
235 } else if (!(T > 0.0) || !(kB > 0.0)) {
236 p = 0.0;
237 } else {
238 p = std::exp(-deltaE / (kB * T));
239 }
240
241 if (eonc::rng::randomDouble(1.0) < p) {
242 decisionResult = "accepted";
243 } else {
244 decisionResult = "rejected";
245 }
246}
247
248void GlobalOptimizationJob::hoppingStep(long istep, Matter &matter_cur,
249 Matter &matter_hop) {
250 bool converged;
251 matter_hop = matter_cur;
252 long fcalls1 = matter_hop.getForceCalls();
253 if (params.global_optimization_options().move_method == "md") {
255 mdescape(matter_hop);
256 } else if (params.global_optimization_options().move_method == "random") {
257 randomMove(matter_hop);
258 }
259 long fcalls2 = matter_hop.getForceCalls();
260 hoppingResult = "unknown";
261 converged =
262 matter_hop.relax(true, params.debug_options().write_movies,
263 params.main_options().checkpoint, "min", "matter_hop");
264 QUILL_LOG_DEBUG(log, "converged {}", (converged) ? "TRUE" : "FALSE");
265 long fcalls3 = matter_hop.getForceCalls();
266 fcallsMove = fcalls2 - fcalls1;
267 fcallsRelax = fcalls3 - fcalls2;
268}
269
271 // create a random displacement
272 AtomMatrix displacement;
273 displacement.resize(matter.numberOfAtoms(), 3);
274 displacement.setZero();
275 int num = matter.numberOfAtoms();
276
277 for (int i = 0; i < num; i++) {
278 double disp = params.basin_hopping_options().displacement;
279 if (!matter.getFixed(i)) {
280 for (int j = 0; j < 3; j++) {
281 if (params.basin_hopping_options().displacement_distribution ==
282 "uniform") {
283 displacement(i, j) = eonc::rng::randomDouble(2 * disp) - disp;
284 } else if (params.basin_hopping_options().displacement_distribution ==
285 "gaussian") {
286 displacement(i, j) = eonc::rng::gaussRandom(0.0, disp);
287 } else {
289 QUILL_LOG_CRITICAL(log, "Unknown displacement_distribution");
290 throw std::invalid_argument(std::format(
291 "[Global Optimization] unknown displacement_distribution: {}",
292 params.basin_hopping_options().displacement_distribution));
293 }
294 }
295 }
296 }
297 matter.setPositions(matter.getPositions() + displacement);
298}
299
301 int nmd;
302 double ekinc, epot, etot, epot0, etot0;
303 auto dyn = std::make_unique<Dynamics>(&matter, params);
304 velopt(matter);
305 epot = matter.getPotentialEnergy();
306 ekinc = matter.getKineticEnergy();
307 etot = ekinc + epot;
308 epot0 = epot;
309 etot0 = etot;
310 size_t nummax = 0, nummin = 0;
311 double enmin1 = 0.0, enmin2 = 0.0, en0000 = 0.0;
312 double econs_max = -1.E100, econs_min = 1.E100, devcon;
313 bool md_presumably_escaped = false;
314 QUILL_LOG_DEBUG(log, "MD {:5d} {:20.10E} {:15.5E} {:15.5E} ", 0,
315 epot - epot0, ekinc, etot - etot0);
316 nmd = 1000;
317 for (int imd = 1; imd <= nmd; imd++) {
318 enmin2 = enmin1;
319 enmin1 = en0000;
320 dyn->velocityVerlet();
321 epot = matter.getPotentialEnergy();
322 ekinc = matter.getKineticEnergy();
323 etot = ekinc + epot;
324 en0000 = epot - epot0;
325 if (enmin1 > enmin2 && enmin1 > en0000)
326 nummax += 1;
327 if (enmin1 < enmin2 && enmin1 < en0000)
328 nummin += 1;
329 QUILL_LOG_TRACE_L1(log,
330 "MD {:5d} {:15.5f} {:15.5f} {:12.2E} {:4} {:4}",
331 imd, epot - epot0, ekinc, etot - etot0, nummax, nummin);
332 econs_max = std::max(econs_max, ekinc + epot);
333 econs_min = std::min(econs_min, ekinc + epot);
334 if (nummin >= static_cast<size_t>(mdmin)) {
335 if (nummax != nummin)
336 QUILL_LOG_WARNING(log, "WARNING: iproc,nummin,nummax {} {}", nummin,
337 nummax);
338 md_presumably_escaped = true;
339 break;
340 }
341 } // end of loop over imd
342 devcon = econs_max - econs_min;
343 if (md_presumably_escaped) {
344 devcon = devcon / static_cast<double>(matter.numberOfFreeAtoms() * 3);
345 if (devcon / ekin < 2.E-3) {
347 } else {
349 }
350 } else {
351 QUILL_LOG_DEBUG(log, "TOO MANY MD STEPS ");
353 }
354}
355
357 AtomMatrix vat(matter.numberOfAtoms(), 3);
358 double tt1, tt2, tt3, vtot[3];
359 int iat;
360 vtot[0] = 0.0;
361 vtot[1] = 0.0;
362 vtot[2] = 0.0;
363 for (iat = 0; iat < matter.numberOfAtoms(); iat++) {
367 vat(iat, 0) = (tt1 - 0.5) * 2.0;
368 vat(iat, 1) = (tt2 - 0.5) * 2.0;
369 vat(iat, 2) = (tt3 - 0.5) * 2.0;
370 vtot[0] += vat(iat, 0);
371 vtot[1] += vat(iat, 1);
372 vtot[2] += vat(iat, 2);
373 }
374 QUILL_LOG_DEBUG(log, "Linear momentum {:15.5E} {:15.5E} {:15.5E} ",
375 vtot[0], vtot[1], vtot[2]);
376 vtot[0] /= matter.numberOfAtoms();
377 vtot[1] /= matter.numberOfAtoms();
378 vtot[2] /= matter.numberOfAtoms();
379 for (iat = 0; iat < matter.numberOfAtoms(); iat++) {
380 vat(iat, 0) -= vtot[0];
381 vat(iat, 1) -= vtot[1];
382 vat(iat, 2) -= vtot[2];
383 }
384 matter.setVelocities(vat);
385 long nFreeCoords = matter.numberOfFreeAtoms() * 3;
386 if (nFreeCoords <= 0) {
387 throw std::invalid_argument("GlobalOptimizationJob::velopt: no free atoms");
388 }
389 double kinE = matter.getKineticEnergy();
390 double kB = params.constants().kB;
391 double kinT = (2.0 * kinE / nFreeCoords / kB);
392 if (!(kinT > 0.0)) {
393 throw std::runtime_error(
394 "GlobalOptimizationJob::velopt: zero kinetic temperature");
395 }
396 double temperature = (2.0 * ekin / kB);
397 matter.setVelocities(vat * std::sqrt(temperature / kinT));
398}
399
401 double epot;
402 size_t jlo, jlo_insert;
403 epot = matter.getPotentialEnergy();
404 jlo = hunt(epot);
405 QUILL_LOG_DEBUG(log, "JLO= {} {:10.5f} ", jlo, std::abs(epot - earr[jlo]));
406 if (!(std::abs(epot - earr[jlo]) <
407 params.structure_comparison_options().energy_difference)) {
408 jlo_insert = jlo;
409 if (epot > earr[jlo])
410 jlo_insert++;
411 earr.insert(earr.begin() + jlo_insert, 1, epot);
412 }
413}
414
415size_t GlobalOptimizationJob::hunt(double epot) {
416 // epot is in interval [earr(jlo),earr(jlo+1)[ ; earr(0)=-Infinity ; earr(n+1)
417 // = Infinity
418 size_t jlo;
419 double de;
420 for (jlo = 0; jlo < earr.size(); jlo++)
421 if (epot < earr[jlo])
422 break;
423 if (jlo == earr.size())
424 jlo--;
425 de = std::abs(epot - earr[jlo]);
426 if (jlo > 0)
427 if (std::abs(epot - earr[jlo - 1]) < de)
428 jlo--;
429 return jlo;
430}
431
432} // namespace eonc
Eigen::Matrix< double, Eigen::Dynamic, 3, eOnStorageOrder > AtomMatrix
Definition Eigen.h:37
void examineEscape(Matter &, Matter &)
void decisionStep(Matter &, Matter &)
void acceptRejectNPEW(Matter &, Matter &)
void analyze(Matter &, Matter &)
void acceptRejectBoltzmann(Matter &, Matter &)
std::vector< std::string > run(void)
Virtual run; used solely for dynamic dispatch.
void hoppingStep(long, Matter &, Matter &)
std::shared_ptr< Potential > pot
Set when one Potential is shared across Matters, images, or a caller.
Definition Job.h:66
Parameters params
Definition Job.h:58
double getKineticEnergy() const
Definition Matter.cpp:632
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
void setPositions(const AtomMatrix &pos)
Definition Matter.cpp:420
long int numberOfAtoms() const
Definition Matter.cpp:343
long getForceCalls() const
Definition Matter.cpp:657
void setVelocities(const AtomMatrix &v)
Definition Matter.cpp:823
double getPotentialEnergy() const
Definition Matter.cpp:624
long int numberOfFreeAtoms() const
Definition Matter.cpp:653
int getFixed(long int atom) const
1 if every Cartesian axis of the atom is fixed, else 0.
Definition Matter.cpp:575
std::string getRelevantFile(std::string filename)
constexpr bool io_ok(IoStatus s) noexcept
Definition ConFileIO.h:38
quill::Logger * traceback() noexcept
Get or create the "_traceback" logger for traceback logging.
Definition EonLogger.h:155
double randomDouble()
double gaussRandom(double avg, double std)
RAII resource manager for the ARTn C library with global synchronization.
static dynamics_options_t & dynamics_options(Parameters &p)