Loading...
Searching...
No Matches
eonc::ReplicaExchangeJob Class Reference

#include <ReplicaExchangeJob.h>

Inheritance diagram for eonc::ReplicaExchangeJob:

Public Member Functions

 ~ReplicaExchangeJob ()=default
std::vector< std::string > run (void) override
 Virtual run; used solely for dynamic dispatch.
std::shared_ptr< Matter > runFromMatter (std::shared_ptr< Matter > initial)
 Matter-first; returns replica-0 Matter after sampling.
 Job (std::unique_ptr< Parameters > parameters, Runtime &rt, ExclusivePotential)
 Job (std::unique_ptr< Parameters > parameters, Runtime &rt)
 Borrow: caller keeps Runtime alive (CLI stack / Python Session).
 Job (std::unique_ptr< Parameters > parameters, std::unique_ptr< Runtime > rt)
 Own a Runtime (one-shot makeJob / rvalue).
 Job (std::unique_ptr< Parameters > parameters)
 Own a default-constructed Runtime.
 Job (std::shared_ptr< Potential > potPassed, const Parameters &parameters)
Public Member Functions inherited from eonc::Job
void adoptRuntime (std::unique_ptr< Runtime > rt)
 Take ownership of a Runtime previously passed as Runtime&.
 Job (std::unique_ptr< Parameters > parameters, Runtime &rt)
 Borrow: caller keeps Runtime alive (CLI stack / Python Session).
 Job (std::unique_ptr< Parameters > parameters, std::unique_ptr< Runtime > rt)
 Own a Runtime (one-shot makeJob / rvalue).
 Job (std::unique_ptr< Parameters > parameters)
 Own a default-constructed Runtime.
 Job (std::shared_ptr< Potential > potPassed, const Parameters &parameters)
virtual ~Job ()=default
JobType getType ()
PotRegistry & pots () noexcept
size_t potRegistryForceCalls () const noexcept
 Force calls charged to pot's registry.
void releasePotential ()
 Drop the Potential so on_destroyed is recorded before Runtime dies.

Private Member Functions

void saveData ()

Private Attributes

size_t forceCalls {0}
std::shared_ptr< Matter > pos
std::vector< std::string > returnFiles
eonc::log::Scoped log

Additional Inherited Members

Protected Member Functions inherited from eonc::Job
 Job (std::unique_ptr< Parameters > parameters, Runtime &rt, ExclusivePotential)
Protected Attributes inherited from eonc::Job
JobType jtype
Parameters params
std::unique_ptr< Runtime > owned_runtime_
 Non-null when this Job owns the composition root (one-shot makeJob).
Runtime * runtime_
 Always valid: either owned_runtime_.get() or a caller-owned Runtime.
std::unique_ptr< Potential > ownedPot
 Exclusive until a multi-owner job promotes it in the public constructor.
std::shared_ptr< Potential > pot
 Set when one Potential is shared across Matters, images, or a caller.

Detailed Description

Definition at line 21 of file ReplicaExchangeJob.h.

Constructor & Destructor Documentation

◆ ~ReplicaExchangeJob()

eonc::ReplicaExchangeJob::~ReplicaExchangeJob ( )
default

Member Function Documentation

◆ Job() [1/5]

eonc::Job::Job ( std::shared_ptr< Potential > potPassed,
const Parameters & parameters )
inline

Definition at line 101 of file Job.h.

102 : jtype{parameters.main_options().job}, params{parameters},
103 owned_runtime_{std::make_unique<Runtime>()},
104 runtime_{owned_runtime_.get()}, pot{std::move(potPassed)} {}
const main_options_t & main_options() const
std::unique_ptr< Runtime > owned_runtime_
Non-null when this Job owns the composition root (one-shot makeJob).
Definition Job.h:60
JobType jtype
Definition Job.h:57
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

◆ Job() [2/5]

