Loading...
Searching...
No Matches
BasinHoppingJob.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
13#include "eon/EonLogger.h"
14#include <cmath>
15#include <format>
16#include <fstream>
17#include <stdexcept>
18#include <string>
19
20#include "eon/BaseStructures.h"
21#include "eon/BasinHoppingJob.h"
22#include "eon/Dynamics.h"
23#include "eon/HelperFunctions.h"
24#include "eon/JobResult.h"
26#include "eon/Optimizer.h"
27#include "eon/PotRegistry.h"
28#include "eon/Potential.h"
29
30namespace eonc {
31
32std::vector<std::string> BasinHoppingJob::run() {
33 bool swapMove;
34 double swap_accept = 0.0;
35 jump_count = 0; // count of jump movies
36 swap_count = 0; // count of swap moves
37 disp_count = 0; // count of displacement moves
38 // Quench tail may not run when stop_energy breaks first.
39 int quench_displacements = 0;
40 int consecutive_rejected_trials = 0;
41 double totalAccept = 0.0;
42 std::unique_ptr<Matter> minTrial = std::make_unique<Matter>(pot, params);
43 std::unique_ptr<Matter> swapTrial = std::make_unique<Matter>(pot, params);
44
45 std::string conFilename =
46 eonc::helpers::getRelevantFile(params.main_options().conFilename);
47 if (!eonc::io::io_ok(current->con2matter(conFilename))) {
48 QUILL_LOG_CRITICAL(log, "Failed to load {}", conFilename);
49 throw std::runtime_error("failed to load " + conFilename);
50 }
51
52 // Sanity Check
53 std::vector<long> Elements;
54 Elements = getElements(current.get());
55 if (params.basin_hopping_options().swap_probability > 0 &&
56 Elements.size() == 1) {
58 QUILL_LOG_CRITICAL(log,
59 "error: [Basin Hopping] swap move probability must be "
60 "zero if there is only one element type\n");
61 throw std::invalid_argument(
62 "[Basin Hopping] swap_probability must be zero with one element type");
63 }
64
65 double randomProb =
66 params.basin_hopping_options().initial_random_structure_probability;
67 if (randomProb > 0.0) {
68 QUILL_LOG_DEBUG(log, "generating random structure with probability {:.4f}",
69 randomProb);
70 }
71 double u = eonc::rng::random();
72 if (u < params.basin_hopping_options().initial_random_structure_probability) {
73 AtomMatrix randomPositions = current->getPositionsFree();
74 for (int i = 0; i < current->numberOfFreeAtoms(); i++) {
75 for (int j = 0; j < 3; j++) {
76 randomPositions(i, j) = eonc::rng::random();
77 }
78 }
79 randomPositions *= current->getCell();
80 current->setPositionsFree(randomPositions);
81
83 current, params.basin_hopping_options().push_apart_distance);
84 }
85
86 *trial = *current;
87 *minTrial = *current;
88
89 current->relax(true);
90
91 double currentEnergy = current->getPotentialEnergy();
92 double minimumEnergy = currentEnergy;
93
94 auto minimumEnergyStructure = std::make_shared<Matter>(pot, params);
95 *minimumEnergyStructure = *current;
96 int nsteps = params.basin_hopping_options().steps +
97 params.basin_hopping_options().quenching_steps;
98
99 QUILL_LOG_DEBUG(
100 log, "[Basin Hopping] {:4s} {:12s} {:12s} {:12s} {:4s} {:5s} {:5s}",
101 "step", "current", "trial", "global min", "fc", "ar", "md");
102 QUILL_LOG_DEBUG(
103 log, "[Basin Hopping] {:4s} {:12s} {:12s} {:12s} {:4s} {:5s} {:5s}",
104 "----", "-------", "-----", "----------", "--", "--", "--");
105
106 int recentAccept = 0;
107 double curDisplacement = params.basin_hopping_options().displacement;
108
109 for (int step = 0; step < nsteps; step++) {
110
111 // Swap or displace
112 if (eonc::rng::randomDouble(1.0) <
113 params.basin_hopping_options().swap_probability &&
114 step < params.basin_hopping_options().steps) {
115 *swapTrial = *current;
116 randomSwap(swapTrial.get());
117 swapMove = true;
118 *minTrial = *swapTrial;
119 } else {
120 AtomMatrix displacement;
121 displacement = displaceRandom(curDisplacement);
122 if (step >= params.basin_hopping_options().steps) {
123 quench_displacements++;
124 }
125
126 trial->setPositions(current->getPositions() + displacement);
127 swapMove = false;
129 trial, params.basin_hopping_options().push_apart_distance);
130
131 *minTrial = *trial;
132 }
133
134 if (params.debug_options().write_movies) {
135 if (!eonc::io::io_ok(trial->matter2con("trials", true))) {
136 QUILL_LOG_WARNING(log, "Failed to append trials movie frame");
137 }
138 }
139
140 minTrial->relax(true);
141
142 double deltaE = minTrial->getPotentialEnergy() - currentEnergy;
143 double p = 0.0;
144 if (step >= params.basin_hopping_options().steps) {
145 if (deltaE <= 0.0) {
146 p = 1.0;
147 }
148 } else {
149 // Divide only for an uphill hop at positive temperature.
150 p = metropolisProbability(deltaE, params.constants().kB,
151 params.main_options().temperature);
152 }
153
154 bool accepted = false;
155 if (eonc::rng::randomDouble(1.0) < p) {
156 accepted = true;
157 if (params.basin_hopping_options().significant_structure) {
158 *current = *minTrial;
159 } else if (swapMove) {
160 *current = *swapTrial;
161 } else {
162 *current = *trial;
163 }
164 if (swapMove) {
165 swap_accept += 1;
166 }
167 if (step < params.basin_hopping_options().steps) {
168 totalAccept += 1;
169 recentAccept += 1;
170 }
171
172 currentEnergy = minTrial->getPotentialEnergy();
173
174 if (currentEnergy < minimumEnergy) {
175 minimumEnergy = currentEnergy;
176 *minimumEnergyStructure = *minTrial;
177 if (!eonc::io::io_ok(minimumEnergyStructure->matter2con("min.con"))) {
178 QUILL_LOG_WARNING(log, "Failed to write min.con");
179 }
180 }
181
182 if (params.basin_hopping_options().write_unique) {
183 bool newStructure = true;
184 for (unsigned int i = 0; i < uniqueEnergies.size(); i++) {
185 // if minTrial has a different energy or a different structure
186 // it is new, otherwise it is old
187 if (std::fabs(currentEnergy - uniqueEnergies[i]) <
188 params.structure_comparison_options().energy_difference) {
189 Matter probe = *current;
190 if (probe.compare(*uniqueStructures[i],
191 params.structure_comparison_options()
192 .indistinguishable_atoms)) {
193 newStructure = false;
194 }
195 }
196 }
197
198 if (newStructure) {
199 uniqueEnergies.push_back(currentEnergy);
200 auto currentCopy = std::make_shared<Matter>(pot, params);
201 *currentCopy = *current;
202 uniqueStructures.push_back(currentCopy);
203
204 char fname[128];
205 snprintf(fname, 128, "min_%.5i.con", step + 1);
206 if (!eonc::io::io_ok(current->matter2con(fname))) {
207 QUILL_LOG_WARNING(log, "Failed to write {}", fname);
208 }
209 returnFiles.push_back(fname);
210
211 snprintf(fname, 128, "energy_%.5i.dat", step + 1);
212 returnFiles.push_back(fname);
213 {
214 std::ofstream fh(fname);
215 if (fh)
216 fh << std::format("{:.10e}\n", currentEnergy);
217 }
218 }
219 }
220
221 consecutive_rejected_trials = 0; // STC: I think this should go here.
222 } else {
223 consecutive_rejected_trials++;
224 }
225
226 if (params.debug_options().write_movies) {
227 if (!eonc::io::io_ok(minTrial->matter2con("movie", true))) {
228 QUILL_LOG_WARNING(log, "Failed to append basin-hopping movie frame");
229 }
230 }
231
232 if (minimumEnergy < params.basin_hopping_options().stop_energy) {
233 break;
234 }
235
236 if (consecutive_rejected_trials ==
237 params.basin_hopping_options().jump_max &&
238 step < params.basin_hopping_options().steps) {
239 consecutive_rejected_trials = 0;
240 AtomMatrix jump;
241 for (int j = 0; j < params.basin_hopping_options().jump_steps; j++) {
242 jump_count++;
243 jump = displaceRandom(curDisplacement);
244 current->setPositions(current->getPositions() + jump);
245 // Only a minimized jump is a basin. The raw geometry must not become
246 // the Metropolis reference or the stored global minimum.
247 if (params.basin_hopping_options().significant_structure) {
249 current, params.basin_hopping_options().push_apart_distance);
250 current->relax(true);
251 currentEnergy = current->getPotentialEnergy();
252 if (currentEnergy < minimumEnergy) {
253 minimumEnergy = currentEnergy;
254 *minimumEnergyStructure = *current;
255 }
256 }
257 }
258 }
259
260 int nadjust = params.basin_hopping_options().adjust_period;
261 double adjustFraction = params.basin_hopping_options().adjust_fraction;
262 // A zero period is not an interval; the modulo would divide by zero.
263 if (nadjust != 0 && (step + 1) % nadjust == 0 &&
264 params.basin_hopping_options().adjust_displacement) {
265 double recentRatio =
266 static_cast<double>(recentAccept) / static_cast<double>(nadjust);
267 if (recentRatio > params.basin_hopping_options().target_ratio) {
268 curDisplacement *= 1.0 + adjustFraction;
269 } else {
270 curDisplacement *= 1.0 - adjustFraction;
271 }
272
273 recentAccept = 0;
274 }
275 }
276 /* Save Results */
277
278 std::string resultsFilename("results.dat");
279
280 if (params.debug_options().write_movies) {
281 std::string movieFilename("movie.con");
282 returnFiles.push_back(movieFilename);
283 }
284
285 {
287 RunStatus::GOOD, params.potential_options().potential,
288 pots().total_force_calls(), true, minimumEnergy);
289 env.provenance = provenanceForJob(params);
290 env.job_type = "basin_hopping";
291 env.random_seed = params.main_options().randomSeed;
292 env.extras.emplace_back("minimum_energy", minimumEnergy);
293 const double nsteps_ratio = params.basin_hopping_options().steps;
294 env.extras.emplace_back("acceptance_ratio",
295 nsteps_ratio ? totalAccept / nsteps_ratio : 0.0);
296 if (params.basin_hopping_options().swap_probability > 0) {
297 env.extras.emplace_back(
298 "swap_acceptance_ratio",
299 swap_count ? swap_accept / static_cast<double>(swap_count) : 0.0);
300 }
301 env.extras.emplace_back(
302 "total_normal_displacement_steps",
303 static_cast<double>(disp_count - jump_count - quench_displacements));
304 env.extras.emplace_back("total_jump_steps",
305 static_cast<double>(jump_count));
306 env.extras.emplace_back("total_swap_steps",
307 static_cast<double>(swap_count));
308 env.writeResultsDat(resultsFilename);
309 returnFiles.push_back(resultsFilename);
310 }
311
312 std::string productFilename("min.con");
313 if (eonc::io::io_ok(minimumEnergyStructure->matter2con(productFilename))) {
314 returnFiles.push_back(productFilename);
315 } else {
316 QUILL_LOG_ERROR(log, "Failed to write {}", productFilename);
317 }
318
319 // minTrial and swapTrial automatically cleaned up by unique_ptr
320 return returnFiles;
321}
322
323double BasinHoppingJob::metropolisProbability(double de, double kB,
324 double temperature) {
325 if (!(de > 0.0)) {
326 return 1.0;
327 }
328 if (!(temperature > 0.0) || !(kB > 0.0)) {
329 return 0.0;
330 }
331 return std::exp(-de / (kB * temperature));
332}
333
335 disp_count++;
336 // Create a random displacement
337 AtomMatrix displacement;
338 displacement.resize(trial->numberOfAtoms(), 3);
339 displacement.setZero();
340 VectorXd distvec = calculateDistanceFromCenter(current.get());
341 // Coincident atoms share a zero radius. Dividing by it writes NaN and
342 // the hop cannot leave the center. Those atoms are the outer shell, so
343 // the step stays the unscaled displacement.
344 const double radius = distvec.size() > 0 ? distvec.maxCoeff() : 0.0;
345 int num = trial->numberOfAtoms();
346 int m = 0;
347 if (params.basin_hopping_options().single_atom_displace) {
348 m = eonc::rng::randomInt(0, trial->numberOfAtoms() - 1);
349 num = m + 1;
350 }
351
352 for (int i = m; i < num; i++) {
353 double dist = distvec(i);
354 double disp = 0.0; // displacement size, possibly scaled
355
356 if (!trial->getFixed(i)) {
357 const std::string &algorithm =
358 params.basin_hopping_options().displacement_algorithm;
359 if (algorithm == "standard") {
360 disp = curDisplacement;
361 }
362 // scale displacement linearly with the particle radius
363 else if (algorithm == "linear") {
364 disp =
365 radius == 0.0 ? curDisplacement : curDisplacement * (dist / radius);
366 }
367 // scale displacement quadratically with the particle radius
368 else if (algorithm == "quadratic") {
369 if (radius == 0.0) {
370 disp = curDisplacement;
371 } else {
372 const double scale = dist / radius;
373 disp = curDisplacement * scale * scale;
374 }
375 } else {
376 if (quill::Logger *trace = eonc::log::traceback()) {
377 log = trace;
378 QUILL_LOG_CRITICAL(log, "Unknown displacement_algorithm\n");
379 }
380 throw std::invalid_argument(
381 std::format("[Basin Hopping] unknown displacement_algorithm: {}",
382 params.basin_hopping_options().displacement_algorithm));
383 }
384 for (int j = 0; j < 3; j++) {
385 if (params.basin_hopping_options().displacement_distribution ==
386 "uniform") {
387 displacement(i, j) = eonc::rng::randomDouble(2 * disp) - disp;
388 } else if (params.basin_hopping_options().displacement_distribution ==
389 "gaussian") {
390 displacement(i, j) = eonc::rng::gaussRandom(0.0, disp);
391 } else {
392 if (quill::Logger *trace = eonc::log::traceback()) {
393 log = trace;
394 QUILL_LOG_CRITICAL(log, "Unknown displacement_distribution\n");
395 }
396 throw std::invalid_argument(std::format(
397 "[Basin Hopping] unknown displacement_distribution: {}",
398 params.basin_hopping_options().displacement_distribution));
399 }
400 }
401 }
402 }
403 return displacement;
404}
405
407 swap_count++;
408 std::vector<long> Elements;
409 Elements = getElements(matter);
410
411 long ela;
412 long elb;
413 long ia = eonc::rng::randomInt(0, Elements.size() - 1);
414 ela = Elements.at(ia);
415 Elements.erase(Elements.begin() + ia);
416
417 long ib = eonc::rng::randomInt(0, Elements.size() - 1);
418 elb = Elements.at(ib);
419
420 int changera = 0;
421 int changerb = 0;
422
423 changera = eonc::rng::randomInt(0, matter->numberOfAtoms() - 1);
424 int guard = 0;
425 while ((matter->getAtomicNr(changera) != ela || matter->getFixed(changera)) &&
426 guard < 10000) {
427 changera = eonc::rng::randomInt(0, matter->numberOfAtoms() - 1);
428 guard++;
429 }
430 changerb = eonc::rng::randomInt(0, matter->numberOfAtoms() - 1);
431 guard = 0;
432 while ((matter->getAtomicNr(changerb) != elb || matter->getFixed(changerb) ||
433 changerb == changera) &&
434 guard < 10000) {
435 changerb = eonc::rng::randomInt(0, matter->numberOfAtoms() - 1);
436 guard++;
437 }
438 if (matter->getAtomicNr(changera) != ela || matter->getFixed(changera) ||
439 matter->getAtomicNr(changerb) != elb || matter->getFixed(changerb)) {
440 return;
441 }
442
443 double posax = matter->getPosition(changera, 0);
444 double posay = matter->getPosition(changera, 1);
445 double posaz = matter->getPosition(changera, 2);
446
447 matter->setPosition(changera, 0, matter->getPosition(changerb, 0));
448 matter->setPosition(changera, 1, matter->getPosition(changerb, 1));
449 matter->setPosition(changera, 2, matter->getPosition(changerb, 2));
450
451 matter->setPosition(changerb, 0, posax);
452 matter->setPosition(changerb, 1, posay);
453 matter->setPosition(changerb, 2, posaz);
454}
455
456std::vector<long> BasinHoppingJob::getElements(Matter *matter) {
457 // Z is 0..118. A 118-slot table stores 118 one past the end.
458 constexpr int kElementSlots = 119;
459 std::array<int, kElementSlots> allElements{};
460 std::vector<long> elements;
461
462 for (long y = 0; y < matter->numberOfAtoms(); ++y) {
463 if (!matter->getFixed(y)) {
464 const long z = matter->getAtomicNr(y);
465 if (z >= 0 && z < kElementSlots) {
466 allElements[static_cast<size_t>(z)] = 1;
467 }
468 }
469 }
470
471 for (int i = 0; i < kElementSlots; ++i) {
472 if (allElements[static_cast<size_t>(i)] != 0) {
473 elements.push_back(i);
474 }
475 }
476
477 return elements;
478}
479
481 AtomMatrix pos = matter->getPositions();
482 Vector3d cen(0, 0, 0);
483 int num = matter->numberOfAtoms();
484
485 cen = pos.colwise().sum() / static_cast<double>(num);
486
487 VectorXd dist(num);
488
489 for (int n = 0; n < num; n++) {
490 pos.row(n) -= cen;
491 dist(n) = pos.row(n).norm();
492 }
493
494 return dist;
495}
496
497} // namespace eonc
Eigen::Matrix< double, Eigen::Dynamic, 3, eOnStorageOrder > AtomMatrix
Definition Eigen.h:37
The optimizer class is used to serve as an abstract class for all optimizers, as well as to call an o...
std::vector< std::string > returnFiles
std::vector< std::shared_ptr< Matter > > uniqueStructures
VectorXd calculateDistanceFromCenter(Matter *matter)
std::shared_ptr< Matter > current
std::vector< long > getElements(Matter *matter)
void randomSwap(Matter *matter)
AtomMatrix displaceRandom(double maxDisplacement)
std::vector< double > uniqueEnergies
eonc::log::Scoped log
static double metropolisProbability(double de, double kB, double temperature)
Metropolis weight for energy change de.
std::shared_ptr< Matter > trial
std::vector< std::string > run(void) override
Virtual run; used solely for dynamic dispatch.
PotRegistry & pots() noexcept
Definition Job.h:109
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
void setPosition(long int atom, int axis, double position)
Definition Matter.cpp:360
const AtomMatrix & getPositions() const
Definition Matter.cpp:378
bool compare(const Matter &matter, bool indistinguishable=false)
Definition Matter.cpp:254
long int numberOfAtoms() const
Definition Matter.cpp:343
double getPosition(long int atom, int axis) const
Definition Matter.cpp:354
long getAtomicNr(long int atom) const
Definition Matter.cpp:565
int getFixed(long int atom) const
1 if every Cartesian axis of the atom is fixed, else 0.
Definition Matter.cpp:575
void pushApart(std::shared_ptr< Matter > m1, double minDistance)
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 random(long newSeed=0)
long randomInt(int lower, int upper)
double randomDouble()
double gaussRandom(double avg, double std)
RAII resource manager for the ARTn C library with global synchronization.
JobResultProvenance provenanceForJob(const Parameters &params)
Optimizer backend, engine identity, rgpot pin, and xts ABI from a job.
static JobResultEnvelope fromMinimization(RunStatus status, PotType pot, std::uint64_t fcalls, bool hasE, double energy)
Definition JobResult.h:251