Loading...
Searching...
No Matches
RgpotFactory.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4#include "RgpotFactory.h"
5
6#include <algorithm>
7#include <cctype>
8#include <cmath>
9#include <cstring>
10#include <fstream>
11#include <functional>
12#include <mutex>
13#include <set>
14#include <sstream>
15#include <stdexcept>
16#include <utility>
17
18#include "AotiPackageIsa.h"
19#include "RgpotAbi.h"
20#if defined(RGPOT_HAS_METATOMIC) || defined(RGPOT_HAS_UMA)
21#include <ATen/Context.h>
22#include <ATen/Parallel.h>
23#endif
24#if __has_include("rgpot/CuH2/CuH2Pot.hpp")
25#include "rgpot/CuH2/CuH2Pot.hpp"
26#define GPR_FACTORY_CUH2_CPP 1
27#endif
28#include "rgpot/LennardJones/LJClusterPot.hpp"
29#include "rgpot/LennardJones/LJPot.hpp"
30#include "rgpot/Morse/MorsePot.hpp"
31#include "rgpot/ZBL/ZBLPot.hpp"
32
33#ifdef RGPOT_HAS_FORTRAN_POTS
34#include "rgpot/fortran/FortranPots.hpp"
35#endif
36#ifdef RGPOT_HAS_XTB
37#include "rgpot/XTBPot/XTBPot.hpp"
38#endif
39#ifdef RGPOT_HAS_TBLITE
40#include "rgpot/TBLitePot/TBLitePot.hpp"
41#endif
42#ifdef RGPOT_HAS_DFTD3
43#include "rgpot/D3Pot/D3Pot.hpp"
44#endif
45#ifdef RGPOT_HAS_DFTD4
46#include "rgpot/D4Pot/D4Pot.hpp"
47#endif
48#ifdef RGPOT_HAS_EXPR
49#include "rgpot/ExprPot/ExprPot.hpp"
50#endif
51#ifdef RGPOT_HAS_METATOMIC
52#include "rgpot/MetatomicPot/MetatomicPot.hpp"
53#endif
54#ifdef RGPOT_HAS_UMA
55#include "rgpot/UmaPot/UmaPot.hpp"
56#endif
57#ifdef RGPOT_HAS_SKALA
58#include "rgpot/SkalaPot/SkalaPot.hpp"
59#endif
60#if defined(GPRN_HAS_MOPAC) && __has_include("rgpot/MOPACPot/MOPACPot.hpp")
61#define GPR_FACTORY_MOPAC 1
62#include "rgpot/MOPACPot/MOPACPot.hpp"
63#endif
64#if defined(USE_CAPNP) && __has_include("rgpot/rpc/Potentials.capnp.h")
65#include <capnp/dynamic.h>
66#include <capnp/serialize.h>
67#include <kj/array.h>
68
69#include "rgpot/rpc/Potentials.capnp.h"
70#define GPR_FACTORY_SCHEMA 1
71#ifdef RGPOT_HAS_NWCHEM_FRONTEND
72#define GPR_FACTORY_NWCHEM 1
73#include "rgpot/NWChemPot/NWChemPot.hpp"
74#endif
75#if __has_include("rgpot/CPMDPot/CPMDPot.hpp")
76#define GPR_FACTORY_CPMD 1
77#include "rgpot/CPMDPot/CPMDPot.hpp"
78#endif
79#if __has_include("rgpot/CP2KPot/CP2KPot.hpp") && defined(RGPOT_HAS_CP2K)
80#define GPR_FACTORY_CP2K 1
81#include "rgpot/CP2KPot/CP2KPot.hpp"
82#endif
83#if __has_include("rgpot/ORCACPot/ORCACPot.hpp")
84#define GPR_FACTORY_ORCA 1
85#include "rgpot/ORCACPot/ORCACPot.hpp"
86#endif
87#endif
88
89namespace pot {
90namespace {
91using Instance = std::unique_ptr<rgpot::PotentialBase>;
92
93class Parameters {
94public:
95 explicit Parameters(const RgpotRequest& request)
96 : overrides_(request.overrides)
97 {
98 if (request.config.empty()) return;
99#ifdef GPR_FACTORY_SCHEMA
100 if (request.config.size() % sizeof(capnp::word) != 0)
101 throw std::invalid_argument(
102 "PotentialConfig must contain complete Cap'n Proto words");
103 words_ = kj::heapArray<capnp::word>(request.config.size() /
104 sizeof(capnp::word));
105 std::memcpy(words_.begin(), request.config.data(),
106 request.config.size());
107 reader_ =
108 std::make_unique<capnp::FlatArrayMessageReader>(words_.asPtr());
109 root_ = reader_->getRoot<::PotentialConfig>();
110 if (root_.hasCommon())
111 throw std::invalid_argument(
112 "Use native backend settings in PotentialConfig; the common "
113 "overlay is not supported by this driver");
114 auto dynamic = capnp::toDynamic(root_);
115 KJ_IF_MAYBE (field, dynamic.which()) {
116 const std::string arm = field->getProto().getName().cStr();
117 if (arm == "none") return;
118 auto name = canonicalRgpotName(request.potential);
119 if (name == "lj_cluster") name = "lj";
120 if (arm != name)
121 throw std::invalid_argument("PotentialConfig arm '" + arm +
122 "' does not match --potential " +
123 request.potential);
124 values_ = dynamic.get(*field).as<capnp::DynamicStruct>();
125#ifdef GPR_SCHEMA_HAS_XTB_CONFIG
126 if (arm == "xtb" && request.potential != "xtb" &&
127 request.potential != root_.getXtb().getMethod().cStr())
128 throw std::invalid_argument(
129 "xTB method conflicts with --potential alias; use "
130 "--potential xtb to select the method from "
131 "PotentialConfig");
132#endif
133 if (arm == "metatomic" && root_.getMetatomic().getOutputs().size())
134 throw std::invalid_argument(
135 "The metatomic oracle requests energy and its forces; "
136 "custom PotentialConfig outputs are not supported");
137 configured_ = true;
138 return;
139 }
140 throw std::invalid_argument("Unknown PotentialConfig arm");
141#else
142 throw std::invalid_argument(
143 "--potential-config requires Cap'n Proto support");
144#endif
145 }
146
147 template <typename T>
148 T get(const char* key, T fallback) const
149 {
150#ifdef GPR_FACTORY_SCHEMA
151 if (!configured_ || overrides_.contains(key)) return fallback;
152 std::string field;
153 bool upper = false;
154 for (char c: std::string(key)) {
155 if (c == '_') {
156 upper = true;
157 continue;
158 }
159 field += upper ? static_cast<char>(
160 std::toupper(static_cast<unsigned char>(c)))
161 : c;
162 upper = false;
163 }
164 if (field == "De") field = "de";
165 // A schema arm that does not carry this key keeps the caller's
166 // fallback. e75577bd's MetatomicParams has no length unit, charge,
167 // spin, or task name.
168 KJ_IF_MAYBE (found,
169 values_.getSchema().findFieldByName(field.c_str())) {
170 (void)found;
171 } else {
172 return fallback;
173 }
174 auto value = values_.get(field.c_str());
175 T result;
176 if constexpr (std::is_same_v<T, std::string>) {
177 if (value.getType() == capnp::DynamicValue::ENUM) {
178 KJ_IF_MAYBE (enumerant,
179 value.as<capnp::DynamicEnum>().getEnumerant()) {
180 result = enumerant->getProto().getName().cStr();
181 } else {
182 throw std::invalid_argument(
183 "Unknown potential configuration enum");
184 }
185 } else
186 result = value.as<capnp::Text>().cStr();
187 } else {
188 result = value.as<T>();
189 }
190 if constexpr (std::is_floating_point_v<T>) {
191 if (!std::isfinite(result))
192 throw std::invalid_argument(
193 std::string("nonfinite potential parameter: ") + key);
194 }
195 return result;
196#else
197 return fallback;
198#endif
199 }
200
201#ifdef GPR_FACTORY_SCHEMA
202 bool configured() const
203 {
204 return configured_;
205 }
206 ::PotentialConfig::Reader root() const
207 {
208 return root_;
209 }
210 capnp::DynamicStruct::Reader values() const
211 {
212 return values_;
213 }
214#endif
215
216private:
217 const std::set<std::string>& overrides_;
218#ifdef GPR_FACTORY_SCHEMA
219 // Under clang capnp::word can be neither copied nor moved, so a
220 // std::vector of words cannot be resized.
221 kj::Array<capnp::word> words_;
222 std::unique_ptr<capnp::FlatArrayMessageReader> reader_;
223 ::PotentialConfig::Reader root_;
224 capnp::DynamicStruct::Reader values_;
225 bool configured_ = false;
226#endif
227};
228
229#ifdef GPR_FACTORY_SCHEMA
230template <class Reader>
231std::vector<unsigned char> serializeConfig(Reader reader)
232{
233 capnp::MallocMessageBuilder message;
234 message.setRoot(reader);
235 const auto words = capnp::messageToFlatArray(message);
236 const auto bytes = words.asBytes();
237 return {bytes.begin(), bytes.end()};
238}
239#endif
240
241void positive(double value, const char* name)
242{
243 if (!(value > 0.0) || !std::isfinite(value))
244 throw std::invalid_argument(
245 std::string("potential parameter must be positive: ") + name);
246}
247
248using Maker = std::function<Instance(const RgpotRequest&, Parameters&)>;
249struct Entry {
250 const char* name;
251 std::vector<std::string> aliases;
252 Maker make;
253 const char* requirement;
254};
255
256Instance construct(const RgpotRequest& request, Parameters& parameters);
257
258#if defined(RGPOT_HAS_EXPR) && defined(GPR_FACTORY_SCHEMA)
259Instance expressionTree(::ExprParams::Reader params);
260
261Instance expressionLeaf(::PotentialSpec::Reader leaf)
262{
263 RgpotRequest request;
264 capnp::MallocMessageBuilder message;
265 auto config = message.initRoot<::PotentialConfig>();
266 switch (leaf.which()) {
267 case ::PotentialSpec::NWCHEM:
268 request.potential = "nwchem";
269 config.setNwchem(leaf.getNwchem());
270 break;
271 case ::PotentialSpec::CPMD:
272 request.potential = "cpmd";
273 config.setCpmd(leaf.getCpmd());
274 break;
275#ifdef GPR_SCHEMA_HAS_CP2K_CONFIG
276 case ::PotentialSpec::CP2K:
277 request.potential = "cp2k";
278 config.setCp2k(leaf.getCp2k());
279 break;
280#endif
281 case ::PotentialSpec::UMA:
282 request.potential = "uma";
283 config.setUma(leaf.getUma());
284 break;
285 case ::PotentialSpec::METATOMIC:
286 request.potential = "metatomic";
287 config.setMetatomic(leaf.getMetatomic());
288 break;
289 case ::PotentialSpec::BUILTIN:
290 request.potential = leaf.getBuiltin().getName().cStr();
291 if (leaf.getBuiltin().getLibrary().size() != 0)
292 throw std::invalid_argument(
293 "Native expression leaves do not load engine libraries");
294 message.setRoot(leaf.getBuiltin().getConfig());
295 break;
296 default:
297 throw std::invalid_argument(
298 "Expression leaf requires a compiled rgpot backend");
299 }
300 request.config =
301 serializeConfig(message.getRoot<::PotentialConfig>().asReader());
302 return makeRgpotPotential(request);
303}
304
305Instance expressionTree(::ExprParams::Reader params)
306{
307 if (params.getExpression().size() == 0 || params.getTerms().size() == 0)
308 throw std::invalid_argument(
309 "expr requires an expression and named terms");
310 std::vector<rgpot::ExprPot::Term> children;
311 for (auto term: params.getTerms()) {
312 auto child = term.getPot();
313 if (child.isExpr())
314 children.emplace_back(term.getName().cStr(),
315 expressionTree(child.getExpr()));
316 else if (child.isPotential())
317 children.emplace_back(term.getName().cStr(),
318 expressionLeaf(child.getPotential()));
319 else
320 throw std::invalid_argument(
321 "Expression terms must contain a potential or an expression");
322 }
323 return std::make_unique<rgpot::ExprPot>(params.getExpression().cStr(),
324 std::move(children));
325}
326
327Instance expression(const RgpotRequest&, Parameters& parameters)
328{
329 if (!parameters.configured())
330 throw std::invalid_argument("expr requires PotentialConfig.expr");
331 return expressionTree(parameters.root().getExpr());
332}
333#endif
334
335#if defined(GPR_FACTORY_NWCHEM) || defined(GPR_FACTORY_CPMD) || \
336 defined(GPR_FACTORY_CP2K)
337template <class Message, class Backend>
338Instance nativeParams(const RgpotRequest&, Parameters& parameters)
339{
340 if (parameters.configured())
341 return std::make_unique<Backend>(parameters.values().as<Message>());
342 capnp::MallocMessageBuilder message;
343 return std::make_unique<Backend>(message.initRoot<Message>().asReader());
344}
345#endif
346
347const std::vector<Entry>& entries()
348{
349 static const std::vector<Entry> table = {
350 {"lj",
351 {},
352 [](const RgpotRequest&, Parameters& p) {
353 rgpot::LJConfig c;
354 c.u0 = p.get("u0", c.u0);
355 c.psi = p.get("psi", c.psi);
356 c.cutoff = p.get("cutoff", c.cutoff);
357 positive(c.u0, "u0");
358 positive(c.psi, "psi");
359 positive(c.cutoff, "cutoff");
360 return std::make_unique<rgpot::LJPot>(c);
361 },
362 ""},
363 {"lj_cluster",
364 {"ljcluster"},
365 [](const RgpotRequest&, Parameters& p) {
366 rgpot::LJClusterConfig c;
367 c.u0 = p.get("u0", c.u0);
368 c.psi = p.get("psi", c.psi);
369 c.cutoff = p.get("cutoff", c.cutoff);
370 positive(c.u0, "u0");
371 positive(c.psi, "psi");
372 positive(c.cutoff, "cutoff");
373 return std::make_unique<rgpot::LJClusterPot>(c);
374 },
375 ""},
376 {"morse",
377 {"morse_pt"},
378 [](const RgpotRequest&, Parameters& p) {
379 rgpot::MorseConfig c;
380 c.De = p.get("De", c.De);
381 c.a = p.get("a", c.a);
382 c.re = p.get("re", c.re);
383 c.cutoff = p.get("cutoff", c.cutoff);
384 positive(c.De, "De");
385 positive(c.a, "a");
386 positive(c.re, "re");
387 positive(c.cutoff, "cutoff");
388 return std::make_unique<rgpot::MorsePot>(c);
389 },
390 ""},
391 {"zbl",
392 {},
393 [](const RgpotRequest&, Parameters& p) {
394 rgpot::ZBLConfig c;
395 c.cut_inner = p.get("cut_inner", c.cut_inner);
396 c.cut_global = p.get("cut_global", c.cut_global);
397 positive(c.cut_inner, "cut_inner");
398 if (!(c.cut_global > c.cut_inner))
399 throw std::invalid_argument(
400 "ZBL cut_global must exceed cut_inner");
401 return std::make_unique<rgpot::ZBLPot>(c);
402 },
403 ""},
404#if defined(GPR_FACTORY_CUH2_CPP) || defined(RGPOT_HAS_FORTRAN_POTS)
405 {"cuh2",
406 {},
407 [](const RgpotRequest&, Parameters&) {
408#ifdef GPR_FACTORY_CUH2_CPP
409 return std::make_unique<rgpot::CuH2Pot>();
410#elif defined(RGPOT_HAS_FORTRAN_POTS)
411 return std::make_unique<rgpot::fortranpots::CuH2Pot>();
412#endif
413 },
414 ""},
415#else
416 {"cuh2", {}, {}, "rgpot CuH2 or Fortran kernels"},
417#endif
418#ifdef RGPOT_HAS_FORTRAN_POTS
419#define FORTRAN_ENTRY(name, aliases, type) \
420 {name, aliases, \
421 [](const RgpotRequest&, Parameters&) { \
422 return std::make_unique<rgpot::fortranpots::type>(); \
423 }, \
424 ""}
425#else
426#define FORTRAN_ENTRY(name, aliases, type) \
427 { \
428 name, aliases, {}, "rgpot Fortran potentials" \
429 }
430#endif
431 FORTRAN_ENTRY("sw_si", {"sw"}, SWPot),
432 FORTRAN_ENTRY("edip", {}, EDIPPot),
433 FORTRAN_ENTRY("lenosky_si", {"lenosky"}, LenoskyPot),
434 FORTRAN_ENTRY("tersoff", {"tersoff_si"}, TersoffPot),
435 FORTRAN_ENTRY("eam_al", {}, EAMAlPot),
436 FORTRAN_ENTRY("fehe", {}, FeHePot),
437 FORTRAN_ENTRY("water_h", {"tip4p_h"}, WaterHPot),
438#undef FORTRAN_ENTRY
439#ifdef RGPOT_HAS_XTB
440 {"xtb",
441 {"gfn2", "gfn1", "gfn0", "gfnff"},
442 [](const RgpotRequest& r, Parameters& p) {
443 rgpot::XTBConfig c;
444 const auto method =
445 p.get("method", r.potential == "xtb" ? std::string("gfn2")
446 : r.potential);
447 if (method == "gfn2")
448 c.method = rgpot::GFNMethod::GFN2xTB;
449 else if (method == "gfn1")
450 c.method = rgpot::GFNMethod::GFN1xTB;
451 else if (method == "gfn0")
452 c.method = rgpot::GFNMethod::GFN0xTB;
453 else if (method == "gfnff")
454 c.method = rgpot::GFNMethod::GFNFF;
455 else
456 throw std::invalid_argument(
457 "xtb method must be gfn0, gfn1, gfn2 or gfnff");
458 c.accuracy = p.get("accuracy", c.accuracy);
459 c.electronic_temperature =
460 p.get("electronic_temperature", c.electronic_temperature);
461 c.max_iterations = p.get("max_iterations", c.max_iterations);
462 c.charge = p.get("charge", c.charge);
463 c.uhf = p.get("uhf", c.uhf);
464 positive(c.accuracy, "accuracy");
465 positive(c.electronic_temperature, "electronic_temperature");
466 positive(c.max_iterations, "max_iterations");
467 if (c.uhf < 0)
468 throw std::invalid_argument("uhf must be nonnegative");
469 return std::make_unique<rgpot::XTBPot>(c);
470 },
471 "libxtb"},
472#else
473 {"xtb", {"gfn2", "gfn1", "gfn0", "gfnff"}, {}, "rgpot xTB support"},
474#endif
475#ifdef RGPOT_HAS_TBLITE
476 {"tblite",
477 {},
478 [](const RgpotRequest&, Parameters& p) {
479 rgpot::TBLiteConfig c;
480 const auto method = p.get("method", std::string("gfn2"));
481 if (method == "gfn2")
482 c.method = rgpot::TBLiteMethod::GFN2;
483 else if (method == "gfn1")
484 c.method = rgpot::TBLiteMethod::GFN1;
485 else if (method == "ipea1")
486 c.method = rgpot::TBLiteMethod::IPEA1;
487 else
488 throw std::invalid_argument(
489 "tblite method must be gfn1, gfn2 or ipea1");
490 c.accuracy = p.get("accuracy", c.accuracy);
491 c.electronic_temperature =
492 p.get("electronic_temperature", c.electronic_temperature);
493 c.max_iterations = p.get("max_iterations", c.max_iterations);
494 c.charge = p.get("charge", c.charge);
495 c.uhf = p.get("uhf", c.uhf);
496 positive(c.accuracy, "accuracy");
497 positive(c.electronic_temperature, "electronic_temperature");
498 positive(c.max_iterations, "max_iterations");
499 if (c.uhf < 0)
500 throw std::invalid_argument("uhf must be nonnegative");
501 return std::make_unique<rgpot::TBLitePot>(c);
502 },
503 "libtblite"},
504#else
505 {"tblite", {}, {}, "rgpot tblite support"},
506#endif
507#ifdef RGPOT_HAS_DFTD3
508 {"d3",
509 {},
510 [](const RgpotRequest&, Parameters& p) {
511 rgpot::D3Config c;
512 c.functional = p.get("functional", c.functional);
513 c.atm = p.get("atm", c.atm);
514 const auto damping = p.get("damping", std::string("bj"));
515 if (damping == "zero")
516 c.damping = rgpot::D3Damping::Zero;
517 else if (damping != "bj")
518 throw std::invalid_argument("d3 damping must be bj or zero");
519 return std::make_unique<rgpot::D3Pot>(c);
520 },
521 "s-dftd3 dispersion correction"},
522#else
523 {"d3", {}, {}, "rgpot D3 support (dispersion correction)"},
524#endif
525#ifdef RGPOT_HAS_DFTD4
526 {"d4",
527 {},
528 [](const RgpotRequest&, Parameters& p) {
529 rgpot::D4Config c;
530 c.functional = p.get("functional", c.functional);
531 c.atm = p.get("atm", c.atm);
532 c.charge = p.get("charge", c.charge);
533 return std::make_unique<rgpot::D4Pot>(c);
534 },
535 "dftd4 dispersion correction"},
536#else
537 {"d4", {}, {}, "rgpot D4 support (dispersion correction)"},
538#endif
539#if defined(RGPOT_HAS_EXPR) && defined(GPR_FACTORY_SCHEMA)
540 {"expr", {}, expression, "named rgpot potential terms"},
541#else
542 {"expr", {}, {}, "rgpot expression support"},
543#endif
544#ifdef GPR_FACTORY_MOPAC
545 {"mopac",
546 {},
547 [](const RgpotRequest& r, Parameters& p) {
548 rgpot::MOPACPot::Config c;
549 c.charge = p.get("charge", r.mopac_charge);
550 c.spin = p.get("spin", r.mopac_spin);
551 c.model = p.get("model", r.mopac_model);
552 c.tolerance = p.get("tolerance", c.tolerance);
553 c.max_time = p.get("max_time", c.max_time);
554 c.engine_path = p.get("engine_path", c.engine_path);
555 positive(c.tolerance, "tolerance");
556 positive(c.max_time, "max_time");
557 auto result = std::make_unique<rgpot::MOPACPot>(c);
558 if (!result->available())
559 throw std::runtime_error(
560 "MOPAC unavailable: set MOPACC_LIBRARY to libmopacc.so");
561 return result;
562 },
563 "libmopacc.so"},
564#else
565 {"mopac", {}, {}, "rgpot MOPAC frontend"},
566#endif
567#ifdef GPR_FACTORY_NWCHEM
568 {"nwchem",
569 {},
570 [](const RgpotRequest& r, Parameters& p) {
571 auto result = nativeParams<::NWChemParams, rgpot::NWChemPot>(r, p);
572 if (!static_cast<rgpot::NWChemPot&>(*result).available())
573 throw std::runtime_error(
574 "NWChem unavailable: set NWCHEMC_LIBRARY to "
575 "libnwchemc.so");
576 return result;
577 },
578 "libnwchemc.so; native NWChemParams"},
579#else
580 {"nwchem", {}, {}, "rgpot NWChem frontend and Cap'n Proto"},
581#endif
582#ifdef GPR_FACTORY_CPMD
583 {"cpmd",
584 {},
585 [](const RgpotRequest& r, Parameters& p) {
586 return nativeParams<::CPMDParams, rgpot::CPMDPot>(r, p);
587 },
588 "libcpmdc.so; native CPMDParams"},
589#else
590 {"cpmd", {}, {}, "rgpot CPMD frontend and Cap'n Proto"},
591#endif
592#ifdef GPR_FACTORY_CP2K
593 {"cp2k",
594 {},
595 [](const RgpotRequest& r, Parameters& p) {
596 auto result = nativeParams<::CP2KParams, rgpot::CP2KPot>(r, p);
597 const auto& cp2k = static_cast<rgpot::CP2KPot&>(*result);
598 if (!cp2k.available())
599 throw std::runtime_error(
600 "CP2K unavailable: " + cp2k.loadError() +
601 "; set CP2KC_LIBRARY to libcp2kc_rgpot.so");
602 return result;
603 },
604 "libcp2kc_rgpot.so; native CP2KParams"},
605#else
606 {"cp2k", {}, {}, "rgpot CP2K frontend and Cap'n Proto"},
607#endif
608#ifdef GPR_FACTORY_ORCA
609 {"orca",
610 {},
611 [](const RgpotRequest&, Parameters& p) -> Instance {
612 // liborcac reads the whole PotentialConfig, so the orca arm
613 // goes over as written; it writes the ORCA input itself.
614 if (!p.configured())
615 throw std::invalid_argument(
616 "orca requires PotentialConfig.orca (method, basis, ...)");
617 rgpot::ORCACConfig c;
618 c.message = serializeConfig(p.root());
619 c.potential_config = true;
620 auto result = std::make_unique<rgpot::ORCACPot>(std::move(c));
621 if (!result->available())
622 throw std::runtime_error(
623 "ORCA unavailable: " + result->loadError() +
624 "; set ORCAC_LIBRARY to liborcac.so");
625 return result;
626 },
627 "liborcac.so; PotentialConfig.orca"},
628#else
629 {"orca", {}, {}, "rgpot ORCA frontend and Cap'n Proto"},
630#endif
631#ifdef RGPOT_HAS_SKALA
632 {"skala",
633 {},
634 [](const RgpotRequest& r, Parameters& p) {
635 rgpot::SkalaConfig c;
636 if (!r.basis.empty()) c.basis = r.basis;
637 if (!r.xc.empty()) c.xc = r.xc;
638 c.basis = p.get("basis", c.basis);
639 c.xc = p.get("xc", c.xc);
640 c.charge = p.get("charge", r.molecular_charge);
641 c.multiplicity = p.get("multiplicity", r.multiplicity);
642 c.engine_path = p.get("engine_path", c.engine_path);
643 c.nwchem_root = p.get("nwchem_root", c.nwchem_root);
644 positive(c.multiplicity, "multiplicity");
645 return std::make_unique<rgpot::SkalaPot>(c);
646 },
647 "libnwchemc.so with Skala"},
648#else
649 {"skala", {}, {}, "rgpot Skala support"},
650#endif
651#ifdef RGPOT_HAS_UMA
652 {"uma",
653 {"omol"},
654 [](const RgpotRequest& r, Parameters& p) {
655 rgpot::UmaConfig c;
656 c.model_path = p.get("model_path", r.model_path);
657 c.device = p.get("device", r.device);
658 c.task_name = p.get("task_name", r.task_name);
659 c.charge = p.get("charge", r.charge);
660 c.spin = p.get("spin", r.spin);
661 const auto cutoff = p.get("cutoff", c.cutoff);
662 const auto neighbors = p.get("max_neighbors", c.max_neighbors);
663 if (cutoff > 0.0) c.cutoff = cutoff;
664 if (neighbors > 0) c.max_neighbors = neighbors;
665 if (c.model_path.empty())
666 throw std::invalid_argument(
667 "--model is required for uma/omol");
668 positive(c.spin, "spin");
669 positive(c.cutoff, "cutoff");
670 positive(c.max_neighbors, "max_neighbors");
671 requireAotiPackageRunsOnHost(c.model_path);
672 return std::make_unique<rgpot::UmaPot>(c);
673 },
674 "UMA model"},
675#else
676 {"uma", {"omol"}, {}, "rgpot UMA support"},
677#endif
678#ifdef RGPOT_HAS_METATOMIC
679 {"metatomic",
680 {},
681 [](const RgpotRequest& r, Parameters& p) {
682 return makeRgpotMetatomicPotential(makeRgpotMetatomicConfig(r));
683 },
684 "metatomic model"},
685#else
686 {"metatomic", {}, {}, "rgpot metatomic support"},
687#endif
688 };
689 return table;
690}
691
692const Entry* find(const std::string& name)
693{
694 for (const auto& entry: entries()) {
695 if (name == entry.name ||
696 std::find(entry.aliases.begin(), entry.aliases.end(), name) !=
697 entry.aliases.end())
698 return &entry;
699 }
700 return nullptr;
701}
702
703Instance construct(const RgpotRequest& request, Parameters& parameters)
704{
705 const auto* entry = find(request.potential);
706 if (!entry)
707 throw std::invalid_argument("unknown potential '" + request.potential +
708 "'; use --list-potentials");
709 if (!entry->make)
710 throw std::invalid_argument("potential '" + request.potential +
711 "' requires " + entry->requirement);
712 auto result = entry->make(request, parameters);
713 return result;
714}
715} // namespace
716
717std::vector<RgpotBackend> rgpotBackends()
718{
719 std::vector<RgpotBackend> result;
720 for (const auto& entry: entries())
721 result.push_back({entry.name, entry.aliases,
722 static_cast<bool>(entry.make), entry.requirement});
723 return result;
724}
725
726bool rgpotBackendAvailable(const std::string& name)
727{
728 const auto* entry = find(name);
729 return entry && static_cast<bool>(entry->make);
730}
731
732std::string canonicalRgpotName(const std::string& name)
733{
734 const auto* entry = find(name);
735 return entry ? entry->name : name;
736}
737
739{
740 std::ostringstream out;
741 out << "Potential\tDirect backend\tAliases / requirements\n";
742 for (const auto& entry: entries()) {
743 out << entry.name << '\t' << (entry.make ? "compiled" : "not compiled")
744 << '\t';
745 for (const auto& alias: entry.aliases)
746 out << alias << ' ';
747 out << entry.requirement << '\n';
748 }
749 out << "lammps\tengine plugin\tliblammps_engine.so, --lammps-params\n"
750 << "UMA, CPMD, CP2K and LAMMPS use the engine path by default; "
751 "--oracle-path direct selects the compiled backend.\n"
752 << "Compiled frontends can require external libraries or model "
753 "files.\n";
754 return out.str();
755}
756
757std::vector<unsigned char> readPotentialConfig(const std::string& path)
758{
759 if (path.empty()) return {};
760 std::ifstream input(path, std::ios::binary);
761 if (!input)
762 throw std::invalid_argument("Cannot open PotentialConfig: " + path);
763 std::vector<unsigned char> bytes{std::istreambuf_iterator<char>(input), {}};
764 if (input.bad() || bytes.empty())
765 throw std::invalid_argument("Cannot read PotentialConfig: " + path);
766 return bytes;
767}
768
769std::vector<unsigned char> potentialConfigArm(
770 const std::vector<unsigned char>& config, const std::string& potential)
771{
772 RgpotRequest request;
773 request.potential = potential;
774 request.config = config;
775 Parameters parameters(request);
776#ifdef GPR_FACTORY_SCHEMA
777 if (parameters.configured()) return serializeConfig(parameters.values());
778#endif
779 return {};
780}
781
783{
784 Parameters parameters(request);
785 const auto name = canonicalRgpotName(request.potential);
786#ifdef GPR_FACTORY_SCHEMA
787 if (parameters.configured() && !request.overrides.empty()) {
788 capnp::MallocMessageBuilder message;
789 message.setRoot(parameters.root());
790 auto root = capnp::toDynamic(message.getRoot<::PotentialConfig>());
791 KJ_IF_MAYBE (field, root.which()) {
792 auto native = root.get(*field).as<capnp::DynamicStruct>();
793 const auto set = [&](const char* key, const char* field_name,
794 auto value) {
795 if (!request.overrides.contains(key)) return;
796 // e75577bd's MetatomicParams has no charge, spin, or task
797 // name. Skip an override the pinned schema cannot store.
798 KJ_IF_MAYBE (found,
799 native.getSchema().findFieldByName(field_name)) {
800 native.set(*found, value);
801 }
802 };
803 if (name == "uma" || name == "metatomic") {
804 set("model_path", "modelPath",
805 capnp::Text::Reader(request.model_path));
806 set("device", "device", capnp::Text::Reader(request.device));
807 set("task_name", "taskName",
808 capnp::Text::Reader(request.task_name));
809 set("charge", "charge", request.charge);
810 set("spin", "spin", request.spin);
811 } else if (name == "mopac") {
812 set("charge", "charge", request.mopac_charge);
813 set("spin", "spin", request.mopac_spin);
814 set("model", "model", request.mopac_model);
815 }
816 }
817 request.config =
818 serializeConfig(message.getRoot<::PotentialConfig>().asReader());
819 }
820#endif
821 if (name == "uma" || name == "metatomic") {
822 request.model_path = parameters.get("model_path", request.model_path);
823 request.device = parameters.get("device", request.device);
824 request.task_name = parameters.get("task_name", request.task_name);
825 request.charge = parameters.get("charge", request.charge);
826 request.spin = parameters.get("spin", request.spin);
827 }
828}
829
831{
832 const auto name = canonicalRgpotName(request.potential);
833 if (name != "uma" && name != "metatomic") return;
834#if defined(RGPOT_HAS_METATOMIC) || defined(RGPOT_HAS_UMA)
835 Parameters parameters(request);
836 const int intra = parameters.get("intraop_threads", 1);
837 const int inter = parameters.get("interop_threads", 1);
838 static std::mutex runtime_mutex;
839 std::lock_guard lock(runtime_mutex);
840 if (inter > 0 && at::get_num_interop_threads() != inter)
841 at::set_num_interop_threads(inter);
842 if (intra > 0) {
843 at::set_num_threads(intra);
844 if (at::get_num_threads() != intra)
845 throw std::runtime_error(
846 "The tensor runtime cannot apply intraopThreads");
847 }
848 if (name == "uma" && parameters.get("deterministic_algorithms", false))
849 at::globalContext().setDeterministicAlgorithms(true, false);
850#endif
851}
852
853#ifdef RGPOT_HAS_METATOMIC
854rgpot::MetatomicConfig makeRgpotMetatomicConfig(const RgpotRequest& r)
855{
856 Parameters p(r);
857 rgpot::MetatomicConfig c;
858 c.model_path = p.get("model_path", r.model_path);
859 c.device = p.get("device", r.device);
860 c.length_unit = p.get("length_unit", c.length_unit);
861 c.extensions_directory =
862 p.get("extensions_directory", c.extensions_directory);
863 c.check_consistency = p.get("check_consistency", c.check_consistency);
864 c.uncertainty_threshold =
865 p.get("uncertainty_threshold", c.uncertainty_threshold);
866 c.dtype_override = p.get("dtype_override", c.dtype_override);
867 c.random_rotation = p.get("random_rotation", c.random_rotation);
868 c.n_symmetry_rotations =
869 p.get("n_symmetry_rotations", c.n_symmetry_rotations);
870 c.so3_probe_scatter = p.get("so3_probe_scatter", c.so3_probe_scatter);
871 const auto determinism = p.get("torch_determinism", std::string("fast"));
872 if (determinism == "strict" || determinism == "deterministic")
873 c.torch_determinism = rgpot::TorchDeterminismPolicy::Strict;
874 else if (determinism != "fast")
875 throw std::invalid_argument("torch_determinism must be fast or strict");
876 c.engine_path = p.get("engine_path", c.engine_path);
877 c.task_name =
878 p.get("task_name",
879 r.overrides.contains("task_name") ? r.task_name : c.task_name);
880 c.charge = p.get("charge", r.charge);
881 c.spin = p.get("spin", r.spin);
882 c.attach_system_extras =
883 p.get("attach_system_extras", c.attach_system_extras);
884 if (c.model_path.empty())
885 throw std::invalid_argument("--model is required for metatomic");
886 if (c.n_symmetry_rotations < 0)
887 throw std::invalid_argument("n_symmetry_rotations must be nonnegative");
888 positive(c.spin, "spin");
889 return c;
890}
891std::unique_ptr<rgpot::PotentialBase> makeRgpotMetatomicPotential(
892 const rgpot::MetatomicConfig& config)
893{
894 return std::make_unique<rgpot::MetatomicPot>(config);
895}
896
897#endif
898
899std::unique_ptr<rgpot::PotentialBase> makeRgpotPotential(
900 const RgpotRequest& request)
901{
902 if (request.thread_count < 1)
903 throw std::invalid_argument("rgpot thread count must be at least one");
904 Parameters parameters(request);
905 configureRgpotRuntime(request);
906 auto potential = construct(request, parameters);
907 const auto configure_threads = [&]<class Potential>(Potential& instance) {
908 if constexpr (requires {
909 instance.setThreadCount(request.thread_count);
910 })
911 instance.setThreadCount(request.thread_count);
912 };
913 configure_threads(*potential);
914 return potential;
915}
916
917} // namespace pot
Host check for the instruction set an AOTInductor package needs.
#define FORTRAN_ENTRY(name, aliases, type)
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
Potential wrappers and the batched oracle interface.
void configureRgpotRuntime(const RgpotRequest &request)
std::vector< unsigned char > readPotentialConfig(const std::string &path)
bool rgpotBackendAvailable(const std::string &name)
std::unique_ptr< rgpot::PotentialBase > makeRgpotPotential(const RgpotRequest &request)
std::vector< unsigned char > potentialConfigArm(const std::vector< unsigned char > &config, const std::string &potential)
void requireAotiPackageRunsOnHost(const std::string &path)
void applyRgpotConfig(RgpotRequest &request)
Resolve shared model settings from the typed configuration for reporting.
std::string formatPotentialCatalog()
std::string canonicalRgpotName(const std::string &name)
std::vector< RgpotBackend > rgpotBackends()
The same table drives construction, name validation and CLI discovery.
Backend inputs shared by the path and single-ended drivers.
std::set< std::string > overrides
Constructor fields explicitly supplied on the command line.
std::string task_name
std::string model_path
std::string potential
std::vector< unsigned char > config
std::string device