Loading...
Searching...
No Matches
GpState.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3#include "GpState.h"
4
5#include <bit>
6#include <cmath>
7#include <cstdint>
8#include <cstring>
9#include <filesystem>
10#include <fstream>
11#include <iostream>
12#include <limits>
13#include <map>
14#include <sstream>
15#include <stdexcept>
16#include <string>
17#include <vector>
18
21#include "SeedKernel.h"
22
23namespace gpr::io {
24namespace {
25
26static_assert(std::endian::native == std::endian::little,
27 "gp-state.npz stores little-endian numpy arrays");
28
29std::uint32_t crc32(const unsigned char* data, std::size_t n)
30{
31 std::uint32_t crc = 0xffffffffu;
32 for (std::size_t i = 0; i < n; ++i) {
33 crc ^= data[i];
34 for (int bit = 0; bit < 8; ++bit)
35 crc = (crc >> 1) ^ (0xedb88320u & (0u - (crc & 1u)));
36 }
37 return ~crc;
38}
39
40void append16(std::vector<unsigned char>& out, std::uint16_t value)
41{
42 out.push_back(static_cast<unsigned char>(value & 0xffu));
43 out.push_back(static_cast<unsigned char>((value >> 8) & 0xffu));
44}
45
46void append32(std::vector<unsigned char>& out, std::uint32_t value)
47{
48 for (int shift = 0; shift < 32; shift += 8)
49 out.push_back(static_cast<unsigned char>((value >> shift) & 0xffu));
50}
51
52std::uint16_t read16(const std::vector<unsigned char>& in, std::size_t at)
53{
54 return static_cast<std::uint16_t>(
55 in[at] | (static_cast<std::uint16_t>(in[at + 1]) << 8));
56}
57
58std::uint32_t read32(const std::vector<unsigned char>& in, std::size_t at)
59{
60 return static_cast<std::uint32_t>(in[at]) |
61 (static_cast<std::uint32_t>(in[at + 1]) << 8) |
62 (static_cast<std::uint32_t>(in[at + 2]) << 16) |
63 (static_cast<std::uint32_t>(in[at + 3]) << 24);
64}
65
66std::string shapeText(const std::vector<Eigen::Index>& shape)
67{
68 std::ostringstream out;
69 out << '(';
70 if (shape.size() == 1) {
71 out << shape[0] << ',';
72 } else {
73 for (std::size_t i = 0; i < shape.size(); ++i) {
74 if (i != 0) out << ", ";
75 out << shape[i];
76 }
77 }
78 out << ')';
79 return out.str();
80}
81
82std::vector<unsigned char> npyArray(const std::string& descr,
83 const std::vector<Eigen::Index>& shape,
84 const unsigned char* data,
85 std::size_t nbytes)
86{
87 const std::string dict =
88 "{'descr': '" + descr +
89 "', 'fortran_order': False, 'shape': " + shapeText(shape) + ", }";
90 const std::size_t preamble = 10 + dict.size() + 1;
91 const std::size_t pad = (64 - (preamble % 64)) % 64;
92 const std::string header = dict + std::string(pad, ' ') + "\n";
93 if (header.size() > 65535)
94 throw std::runtime_error("gp-state array header is too long");
95 std::vector<unsigned char> out;
96 out.reserve(10 + header.size() + nbytes);
97 const unsigned char magic[] = {0x93, 'N', 'U', 'M', 'P', 'Y', 1, 0};
98 out.insert(out.end(), magic, magic + 8);
99 append16(out, static_cast<std::uint16_t>(header.size()));
100 out.insert(out.end(), header.begin(), header.end());
101 if (nbytes > 0) out.insert(out.end(), data, data + nbytes);
102 return out;
103}
104
105void writeZip(
106 const std::string& path,
107 const std::vector<std::pair<std::string, std::vector<unsigned char>>>&
108 members)
109{
110 std::vector<unsigned char> local;
111 struct Central {
112 std::string name;
113 std::uint32_t crc = 0;
114 std::uint32_t size = 0;
115 std::uint32_t offset = 0;
116 };
117 std::vector<Central> central;
118 central.reserve(members.size());
119 for (const auto& member: members) {
120 Central entry;
121 entry.name = member.first;
122 entry.crc = crc32(member.second.data(), member.second.size());
123 entry.size = static_cast<std::uint32_t>(member.second.size());
124 entry.offset = static_cast<std::uint32_t>(local.size());
125 append32(local, 0x04034b50u);
126 append16(local, 20);
127 append16(local, 0);
128 append16(local, 0);
129 append16(local, 0);
130 append16(local, 0);
131 append32(local, entry.crc);
132 append32(local, entry.size);
133 append32(local, entry.size);
134 append16(local, static_cast<std::uint16_t>(entry.name.size()));
135 append16(local, 0);
136 local.insert(local.end(), entry.name.begin(), entry.name.end());
137 local.insert(local.end(), member.second.begin(), member.second.end());
138 central.push_back(std::move(entry));
139 }
140 const std::uint32_t cd_offset = static_cast<std::uint32_t>(local.size());
141 std::vector<unsigned char> directory;
142 for (const auto& entry: central) {
143 append32(directory, 0x02014b50u);
144 append16(directory, 20);
145 append16(directory, 20);
146 append16(directory, 0);
147 append16(directory, 0);
148 append16(directory, 0);
149 append16(directory, 0);
150 append32(directory, entry.crc);
151 append32(directory, entry.size);
152 append32(directory, entry.size);
153 append16(directory, static_cast<std::uint16_t>(entry.name.size()));
154 append16(directory, 0);
155 append16(directory, 0);
156 append16(directory, 0);
157 append16(directory, 0);
158 append32(directory, 0);
159 append32(directory, entry.offset);
160 directory.insert(directory.end(), entry.name.begin(), entry.name.end());
161 }
162 const std::uint32_t cd_size = static_cast<std::uint32_t>(directory.size());
163 append32(directory, 0x06054b50u);
164 append16(directory, 0);
165 append16(directory, 0);
166 append16(directory, static_cast<std::uint16_t>(central.size()));
167 append16(directory, static_cast<std::uint16_t>(central.size()));
168 append32(directory, cd_size);
169 append32(directory, cd_offset);
170 append16(directory, 0);
171
172 const auto parent = std::filesystem::path(path).parent_path();
173 if (!parent.empty()) std::filesystem::create_directories(parent);
174 const auto temporary = path + ".writing";
175 {
176 std::ofstream out(temporary, std::ios::binary | std::ios::trunc);
177 if (!out) throw std::runtime_error("could not write " + path);
178 out.write(reinterpret_cast<const char*>(local.data()),
179 static_cast<std::streamsize>(local.size()));
180 out.write(reinterpret_cast<const char*>(directory.data()),
181 static_cast<std::streamsize>(directory.size()));
182 if (!out) throw std::runtime_error("could not write " + path);
183 }
184 std::filesystem::rename(temporary, path);
185}
186
187std::map<std::string, std::vector<unsigned char>> readZip(
188 const std::vector<unsigned char>& blob)
189{
190 std::map<std::string, std::vector<unsigned char>> files;
191 std::size_t at = 0;
192 while (at + 30 <= blob.size()) {
193 if (read32(blob, at) != 0x04034b50u) break;
194 const auto flags = read16(blob, at + 6);
195 const auto method = read16(blob, at + 8);
196 const auto stored_crc = read32(blob, at + 14);
197 const auto size = read32(blob, at + 18);
198 const auto name_len = read16(blob, at + 26);
199 const auto extra_len = read16(blob, at + 28);
200 if (method != 0)
201 throw std::runtime_error(
202 "gp-state.npz must be stored, not compressed");
203 const std::size_t name_at = at + 30;
204 const std::size_t data_at = name_at + name_len + extra_len;
205 if (data_at + size > blob.size())
206 throw std::runtime_error("gp-state.npz is truncated");
207 // Bit 3 postpones the CRC to a data descriptor, which this writer
208 // never sets. A stored CRC that does not match the bytes is a
209 // corrupt file.
210 if ((flags & 0x8u) == 0 &&
211 crc32(blob.data() + data_at, size) != stored_crc)
212 throw std::runtime_error("gp-state.npz checksum does not match");
213 files.emplace(
214 std::string(reinterpret_cast<const char*>(blob.data() + name_at),
215 name_len),
216 std::vector<unsigned char>(
217 blob.begin() + static_cast<std::ptrdiff_t>(data_at),
218 blob.begin() + static_cast<std::ptrdiff_t>(data_at + size)));
219 at = data_at + size;
220 }
221 if (files.empty()) throw std::runtime_error("gp-state.npz has no arrays");
222 return files;
223}
224
225struct ParsedNpy {
226 std::string descr;
227 std::vector<Eigen::Index> shape;
228 const unsigned char* data = nullptr;
229 std::size_t nbytes = 0;
230};
231
232ParsedNpy parseNpy(const std::vector<unsigned char>& bytes,
233 const std::string& name)
234{
235 if (bytes.size() < 10 || bytes[0] != 0x93 ||
236 std::memcmp(bytes.data() + 1, "NUMPY", 5) != 0)
237 throw std::runtime_error(name + " is not a numpy array");
238 const auto header_len = read16(bytes, 8);
239 if (static_cast<std::size_t>(10 + header_len) > bytes.size())
240 throw std::runtime_error(name + " header is truncated");
241 const std::string header(reinterpret_cast<const char*>(bytes.data() + 10),
242 header_len);
243 if (header.find("fortran_order") != std::string::npos &&
244 header.find("True") != std::string::npos &&
245 header.find("False") == std::string::npos)
246 throw std::runtime_error(name + " is Fortran-ordered");
247 // The key is quoted ('descr': '<f8'), so the search starts after that
248 // closing quote. Starting on it would take ": " as the dtype.
249 const auto descr_key = header.find("'descr'");
250 const auto descr_quote =
251 descr_key == std::string::npos
252 ? std::string::npos
253 : header.find('\'', descr_key + std::strlen("'descr'"));
254 const auto descr_end = descr_quote == std::string::npos
255 ? std::string::npos
256 : header.find('\'', descr_quote + 1);
257 if (descr_key == std::string::npos || descr_quote == std::string::npos ||
258 descr_end == std::string::npos)
259 throw std::runtime_error(name + " has no descr");
260 ParsedNpy parsed;
261 parsed.descr = header.substr(descr_quote + 1, descr_end - descr_quote - 1);
262 const auto shape_at = header.find('(', header.find("shape"));
263 const auto shape_end = header.find(')', shape_at);
264 if (shape_at == std::string::npos || shape_end == std::string::npos)
265 throw std::runtime_error(name + " has no shape");
266 std::istringstream shape_text(
267 header.substr(shape_at + 1, shape_end - shape_at - 1));
268 for (std::string token; std::getline(shape_text, token, ',');) {
269 if (token.find_first_not_of(" \t") == std::string::npos) continue;
270 long long raw = 0;
271 try {
272 raw = std::stoll(token);
273 } catch (const std::out_of_range&) {
274 throw std::runtime_error(name + " shape overflows");
275 }
276 if (raw > std::numeric_limits<Eigen::Index>::max())
277 throw std::runtime_error(name + " shape overflows");
278 parsed.shape.push_back(static_cast<Eigen::Index>(raw));
279 }
280 std::size_t count = 1;
281 for (const auto dim: parsed.shape) {
282 if (dim < 0) throw std::runtime_error(name + " has a negative shape");
283 const auto wide = static_cast<std::size_t>(dim);
284 if (wide != 0 && count > std::numeric_limits<std::size_t>::max() / wide)
285 throw std::runtime_error(name + " shape overflows");
286 count *= wide;
287 }
288 if (count >
289 static_cast<std::size_t>(std::numeric_limits<Eigen::Index>::max()))
290 throw std::runtime_error(name + " shape overflows");
291 const std::size_t width = parsed.descr == "<f8" || parsed.descr == "<i8"
292 ? 8
293 : (parsed.descr == "|u1" ? 1 : 0);
294 if (width == 0)
295 throw std::runtime_error(name + " has descr " + parsed.descr);
296 if (count > std::numeric_limits<std::size_t>::max() / width)
297 throw std::runtime_error(name + " shape overflows");
298 parsed.nbytes = count * width;
299 parsed.data = bytes.data() + 10 + header_len;
300 if (10 + header_len + parsed.nbytes != bytes.size())
301 throw std::runtime_error(name + " has a trailing payload");
302 return parsed;
303}
304
305const std::vector<unsigned char>& needMember(
306 const std::map<std::string, std::vector<unsigned char>>& files,
307 const std::string& name)
308{
309 const auto found = files.find(name);
310 if (found == files.end())
311 throw std::runtime_error("gp-state.npz is missing " + name);
312 return found->second;
313}
314
315double scalarF8(const std::map<std::string, std::vector<unsigned char>>& files,
316 const std::string& name)
317{
318 const auto parsed = parseNpy(needMember(files, name), name);
319 if (parsed.descr != "<f8" || parsed.nbytes != sizeof(double))
320 throw std::runtime_error(name + " must be one float64");
321 double value = 0.0;
322 std::memcpy(&value, parsed.data, sizeof(double));
323 return value;
324}
325
326std::int64_t scalarI64(
327 const std::map<std::string, std::vector<unsigned char>>& files,
328 const std::string& name)
329{
330 const auto parsed = parseNpy(needMember(files, name), name);
331 if (parsed.descr != "<i8" || parsed.nbytes != sizeof(std::int64_t))
332 throw std::runtime_error(name + " must be one int64");
333 std::int64_t value = 0;
334 std::memcpy(&value, parsed.data, sizeof(value));
335 return value;
336}
337
338unsigned char scalarU8(
339 const std::map<std::string, std::vector<unsigned char>>& files,
340 const std::string& name)
341{
342 const auto parsed = parseNpy(needMember(files, name), name);
343 if (parsed.descr != "|u1" || parsed.nbytes != 1)
344 throw std::runtime_error(name + " must be one byte");
345 return parsed.data[0];
346}
347
348FieldMatrixd matrixF8(
349 const std::map<std::string, std::vector<unsigned char>>& files,
350 const std::string& name)
351{
352 const auto parsed = parseNpy(needMember(files, name), name);
353 if (parsed.descr != "<f8" || parsed.shape.size() != 2)
354 throw std::runtime_error(name + " must be a float64 matrix");
355 FieldMatrixd matrix(parsed.shape[0], parsed.shape[1]);
356 if (parsed.nbytes > 0)
357 std::memcpy(matrix.data(), parsed.data, parsed.nbytes);
358 return matrix;
359}
360
361std::string bytesText(
362 const std::map<std::string, std::vector<unsigned char>>& files,
363 const std::string& name)
364{
365 const auto parsed = parseNpy(needMember(files, name), name);
366 if (parsed.descr != "|u1")
367 throw std::runtime_error(name + " must be bytes");
368 return std::string(reinterpret_cast<const char*>(parsed.data),
369 parsed.nbytes);
370}
371
372std::vector<unsigned char> f8Scalar(double value)
373{
374 return npyArray("<f8", {1}, reinterpret_cast<const unsigned char*>(&value),
375 sizeof(value));
376}
377
378std::vector<unsigned char> i64Scalar(std::int64_t value)
379{
380 return npyArray("<i8", {1}, reinterpret_cast<const unsigned char*>(&value),
381 sizeof(value));
382}
383
384std::vector<unsigned char> u8Scalar(unsigned char value)
385{
386 return npyArray("|u1", {1}, &value, 1);
387}
388
389std::vector<unsigned char> u8Text(const std::string& text)
390{
391 return npyArray("|u1", {static_cast<Eigen::Index>(text.size())},
392 reinterpret_cast<const unsigned char*>(text.data()),
393 text.size());
394}
395
396std::vector<unsigned char> f8Matrix(const FieldMatrixd& matrix)
397{
398 return npyArray("<f8", {matrix.rows(), matrix.cols()},
399 reinterpret_cast<const unsigned char*>(matrix.data()),
400 static_cast<std::size_t>(matrix.size()) * sizeof(double));
401}
402
403double energyAt(const Observation& observations, Eigen::Index row)
404{
405 if (observations.E.rows() == observations.R.rows() &&
406 observations.E.cols() >= 1)
407 return observations.E(row, 0);
408 if (observations.E.cols() == observations.R.rows() &&
409 observations.E.rows() >= 1)
410 return observations.E(0, row);
411 throw std::runtime_error(
412 "training energies are neither one column nor one row");
413}
414
415Observation normalizedObservations(const Observation& observations)
416{
417 if (observations.R.rows() == 0) {
418 // A fitted kernel can sit beside an empty design. E stays one
419 // column so the loader's shape check accepts the file.
420 Observation out;
421 const Eigen::Index cols =
422 std::max(observations.R.cols(), observations.G.cols());
423 out.R.resize(0, cols);
424 out.G.resize(0, cols);
425 out.E.resize(0, 1);
426 return out;
427 }
428 if (observations.G.rows() != observations.R.rows() ||
429 observations.G.cols() != observations.R.cols())
430 throw std::runtime_error("training gradients do not match positions");
431 Observation out;
432 out.R = observations.R;
433 out.G = observations.G;
434 out.E.resize(observations.R.rows(), 1);
435 for (Eigen::Index row = 0; row < observations.R.rows(); ++row)
436 out.E(row, 0) = energyAt(observations, row);
437 return out;
438}
439
440void copyMatrix(FieldMatrixd& destination, const FieldMatrixd& source)
441{
442 destination.resize(source.rows(), source.cols());
443 if (source.size() > 0)
444 std::memcpy(destination.data(), source.data(),
445 static_cast<std::size_t>(source.size()) * sizeof(double));
446}
447
448} // namespace
449
450void saveTrainedGpState(const std::string& path,
452 const Observation& observations,
453 const AtomsConfiguration& atoms)
454{
455 TrainedGpState state;
456 state.observations = normalizedObservations(observations);
457 state.output_mean = gp.outputMean();
458 state.output_scale = gp.outputScale();
460 state.model_profile = static_cast<int>(gp.getModelProfile());
461 state.pair_cutoff = atoms.pair_cutoff;
463 try {
464 std::ostringstream kernel;
465 writeSeedKernel(kernel, gp, atoms);
466 state.kernel_text = kernel.str();
467 state.identity = seedKernelIdentity(gp, atoms);
468 const auto& covariance = gp.getSexpAtCovarianceFunction();
469 state.magn_sigma2 = covariance.getMagnSigma2();
470 state.const_sigma2 =
472 state.sigma2 = gp.getLikGaussian().getSigma2();
473 state.length_scale = covariance.getLengthScaleRef();
474 const auto& atomistic = covariance.getAtomisticLengthScaleRef();
475 if (atomistic.data() != covariance.getLengthScaleRef().data()) {
476 state.atomistic_length_scale = atomistic;
477 state.has_atomistic_length_scale = true;
478 }
479 state.has_pair_kernel = true;
480 } catch (const std::invalid_argument&) {
481 state.has_pair_kernel = false;
482 }
483
484 std::int64_t version = 1;
485 std::vector<std::pair<std::string, std::vector<unsigned char>>> members;
486 members.emplace_back("format_version.npy", i64Scalar(version));
487 members.emplace_back("R.npy", f8Matrix(state.observations.R));
488 members.emplace_back("E.npy", f8Matrix(state.observations.E));
489 members.emplace_back("G.npy", f8Matrix(state.observations.G));
490 members.emplace_back("length_scale.npy", f8Matrix(state.length_scale));
492 members.emplace_back("atomistic_length_scale.npy",
493 f8Matrix(state.atomistic_length_scale));
494 members.emplace_back("magn_sigma2.npy", f8Scalar(state.magn_sigma2));
495 members.emplace_back("const_sigma2.npy", f8Scalar(state.const_sigma2));
496 members.emplace_back("sigma2.npy", f8Scalar(state.sigma2));
497 members.emplace_back("output_mean.npy", f8Scalar(state.output_mean));
498 members.emplace_back("output_scale.npy", f8Scalar(state.output_scale));
499 members.emplace_back("output_mean_frozen.npy",
500 u8Scalar(state.output_mean_frozen ? 1 : 0));
501 members.emplace_back("pair_cutoff.npy", f8Scalar(state.pair_cutoff));
502 members.emplace_back("pair_cutoff_width.npy",
503 f8Scalar(state.pair_cutoff_width));
504 members.emplace_back(
505 "model_profile.npy",
506 i64Scalar(static_cast<std::int64_t>(state.model_profile)));
507 members.emplace_back("has_pair_kernel.npy",
508 u8Scalar(state.has_pair_kernel ? 1 : 0));
509 members.emplace_back("has_atomistic_length_scale.npy",
510 u8Scalar(state.has_atomistic_length_scale ? 1 : 0));
511 members.emplace_back("kernel_text.npy", u8Text(state.kernel_text));
512 members.emplace_back("identity.npy", u8Text(state.identity));
513 writeZip(path, members);
514}
515
516TrainedGpState loadTrainedGpState(const std::string& path)
517{
518 std::ifstream in(path, std::ios::binary);
519 if (!in) throw std::runtime_error("could not read " + path);
520 std::vector<unsigned char> blob((std::istreambuf_iterator<char>(in)),
521 std::istreambuf_iterator<char>());
522 const auto files = readZip(blob);
523 if (scalarI64(files, "format_version.npy") != 1)
524 throw std::runtime_error("unsupported gp-state.npz version");
525 TrainedGpState state;
526 state.observations.R = matrixF8(files, "R.npy");
527 state.observations.E = matrixF8(files, "E.npy");
528 state.observations.G = matrixF8(files, "G.npy");
529 state.length_scale = matrixF8(files, "length_scale.npy");
531 scalarU8(files, "has_atomistic_length_scale.npy") != 0;
534 matrixF8(files, "atomistic_length_scale.npy");
535 state.magn_sigma2 = scalarF8(files, "magn_sigma2.npy");
536 state.const_sigma2 = scalarF8(files, "const_sigma2.npy");
537 state.sigma2 = scalarF8(files, "sigma2.npy");
538 state.output_mean = scalarF8(files, "output_mean.npy");
539 state.output_scale = scalarF8(files, "output_scale.npy");
540 state.output_mean_frozen = scalarU8(files, "output_mean_frozen.npy") != 0;
541 state.pair_cutoff = scalarF8(files, "pair_cutoff.npy");
542 state.pair_cutoff_width = scalarF8(files, "pair_cutoff_width.npy");
543 state.model_profile =
544 static_cast<int>(scalarI64(files, "model_profile.npy"));
545 state.has_pair_kernel = scalarU8(files, "has_pair_kernel.npy") != 0;
546 state.kernel_text = bytesText(files, "kernel_text.npy");
547 state.identity = bytesText(files, "identity.npy");
548 if (state.observations.R.rows() != state.observations.E.rows() ||
549 state.observations.R.rows() != state.observations.G.rows() ||
550 state.observations.E.cols() != 1 ||
551 state.observations.G.cols() != state.observations.R.cols())
552 throw std::runtime_error("gp-state.npz observations do not match");
553 return state;
554}
555
557{
558 TrainedGpState state;
559 state.observations = normalizedObservations(observations);
560 state.output_scale = 1.0;
561 return state;
562}
563
565 const TrainedGpState& state,
566 const AtomsConfiguration& atoms, bool require_identity)
567{
568 if (!state.has_pair_kernel || state.kernel_text.empty()) return false;
569 std::istringstream kernel(state.kernel_text);
570 if (!readSeedKernel(kernel, gp, atoms, require_identity)) return false;
571 auto& covariance = gp.getSexpAtCovarianceFunction();
572 covariance.setMagnSigma2(state.magn_sigma2);
574 gp.getLikGaussian().setSigma2(state.sigma2);
576 state.output_mean_frozen);
577 copyMatrix(covariance.getLengthScaleRef(), state.length_scale);
578 if (state.has_atomistic_length_scale &&
579 covariance.getAtomisticLengthScaleRef().data() !=
580 covariance.getLengthScaleRef().data())
581 copyMatrix(covariance.getAtomisticLengthScaleRef(),
584 return true;
585}
586
587void refuseNonFiniteSeedRows(const Observation& observations,
588 Eigen::Index expected_cols)
589{
590 if (observations.R.rows() > 0 && expected_cols >= 0 &&
591 observations.R.cols() != expected_cols)
592 throw std::runtime_error(
593 "gp-state.npz coordinates do not match this search (" +
594 std::to_string(observations.R.cols()) +
595 " columns, this search has " + std::to_string(expected_cols) + ")");
596 int kept = 0;
597 int dropped = 0;
598 for (Eigen::Index row = 0; row < observations.R.rows(); ++row) {
599 const Eigen::VectorXd positions = observations.R.row(row).transpose();
600 const Eigen::VectorXd gradient =
601 observations.G.rows() > row ? observations.G.row(row).transpose()
602 : Eigen::VectorXd();
603 const bool energy_ok = observations.E.rows() > row &&
604 observations.E.cols() > 0 &&
605 std::isfinite(observations.E(row, 0));
606 if (gradient.size() != positions.size() || !positions.allFinite() ||
607 !gradient.allFinite() || !energy_ok)
608 ++dropped;
609 else
610 ++kept;
611 }
612 if (dropped > 0)
613 throw std::runtime_error("gp-state.npz: kept " + std::to_string(kept) +
614 " observation(s), dropped " +
615 std::to_string(dropped) +
616 " non-finite row(s)");
617}
618
620 const TrainedGpState& state)
621{
622 if (!(std::isfinite(state.magn_sigma2) && state.magn_sigma2 > 0.0)) return;
623 double log_sum = 0.0;
624 int count = 0;
625 const double* scales = state.length_scale.data();
626 for (Eigen::Index i = 0; i < state.length_scale.size(); ++i) {
627 const double ell = scales[i];
628 if (std::isfinite(ell) && ell > 0.0) {
629 log_sum += std::log(ell);
630 ++count;
631 }
632 }
633 if (count == 0) return;
634 session.noteLocalKernelSeed(state.magn_sigma2,
635 std::exp(log_sum / static_cast<double>(count)));
636}
637
639 const TrainedGpState& state, bool require_identity,
640 Eigen::Index expected_cols)
641{
642 const auto& observations = state.observations;
643 // Each row is checked against the session's expected width. The stored
644 // matrix width is not that number: a concatenated seed keeps the first
645 // block's column count.
646 const Eigen::Index session_cols = session.training_obs.R.rows() > 0
647 ? session.training_obs.R.cols()
648 : Eigen::Index(-1);
649 for (Eigen::Index row = 0; row < observations.R.rows(); ++row) {
650 const Eigen::Index row_cols = observations.R.row(row).size();
651 const Eigen::Index grad_cols = row < observations.G.rows()
652 ? observations.G.row(row).size()
653 : Eigen::Index(-1);
654 const Eigen::Index want =
655 expected_cols >= 0 ? expected_cols : session_cols;
656 if (want >= 0 && (row_cols != want || grad_cols != want))
657 throw std::runtime_error(
658 "gp-state.npz coordinates do not match this search (" +
659 std::to_string(row_cols) + " columns, this search has " +
660 std::to_string(want) + ")");
661 if (expected_cols >= 0 && session_cols >= 0 && row_cols != session_cols)
662 throw std::runtime_error(
663 "gp-state.npz coordinates do not match this search (" +
664 std::to_string(row_cols) + " columns, this search has " +
665 std::to_string(session_cols) + ")");
666 }
667 refuseNonFiniteSeedRows(observations, -1);
668 const int kept = static_cast<int>(observations.R.rows());
669 for (Eigen::Index row = 0; row < observations.R.rows(); ++row) {
670 const Eigen::VectorXd positions = observations.R.row(row).transpose();
671 const Eigen::VectorXd gradient = observations.G.row(row).transpose();
672 session.appendObservation(positions, observations.E(row, 0), gradient,
674 }
675 session.notePriorObservations(kept);
676 noteLocalKernel(session, state);
677 if (state.has_pair_kernel) {
678 session.setAfterInitialise(
679 [state, require_identity](GaussianProcessRegression& gp,
680 const AtomsConfiguration& atoms,
681 const Observation& training) {
682 if (!applyTrainedGpState(gp, state, atoms, require_identity)) {
683 std::cerr << "saved GP kernel does not match this search; "
684 "seed observations were loaded\n";
685 return false;
686 }
687 if (training.R.rows() > 0) gp.updateModelWithFullData(training);
688 return true;
689 });
690 }
691 return kept;
692}
693
694std::string resolveGpStatePath(const std::string& spec, bool restart)
695{
696 namespace fs = std::filesystem;
697 const fs::path path(spec);
698 std::error_code error;
699 if (restart && fs::is_directory(path, error)) {
700 const auto file = path / "gp-state.npz";
701 if (!fs::is_regular_file(file))
702 throw std::runtime_error("no gp-state.npz in " + spec);
703 return file.string();
704 }
705 if (fs::is_regular_file(path, error)) {
706 if (!restart || path.filename() == "gp-state.npz") return path.string();
707 const auto sibling = path.parent_path() / "gp-state.npz";
708 if (fs::is_regular_file(sibling)) return sibling.string();
709 throw std::runtime_error("no gp-state.npz beside " + spec);
710 }
711 throw std::runtime_error("could not read GP state from " + spec);
712}
713
714std::string outputDirectory(const std::string& output_path)
715{
716 const auto parent = std::filesystem::path(output_path).parent_path();
717 if (parent.empty()) return ".";
718 return parent.string();
719}
720
721} // namespace gpr::io
ActiveLearningSession: shared GP + training data across GP-NEB and GP-Dimer phases.
double getConstSigma2()
void setConstSigma2(const double _constSigma2)
Set the constSigma2 value.
void updateModelWithFullData(const Observation &full_observation)
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.
void setMagnSigma2(double value)
Definition SexpatCF.inl:19
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
Eigen::Vector3d at(const FieldMatrixd &mat, Index_t i)
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 applyTrainedGpState(GaussianProcessRegression &gp, const TrainedGpState &state, const AtomsConfiguration &atoms, bool require_identity)
Definition GpState.cpp:564
std::string resolveGpStatePath(const std::string &spec, bool restart)
Definition GpState.cpp:694
void refuseNonFiniteSeedRows(const Observation &observations, Eigen::Index expected_cols)
Definition GpState.cpp:587
void noteLocalKernel(neb::ActiveLearningSession &session, const TrainedGpState &state)
Definition GpState.cpp:619
TrainedGpState observationState(const Observation &observations)
A state that carries observations and no pair kernel.
Definition GpState.cpp:556
TrainedGpState loadTrainedGpState(const std::string &path)
Definition GpState.cpp:516
void saveTrainedGpState(const std::string &path, const GaussianProcessRegression &gp, const Observation &observations, const AtomsConfiguration &atoms)
Write gp-state.npz. A second save of the same state is the same bytes.
Definition GpState.cpp:450
std::string seedKernelIdentity(const GaussianProcessRegression &gp, const AtomsConfiguration &atoms)
std::string outputDirectory(const std::string &output_path)
Directory of an output path, or . when the path has no directory.
Definition GpState.cpp:714
int seedSession(neb::ActiveLearningSession &session, const TrainedGpState &state, bool require_identity, Eigen::Index expected_cols)
Definition GpState.cpp:638
Eigen::Matrix< double, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixd
Definition Macros.h:25
Stores configurations of all atoms in the system.
Definition Structures.h:832
Observation data: energy, gradient and positions.
FieldMatrixd E
std::string kernel_text
Definition GpState.h:36
Observation observations
Definition GpState.h:22
FieldMatrixd atomistic_length_scale
Definition GpState.h:24
std::string identity
Definition GpState.h:37
FieldMatrixd length_scale
Definition GpState.h:23
bool has_atomistic_length_scale
Definition GpState.h:25
void setAfterInitialise(AfterInitialise hook)
Definition Session.h:1282
void notePriorObservations(int count) noexcept
Definition Session.h:1293
gpr::Observation training_obs
Definition Session.h:246
void noteLocalKernelSeed(double signal_variance, double length_scale) noexcept
Definition Session.h:1307
void appendObservation(const Eigen::VectorXd &positions, double energy, const Eigen::VectorXd &gradient, ObservationRetention retention=ObservationRetention::RecordAcquisition, optim::SecantAccounting secant_accounting=optim::SecantAccounting::Count)
Definition Session.h:1574