16#include <unordered_map>
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);
43 for (
const double entry: atoms.
cell)
52 bool heat,
bool components)
54 std::ostringstream
out;
55 out << (components ?
"v2 " :
"v1 ")
59 if (components)
out <<
' ' << heat;
64void writeChart(std::ostream&
out,
65 const geometry::InternalCoordinateChart& chart)
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())
76 out <<
' ' << coordinates.primitives().size();
77 for (
const auto& primitive: coordinates.primitives()) {
79 for (
const int atom: primitive.atoms)
81 for (Eigen::Index axis = 0; axis < 3; ++axis)
82 out <<
' ' << primitive.reference(axis);
87std::shared_ptr<const geometry::InternalCoordinateChart> readChart(
88 std::istream& row, Eigen::Index moving_atoms, std::size_t line_size)
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))
95 std::vector<char> mask(mask_count);
96 for (
auto& moving: mask) {
98 if (!(row >> value) || (value != 0 && value != 1))
return {};
99 moving =
static_cast<char>(value);
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)
111 std::vector<geometry::PrimitiveInternal> primitives(primitive_count);
112 for (
auto& primitive: primitives) {
114 if (!(row >> kind) || kind < 0 ||
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 {};
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;
131std::shared_ptr<const GeodesicHeatEnergyForceKernel> readHeat(
132 std::istream& row,
const AtomsConfiguration& atoms, std::size_t line_size)
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 ||
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))
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);
162 throw std::invalid_argument(
163 "atomic environment parameters cannot use the pair seed-kernel "
167 const bool heat = covariance.usesGeodesicHeatKernel();
168 return kernelIdentity(gp, atoms, chart, heat, chart || heat);
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);
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;
190 if (input.bad() || identity.empty())
return false;
191 std::istringstream row(identity);
193 int profile, zbl, ff, manifold, heat = 0;
194 if (!(row >> version >> profile >> zbl >> ff >> manifold) ||
195 (version !=
"v1" && version !=
"v2"))
197 if (version ==
"v2" && (!(row >> heat) || (heat != 0 && heat != 1)))
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))
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();
213 if (!read_matrix(archived.
atomicNrs, n) || !read_matrix(frozen, n) ||
214 !read_matrix(archived.
type, n) ||
219 static_cast<Eigen::Index
>(identity.size())))
221 for (
double& entry: archived.
cell)
222 if (!(row >> entry) || !std::isfinite(entry))
return false;
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())
232 !same(frozen, atoms.
is_frozen) || archived.
type.rows() != 1 ||
233 archived.
type.cols() != n || archived.
pairtype.rows() <= 0 ||
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;
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));
263 throw std::invalid_argument(
264 "atomic environment parameters cannot use the pair seed-kernel "
268 const auto& chart = covariance.manifoldChart();
269 const auto& heat = covariance.geodesicHeatKernel();
270 out << std::setprecision(17);
272 out <<
"components 1 " <<
static_cast<bool>(chart) <<
' '
273 <<
static_cast<bool>(heat) <<
'\n';
274 out <<
"magnSigma2 " << covariance.getMagnSigma2() <<
'\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];
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];
292 writeChart(
out, *chart);
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);
306 if (!
out)
throw std::runtime_error(
"could not write seed kernel");
312 bool preserve_source_noise)
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;
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);
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;
336 if (key ==
"components") {
338 if (!(row >> version >> chart_present >> heat_present) ||
339 version != 1 || (chart_present != 0 && chart_present != 1) ||
340 (heat_present != 0 && heat_present != 1))
342 }
else if (key ==
"chart") {
346 }
catch (
const std::exception&) {
349 if (!chart)
return false;
350 }
else if (key ==
"heat") {
352 heat = readHeat(row, atoms, line.size());
353 }
catch (
const std::exception&) {
356 if (!heat)
return false;
357 }
else if (key ==
"magnSigma2") {
359 }
else if (key ==
"constSigma2") {
361 }
else if (key ==
"lengthScale" || key ==
"atomisticLengthScale") {
362 std::size_t count = 0;
364 if (!row || count == 0 || (count != 1 && count != atoms.
n_pt))
366 auto& values = key ==
"lengthScale" ? lengths : atomistic_lengths;
367 values.resize(count);
368 for (
auto& length: values)
370 }
else if (key ==
"outputTransform") {
371 row >> mean >> scale >> frozen_mean;
372 }
else if (key ==
"sigma2") {
374 if (!std::isfinite(source_noise) || source_noise < 0.0)
376 }
else if (key ==
"pairCutoff") {
377 row >> pair_cutoff >> pair_cutoff_width;
379 (void)
PairCutoff(pair_cutoff, pair_cutoff_width);
380 }
catch (
const std::invalid_argument&) {
386 if (!row)
return false;
388 if (row >> extra)
return false;
395 pair_cutoff != descriptor.pair_cutoff ||
396 pair_cutoff_width != descriptor.pair_cutoff_width)
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())) ||
403 (!seen.count(
"identity") || !seen.count(
"outputTransform"))) ||
404 (chart && atomistic_lengths.size() != atoms.
n_pt) ||
405 (!chart && !atomistic_lengths.empty()))
407 if (!identity.empty() &&
408 identity != kernelIdentity(gp, atoms,
static_cast<bool>(chart),
409 static_cast<bool>(heat), components))
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))
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;
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)))
432 const double physical_noise = preserve_source_noise
433 ? source_noise * scale_squared
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)))
445 if (preserve_source_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());
void setConstSigma2(const double _constSigma2)
Set the constSigma2 value.
ConstantCF & getConstantCovarianceFunction()
LikelihoodNoiseVarianceUpdate setLikelihoodNoiseVariance(double physical_sigma2, const Observation *full_observation=nullptr)
Set the likelihood noise variance in physical output units.
LikGaussian & getLikGaussian()
void setGeodesicHeatPrior(std::shared_ptr< const GeodesicHeatEnergyForceKernel > kernel)
bool outputMeanFrozen() const noexcept
void setInternalCoordinateChart(std::shared_ptr< const geometry::InternalCoordinateChart > chart, double length_scale)
void markHyperparametersFitted() noexcept
bool atomicEnvironmentModelEnabled() const noexcept
SexpatCF & getSexpAtCovarianceFunction()
double outputMean() const noexcept
GPModelProfile getModelProfile() const noexcept
bool getUseFFPriorMean() const noexcept
void restoreOutputTransform(double mean, double scale, bool frozen_mean)
Restore output coordinates alongside a kernel represented in them.
double outputScale() const noexcept
bool getUseZBLPriorMean() const noexcept
void clearGeodesicHeatPrior()
double getSigma2() const noexcept
Get sigma2 value (the per-row noise variance added to the energy diagonal of the training kernel by e...
void setSigma2(const double value)
Set sigma2 value.
const AtomsConfiguration & getConfInfo() const noexcept
bool usesManifoldChart() const noexcept
void clearManifoldChart()
FieldMatrixd & getLengthScaleRef()
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 ¶meters)
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 ¶meters, 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
Eigen::Matrix< double, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixd
Stores configurations of all atoms in the system.
FieldMatrixi atomicNrs
Atomic Number of each atom.
FieldMatrixU8 is_frozen
Indicates whether atom is frozen or not.
AtomsPositionAndType atoms_froz_active
Info on active frozen atoms.
AtomsPositionAndType atoms_mov
Info on moving atoms.
void copy(const AtomsConfiguration &other)
FieldMatrixIdx type
Type of each atom.
Coord positions
Positions of all atoms in the system.