Loading...
Searching...
No Matches
ReplicaExchangeJob.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/BaseStructures.h"
14#include "eon/Dynamics.h"
15#include "eon/HelperFunctions.h"
16#include "eon/Matter.h"
17#include "eon/PotCapabilities.h"
18#include "eon/RandomNumbers.h"
19#include "eon/SafeMath.h"
20
21#include <algorithm>
22#include <cmath>
23#include <format>
24#include <fstream>
25#include <stdexcept>
26#include <string>
27#include <thread>
28
29namespace eonc {
30
31std::vector<std::string> ReplicaExchangeJob::run() {
32 std::string posFilename =
33 eonc::helpers::getRelevantFile(params.main_options().conFilename);
34 pos = std::make_shared<Matter>(pot, params);
35 if (!eonc::io::io_ok(pos->con2matter(posFilename))) {
36 QUILL_LOG_CRITICAL(log, "Failed to load {}", posFilename);
37 throw std::runtime_error("failed to load " + posFilename);
38 }
39 static_cast<void>(runFromMatter(pos));
40 return returnFiles;
41}
42
43std::shared_ptr<Matter>
44ReplicaExchangeJob::runFromMatter(std::shared_ptr<Matter> initial) {
45 if (!initial) {
46 throw std::runtime_error("ReplicaExchangeJob::runFromMatter: null Matter");
47 }
48 pos = initial;
49 pos->setPotential(pot);
50
52 if (rex.replicas < 1) {
53 throw std::invalid_argument(
54 "ReplicaExchangeJob: replica_exchange.replicas must be >= 1");
55 }
56 if (rex.temperature_low <= 0.0) {
57 rex.temperature_low = params.main_options().temperature > 0.0
58 ? params.main_options().temperature
59 : 300.0;
60 }
61 if (rex.temperature_high <= rex.temperature_low) {
62 rex.temperature_high = rex.temperature_low * 1.5;
63 }
64
65 long samplingSteps =
66 static_cast<long>(params.replica_exchange_options().sampling_time /
67 params.dynamics_options().time_step +
68 0.5);
69 long exchangePeriodSteps =
70 static_cast<long>(params.replica_exchange_options().exchange_period /
71 params.dynamics_options().time_step +
72 0.5);
73 const double kB = params.constants().kB;
74 if (samplingSteps <= 0)
75 samplingSteps = 1;
76 if (exchangePeriodSteps <= 0)
77 exchangePeriodSteps = 1;
78
79 QUILL_LOG_DEBUG(log, "Running Replica Exchange");
80
81 const long refForceCalls = static_cast<long>(pot->forceCallCounter.load());
82
83 const long nReplicas = params.replica_exchange_options().replicas;
84 std::vector<std::shared_ptr<Matter>> replica(nReplicas);
85 std::vector<std::unique_ptr<Dynamics>> replicaDynamics(nReplicas);
86
87 // Per-image potentials: each replica gets its own potential instance when
88 // the potential requires it (e.g. ML potentials with internal state)
89 const bool perImage = pot->needsPerImageInstance();
90 // Per-image potentials start at zero calls; the shared one is counted
91 // from refForceCalls.
92 std::vector<std::shared_ptr<Potential>> replicaPots;
93 for (long i = 0; i < nReplicas; i++) {
94 auto replicaPot =
96 params.potential_options().potential, params, *runtime_))
97 : pot;
98 if (perImage) {
99 replicaPots.push_back(replicaPot);
100 }
101 replica[i] = std::make_shared<Matter>(replicaPot, params);
102 *replica[i] = *pos;
103 replica[i]->setPotential(replicaPot);
104 replicaDynamics[i] = std::make_unique<Dynamics>(replica[i].get(), params);
105 }
106
107 std::vector<double> replicaTemperature(nReplicas);
108
109 QUILL_LOG_DEBUG(log, "Temperature distribution:");
110 if (nReplicas < 2) {
111 replicaTemperature[0] = params.replica_exchange_options().temperature_low;
112 replicaDynamics[0]->setTemperature(replicaTemperature[0]);
113 replicaDynamics[0]->setThermalVelocity();
114 } else if (params.replica_exchange_options().temperature_distribution ==
115 "linear") {
116 for (long i = 0; i < nReplicas; i++) {
117 replicaTemperature[i] =
118 params.replica_exchange_options().temperature_low +
119 static_cast<double>(i) / static_cast<double>(nReplicas - 1) *
120 (params.replica_exchange_options().temperature_high -
121 params.replica_exchange_options().temperature_low);
122 replicaDynamics[i]->setTemperature(replicaTemperature[i]);
123 replicaDynamics[i]->setThermalVelocity();
124 }
125 } else if (params.replica_exchange_options().temperature_distribution ==
126 "exponential") {
127 double kTemp = std::log(params.replica_exchange_options().temperature_high /
128 params.replica_exchange_options().temperature_low) /
129 static_cast<double>(nReplicas - 1);
130 for (long i = 0; i < nReplicas; i++) {
131 replicaTemperature[i] =
132 params.replica_exchange_options().temperature_low *
133 std::exp(kTemp * static_cast<double>(i));
134 replicaDynamics[i]->setTemperature(replicaTemperature[i]);
135 replicaDynamics[i]->setThermalVelocity();
136 QUILL_LOG_DEBUG(log, "replica: {} temperature {:.0f}", i + 1,
137 replicaTemperature[i]);
138 }
139 } else {
140 throw std::invalid_argument(
141 "replica_exchange.temperature_distribution must be linear or "
142 "exponential");
143 }
144
145 QUILL_LOG_DEBUG(
146 log, "Replica Exchange sampling for {:.0f} fs; {} steps; {} replicas.",
147 params.replica_exchange_options().sampling_time * 10.18, samplingSteps,
148 params.replica_exchange_options().replicas);
149
150 // Parallel replica dynamics when enabled and potential supports it
151 const bool canParallel = params.main_options().parallel &&
152 (eonc::potAllowsSharedInstance(*pot) || perImage);
153
154 for (long step = 1; step <= samplingSteps; step++) {
155 if (canParallel && nReplicas > 1) {
156 // Parallel: each replica runs its MD step in a separate thread
157 std::vector<std::thread> threads;
158 threads.reserve(nReplicas);
159 for (long i = 0; i < nReplicas; i++) {
160 threads.emplace_back([&, i] {
161 // New std::thread, new TLS ran2. Split the stream by replica and
162 // step so Langevin/Andersen noise is not identical across replicas.
163 const long userSeed = params.main_options().randomSeed;
164 const long base = (userSeed > 0) ? userSeed : 1;
165 eonc::rng::random(base + (step + 1) * 10007 + (i + 1));
166 replicaDynamics[i]->oneStep();
167 });
168 }
169 for (auto &t : threads) {
170 t.join();
171 }
172 } else {
173 for (long i = 0; i < nReplicas; i++) {
174 replicaDynamics[i]->oneStep();
175 }
176 }
177
178 // Metropolis replica exchange
179 if (nReplicas >= 2 && (step % exchangePeriodSteps) == 0) {
180 for (long trial = 0;
181 trial < params.replica_exchange_options().exchange_trials; trial++) {
182 long i = eonc::rng::randomInt(0, nReplicas - 2);
183 double energyLow = replica[i]->getPotentialEnergy();
184 double energyHigh = replica[i + 1]->getPotentialEnergy();
185 double kbTLow = kB * replicaTemperature[i];
186 double kbTHigh = kB * replicaTemperature[i + 1];
187 double pAcc =
188 std::min(1.0, std::exp((energyHigh - energyLow) *
189 (eonc::safemath::safe_recip(kbTHigh, 0.0) -
190 eonc::safemath::safe_recip(kbTLow, 0.0))));
191 double rnd = eonc::rng::randomDouble();
192 QUILL_LOG_INFO(log,
193 "step: {} trial swap, i {}, elow: {:.5f}, ehigh: "
194 "{:.5f}, pAcc: {:.5f}, rand: {}",
195 step, i, energyLow, energyHigh, pAcc, rnd);
196 if (rnd < pAcc) {
197 QUILL_LOG_INFO(log, "swap");
198 // Swap configurations, not pointers. Dynamics stays on its T slot.
199 auto potLow = replica[i]->getPotential();
200 auto potHigh = replica[i + 1]->getPotential();
201 Matter tmp = *replica[i];
202 *replica[i] = *replica[i + 1];
203 *replica[i + 1] = tmp;
204 replica[i]->setPotential(potLow);
205 replica[i + 1]->setPotential(potHigh);
206 replicaDynamics[i]->setThermalVelocity();
207 replicaDynamics[i + 1]->setThermalVelocity();
208 } else {
209 QUILL_LOG_INFO(log, "no swap");
210 }
211 }
212 }
213 }
214
215 forceCalls = static_cast<long>(pot->forceCallCounter.load()) - refForceCalls;
216 for (const auto &replicaPot : replicaPots) {
217 forceCalls += static_cast<long>(replicaPot->forceCallCounter.load());
218 }
219 if (!replica.empty()) {
220 *pos = *replica[0];
221 }
222 saveData();
223 return pos;
224}
225
227 std::string resultsFilename("results.dat");
228 returnFiles.push_back(resultsFilename);
229
230 std::ofstream out(resultsFilename, std::ios::binary);
231 if (out) {
232 out << std::format("{} termination_reason\n", 0);
233 out << "GOOD termination_reason_text\n";
234 out << "replica_exchange job_type\n";
235 out << std::format("{} random_seed\n", params.main_options().randomSeed);
236 out << std::format(
237 "{} potential_type\n",
238 magic_enum::enum_name<PotType>(params.potential_options().potential));
239 out << std::format("{} force_calls_sampling\n", forceCalls);
240 }
241
242 std::string posFilename("pos_out.con");
243 returnFiles.push_back(posFilename);
244 if (pos) {
245 if (!eonc::io::io_ok(pos->matter2con(posFilename))) {
246 QUILL_LOG_ERROR(log, "Failed to write {}", posFilename);
247 }
248 }
249}
250
251} // namespace eonc
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
Runtime * runtime_
Always valid: either owned_runtime_.get() or a caller-owned Runtime.
Definition Job.h:62
std::vector< std::string > returnFiles
std::vector< std::string > run(void) override
Virtual run; used solely for dynamic dispatch.
std::shared_ptr< Matter > pos
std::shared_ptr< Matter > runFromMatter(std::shared_ptr< Matter > initial)
Matter-first; returns replica-0 Matter after sampling.
std::string getRelevantFile(std::string filename)
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
constexpr bool io_ok(IoStatus s) noexcept
Definition ConFileIO.h:38
double random(long newSeed=0)
long randomInt(int lower, int upper)
double randomDouble()
constexpr double safe_recip(double x, double fallback=0.0)
Definition SafeMath.h:29
RAII resource manager for the ARTn C library with global synchronization.
bool potAllowsSharedInstance(const P &p) noexcept
static replica_exchange_options_t & replica_exchange_options(Parameters &p)