eonc::Job::Job ( std::unique_ptr< Parameters > parameters)
inlineexplicit

Own a default-constructed Runtime.

Definition at line 99 of file Job.h.

100 : Job(std::move(parameters), std::make_unique<Runtime>()) {}
Job(std::unique_ptr< Parameters > parameters, Runtime &rt, ExclusivePotential)
Definition Job.h:71

◆ Job() [3/5]

eonc::Job::Job ( std::unique_ptr< Parameters > parameters,
Runtime & rt )
inline

Borrow: caller keeps Runtime alive (CLI stack / Python Session).

The potential is shared. Point and minimization use ExclusivePotential.

Definition at line 89 of file Job.h.

90 : Job(std::move(parameters), rt, ExclusivePotential{}) {
92 }
std::unique_ptr< Potential > ownedPot
Exclusive until a multi-owner job promotes it in the public constructor.
Definition Job.h:64
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
Point and Minimization keep ownedPot. Other jobs share in the public ctor.
Definition Job.h:69

◆ Job() [4/5]

eonc::Job::Job ( std::unique_ptr< Parameters > parameters,
Runtime & rt,
ExclusivePotential  )
inline

Definition at line 71 of file Job.h.

72 : jtype{parameters->main_options().job}, params{*std::move(parameters)},
74 ownedPot{helpers::makePotential(params.potential_options().potential,
75 params, rt)} {}
std::unique_ptr< Potential > makePotential(const Parameters &params)
Exclusive ownership.

◆ Job() [5/5]

eonc::Job::Job ( std::unique_ptr< Parameters > parameters,
std::unique_ptr< Runtime > rt )
inline

Own a Runtime (one-shot makeJob / rvalue).

Definition at line 94 of file Job.h.

95 : Job(std::move(parameters), *rt) {
96 adoptRuntime(std::move(rt));
97 }
void adoptRuntime(std::unique_ptr< Runtime > rt)
Take ownership of a Runtime previously passed as Runtime&.
Definition Job.h:79

◆ run()

std::vector< std::string > eonc::ReplicaExchangeJob::run ( void )
overridevirtual

Virtual run; used solely for dynamic dispatch.

Implements eonc::Job.

Definition at line 31 of file ReplicaExchangeJob.cpp.

31 {
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}
std::vector< std::string > returnFiles
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)
constexpr bool io_ok(IoStatus s) noexcept
Definition ConFileIO.h:38

◆ runFromMatter()

std::shared_ptr< Matter > eonc::ReplicaExchangeJob::runFromMatter ( std::shared_ptr< Matter > initial)

Matter-first; returns replica-0 Matter after sampling.

Definition at line 44 of file ReplicaExchangeJob.cpp.

44 {
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}
void setPotential(std::shared_ptr< Potential > pot)
Definition Matter.cpp:850
quill::Logger * get() noexcept
Get or create the default "combi" logger.
Definition EonLogger.h:111
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
bool potAllowsSharedInstance(const P &p) noexcept
static replica_exchange_options_t & replica_exchange_options(Parameters &p)

◆ saveData()

void eonc::ReplicaExchangeJob::saveData ( )
private

Definition at line 226 of file ReplicaExchangeJob.cpp.

226 {
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}

Member Data Documentation

◆ forceCalls

size_t eonc::ReplicaExchangeJob::forceCalls {0}
private

Definition at line 32 of file ReplicaExchangeJob.h.

32{0};

◆ log

eonc::log::Scoped eonc::ReplicaExchangeJob::log
private

Definition at line 35 of file ReplicaExchangeJob.h.

◆ pos

std::shared_ptr<Matter> eonc::ReplicaExchangeJob::pos
private

Definition at line 33 of file ReplicaExchangeJob.h.

◆ returnFiles

std::vector<std::string> eonc::ReplicaExchangeJob::returnFiles
private

Definition at line 34 of file ReplicaExchangeJob.h.


The documentation for this class was generated from the following files: