Loading...
Searching...
No Matches
SeedKernel.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3#include "SeedKernel.h"
4
5#include <algorithm>
6#include <cmath>
7#include <iomanip>
8#include <istream>
9#include <map>
10#include <memory>
11#include <ostream>
12#include <set>
13#include <sstream>
14#include <stdexcept>
15#include <string>
16#include <unordered_map>
17#include <vector>
18
21#include "ReadConLoader.h"
22
23namespace gpr::io {
24
27{
28 std::ostringstream out;
29 out << std::setprecision(17);
30 const auto matrix = [&](const auto& value) {
31 out << ' ' << value.rows() << ' ' << value.cols();
32 for (Eigen::Index i = 0; i < value.rows(); ++i)
33 for (Eigen::Index j = 0; j < value.cols(); ++j)
34 out << ' ' << +value(i, j);
35 };
36 matrix(atoms.atomicNrs);
37 matrix(atoms.is_frozen);
38 matrix(atoms.type);
39 matrix(atoms.atoms_mov.type);
40 matrix(atoms.atoms_froz_active.type);
41 matrix(atoms.atoms_froz_active.positions);
42 matrix(atoms.pairtype);
43 for (const double entry: atoms.cell)
44 out << ' ' << entry;
45 return out.str();
46}
47
48namespace {
49
50std::string kernelIdentity(const GaussianProcessRegression& gp,
51 const AtomsConfiguration& atoms, bool chart,
52 bool heat, bool components)
53{
54 std::ostringstream out;
55 out << (components ? "v2 " : "v1 ")
56 << static_cast<int>(gp.getModelProfile()) << ' '
57 << gp.getUseZBLPriorMean() << ' ' << gp.getUseFFPriorMean() << ' '
58 << chart;
59 if (components) out << ' ' << heat;
61 return out.str();
62}
63
64void writeChart(std::ostream& out,
65 const geometry::InternalCoordinateChart& chart)
66{
67 const auto& coordinates = chart.internalCoordinates();
68 out << "chart " << coordinates.numAtoms() << ' '
69 << coordinates.movingAtoms().size();
70 for (const char moving: coordinates.movingAtoms())
71 out << ' ' << (moving != 0);
72 for (Eigen::Index i = 0; i < chart.anchor().size(); ++i)
73 out << ' ' << chart.anchor()(i);
74 for (const double cell: coordinates.cell())
75 out << ' ' << cell;
76 out << ' ' << coordinates.primitives().size();
77 for (const auto& primitive: coordinates.primitives()) {
78 out << ' ' << static_cast<int>(primitive.kind);
79 for (const int atom: primitive.atoms)
80 out << ' ' << atom;
81 for (Eigen::Index axis = 0; axis < 3; ++axis)
82 out << ' ' << primitive.reference(axis);
83 }
84 out << '\n';
85}
86
87std::shared_ptr<const geometry::InternalCoordinateChart> readChart(
88 std::istream& row, Eigen::Index moving_atoms, std::size_t line_size)
89{
90 int atom_count = 0;
91 std::size_t mask_count = 0;
92 if (!(row >> atom_count >> mask_count) || atom_count != moving_atoms ||
93 atom_count <= 0 || (mask_count != 0 && mask_count != moving_atoms))
94 return {};
95 std::vector<char> mask(mask_count);
96 for (auto& moving: mask) {
97 int value = -1;
98 if (!(row >> value) || (value != 0 && value != 1)) return {};
99 moving = static_cast<char>(value);
100 }
101 Eigen::VectorXd anchor(3 * moving_atoms);
102 for (Eigen::Index i = 0; i < anchor.size(); ++i)
103 if (!(row >> anchor(i))) return {};
104 std::array<double, 9> cell{};
105 for (double& value: cell)
106 if (!(row >> value) || !std::isfinite(value)) return {};
107 std::size_t primitive_count = 0;
108 if (!(row >> primitive_count) || primitive_count == 0 ||
109 primitive_count > line_size / 8)
110 return {};
111 std::vector<geometry::PrimitiveInternal> primitives(primitive_count);
112 for (auto& primitive: primitives) {
113 int kind = -1;
114 if (!(row >> kind) || kind < 0 ||
115 kind > static_cast<int>(geometry::PrimitiveKind::LinearBend))
116 return {};
117 primitive.kind = static_cast<geometry::PrimitiveKind>(kind);
118 for (int& atom: primitive.atoms)
119 if (!(row >> atom)) return {};
120 for (Eigen::Index axis = 0; axis < 3; ++axis)
121 if (!(row >> primitive.reference(axis))) return {};
122 if (!primitive.reference.allFinite()) return {};
123 }
124 auto internals = std::make_shared<const geometry::InternalCoordinateSet>(
125 atom_count, std::move(mask), std::move(primitives), cell);
126 auto chart = std::make_shared<const geometry::InternalCoordinateChart>(
127 std::move(internals), std::move(anchor));
128 return chart->valid() ? chart : nullptr;
129}
130
131std::shared_ptr<const GeodesicHeatEnergyForceKernel> readHeat(
132 std::istream& row, const AtomsConfiguration& atoms, std::size_t line_size)
133{
134 double weight = -1.0;
135 Eigen::Index metric_count = 0, rows = 0, columns = 0;
136 if (!(row >> weight >> metric_count) || !(weight > 0.0) ||
137 !std::isfinite(weight) || metric_count != atoms.n_pt ||
138 metric_count <= 0)
139 return {};
140 FieldMatrixd metric(1, metric_count);
141 for (Eigen::Index i = 0; i < metric_count; ++i)
142 if (!(row >> metric(0, i))) return {};
143 if (!(row >> rows >> columns) || rows <= 0 ||
144 columns != 3 * atoms.atoms_mov.type.size() || columns <= 0 ||
145 static_cast<std::size_t>(rows) >
146 line_size / static_cast<std::size_t>(columns))
147 return {};
148 Coord reference(rows, columns);
149 for (Eigen::Index i = 0; i < rows; ++i)
150 for (Eigen::Index j = 0; j < columns; ++j)
151 if (!(row >> reference(i, j))) return {};
152 return std::make_shared<const GeodesicHeatEnergyForceKernel>(
153 reference, atoms, metric, weight);
154}
155
156} // namespace
157
159 const AtomsConfiguration& atoms)
160{
162 throw std::invalid_argument(
163 "atomic environment parameters cannot use the pair seed-kernel "
164 "format");
165 const auto& covariance = gp.getSexpAtCovarianceFunction();
166 const bool chart = covariance.usesManifoldChart();
167 const bool heat = covariance.usesGeodesicHeatKernel();
168 return kernelIdentity(gp, atoms, chart, heat, chart || heat);
169}
170
175bool readSeedKernelAtomTypes(std::istream& input, AtomsConfiguration& atoms,
176 const InputParameters& parameters)
177{
178 const Eigen::Index n = atoms.atomicNrs.size();
179 if (n <= 0) return false;
180 std::string line, identity;
181 while (std::getline(input, line)) {
182 std::istringstream row(line);
183 std::string key;
184 if (row >> key && key == "identity") {
185 if (!identity.empty()) return false;
186 std::getline(row >> std::ws, identity);
187 if (identity.empty()) return false;
188 }
189 }
190 if (input.bad() || identity.empty()) return false;
191 std::istringstream row(identity);
192 std::string version;
193 int profile, zbl, ff, manifold, heat = 0;
194 if (!(row >> version >> profile >> zbl >> ff >> manifold) ||
195 (version != "v1" && version != "v2"))
196 return false;
197 if (version == "v2" && (!(row >> heat) || (heat != 0 && heat != 1)))
198 return false;
199 const auto read_matrix = [&](auto& matrix, Eigen::Index max_entries) {
200 Eigen::Index rows, cols;
201 if (!(row >> rows >> cols) || rows < 0 || cols < 0 ||
202 rows > max_entries || cols > max_entries ||
203 (cols > 0 && rows > max_entries / cols))
204 return false;
205 matrix.resize(rows, cols);
206 for (Eigen::Index i = 0; i < rows; ++i)
207 for (Eigen::Index j = 0; j < cols; ++j)
208 if (!(row >> matrix(i, j))) return false;
209 return matrix.allFinite();
210 };
211 AtomsConfiguration archived;
212 FieldMatrixi frozen;
213 if (!read_matrix(archived.atomicNrs, n) || !read_matrix(frozen, n) ||
214 !read_matrix(archived.type, n) ||
215 !read_matrix(archived.atoms_mov.type, n) ||
216 !read_matrix(archived.atoms_froz_active.type, n) ||
217 !read_matrix(archived.atoms_froz_active.positions, 3 * n) ||
218 !read_matrix(archived.pairtype,
219 static_cast<Eigen::Index>(identity.size())))
220 return false;
221 for (double& entry: archived.cell)
222 if (!(row >> entry) || !std::isfinite(entry)) return false;
223 std::string extra;
224 if (row >> extra) return false;
225 const auto same = [](const auto& a, const auto& b) {
226 return a.rows() == b.rows() && a.cols() == b.cols() &&
227 (a.template cast<double>().array() ==
228 b.template cast<double>().array())
229 .all();
230 };
231 if (!same(archived.atomicNrs, atoms.atomicNrs) ||
232 !same(frozen, atoms.is_frozen) || archived.type.rows() != 1 ||
233 archived.type.cols() != n || archived.pairtype.rows() <= 0 ||
234 archived.pairtype.rows() != archived.pairtype.cols())
235 return false;
236 archived.is_frozen = atoms.is_frozen;
237 std::map<int, int> elements;
238 for (Eigen::Index i = 0; i < n; ++i) {
239 const int type = archived.type(0, i);
240 const int element = archived.atomicNrs(0, i);
241 if (type < 0 || type >= archived.pairtype.rows()) return false;
242 const auto [it, inserted] = elements.emplace(type, element);
243 if (!inserted && it->second != element) return false;
244 }
245 std::unordered_map<std::string, Index_t> names;
246 for (Eigen::Index i = 0; i < archived.pairtype.rows(); ++i)
247 names.emplace("seed:" + std::to_string(i), static_cast<Index_t>(i));
248 AtomsConfiguration typed;
249 typed.copy(atoms);
250 typed.type = archived.type;
251 typed.atoms_froz_active.clear();
252 initializeAtomsConfiguration(typed.positions, parameters, names, typed);
253 if (seedKernelAtomsIdentity(typed) != seedKernelAtomsIdentity(archived))
254 return false;
255 atoms.copy(typed);
256 return true;
257}
258
259void writeSeedKernel(std::ostream& out, const GaussianProcessRegression& gp,
260 const AtomsConfiguration& atoms)
261{
263 throw std::invalid_argument(
264 "atomic environment parameters cannot use the pair seed-kernel "
265 "format");
266 const auto& covariance = gp.getSexpAtCovarianceFunction();
267 const auto& lengths = covariance.getLengthScaleRef();
268 const auto& chart = covariance.manifoldChart();
269 const auto& heat = covariance.geodesicHeatKernel();
270 out << std::setprecision(17);
271 if (chart || heat)
272 out << "components 1 " << static_cast<bool>(chart) << ' '
273 << static_cast<bool>(heat) << '\n';
274 out << "magnSigma2 " << covariance.getMagnSigma2() << '\n'
275 << "constSigma2 " << gp.getConstantCovarianceFunction().getConstSigma2()
276 << '\n'
277 << "sigma2 " << gp.getLikGaussian().getSigma2() << '\n'
278 << "pairCutoff " << covariance.getConfInfo().pair_cutoff << ' '
279 << covariance.getConfInfo().pair_cutoff_width << '\n'
280 << "lengthScale " << lengths.size();
281 for (Eigen::Index i = 0; i < lengths.size(); ++i)
282 out << ' ' << lengths.data()[i];
283 out << "\noutputTransform " << gp.outputMean() << ' ' << gp.outputScale()
284 << ' ' << gp.outputMeanFrozen() << "\nidentity "
285 << seedKernelIdentity(gp, atoms) << '\n';
286 if (chart) {
287 const auto& pair_lengths = covariance.getAtomisticLengthScaleRef();
288 out << "atomisticLengthScale " << pair_lengths.size();
289 for (Eigen::Index i = 0; i < pair_lengths.size(); ++i)
290 out << ' ' << pair_lengths.data()[i];
291 out << '\n';
292 writeChart(out, *chart);
293 }
294 if (heat) {
295 const auto& metric = heat->atomisticLengthScales();
296 const auto& reference = heat->referencePath();
297 out << "heat " << heat->covarianceWeight() << ' ' << metric.size();
298 for (Eigen::Index i = 0; i < metric.size(); ++i)
299 out << ' ' << metric.data()[i];
300 out << ' ' << reference.rows() << ' ' << reference.cols();
301 for (Eigen::Index i = 0; i < reference.rows(); ++i)
302 for (Eigen::Index j = 0; j < reference.cols(); ++j)
303 out << ' ' << reference(i, j);
304 out << '\n';
305 }
306 if (!out) throw std::runtime_error("could not write seed kernel");
307}
308
310bool readSeedKernel(std::istream& input, GaussianProcessRegression& gp,
311 const AtomsConfiguration& atoms, bool require_identity,
312 bool preserve_source_noise)
313{
314 if (gp.atomicEnvironmentModelEnabled()) return false;
315 double magnitude = -1.0, constant = -1.0;
316 double source_noise = -1.0;
317 double pair_cutoff = 0.0, pair_cutoff_width = 0.0;
318 double mean = gp.outputMean(), scale = gp.outputScale();
319 int frozen_mean = gp.outputMeanFrozen();
320 std::vector<double> lengths, atomistic_lengths;
321 std::shared_ptr<const geometry::InternalCoordinateChart> chart;
322 std::shared_ptr<const GeodesicHeatEnergyForceKernel> heat;
323 int chart_present = 0, heat_present = 0;
324 std::set<std::string> seen;
325 std::string line, identity;
326 while (std::getline(input, line)) {
327 std::istringstream row(line);
328 std::string key;
329 if (!(row >> key)) continue;
330 if (!seen.insert(key).second) return false;
331 if (key == "identity") {
332 std::getline(row >> std::ws, identity);
333 if (identity.empty()) return false;
334 continue;
335 }
336 if (key == "components") {
337 int version = 0;
338 if (!(row >> version >> chart_present >> heat_present) ||
339 version != 1 || (chart_present != 0 && chart_present != 1) ||
340 (heat_present != 0 && heat_present != 1))
341 return false;
342 } else if (key == "chart") {
343 try {
344 chart =
345 readChart(row, atoms.atoms_mov.type.size(), line.size());
346 } catch (const std::exception&) {
347 return false;
348 }
349 if (!chart) return false;
350 } else if (key == "heat") {
351 try {
352 heat = readHeat(row, atoms, line.size());
353 } catch (const std::exception&) {
354 return false;
355 }
356 if (!heat) return false;
357 } else if (key == "magnSigma2") {
358 row >> magnitude;
359 } else if (key == "constSigma2") {
360 row >> constant;
361 } else if (key == "lengthScale" || key == "atomisticLengthScale") {
362 std::size_t count = 0;
363 row >> count;
364 if (!row || count == 0 || (count != 1 && count != atoms.n_pt))
365 return false;
366 auto& values = key == "lengthScale" ? lengths : atomistic_lengths;
367 values.resize(count);
368 for (auto& length: values)
369 row >> length;
370 } else if (key == "outputTransform") {
371 row >> mean >> scale >> frozen_mean;
372 } else if (key == "sigma2") {
373 row >> source_noise;
374 if (!std::isfinite(source_noise) || source_noise < 0.0)
375 return false;
376 } else if (key == "pairCutoff") {
377 row >> pair_cutoff >> pair_cutoff_width;
378 try {
379 (void)PairCutoff(pair_cutoff, pair_cutoff_width);
380 } catch (const std::invalid_argument&) {
381 return false;
382 }
383 } else {
384 return false;
385 }
386 if (!row) return false;
387 std::string extra;
388 if (row >> extra) return false;
389 }
390 // An absent cutoff record denotes the unbounded descriptor. A seed
391 // changes fitted parameters, not the destination's descriptor domain.
392 const auto& descriptor = gp.getSexpAtCovarianceFunction().getConfInfo();
393 if (pair_cutoff != atoms.pair_cutoff ||
394 pair_cutoff_width != atoms.pair_cutoff_width ||
395 pair_cutoff != descriptor.pair_cutoff ||
396 pair_cutoff_width != descriptor.pair_cutoff_width)
397 return false;
398 const bool components = seen.count("components") != 0;
399 if (static_cast<bool>(chart) != (chart_present != 0) ||
400 static_cast<bool>(heat) != (heat_present != 0) ||
401 (!components && (chart || heat || !atomistic_lengths.empty())) ||
402 (components &&
403 (!seen.count("identity") || !seen.count("outputTransform"))) ||
404 (chart && atomistic_lengths.size() != atoms.n_pt) ||
405 (!chart && !atomistic_lengths.empty()))
406 return false;
407 if (!identity.empty() &&
408 identity != kernelIdentity(gp, atoms, static_cast<bool>(chart),
409 static_cast<bool>(heat), components))
410 return false;
411 if (input.bad() || (require_identity && !seen.count("identity")) ||
412 (seen.count("identity") && !seen.count("outputTransform")) ||
413 lengths.size() != (chart ? 1 : atoms.n_pt) || lengths.empty() ||
414 !std::isfinite(magnitude) || magnitude <= 0.0 ||
415 !std::isfinite(constant) || constant < 0.0 || !std::isfinite(mean) ||
416 !std::isfinite(scale) || scale <= 0.0 ||
417 (frozen_mean != 0 && frozen_mean != 1))
418 return false;
419 for (const double length: lengths)
420 if (!std::isfinite(length) || length <= 0.0) return false;
421 for (const double length: atomistic_lengths)
422 if (!std::isfinite(length) || length <= 0.0) return false;
423
424 // An archive handoff preserves its physical likelihood variance. An
425 // independent fit keeps the destination's configured resolution.
426 const double scale_squared = scale * scale;
427 if (preserve_source_noise &&
428 (!seen.count("sigma2") || !seen.count("outputTransform") ||
429 !(source_noise > 0.0) || !std::isfinite(scale_squared) ||
430 !(scale_squared > 0.0)))
431 return false;
432 const double physical_noise = preserve_source_noise
433 ? source_noise * scale_squared
434 : gp.getLikGaussian().getSigma2() *
435 gp.outputScale() * gp.outputScale();
436 const double training_noise = physical_noise / scale / scale;
437 if (!std::isfinite(physical_noise) || !std::isfinite(training_noise) ||
438 training_noise < 0.0 ||
439 (preserve_source_noise && !(training_noise > 0.0)))
440 return false;
441 auto& covariance = gp.getSexpAtCovarianceFunction();
442 covariance.clearManifoldChart();
444 gp.restoreOutputTransform(mean, scale, frozen_mean != 0);
445 if (preserve_source_noise)
446 (void)gp.setLikelihoodNoiseVariance(physical_noise);
447 else
448 gp.getLikGaussian().setSigma2(training_noise);
449 covariance.setMagnSigma2(magnitude);
451 const auto& pair_lengths = chart ? atomistic_lengths : lengths;
452 covariance.getAtomisticLengthScaleRef().resize(1, pair_lengths.size());
453 std::copy(pair_lengths.begin(), pair_lengths.end(),
454 covariance.getAtomisticLengthScaleRef().data());
455 if (chart) gp.setInternalCoordinateChart(std::move(chart), lengths.front());
456 if (heat) gp.setGeodesicHeatPrior(std::move(heat));
457 // The archive kernel is the band's fitted maximum-evidence kernel for
458 // these rows; the destination starts from a fitted state.
460 return true;
461}
462
463} // namespace gpr::io
double getConstSigma2()
void setConstSigma2(const double _constSigma2)
Set the constSigma2 value.
LikelihoodNoiseVarianceUpdate setLikelihoodNoiseVariance(double physical_sigma2, const Observation *full_observation=nullptr)
Set the likelihood noise variance in physical output units.
void setGeodesicHeatPrior(std::shared_ptr< const GeodesicHeatEnergyForceKernel > kernel)
void setInternalCoordinateChart(std::shared_ptr< const geometry::InternalCoordinateChart > chart, double length_scale)
bool atomicEnvironmentModelEnabled() const noexcept
GPModelProfile getModelProfile() const noexcept
void restoreOutputTransform(double mean, double scale, bool frozen_mean)
Restore output coordinates alongside a kernel represented in them.
double getSigma2() const noexcept
Get sigma2 value (the per-row noise variance added to the energy diagonal of the training kernel by e...
Definition LikGaussian.h:74
void setSigma2(const double value)
Set sigma2 value.
const AtomsConfiguration & getConfInfo() const noexcept
Definition SexpatCF.h:678
bool usesManifoldChart() const noexcept
Definition SexpatCF.h:616
void clearManifoldChart()
Definition SexpatCF.cpp:513
FieldMatrixd & getLengthScaleRef()
Definition SexpatCF.inl:58
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
bool readSeedKernel(std::istream &input, GaussianProcessRegression &gp, const AtomsConfiguration &atoms, bool require_identity, bool preserve_source_noise)
Validate the complete seed before changing any model parameter.
void writeSeedKernel(std::ostream &out, const GaussianProcessRegression &gp, const AtomsConfiguration &atoms)
Write fitted covariance parameters, output units, and descriptor identity.
bool readSeedKernelAtomTypes(std::istream &input, AtomsConfiguration &atoms, const InputParameters &parameters)
Restore the archived type map after checking physical atom identity.
std::string seedKernelIdentity(const GaussianProcessRegression &gp, const AtomsConfiguration &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)
std::string seedKernelAtomsIdentity(const AtomsConfiguration &atoms)
Atomic descriptor identity; moving positions belong to the observations.
Eigen::Matrix< int, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixi
Definition Macros.h:27
FieldMatrixd Coord
Definition Macros.h:35
uint32_t Index_t
Definition Macros.h:17
Eigen::Matrix< double, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixd
Definition Macros.h:25
Stores configurations of all atoms in the system.
Definition Structures.h:832
FieldMatrixi atomicNrs
Atomic Number of each atom.
Definition Structures.h:836
FieldMatrixU8 is_frozen
Indicates whether atom is frozen or not.
Definition Structures.h:834
AtomsPositionAndType atoms_froz_active
Info on active frozen atoms.
Definition Structures.h:841
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
Structure of the input parameters. All input parameters are pairs of string names and values.
Definition Structures.h:370