Loading...
Searching...
No Matches
RGPotEngine.cpp
Go to the documentation of this file.
1// Isolated TU: rgpot only (no eOn Potential.h) — avoids Cap'n Proto Potential
2// clash.
3// on_exit is a glibc extension. -std=c++20 hides it unless this is set
4// before the libc headers.
5#ifndef _GNU_SOURCE
6#define _GNU_SOURCE
7#endif
10
11#include <algorithm>
12#include <array>
13#include <cctype>
14#include <cstdint>
15#include <cstdio>
16#include <cstdlib>
17#include <cstring>
18#include <fstream>
19#include <stdexcept>
20#include <string>
21#include <tuple>
22#include <vector>
23
24#if !defined(_WIN32)
25#include <dlfcn.h>
26#endif
28
29#include <capnp/message.h>
30#include <capnp/serialize.h>
31
35#include "rgpot/CPMDPot/CPMDPot.hpp"
36#include "rgpot/CalculatorGroup.hpp"
37#include "rgpot/NWChemPot/NWChemPot.hpp"
38#include "rgpot/rpc/Potentials.capnp.h"
39
40using rgpot::types::AtomMatrix;
41
42namespace {
43
44// Serialized Cap'n Proto message (standard segment framing, word-aligned) as
45// written by `capnp encode` or messageToFlatArray.
46std::vector<::capnp::word> read_params_file(const std::string &path) {
47 std::ifstream in(path, std::ios::binary | std::ios::ate);
48 if (!in)
49 throw std::runtime_error("RGPOT: cannot open params_path: " + path);
50 const std::streamsize bytes = in.tellg();
51 if (bytes <= 0 || (static_cast<size_t>(bytes) % sizeof(::capnp::word)) != 0)
52 throw std::runtime_error(
53 "RGPOT: params_path is not a capnp flat message: " + path);
54 std::vector<::capnp::word> words(static_cast<size_t>(bytes) /
55 sizeof(::capnp::word));
56 in.seekg(0);
57 in.read(reinterpret_cast<char *>(words.data()), bytes);
58 if (!in)
59 throw std::runtime_error("RGPOT: short read on params_path: " + path);
60 return words;
61}
62
63std::string to_lower(std::string s) {
64 for (char &c : s)
65 c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
66 return s;
67}
68
69std::array<std::array<double, 3>, 3> box_from_row_major(const double *box) {
70 std::array<std::array<double, 3>, 3> out{};
71 for (int i = 0; i < 3; ++i)
72 for (int j = 0; j < 3; ++j)
73 out[static_cast<size_t>(i)][static_cast<size_t>(j)] = box[i * 3 + j];
74 return out;
75}
76
77bool looks_like_dft_xc(const std::string &s) {
78 if (s.empty())
79 return false;
80 static const char *k[] = {"b3lyp", "blyp", "pbe", "pw91", "bp86",
81 "hcth", "ft97", "hfexch", "xperpbe", nullptr};
82 for (int i = 0; k[i]; ++i) {
83 if (s.size() >= std::char_traits<char>::length(k[i]) &&
84 s.compare(0, std::char_traits<char>::length(k[i]), k[i]) == 0)
85 return true;
86 }
87 return false;
88}
89
91int xtb_method_from_paramset(const std::string &paramset) {
92 const std::string p = to_lower(paramset);
93 if (p == "gfnff" || p == "gfn-ff")
95 if (p == "gfn0xtb" || p == "gfn0" || p == "gfn0-xtb")
97 if (p == "gfn1xtb" || p == "gfn1" || p == "gfn1-xtb")
99 if (p == "gfn2xtb" || p == "gfn2" || p == "gfn2-xtb" || p.empty())
101 throw std::runtime_error(
102 "RGPOT(xtb): paramset must be GFNFF, GFN0xTB, GFN1xTB, or GFN2xTB "
103 "(got '" +
104 paramset + "')");
105}
106
107// Ranks mpirun assigned. 1 when this process was not started under mpirun,
108// so a one-process test does not call MPI_Init.
109int mpi_world_hint() {
110 const char *s = std::getenv("OMPI_COMM_WORLD_SIZE");
111 if (s == nullptr || s[0] == '\0')
112 s = std::getenv("PMI_SIZE");
113 if (s == nullptr || s[0] == '\0')
114 return 1;
115 return std::atoi(s);
116}
117
118void pin_cpmd_library(const std::string &path) {
119#if !defined(_WIN32)
120 // A later dlclose must not run Fortran destructors. The mapping stays
121 // until process exit, and the grouped exit path does not run them.
122 const char *name = path.empty() ? "libcpmdc.so" : path.c_str();
123 dlopen(name, RTLD_NOW | RTLD_NOLOAD | RTLD_GLOBAL | RTLD_NODELETE);
124#else
125 static_cast<void>(path);
126#endif
127}
128
129// librgpot_pot_mpi, the MPI half of the calculator groups, or nullptr.
130// Loaded on first use only, so a process started without an MPI launcher
131// never maps libmpi. Search: EON_RGPOT_MPI_LIBRARY, the file next to this
132// library, then the linker path.
133const EonRgpotGroupMpi *group_mpi() {
134#if defined(__linux__)
135 static const EonRgpotGroupMpi *api = [] {
136 std::vector<std::string> candidates;
137 if (const char *e = std::getenv("EON_RGPOT_MPI_LIBRARY"); e && *e)
138 candidates.emplace_back(e);
139 Dl_info info{};
140 if (dladdr(reinterpret_cast<void *>(&group_mpi), &info) != 0 &&
141 info.dli_fname != nullptr) {
142 std::string self(info.dli_fname);
143 const auto slash = self.rfind('/');
144 if (slash != std::string::npos)
145 candidates.push_back(self.substr(0, slash + 1) + "librgpot_pot_mpi.so");
146 }
147 candidates.emplace_back("librgpot_pot_mpi.so");
148 for (const auto &path : candidates) {
149 void *h = dlopen(path.c_str(), RTLD_NOW | RTLD_GLOBAL);
150 if (h == nullptr)
151 continue;
152 using Entry = const EonRgpotGroupMpi *(*)();
153 auto entry = reinterpret_cast<Entry>(dlsym(h, "eon_rgpot_group_mpi_v1"));
154 const EonRgpotGroupMpi *table = entry ? entry() : nullptr;
155 if (table != nullptr && table->version == EON_RGPOT_GROUP_MPI_VERSION)
156 return table;
157 }
158 return static_cast<const EonRgpotGroupMpi *>(nullptr);
159 }();
160 return api;
161#else
162 return nullptr;
163#endif
164}
165
166// Every rank calls this when started under an MPI launcher. False when any
167// rank failed; message is then the lowest failing rank's text.
168bool agree_construction(std::string &message) {
169 const EonRgpotGroupMpi *api = group_mpi();
170 if (api == nullptr)
171 return message.empty();
172 std::array<char, 4096> shared{};
173 if (api->agree(message.c_str(), shared.data(), shared.size()) != 0)
174 return true;
175 message.assign(shared.data());
176 return false;
177}
178
179} // namespace
180
181std::string nwchemDftInputBlock(const std::string &theory,
182 const std::string &scfType, int multiplicity,
183 const std::string &existing) {
184 if (!existing.empty()) {
185 return existing;
186 }
187 const std::string theoryKey = to_lower(theory);
188 const std::string scfKey = to_lower(scfType);
189 if (theoryKey == "dft" && looks_like_dft_xc(scfKey)) {
190 return "dft\n xc " + scfType + "\n mult " + std::to_string(multiplicity) +
191 "\nend";
192 }
193 if (looks_like_dft_xc(theoryKey)) {
194 return "dft\n xc " + theory + "\n mult " + std::to_string(multiplicity) +
195 "\nend";
196 }
197 return {};
198}
199
200namespace eon {
201::CPMDParams::Builder fillCpmdParams(::capnp::MallocMessageBuilder &msg,
202 const RGPotEngineOptions &opt) {
203 ::CPMDParams::Builder params = msg.initRoot<::CPMDParams>();
204 if (!opt.params_path.empty()) {
205 const auto words = read_params_file(opt.params_path);
206 ::capnp::FlatArrayMessageReader reader(
207 kj::arrayPtr(words.data(), words.size()));
208 msg.setRoot(reader.getRoot<::CPMDParams>());
209 params = msg.getRoot<::CPMDParams>();
210 } else {
211 params.setFunctional(opt.functional);
212 params.setCutOffRy(opt.cutoff_ry);
213 params.setCharge(opt.charge);
214 params.setMultiplicity(opt.multiplicity);
215 if (!opt.title.empty())
216 params.setTitle(opt.title);
217 if (opt.memory_mb > 0)
218 params.setMemoryMb(static_cast<uint32_t>(opt.memory_mb));
219 }
220 if (!opt.engine_path.empty())
221 params.setEnginePath(opt.engine_path);
222 else if (!opt.engine_library.empty())
223 params.setEnginePath(opt.engine_library);
224 if (!opt.engine_root.empty())
225 params.setCpmdRoot(opt.engine_root);
226 if (!opt.scratch_dir.empty())
227 params.setScratchDir(opt.scratch_dir);
228 if (!opt.permanent_dir.empty())
229 params.setPermanentDir(opt.permanent_dir);
230
231 std::string block = opt.input_block;
232 if (block.empty()) {
233 if (const char *env = std::getenv("RGPOT_CPMD_INPUT_BLOCK"))
234 block = env;
235 }
236 if (!block.empty()) {
237 std::vector<std::string> kept;
238 {
239 auto existing = params.getInputBlocks();
240 kept.reserve(existing.size());
241 for (auto text : existing)
242 kept.emplace_back(text.cStr());
243 }
244 auto blocks = params.initInputBlocks(kept.size() + 1);
245 for (std::size_t i = 0; i < kept.size(); ++i)
246 blocks.set(i, kept[i]);
247 blocks.set(kept.size(), block);
248 }
249 return params;
250}
251} // namespace eon
252
254 enum class Backend { Nwchemc, Cpmdc, Metatomic, Uma, Xtb };
256 std::unique_ptr<rgpot::NWChemPot> nwchem;
257 std::unique_ptr<rgpot::CPMDPot> cpmd;
258 std::unique_ptr<MetatomicEngineLoader> metatomic;
259 std::unique_ptr<GenericEngineLoader> uma;
260 std::unique_ptr<XTBEngineLoader> xtb;
261 // Calculator groups (cpmdc, ranks_per_image > 0). One group when off.
262 int groups{1};
263 int group{0};
264 int world{1};
265 bool module_down{false};
266};
267
269 : impl_(std::make_unique<Impl>()) {
270 backend_ = to_lower(opt.backend);
271 if (backend_ == "nwchem" || backend_ == "nwchemc" ||
272 backend_ == "nwchempot") {
273 backend_ = "nwchemc";
274 impl_->backend = Impl::Backend::Nwchemc;
275 ::capnp::MallocMessageBuilder msg;
276 auto params = msg.initRoot<::NWChemParams>();
277 params.setBasis(opt.basis);
278 params.setTheory(opt.theory);
279 params.setScfType(opt.scf_type);
280 params.setCharge(opt.charge);
281 params.setMultiplicity(opt.multiplicity);
282 if (!opt.engine_path.empty())
283 params.setEnginePath(opt.engine_path);
284 else if (!opt.engine_library.empty())
285 params.setEnginePath(opt.engine_library);
286 if (!opt.engine_root.empty())
287 params.setNwchemRoot(opt.engine_root);
288 if (!opt.title.empty())
289 params.setTitle(opt.title);
290 if (opt.memory_mb > 0)
291 params.setMemoryMb(static_cast<uint32_t>(opt.memory_mb));
292 if (!opt.scratch_dir.empty())
293 params.setScratchDir(opt.scratch_dir);
294 // DFT XC as inputBlocks when theory=dft and scfType is an XC label
295 std::string block = opt.input_block;
296 if (block.empty()) {
297 if (const char *env = std::getenv("RGPOT_NWCHEM_INPUT_BLOCK"))
298 block = env;
299 }
300 if (block.empty()) {
301 block = nwchemDftInputBlock(opt.theory, opt.scf_type, opt.multiplicity,
302 block);
303 }
304 if (!block.empty()) {
305 auto blocks = params.initInputBlocks(1);
306 blocks.set(0, block);
307 }
308 impl_->nwchem = std::make_unique<rgpot::NWChemPot>(params.asReader());
309 if (!impl_->nwchem->available())
310 throw std::runtime_error(
311 "RGPOT(nwchemc): engine not available (set NWCHEMC_LIBRARY / "
312 "RGPOT_NWCHEMC_ENGINE or [RgpotPot] engine_path)");
313 } else if (backend_ == "cpmd" || backend_ == "cpmdc" ||
314 backend_ == "cpmdpot") {
315 backend_ = "cpmdc";
316 impl_->backend = Impl::Backend::Cpmdc;
317 std::string local_error;
318 ::capnp::MallocMessageBuilder msg;
319 try {
320 static_cast<void>(eon::fillCpmdParams(msg, opt));
321 } catch (const std::exception &ex) {
322 local_error = ex.what();
323 }
324 // Several ranks: agree before MPI_Comm_split. One rank that cannot
325 // read params_path must not leave the others inside the split.
326 if (mpi_world_hint() <= 1 && !local_error.empty())
327 throw std::runtime_error(local_error);
328 // rgpot reports MPI only once MPI_Init has run, and agree_construction
329 // is what initialises it, so the agreement keys on the launch size.
330 if (mpi_world_hint() > 1 && !agree_construction(local_error)) {
332 throw std::runtime_error(
333 local_error.empty()
334 ? std::string(
335 "RGPOT(cpmdc): a rank failed before the calculator split")
336 : local_error);
337 }
338 if (!local_error.empty())
339 throw std::runtime_error(local_error);
340 if (::rgpot::calculatorsUseMpi()) {
341 // Collective on MPI_COMM_WORLD, before the engine holds a session.
342 // cpmdc adopts a calculator communicator only while no session is
343 // live, and CPMD's mp_start reads that communicator. The CPMDPot
344 // built below finds the split made and hands its engine the group
345 // communicator before it creates its session.
346 // ranks_per_image = 0 is one calculator on the whole world.
347 const rgpot::CalculatorGroup g =
348 ::rgpot::bindCalculators(opt.ranks_per_image);
349 ::rgpot::finalizeMpiAtExit();
350 if (mpi_world_hint() > 1)
352 if (g.index < 0)
353 throw std::runtime_error(
354 "RGPOT(cpmdc): ranks_per_image=" +
355 std::to_string(opt.ranks_per_image) +
356 " does not divide the MPI world into calculator groups");
357 impl_->groups = ::rgpot::calculatorCount();
358 impl_->group = g.index;
359 impl_->world = ::rgpot::calculatorWorldSize();
360 } else if (opt.ranks_per_image > 0) {
361 throw std::runtime_error(
362 "RGPOT(cpmdc): ranks_per_image needs rgpot built with MPI "
363 "(-Drgpot:with_mpi=enabled)");
364 }
365 try {
366 impl_->cpmd = std::make_unique<rgpot::CPMDPot>(
367 msg.getRoot<::CPMDParams>().asReader());
368 pin_cpmd_library(opt.engine_path.empty() ? opt.engine_library
369 : opt.engine_path);
370 if (!impl_->cpmd->available())
371 throw std::runtime_error(
372 "RGPOT(cpmdc): engine not available (set CPMDC_LIBRARY / "
373 "RGPOT_CPMDC_ENGINE or [RgpotPot] engine_path)");
374 } catch (const std::exception &ex) {
375 local_error = ex.what();
376 }
377 // A rank whose engine did not load or refused the group communicator
378 // must not leave the others waiting in the first force.
379 if (mpi_world_hint() > 1 && !agree_construction(local_error))
380 throw std::runtime_error(
381 local_error.empty()
382 ? std::string("RGPOT(cpmdc): a rank failed to load the engine")
383 : local_error);
384 if (!local_error.empty())
385 throw std::runtime_error(local_error);
386 } else if (backend_ == "metatomic" || backend_ == "mta" ||
387 backend_ == "metatomicpot") {
388 backend_ = "metatomic";
391 mopt.model_path = opt.model_path;
392 mopt.device = opt.device;
393 mopt.length_unit = opt.length_unit;
397 mopt.engine_path =
398 !opt.engine_path.empty() ? opt.engine_path : opt.engine_library;
400 impl_->metatomic = std::make_unique<MetatomicEngineLoader>(mopt);
401 if (!impl_->metatomic->available())
402 throw std::runtime_error(
403 "RGPOT(metatomic): engine not available (set RGPOT_METATOMIC_ENGINE "
404 "or [RgpotPot] engine_path to librgpot_metatomic_engine.so)");
405 } else if (backend_ == "uma" || backend_ == "omol" || backend_ == "umapot") {
406 backend_ = "uma";
407 impl_->backend = Impl::Backend::Uma;
409 gopt.library = "libuma_engine.so";
410 gopt.env_var = "RGPOT_UMA_ENGINE";
411 gopt.engine_path =
412 !opt.engine_path.empty() ? opt.engine_path : opt.engine_library;
413 gopt.tag = "uma";
414 {
415 ::capnp::MallocMessageBuilder msg;
416 auto params = msg.initRoot<::UmaParams>();
417 params.setModelPath(opt.model_path);
418 params.setTaskName(opt.task_name);
419 params.setDevice(opt.device);
420 params.setCharge(opt.charge);
421 params.setSpin(opt.multiplicity);
422 const auto words = ::capnp::messageToFlatArray(msg);
423 const auto bytes = words.asBytes();
424 gopt.config.assign(bytes.begin(), bytes.end());
425 }
426 impl_->uma = std::make_unique<GenericEngineLoader>(gopt);
427 if (!impl_->uma->available())
428 throw std::runtime_error(
429 "RGPOT(uma): engine not available (set RGPOT_UMA_ENGINE or "
430 "[RgpotPot] engine_path to libuma_engine.so)");
431 } else if (backend_ == "xtb" || backend_ == "xtbpot" || backend_ == "gfn" ||
432 backend_ == "gfnxtb") {
433 backend_ = "xtb";
434 impl_->backend = Impl::Backend::Xtb;
435 XTBEngineOptions xopt;
436 xopt.method = xtb_method_from_paramset(opt.xtb_paramset);
437 xopt.accuracy = opt.xtb_accuracy;
440 xopt.charge = opt.xtb_charge;
441 xopt.uhf = opt.xtb_uhf;
442 xopt.engine_path =
443 !opt.engine_path.empty() ? opt.engine_path : opt.engine_library;
444 impl_->xtb = std::make_unique<XTBEngineLoader>(xopt);
445 if (!impl_->xtb->available())
446 throw std::runtime_error(
447 "RGPOT(xtb): engine not available (set RGPOT_XTB_ENGINE or "
448 "[RgpotPot] engine_path to librgpot_xtb_engine.so)");
449 } else {
450 throw std::runtime_error(
451 "RGPOT: unknown backend '" + opt.backend +
452 "' (expected nwchemc, cpmdc, metatomic, uma, or xtb)");
453 }
454}
455
456RGPotEngine::~RGPotEngine() = default;
457
458int RGPotEngine::calculatorGroups() const noexcept {
459 return impl_ ? impl_->groups : 1;
460}
461
462int RGPotEngine::calculatorIndex() const noexcept {
463 return impl_ ? impl_->group : 0;
464}
465
466int RGPotEngine::calculatorWorld() const noexcept {
467 return impl_ ? impl_->world : 1;
468}
469
470int RGPotEngine::worldRank() const noexcept {
471 if (!impl_ || impl_->world <= 1)
472 return 0;
473 const rgpot::CalculatorGroup &g = ::rgpot::thisCalculator();
474 return g.index * g.ranks + g.rank_in_group;
475}
476
478 if (impl_ && impl_->world > 1)
479 ::rgpot::finalizeMpiAtExit();
480}
481
483 return ::rgpot::mpiAbortRequested();
484}
485
487#if defined(__linux__)
488 if (mpi_world_hint() <= 1)
489 return;
490 const EonRgpotGroupMpi *api = group_mpi();
491 if (api == nullptr || api->hard_exit == nullptr)
492 return;
493 // A library loaded during the run can register an exit handler after
494 // the first call. Registering again puts this handler last, so it runs
495 // first and _Exit skips those destructors. The handler does not return.
496 ::on_exit(api->hard_exit, nullptr);
497#else
498 static_cast<void>(this);
499#endif
500}
501
503 if (!impl_ || impl_->module_down)
504 return;
505 impl_->module_down = true;
506#if !defined(_WIN32)
507 if (auto *fin =
508 reinterpret_cast<void (*)()>(dlsym(RTLD_DEFAULT, "cpmdc_finalize")))
509 fin();
510 pin_cpmd_library({});
511#endif
512}
513
514void RGPotEngine::broadcastFromDriver(void *data, std::size_t bytes) const {
515 if (!impl_ || impl_->world <= 1 || bytes == 0)
516 return;
517 // World rank 0 is the first rank of calculator 0.
518 if (::rgpot::shareFromCalculator(0, data, bytes) == 0)
519 throw std::runtime_error("RGPOT: could not broadcast from the driver rank");
520}
521
522bool RGPotEngine::shareResult(int owner, long N, double *F, double *U, bool ok,
523 std::string &error) const {
524 if (!impl_ || impl_->world <= 1) {
525 static_cast<void>(error);
526 return ok;
527 }
528 // Slot 0 carries the owner's status, so a failed evaluation reaches
529 // every rank through the same broadcast as a good one.
530 std::vector<double> buf(static_cast<size_t>(3 * N + 2));
531 if (owner == impl_->group) {
532 buf[0] = ok ? 1.0 : 0.0;
533 buf[1] = *U;
534 std::copy(F, F + 3 * N, buf.begin() + 2);
535 }
536 if (::rgpot::shareFromCalculator(owner, buf.data(),
537 buf.size() * sizeof(double)) == 0)
538 throw std::runtime_error("RGPOT: could not share a calculator result");
539 *U = buf[1];
540 std::copy(buf.begin() + 2, buf.end(), F);
541 // The owner's engine text travels with the status. Other ranks hold an
542 // empty string until this broadcast.
543 std::array<char, 512> msg{};
544 if (owner == impl_->group && !error.empty()) {
545 const auto n = std::min(error.size(), msg.size() - 1);
546 std::memcpy(msg.data(), error.data(), n);
547 }
548 if (::rgpot::shareFromCalculator(owner, msg.data(), msg.size()) == 0)
549 throw std::runtime_error("RGPOT: could not share a calculator error");
550 if (msg[0] != '\0')
551 error.assign(msg.data());
552 return buf[0] == 1.0;
553}
554
556 if (!impl_)
557 return false;
558 if (impl_->backend == Impl::Backend::Nwchemc && impl_->nwchem)
559 return impl_->nwchem->available();
560 if (impl_->backend == Impl::Backend::Cpmdc && impl_->cpmd)
561 return impl_->cpmd->available();
562 if (impl_->backend == Impl::Backend::Metatomic && impl_->metatomic)
563 return impl_->metatomic->available();
564 if (impl_->backend == Impl::Backend::Uma && impl_->uma)
565 return impl_->uma->available();
566 if (impl_->backend == Impl::Backend::Xtb && impl_->xtb)
567 return impl_->xtb->available();
568 return false;
569}
570
571namespace {
572// rgpot gained per-key orbitals after 3.4.0; an older rgpot has neither
573// call, and its CPMD session keeps one stored copy.
574template <class Pot> void select_orbitals(Pot &pot, std::int64_t key) {
575 if constexpr (requires { pot.selectOrbitals(key); })
576 pot.selectOrbitals(key);
577}
578
579template <class Pot> bool keeps_orbitals_per_key(const Pot &pot) {
580 if constexpr (requires { pot.keepsOrbitalsPerKey(); })
581 return pot.keepsOrbitalsPerKey();
582 else
583 return false;
584}
585} // namespace
586
587void RGPotEngine::selectOrbitals(std::int64_t key) const {
588 if (impl_ && impl_->backend == Impl::Backend::Cpmdc && impl_->cpmd)
589 select_orbitals(*impl_->cpmd, key);
590}
591
593 return impl_ && impl_->backend == Impl::Backend::Cpmdc && impl_->cpmd &&
594 keeps_orbitals_per_key(*impl_->cpmd);
595}
596
597void RGPotEngine::force(long N, const double *R, const int *atomicNrs,
598 double *F, double *U, const double *box) const {
599 forceEngine(N, R, atomicNrs, F, U, box);
600 // Set on one rank by the multi-rank failure test. The text is the
601 // engine error that rank has to deliver to rank 0. It is raised after
602 // the engine call, where an engine error surfaces, so the rank has
603 // already taken part in every collective the engine runs.
604 if (const char *fail = std::getenv("RGPOT_FORCE_FAIL")) {
605 if (fail[0] != '\0')
606 throw std::runtime_error(fail);
607 }
608}
609
610void RGPotEngine::forceEngine(long N, const double *R, const int *atomicNrs,
611 double *F, double *U, const double *box) const {
612 if (N <= 0)
613 throw std::runtime_error("RGPotEngine::force called with N <= 0");
614
615 AtomMatrix positions(static_cast<int>(N), 3);
616 for (long i = 0; i < N; ++i) {
617 const int ii = static_cast<int>(i);
618 positions(ii, 0) = R[3 * i + 0];
619 positions(ii, 1) = R[3 * i + 1];
620 positions(ii, 2) = R[3 * i + 2];
621 }
622 std::vector<int> atmtypes(atomicNrs, atomicNrs + N);
623 const auto cell = box_from_row_major(box);
624
625 if (impl_->backend == Impl::Backend::Metatomic) {
626 impl_->metatomic->force(N, R, atomicNrs, F, U, nullptr, box);
627 return;
628 }
629 if (impl_->backend == Impl::Backend::Uma) {
630 // A molecular .con may omit the cell. A 25 A diagonal stands in, so
631 // a singular box does not reach the neighbor list.
632 const bool got_cell = box && box[0] > 0.0 && box[4] > 0.0 && box[8] > 0.0;
633 std::array<double, 9> cell_sub{};
634 const double *effective_box = box;
635 if (!got_cell) {
636 cell_sub[0] = cell_sub[4] = cell_sub[8] = 25.0;
637 effective_box = cell_sub.data();
638 }
639 impl_->uma->force(N, R, atomicNrs, F, U, nullptr, effective_box);
640 return;
641 }
642 if (impl_->backend == Impl::Backend::Xtb) {
643 impl_->xtb->force(N, R, atomicNrs, F, U, nullptr, box);
644 return;
645 }
646
647 // rgpot >= 2.5.0: operator() returns (energy, forces, variance).
648 std::tuple<double, AtomMatrix, double> result;
649 if (impl_->backend == Impl::Backend::Nwchemc)
650 result = (*impl_->nwchem)(positions, atmtypes, cell);
651 else
652 result = (*impl_->cpmd)(positions, atmtypes, cell);
653
654 *U = std::get<0>(result);
655 const auto &forces = std::get<1>(result);
656 for (long i = 0; i < N; ++i) {
657 const int ii = static_cast<int>(i);
658 F[3 * i + 0] = forces(ii, 0);
659 F[3 * i + 1] = forces(ii, 1);
660 F[3 * i + 2] = forces(ii, 2);
661 }
662}
Eigen::Matrix< double, Eigen::Dynamic, 3, eOnStorageOrder > AtomMatrix
Definition Eigen.h:37
std::string nwchemDftInputBlock(const std::string &theory, const std::string &scfType, int multiplicity, const std::string &existing)
NWChem input block for a DFT theory.
std::string nwchemDftInputBlock(const std::string &theory, const std::string &scfType, int multiplicity, const std::string &existing)
NWChem input block for a DFT theory.
#define EON_RGPOT_GROUP_MPI_VERSION
Function table of librgpot_pot_mpi, the MPI half of RgpotPot's calculator groups.
void selectOrbitals(std::int64_t key) const
Names the calculation the next force() belongs to (cpmdc: the engine keeps converged orbitals per key...
bool available() const
RGPotEngine(const RGPotEngineOptions &opt)
void broadcastFromDriver(void *data, std::size_t bytes) const
Collective on MPI_COMM_WORLD: every rank leaves with world rank 0's bytes.
static bool mpiAbortRequested() noexcept
True once rgpot asked for MPI_Abort at exit in this process.
bool keepsOrbitalsPerKey() const
True when the engine keeps converged orbitals per key.
void armGroupedExit() const
After MPI_Finalize, _Exit.
int calculatorGroups() const noexcept
Number of calculator groups the MPI world is split into (1 when ranks_per_image is off) and the group...
void forceEngine(long N, const double *R, const int *atomicNrs, double *F, double *U, const double *box) const
void shutdownModule() noexcept
Calls cpmdc_finalize while the engine is still mapped. MPI stays up.
int calculatorWorld() const noexcept
Ranks in the MPI world the groups were bound on (1 without MPI).
int calculatorIndex() const noexcept
int worldRank() const noexcept
This process's rank in that world (0 without MPI).
void finalizeMpiAtExit() const
Registers MPI_Finalize at exit (once per process) when the world has more than one rank.
std::unique_ptr< Impl > impl_
bool shareResult(int owner, long N, double *F, double *U, bool ok, std::string &error) const
Collective on MPI_COMM_WORLD: every rank leaves with the energy and the 3N forces computed by the fir...
std::string backend_
void force(long N, const double *R, const int *atomicNrs, double *F, double *U, const double *box) const
::CPMDParams::Builder fillCpmdParams(::capnp::MallocMessageBuilder &msg, const RGPotEngineOptions &opt)
int(* agree)(const char *local, char *shared, std::size_t cap)
Collective on MPI_COMM_WORLD; initialises MPI when needed.
void(* hard_exit)(int status, void *arg)
on_exit handler: MPI_Abort when rgpot asked for it, else MPI_Finalize, then _Exit.
std::string tag
Backend tag for error messages ("uma", ...).
std::string env_var
Optional env var naming an explicit .so path (checked first).
std::vector< unsigned char > config
Cap'n Proto flat-array message (the engine's params struct on the shared Potentials....
std::string engine_path
Optional explicit .so path from config.
std::string library
Library basename to search for, e.g. "libuma_engine.so".
std::string scf_type
Definition RGPotEngine.h:12
std::string title
Definition RGPotEngine.h:20
std::string xtb_paramset
Definition RGPotEngine.h:38
std::string basis
Definition RGPotEngine.h:10
std::string scratch_dir
Definition RGPotEngine.h:22
std::string engine_path
Definition RGPotEngine.h:17
std::string params_path
Definition RGPotEngine.h:27
std::string backend
Definition RGPotEngine.h:9
std::string extensions_directory
Definition RGPotEngine.h:33
std::string engine_library
Definition RGPotEngine.h:18
double xtb_electronic_temperature
Definition RGPotEngine.h:40
std::string permanent_dir
Definition RGPotEngine.h:25
std::string functional
Definition RGPotEngine.h:13
std::string length_unit
Definition RGPotEngine.h:32
bool torch_determinism_strict
Definition RGPotEngine.h:36
std::string device
Definition RGPotEngine.h:31
std::string model_path
Definition RGPotEngine.h:30
std::string task_name
Definition RGPotEngine.h:47
std::string engine_root
Definition RGPotEngine.h:19
double uncertainty_threshold
Definition RGPotEngine.h:35
std::string theory
Definition RGPotEngine.h:11
std::string input_block
Definition RGPotEngine.h:24
std::unique_ptr< rgpot::NWChemPot > nwchem
std::unique_ptr< rgpot::CPMDPot > cpmd
std::unique_ptr< MetatomicEngineLoader > metatomic
std::unique_ptr< XTBEngineLoader > xtb
std::unique_ptr< GenericEngineLoader > uma
std::string engine_path
double electronic_temperature
@ RGPOT_XTB_METHOD_GFNFF
Definition xtb_c_abi.h:32
@ RGPOT_XTB_METHOD_GFN1
Definition xtb_c_abi.h:34
@ RGPOT_XTB_METHOD_GFN2
Definition xtb_c_abi.h:35
@ RGPOT_XTB_METHOD_GFN0
Definition xtb_c_abi.h:33