Loading...
Searching...
No Matches
ReadConLoader.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
5#include "ReadConLoader.h"
6
7#include <algorithm>
8#include <fstream>
9#include <iostream>
10#include <map>
11#include <sstream>
12#include <stdexcept>
13#ifdef USE_READCON_DB
14#include <filesystem>
15
16#include "readcon-db.h"
17#endif
18
20#include "../../gpr/Enums.h"
24
25namespace gpr::io {
26
27void loadEnvironmentAtomTypes(std::istream& input,
28 gpr::AtomsConfiguration& atoms_config,
29 const gpr::InputParameters& parameters)
30{
31 const Eigen::Index n = atoms_config.atomicNrs.size();
32 if (n <= 0 || atoms_config.positions.size() != 3 * n ||
33 atoms_config.is_frozen.size() != n) {
34 throw std::invalid_argument(
35 "environment types require a complete atomic configuration");
36 }
37 std::vector<long long> labels;
38 std::vector<long long> bases;
39 std::map<long long, int> elements;
40 std::map<long long, long long> base_of_label;
41 std::string line;
42 while (std::getline(input, line)) {
43 line.erase(line.find('#') == std::string::npos ? line.size()
44 : line.find('#'));
45 std::istringstream row(line);
46 row >> std::ws;
47 if (row.eof()) continue;
48 long long atom, atomic_number, label;
49 long long base = -1;
50 std::string extra;
51 if (!(row >> atom >> atomic_number >> label) ||
52 atom != static_cast<long long>(labels.size()) || atom >= n ||
53 label < 0 || atomic_number != atoms_config.atomicNrs(0, atom)) {
54 throw std::invalid_argument(
55 "environment types require one ordered index, atomic number, "
56 "and nonnegative type per atom");
57 }
58 // An optional fourth column names the base type (element and
59 // reaction role) the environment type refines. Trailing text that
60 // is not that integer is rejected; a failed extraction must not
61 // look like an absent column.
62 row >> std::ws;
63 if (row.eof()) {
64 base = -1;
65 } else if (!(row >> base) || base < 0 || (row >> extra)) {
66 throw std::invalid_argument(
67 "environment types take one optional nonnegative base "
68 "type per atom");
69 }
70 if (!bases.empty() && (bases.back() < 0) != (base < 0))
71 throw std::invalid_argument(
72 "environment types either all carry a base type or none");
73 const auto [it, inserted] =
74 elements.emplace(label, static_cast<int>(atomic_number));
75 if (!inserted && it->second != atomic_number) {
76 throw std::invalid_argument(
77 "an environment type cannot contain different elements");
78 }
79 if (base >= 0) {
80 const auto [bit, binserted] = base_of_label.emplace(label, base);
81 if (!binserted && bit->second != base)
82 throw std::invalid_argument(
83 "an environment type cannot refine two base types");
84 }
85 labels.push_back(label);
86 bases.push_back(base);
87 }
88 if (input.bad() || static_cast<Eigen::Index>(labels.size()) != n) {
89 throw std::invalid_argument(
90 "environment types do not cover every atom");
91 }
92
93 std::map<long long, gpr::Index_t> compact;
94 std::unordered_map<std::string, gpr::Index_t> names;
95 for (const auto& [label, element]: elements) {
96 const auto type = static_cast<gpr::Index_t>(compact.size());
97 compact.emplace(label, type);
98 names.emplace(
99 "Z" + std::to_string(element) + ":env" + std::to_string(label),
100 type);
101 }
103 typed.copy(atoms_config);
104 typed.type.resize(1, n);
105 for (Eigen::Index atom = 0; atom < n; ++atom)
106 typed.type(0, atom) =
107 compact.at(labels[static_cast<std::size_t>(atom)]);
108 typed.atoms_froz_active.clear();
109 initializeAtomsConfiguration(typed.positions, parameters, names, typed);
110 typed.pair_type_parent.clear();
111 typed.n_base_pt = 0;
112 if (!bases.empty() && bases.front() >= 0) {
113 // Base pair types in order of first appearance over the pair types.
114 std::map<std::pair<long long, long long>, gpr::Index_t> base_pairs;
115 typed.pair_type_parent.assign(static_cast<std::size_t>(typed.n_pt),
116 static_cast<gpr::Index_t>(0));
117 std::vector<char> seen(static_cast<std::size_t>(typed.n_pt), 0);
118 std::vector<long long> base_of_type(compact.size(), -1);
119 for (const auto& [label, type]: compact)
120 base_of_type[static_cast<std::size_t>(type)] =
121 base_of_label.at(label);
122 for (gpr::Index_t a = 0; a < typed.pairtype.rows(); ++a) {
123 for (gpr::Index_t b = a; b < typed.pairtype.cols(); ++b) {
124 const auto k = typed.pairtype(a, b);
125 if (k == EMPTY || k < 0 || k >= typed.n_pt) continue;
126 const long long ba = base_of_type[static_cast<std::size_t>(a)];
127 const long long bb = base_of_type[static_cast<std::size_t>(b)];
128 const auto key =
129 std::make_pair(std::min(ba, bb), std::max(ba, bb));
130 const auto found = base_pairs.find(key);
131 const gpr::Index_t parent =
132 found != base_pairs.end()
133 ? found->second
134 : base_pairs
135 .emplace(key, static_cast<gpr::Index_t>(
136 base_pairs.size()))
137 .first->second;
138 if (seen[static_cast<std::size_t>(k)] &&
139 typed.pair_type_parent[static_cast<std::size_t>(k)] !=
140 parent)
141 throw std::invalid_argument(
142 "a pair type cannot refine two base pair types");
143 typed.pair_type_parent[static_cast<std::size_t>(k)] = parent;
144 seen[static_cast<std::size_t>(k)] = 1;
145 }
146 }
147 typed.n_base_pt = static_cast<gpr::Index_t>(base_pairs.size());
148 }
149 atoms_config.copy(typed);
150}
151
152void loadEnvironmentAtomTypes(const std::string& path,
153 gpr::AtomsConfiguration& atoms_config,
154 const gpr::InputParameters& parameters)
155{
156 std::ifstream input(path);
157 if (!input)
158 throw std::invalid_argument("could not open environment types: " +
159 path);
160 loadEnvironmentAtomTypes(input, atoms_config, parameters);
161}
162
164 const gpr::Coord& R_init, const gpr::InputParameters& parameters,
165 const std::unordered_map<std::string, gpr::Index_t>& atomtypes,
166 gpr::AtomsConfiguration& atoms_config)
167{
168 aux::ProblemSetUp problem_setup;
169 const gpr::Index_t number_of_mov_atoms = atoms_config.countMovingAtoms();
170 const gpr::Index_t number_of_fro_atoms =
171 static_cast<gpr::Index_t>(atoms_config.is_frozen.size()) -
172 number_of_mov_atoms;
173 const bool use_legacy_cuh2_types =
174 atomtypes.count("H2") && atomtypes.count("Cu");
175
176 atoms_config.atoms_mov.resize(number_of_mov_atoms);
177 atoms_config.atoms_froz_inactive.resize(number_of_fro_atoms);
178 atoms_config.atoms_mov.type.resize(1, number_of_mov_atoms);
179 atoms_config.atoms_froz_inactive.type.resize(1, number_of_fro_atoms);
180
181 if (use_legacy_cuh2_types) {
182 atoms_config.atoms_mov.type.setConstant(atomtypes.at("H2"));
183 atoms_config.atoms_froz_inactive.type.setConstant(atomtypes.at("Cu"));
184 }
185
186 gpr::Index_t counter_f = 0, counter_m = 0;
187 for (Eigen::Index n = 0; n < atoms_config.is_frozen.size(); ++n) {
188 if (*(atoms_config.is_frozen.data() + n) == MOVING_ATOM) {
189 gpr::coord::set(atoms_config.atoms_mov.positions, 0, counter_m,
190 gpr::coord::at(atoms_config.positions,
191 static_cast<gpr::Index_t>(n)));
192 if (!use_legacy_cuh2_types)
193 atoms_config.atoms_mov.type(0, counter_m) =
194 atoms_config.type(0, n);
195 ++counter_m;
196 } else {
198 counter_f,
199 gpr::coord::at(atoms_config.positions,
200 static_cast<gpr::Index_t>(n)));
201 if (!use_legacy_cuh2_types)
202 atoms_config.atoms_froz_inactive.type(0, counter_f) =
203 atoms_config.type(0, n);
204 ++counter_f;
205 }
206 }
207
208 atoms_config.pairtype.resize((gpr::Index_t)atomtypes.size(),
209 (gpr::Index_t)atomtypes.size());
210 atoms_config.pairtype.setConstant(EMPTY);
211 atoms_config.n_pt = 0;
212
213 problem_setup.setPairtypeForMovingAtoms(
214 atoms_config.atoms_mov.type, atoms_config.n_pt, atoms_config.pairtype);
215
216 // Active-frozen-set policy from the input parameters.
217 atoms_config.evict_frozen = parameters.evict_frozen.value != 0;
218 atoms_config.nn_frozen =
219 static_cast<gpr::Index_t>(parameters.nn_frozen.value);
220 atoms_config.nn_auto = parameters.nn_auto.value != 0;
221
222 // Selection and covariance features use the same periodic lattice.
223 std::fill(std::begin(atoms_config.cell), std::end(atoms_config.cell), 0.0);
224 if (!parameters.gp_nonperiodic.value)
225 geometry::copyMicLattice(atoms_config.cell,
226 parameters.cell_dimensions.value);
227 geometry::zeroOpenAxes(atoms_config.cell,
228 {parameters.cell_periodic.value[0] != 0,
229 parameters.cell_periodic.value[1] != 0,
230 parameters.cell_periodic.value[2] != 0});
231 problem_setup.activateFrozenAtoms(R_init, parameters.actdist_fro.value,
232 atoms_config);
233 // Default policy: hold the active set at the radius-seeded size with the
234 // nearest-neighbour rule (no effect for molecular systems with no frozen
235 // atoms, or when nn_frozen / eviction were set explicitly).
236 atoms_config.seedNearestNeighbourFromActive();
237}
238
239std::array<double, 9> cellMatrixFromLengthsAndAngles(
240 const std::array<double, 3>& cell, const std::array<double, 3>& angles)
241{
242 // An angle that compares equal to 90 is an exact zero cosine, so
243 // the 25 A Baker box stays the diagonal cellIsVacuumBox recognises.
244 mi_cell box{};
245 if (minimage_cell_from_con_box_exact(cell.data(), angles.data(), &box) !=
246 0) {
247 const char* msg = minimage_last_error();
248 throw std::invalid_argument(msg ? std::string(msg)
249 : "minimage: con box failed");
250 }
251 return {box.ax, box.ay, box.az, box.bx, box.by,
252 box.bz, box.cx, box.cy, box.cz};
253}
254
255void setCellDimensionsFromLengthsAndAngles(const std::array<double, 3>& cell,
256 const std::array<double, 3>& angles,
257 gpr::InputParameters& parameters)
258{
259 const std::array<double, 9> m =
260 cellMatrixFromLengthsAndAngles(cell, angles);
261 std::copy(m.begin(), m.end(), std::begin(parameters.cell_dimensions.value));
262}
263
264// The coordinate index and the C frame count are not the same width. A
265// count that does not fit in 3N as int, or a positive count with a null
266// atom pointer, is rejected before any index or product is formed.
267static void requireUsableFrame(const readcon::CFrame& frame, const char* role)
268{
269 if (frame.num_atoms >
270 static_cast<std::size_t>(std::numeric_limits<int>::max() / 3)) {
271 throw std::invalid_argument(
272 std::string(role) +
273 " atom count does not fit in the coordinate index");
274 }
275 if (frame.num_atoms > 0 && frame.atoms == nullptr) {
276 throw std::invalid_argument(
277 std::string(role) + " declares atoms but the atom pointer is null");
278 }
279}
280
281template <class To, class From>
282static To checkedNarrow(From value, const char* field)
283{
284 if (value > static_cast<From>(std::numeric_limits<To>::max())) {
285 throw std::invalid_argument(std::string(field) +
286 " is out of range for this build");
287 }
288 return static_cast<To>(value);
289}
290
291void loadAtomsConfigurationFromFrame(const readcon::CFrame& frame,
292 gpr::AtomsConfiguration& atoms_config,
293 gpr::Coord& R_init,
294 gpr::InputParameters& parameters,
295 const readcon::CFrame* product,
296 std::vector<int>* reactive_atoms)
297{
298 requireUsableFrame(frame, "frame");
299 const int n_atoms = static_cast<int>(frame.num_atoms);
300 atoms_config.clear();
301
302 atoms_config.positions.resize(1, 3 * n_atoms);
303 atoms_config.is_frozen.resize(1, n_atoms);
304 atoms_config.id.resize(1, n_atoms);
305 atoms_config.atomicNrs.resize(1, n_atoms);
306 atoms_config.atomic_masses.resize(n_atoms);
307 atoms_config.type.resize(1, n_atoms);
308
309 std::vector<std::uint64_t> atomic_nrs(static_cast<std::size_t>(n_atoms));
310 for (int i = 0; i < n_atoms; ++i)
311 atomic_nrs[static_cast<std::size_t>(i)] = frame.atoms[i].atomic_number;
312 const auto element_types =
313 elementAtomTypes<gpr::Index_t>(atomic_nrs.data(), atomic_nrs.size());
314 std::unordered_map<std::string, gpr::Index_t> atomtypes;
315 for (std::size_t i = 0; i < atomic_nrs.size(); ++i)
316 atomtypes["Z" + std::to_string(atomic_nrs[i])] = element_types[i];
317
318 int n_partially_fixed = 0;
319 for (int i = 0; i < n_atoms; ++i) {
320 atoms_config.positions(0, 3 * i) = frame.atoms[i].x;
321 atoms_config.positions(0, 3 * i + 1) = frame.atoms[i].y;
322 atoms_config.positions(0, 3 * i + 2) = frame.atoms[i].z;
323 // CAtom.is_fixed is true when ANY axis is fixed; gpr's
324 // is_frozen is all-or-nothing, so a partially fixed atom
325 // becomes fully frozen here. Count and warn below rather than
326 // silently over-constraining.
327 atoms_config.is_frozen(0, i) =
328 frame.atoms[i].is_fixed ? FROZEN_ATOM : MOVING_ATOM;
329 if (frame.atoms[i].is_fixed &&
330 !(frame.atoms[i].fixed_x && frame.atoms[i].fixed_y &&
331 frame.atoms[i].fixed_z))
332 ++n_partially_fixed;
333 atoms_config.id(0, i) =
334 checkedNarrow<gpr::Index_t>(frame.atoms[i].atom_id, "atom_id");
335 atoms_config.atomicNrs(0, i) = checkedNarrow<gpr::Index_t>(
336 frame.atoms[i].atomic_number, "atomic_number");
337 atoms_config.atomic_masses(i) = frame.atoms[i].mass;
338 atoms_config.type(0, i) = element_types[static_cast<std::size_t>(i)];
339 }
340 if (n_partially_fixed > 0)
341 std::cerr << "ReadConLoader: " << n_partially_fixed
342 << " atom(s) carry per-axis fixed flags; gpr supports "
343 "only fully frozen atoms and treats them as frozen "
344 "on all axes\n";
345 if (frame.has_velocities)
346 std::cerr << "ReadConLoader: frame declares a velocities section; "
347 "the GP drivers are static (dimer / NEB) and the "
348 "velocity data is not used\n";
349
350 R_init = atoms_config.positions;
352 {frame.cell[0], frame.cell[1], frame.cell[2]},
353 {frame.angles[0], frame.angles[1], frame.angles[2]}, parameters);
354
355 if (reactive_atoms) reactive_atoms->clear();
356 if (product) {
357 requireUsableFrame(*product, "product frame");
358 if (static_cast<int>(product->num_atoms) != n_atoms) {
359 std::cerr << "ReadConLoader: product frame has "
360 << product->num_atoms << " atoms, reactant " << n_atoms
361 << "; reactive atom types skipped\n";
362 } else {
363 bool same_elements = true;
364 std::vector<int> Z(static_cast<std::size_t>(n_atoms));
365 std::vector<gpr::Index_t> types(static_cast<std::size_t>(n_atoms));
366 Eigen::VectorXd x_react(3 * n_atoms), x_prod(3 * n_atoms);
367 for (int i = 0; i < n_atoms; ++i) {
368 Z[static_cast<std::size_t>(i)] = checkedNarrow<int>(
369 frame.atoms[i].atomic_number, "atomic_number");
370 same_elements =
371 same_elements && product->atoms[i].atomic_number ==
372 frame.atoms[i].atomic_number;
373 types[static_cast<std::size_t>(i)] = atoms_config.type(0, i);
374 x_react.segment<3>(3 * i) << frame.atoms[i].x, frame.atoms[i].y,
375 frame.atoms[i].z;
376 x_prod.segment<3>(3 * i) << product->atoms[i].x,
377 product->atoms[i].y, product->atoms[i].z;
378 }
379 if (!same_elements) {
380 std::cerr << "ReadConLoader: product elements differ from "
381 "the reactant; reactive atom types skipped\n";
382 } else {
383 std::array<double, 9> cell{};
384 if (!parameters.gp_nonperiodic.value)
385 std::copy(std::begin(parameters.cell_dimensions.value),
386 std::begin(parameters.cell_dimensions.value) + 9,
387 cell.begin());
388 const auto reactive = gpr::geometry::assignReactiveAtomTypes(
389 x_react, x_prod, Z, types, atomtypes, cell);
390 for (int i = 0; i < n_atoms; ++i)
391 atoms_config.type(0, i) =
392 reactive.types[static_cast<std::size_t>(i)];
393 atomtypes = reactive.atomtypes;
394 if (reactive_atoms) *reactive_atoms = reactive.reactive_atoms;
395 }
396 }
397 }
398
399 initializeAtomsConfiguration(R_init, parameters, atomtypes, atoms_config);
400}
401
402#ifdef USE_READCON_DB
403std::size_t ingestConDirectory(const std::string& corpus_dir,
404 const std::string& tree)
405{
406 namespace fs = std::filesystem;
407 fs::create_directories(corpus_dir);
408 readcon_db::Corpus corpus(corpus_dir.c_str());
409 std::vector<fs::path> files;
410 for (const auto& entry: fs::recursive_directory_iterator(tree)) {
411 if (!entry.is_regular_file()) continue;
412 if (entry.path().extension() != ".con") continue;
413 files.push_back(entry.path());
414 }
415 std::sort(files.begin(), files.end());
416 std::size_t ingested = 0;
417 for (const auto& file: files) {
418 uint32_t n = 0;
419 const int status = rkrdb_append_trajectory(
420 corpus.id(), static_cast<uint64_t>(ingested + 1),
421 file.string().c_str(), &n);
422 if (status != RKRDB_OK || n == 0)
423 throw std::runtime_error("ingest failed for " + file.string());
424 ++ingested;
425 }
426 return ingested;
427}
428#endif
429
430} // namespace gpr::io
@ FROZEN_ATOM
Definition Enums.h:36
@ MOVING_ATOM
Definition Enums.h:35
#define EMPTY
Definition Macros.h:39
Set up the GP-dimer problem.
bool activateFrozenAtoms(const gpr::Coord &R, const double activation_distance, gpr::AtomsConfiguration &atoms_config)
Update the active frozen-atom set for one or more configurations.
void setPairtypeForMovingAtoms(const gpr::FieldMatrixIdx &atomtype_mov, gpr::Index_t &n_pt, gpr::FieldMatrixi &pairtype)
Set pairtype indices for moving+moving atom pairs and gives the updated number of active pairtypes.
int status
Eigen::Vector3d at(const FieldMatrixd &mat, Index_t i)
void set(FieldMatrixd &mat, Index_t i, const Eigen::Vector3d &vec)
void zeroOpenAxes(double cell[9], const std::array< bool, 3 > &periodic) noexcept
Definition MinImage.h:136
bool copyMicLattice(double dest[9], const double src[9]) noexcept
Copy src onto dest only when src is a MIC lattice.
Definition MinImage.h:68
ReactiveAtomTypes assignReactiveAtomTypes(const Eigen::VectorXd &reactant, const Eigen::VectorXd &product, const std::vector< int > &atomic_numbers, const std::vector< Index_t > &types, const std::unordered_map< std::string, Index_t > &atomtypes, const std::array< double, 9 > &cell)
void setCellDimensionsFromLengthsAndAngles(const std::array< double, 3 > &cell, const std::array< double, 3 > &angles, gpr::InputParameters &parameters)
void loadEnvironmentAtomTypes(std::istream &input, gpr::AtomsConfiguration &atoms_config, const gpr::InputParameters &parameters)
void loadAtomsConfigurationFromFrame(const readcon::CFrame &frame, gpr::AtomsConfiguration &atoms_config, gpr::Coord &R_init, gpr::InputParameters &parameters, const readcon::CFrame *product, std::vector< int > *reactive_atoms)
static To checkedNarrow(From value, const char *field)
std::array< double, 9 > cellMatrixFromLengthsAndAngles(const std::array< double, 3 > &cell, const std::array< double, 3 > &angles)
static void requireUsableFrame(const readcon::CFrame &frame, const char *role)
std::vector< Type > elementAtomTypes(const AtomicNr *atomic_nrs, std::size_t n_atoms)
void initializeAtomsConfiguration(const gpr::Coord &R_init, const gpr::InputParameters &parameters, const std::unordered_map< std::string, gpr::Index_t > &atomtypes, gpr::AtomsConfiguration &atoms_config)
FieldMatrixd Coord
Definition Macros.h:35
uint32_t Index_t
Definition Macros.h:17
Stores configurations of all atoms in the system.
Definition Structures.h:832
std::vector< Index_t > pair_type_parent
Definition Structures.h:854
void seedNearestNeighbourFromActive()
Seed the fixed-N nearest-neighbour set from the current active (radius-activated) frozen count....
Definition Structures.h:890
FieldMatrixi atomicNrs
Atomic Number of each atom.
Definition Structures.h:836
AtomsPositionAndType atoms_froz_inactive
Info on inactive frozen atoms.
Definition Structures.h:843
FieldMatrixU8 is_frozen
Indicates whether atom is frozen or not.
Definition Structures.h:834
FieldMatrixIdx id
ID of each atom (we do not use it).
Definition Structures.h:835
AtomsPositionAndType atoms_froz_active
Info on active frozen atoms.
Definition Structures.h:841
Index_t n_base_pt
Number of base pair types (0: none).
Definition Structures.h:855
AtomsPositionAndType atoms_mov
Info on moving atoms.
Definition Structures.h:844
void copy(const AtomsConfiguration &other)
Definition Structures.h:959
FieldMatrixIdx type
Type of each atom.
Definition Structures.h:839
Coord positions
Positions of all atoms in the system.
Definition Structures.h:833
Eigen::VectorXd atomic_masses
Per-atom input masses; empty selects unit masses.
Definition Structures.h:838
void resize(const Index_t num_atoms)
Definition Structures.h:814
Structure of the input parameters. All input parameters are pairs of string names and values.
Definition Structures.h:370
KeyValuePair< double[9]> cell_dimensions
Definition Structures.h:605
KeyValuePair< int > nn_frozen
Definition Structures.h:381
KeyValuePair< int > gp_nonperiodic
Definition Structures.h:603
KeyValuePair< int > nn_auto
Definition Structures.h:382
KeyValuePair< double > actdist_fro
Definition Structures.h:379
KeyValuePair< int > evict_frozen
Definition Structures.h:380