Loading...
Searching...
No Matches
LammpsEngineAbi.cc
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
5// LAMMPS engine behind the generic rgpot engine C ABI. The calculator is
6// liblammpc.so (OmniPotentRPC lammpc): this plugin dlopens it and never
7// links liblammps. Create takes a flat LammpsParams message. Each force
8// call sends a ForceInput in angstrom and eV and reads the PotentialResult
9// in those units (eV, eV/Angstrom), which is the engine ABI.
10
11#define RGPOT_ENGINE_BUILD
12#include <capnp/message.h>
13#include <capnp/serialize.h>
14#include <dlfcn.h>
15
16#include <algorithm>
17#include <cstdio>
18#include <cstdlib>
19#include <cstring>
20#include <filesystem>
21#include <memory>
22#include <string>
23#include <vector>
24
25#include "rgpot/engine_c_abi.h"
26#include "rgpot/rpc/Potentials.capnp.h"
27
28namespace {
29
30// Layout of lammpc.h LammpcResult. The struct is part of lammpc ABI 0 and
31// is returned by value from the session calls resolved with dlsym.
32struct LammpcResult {
33 int ok;
34 double energy_h;
35 char message[512];
36};
37
38struct LammpcSession;
39
40using SessionCreateFn = LammpcSession* (*)(const void*, size_t);
41using SessionCalcFn = LammpcResult (*)(LammpcSession*, const void*, size_t,
42 void*, size_t, size_t*);
43using SessionDestroyFn = void (*)(LammpcSession*);
44using ResultSizeFn = size_t (*)(const void*, size_t);
45using LastErrorFn = const char* (*)();
46using AvailableFn = int (*)();
47
48struct LammpcApi {
49 void* handle = nullptr;
50 SessionCreateFn create = nullptr;
51 SessionCalcFn calculate = nullptr;
52 SessionDestroyFn destroy = nullptr;
53 ResultSizeFn result_size = nullptr;
54 LastErrorFn last_error = nullptr;
55 AvailableFn available = nullptr;
56};
57
58void set_err(char* errbuf, size_t errlen, const char* msg)
59{
60 if (errbuf == nullptr || errlen == 0) return;
61 std::snprintf(errbuf, errlen, "%s", msg != nullptr ? msg : "unknown");
62}
63
64const char* api_error(const LammpcApi& api, const char* fallback)
65{
66 if (api.last_error == nullptr) return fallback;
67 const char* msg = api.last_error();
68 return (msg != nullptr && msg[0] != '\0') ? msg : fallback;
69}
70
71std::string lammpcLibraryPath()
72{
73 if (const char* env = std::getenv("LAMMPC_LIBRARY")) {
74 if (env[0] != '\0') return env;
75 }
76 if (const char* env = std::getenv("RGPOT_LAMMPC_ENGINE")) {
77 if (env[0] != '\0') return env;
78 }
79 Dl_info info{};
80 if (dladdr(reinterpret_cast<const void*>(&lammpcLibraryPath), &info) == 0 ||
81 info.dli_fname == nullptr) {
82 return "liblammpc.so";
83 }
84 const auto beside =
85 std::filesystem::path(info.dli_fname).parent_path() / "liblammpc.so";
86 std::error_code ec;
87 if (std::filesystem::exists(beside, ec)) return beside.string();
88 return "liblammpc.so";
89}
90
91bool loadApi(LammpcApi& api, std::string& err)
92{
93 const std::string path = lammpcLibraryPath();
94 api.handle = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL);
95 if (api.handle == nullptr) {
96 const char* why = dlerror();
97 err = "dlopen " + path + ": " + (why != nullptr ? why : "unknown");
98 return false;
99 }
100 auto sym = [&](const char* name) { return dlsym(api.handle, name); };
101 api.create =
102 reinterpret_cast<SessionCreateFn>(sym("lammpc_session_create"));
103 api.calculate =
104 reinterpret_cast<SessionCalcFn>(sym("lammpc_session_calculate_result"));
105 api.destroy =
106 reinterpret_cast<SessionDestroyFn>(sym("lammpc_session_destroy"));
107 api.result_size = reinterpret_cast<ResultSizeFn>(
108 sym("lammpc_potential_result_size_for_force_input"));
109 api.last_error = reinterpret_cast<LastErrorFn>(sym("lammpc_last_error"));
110 api.available = reinterpret_cast<AvailableFn>(sym("lammpc_available"));
111 if (api.create == nullptr || api.calculate == nullptr ||
112 api.destroy == nullptr || api.result_size == nullptr) {
113 err = path + ": lammpc C ABI incomplete";
114 dlclose(api.handle);
115 api.handle = nullptr;
116 return false;
117 }
118 if (api.available != nullptr && api.available() == 0) {
119 err = path +
120 ": lammpc was built without LAMMPS (stub); rebuild lammpc "
121 "with -Dwith_lammps=true";
122 dlclose(api.handle);
123 api.handle = nullptr;
124 return false;
125 }
126 return true;
127}
128
129} // namespace
130
131struct RgpotEnginePot {
132 LammpcApi api{};
133 LammpcSession* session = nullptr;
134};
135
136extern "C" {
137
139{
140 return RGPOT_ENGINE_ABI_VERSION;
141}
142
144{
145 return 1;
146}
147
149 char* errbuf, size_t errlen)
150{
151 if (config == nullptr || config_len == 0 ||
152 config_len % sizeof(capnp::word) != 0) {
154 "rgpot_engine_create(lammps): capnp LammpsParams message "
155 "required");
156 return nullptr;
157 }
158 auto pot = std::make_unique<RgpotEnginePot>();
159 std::string err;
160 if (!loadApi(pot->api, err)) {
161 set_err(errbuf, errlen, err.c_str());
162 return nullptr;
163 }
164 pot->session = pot->api.create(config, config_len);
165 if (pot->session == nullptr) {
167 api_error(pot->api, "lammpc_session_create failed"));
168 dlclose(pot->api.handle);
169 return nullptr;
170 }
171 return pot.release();
172}
173
175{
176 if (pot == nullptr) return;
177 if (pot->session != nullptr && pot->api.destroy != nullptr)
178 pot->api.destroy(pot->session);
179 if (pot->api.handle != nullptr) dlclose(pot->api.handle);
180 delete pot;
181}
182
184 const double* positions, const int* atomicNrs,
185 double* forces, double* energy, double* variance,
186 const double* box,
187 rgpot_engine_coord_transform transform,
188 void* transform_user)
189{
190 if (pot == nullptr || pot->session == nullptr || positions == nullptr ||
191 atomicNrs == nullptr || forces == nullptr || energy == nullptr ||
192 nAtoms <= 0) {
193 return 1;
194 }
195 try {
196 std::vector<double> R(positions, positions + 3 * nAtoms);
197 std::vector<double> cell(9, 0.0);
198 const bool have_box = box != nullptr;
199 if (have_box) std::copy(box, box + 9, cell.begin());
200 if (transform != nullptr) {
201 const int rc =
202 transform(transform_user, nAtoms, R.data(), cell.data());
203 if (rc != 0) return rc;
204 }
205
206 capnp::MallocMessageBuilder message;
207 auto input = message.initRoot<::ForceInput>();
208 auto pos = input.initPos(static_cast<unsigned>(3 * nAtoms));
209 for (long i = 0; i < 3 * nAtoms; ++i)
210 pos.set(static_cast<unsigned>(i), R[static_cast<size_t>(i)]);
211 auto z = input.initAtmnrs(static_cast<unsigned>(nAtoms));
212 for (long i = 0; i < nAtoms; ++i)
213 z.set(static_cast<unsigned>(i), atomicNrs[i]);
214 bool diagonal = true;
215 for (int i: {1, 2, 3, 5, 6, 7}) {
216 if (cell[static_cast<size_t>(i)] != 0.0) diagonal = false;
217 }
218 if (have_box && diagonal && cell[0] > 0.0 && cell[4] > 0.0 &&
219 cell[8] > 0.0) {
220 auto capnp_box = input.initBox(9);
221 for (int i = 0; i < 9; ++i)
222 capnp_box.set(i, cell[static_cast<size_t>(i)]);
223 }
224 input.setLengthUnit("angstrom");
225 input.setEnergyUnit("eV");
226
227 const kj::Array<capnp::word> words = capnp::messageToFlatArray(message);
228 const kj::ArrayPtr<const kj::byte> bytes = words.asBytes();
229 const size_t need = pot->api.result_size(bytes.begin(), bytes.size());
230 if (need == 0) {
231 std::fprintf(stderr,
232 "rgpot_engine_force(lammps): ForceInput rejected\n");
233 return 2;
234 }
235 // PotentialResult is a capnp flat array: the buffer has to be
236 // aligned to a word, which unsigned char storage is not.
237 std::vector<capnp::word> out((need + sizeof(capnp::word) - 1) /
238 sizeof(capnp::word));
239 size_t wrote = 0;
240 const LammpcResult result = pot->api.calculate(
241 pot->session, bytes.begin(), bytes.size(), out.data(),
242 out.size() * sizeof(capnp::word), &wrote);
243 if (result.ok == 0 || wrote == 0 || wrote % sizeof(capnp::word) != 0) {
244 std::fprintf(stderr, "rgpot_engine_force(lammps): %s\n",
245 result.message[0] != '\0'
246 ? result.message
247 : api_error(pot->api, "lammpc force failed"));
248 return 2;
249 }
250 const kj::ArrayPtr<const capnp::word> out_words(
251 out.data(), wrote / sizeof(capnp::word));
252 capnp::FlatArrayMessageReader reader(out_words);
253 const auto decoded = reader.getRoot<::PotentialResult>();
254 const auto f = decoded.getForces();
255 if (f.size() != static_cast<unsigned>(3 * nAtoms)) {
256 std::fprintf(
257 stderr,
258 "rgpot_engine_force(lammps): force length %u, expected "
259 "%ld\n",
260 f.size(), 3 * nAtoms);
261 return 2;
262 }
263 *energy = decoded.getEnergy();
264 for (unsigned i = 0; i < f.size(); ++i)
265 forces[i] = f[i];
266 if (variance != nullptr) *variance = 0.0;
267 return 0;
268 } catch (const std::exception& ex) {
269 std::fprintf(stderr, "rgpot_engine_force(lammps): %s\n", ex.what());
270 return 2;
271 } catch (...) {
272 std::fprintf(stderr, "rgpot_engine_force(lammps): unknown exception\n");
273 return 2;
274 }
275}
276
277int rgpot_engine_force_batch(RgpotEnginePot* pot, long nSystems, long nAtoms,
278 const double* positions, const int* atomicNrs,
279 double* forces, double* energies,
280 double* variances, const double* boxes,
281 rgpot_engine_coord_transform transform,
282 void* transform_user)
283{
284 if (nSystems <= 0) return 1;
285 const size_t stride = static_cast<size_t>(nAtoms) * 3;
286 for (long i = 0; i < nSystems; ++i) {
287 const int rc = rgpot_engine_force(
288 pot, nAtoms, positions + i * static_cast<long>(stride), atomicNrs,
289 forces + i * static_cast<long>(stride), energies + i,
290 variances != nullptr ? variances + i : nullptr, boxes + i * 9,
291 transform, transform_user);
292 if (rc != 0) return rc;
293 }
294 return 0;
295}
296
297} // extern "C"
static void set_err(char *errbuf, size_t errlen, const char *msg)
@ z
Definition Enums.h:28
int rgpot_engine_force(RgpotEnginePot *pot, long nAtoms, const double *positions, const int *atomicNrs, double *forces, double *energy, double *variance, const double *box, rgpot_engine_coord_transform transform, void *transform_user)
RgpotEnginePot * rgpot_engine_create(const void *config, size_t config_len, char *errbuf, size_t errlen)
int rgpot_engine_available(void)
int rgpot_engine_abi_version(void)
void rgpot_engine_destroy(RgpotEnginePot *pot)
int rgpot_engine_force_batch(RgpotEnginePot *pot, long nSystems, long nAtoms, const double *positions, const int *atomicNrs, double *forces, double *energies, double *variances, const double *boxes, rgpot_engine_coord_transform transform, void *transform_user)
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
size_t char size_t errlen
size_t char * errbuf
size_t config_len
Potential wrappers and the batched oracle interface.
std::shared_ptr< gpr::neb::ActiveLearningSession > session