Loading...
Searching...
No Matches
TomlConfigLoader.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 "TomlConfigLoader.h"
6
7#ifdef USE_CAPNP
8#include <capnp/dynamic.h>
9
10#include <algorithm>
11#include <cctype>
12#include <cmath>
13#include <cstdint>
14#include <initializer_list>
15#include <iostream>
16#include <limits>
17#include <optional>
18#include <stdexcept>
19#include <string>
20#include <string_view>
21#include <toml++/toml.hpp>
22#include <type_traits>
23#include <utility>
24#include <vector>
25
28#include "gpr/neb/GPNEB.h"
29#include "schema/params.capnp.h"
30
31namespace gpr::io {
32
33ConfigValueRangeError::ConfigValueRangeError(std::string key, Reason reason)
34 : std::invalid_argument(
35 std::string(reason == Reason::NotFinite ? "Non-finite"
36 : reason == Reason::NotIntegral ? "Fractional"
37 : "Out-of-range") +
38 " value for integer configuration key: " + key),
39 key_(std::move(key)),
40 reason_(reason)
41{
42}
43
44namespace {
45
46const toml::table* tableAt(const toml::table& parent, std::string_view key)
47{
48 const auto node = parent[key];
49 if (!node) return nullptr;
50 if (const auto* table = node.as_table()) return table;
51 throw std::invalid_argument("Expected a table for configuration key: " +
52 std::string(key));
53}
54
55std::size_t editDistance(std::string_view left, std::string_view right)
56{
57 std::vector<std::size_t> previous(right.size() + 1);
58 std::vector<std::size_t> current(right.size() + 1);
59 for (std::size_t j = 0; j <= right.size(); ++j)
60 previous[j] = j;
61 for (std::size_t i = 1; i <= left.size(); ++i) {
62 current[0] = i;
63 for (std::size_t j = 1; j <= right.size(); ++j) {
64 const std::size_t substitution =
65 previous[j - 1] + (left[i - 1] == right[j - 1] ? 0 : 1);
66 current[j] =
67 std::min({previous[j] + 1, current[j - 1] + 1, substitution});
68 }
69 std::swap(previous, current);
70 }
71 return previous.back();
72}
73
74// The allow-list of each table must name exactly the keys that the populate
75// function reads from it.
76void rejectUnknownKeys(const toml::table& table,
77 std::initializer_list<std::string_view> allowed,
78 std::string_view context)
79{
80 for (const auto& entry: table) {
81 const std::string_view key = entry.first.str();
82 if (std::find(allowed.begin(), allowed.end(), key) != allowed.end())
83 continue;
84 const auto closest = std::min_element(
85 allowed.begin(), allowed.end(),
86 [&](const auto& left, const auto& right) {
87 return editDistance(key, left) < editDistance(key, right);
88 });
89 // One edit per three characters of the shorter spelling, and at
90 // least one so a single-character typo on a short key still matches.
91 const std::size_t shorter =
92 closest == allowed.end()
93 ? 0
94 : std::min(key.size(), std::string(*closest).size());
95 const std::size_t suggestion_limit =
96 std::max<std::size_t>(1, shorter / 3);
97 const auto hint =
98 closest != allowed.end() &&
99 editDistance(key, *closest) <= suggestion_limit
100 ? std::string("; did you mean '") + std::string(*closest) + "'?"
101 : "";
102 throw std::invalid_argument(
103 "Unknown configuration key: " +
104 (context.empty() ? std::string() : std::string(context) + ".") +
105 std::string(key) + hint);
106 }
107}
108
109// toml++ converts a floating-point node to an integer through int64_t before
110// it compares the value with the range of T, and that conversion is undefined
111// outside [-2^63, 2^63). A number therefore reaches an integer type only after
112// these checks.
113template <class T>
114std::optional<T> checkedValue(const toml::node& node, std::string_view key)
115{
116 if constexpr (!std::is_integral_v<T> || std::is_same_v<T, bool>) {
117 return node.value<T>();
118 } else {
119 using Reason = ConfigValueRangeError::Reason;
120 if (const auto* integer = node.as_integer()) {
121 if (!std::in_range<T>(integer->get()))
122 throw ConfigValueRangeError(std::string(key),
123 Reason::OutOfRange);
124 return static_cast<T>(integer->get());
125 }
126 if (const auto* floating = node.as_floating_point()) {
127 const double value = floating->get();
128 if (!std::isfinite(value))
129 throw ConfigValueRangeError(std::string(key),
130 Reason::NotFinite);
131 if (std::trunc(value) != value)
132 throw ConfigValueRangeError(std::string(key),
133 Reason::NotIntegral);
134 // lowest() is 0 or -2^digits and the first whole number above
135 // max() is 2^digits, so both bounds are exact in binary64.
136 if (value < static_cast<double>(std::numeric_limits<T>::lowest()) ||
137 value >= std::ldexp(1.0, std::numeric_limits<T>::digits))
138 throw ConfigValueRangeError(std::string(key),
139 Reason::OutOfRange);
140 return static_cast<T>(value);
141 }
142 return node.value<T>();
143 }
144}
145
146template <class T, class Setter>
147void setIfPresent(const toml::table& table, std::string_view key, Setter setter)
148{
149 const auto node = table[key];
150 if (!node) return;
151 const auto value = checkedValue<T>(*node.node(), key);
152 if (!value) {
153 throw std::invalid_argument(
154 "Invalid type or range for configuration key: " + std::string(key));
155 }
156 setter(*value);
157}
158
159gpr::schema::VibrationalStencil parseVibrationalStencilToml(
160 const std::string& value)
161{
162 if (value == "full") return gpr::schema::VibrationalStencil::FULL;
163 if (value == "vibrational")
164 return gpr::schema::VibrationalStencil::VIBRATIONAL;
165 throw std::invalid_argument("Unknown band.vibrational_stencil: " + value);
166}
167
168gpr::schema::NebMode parseNebModeToml(const std::string& s)
169{
170 if (s == "standard") return gpr::schema::NebMode::STANDARD;
171 if (s == "aie") return gpr::schema::NebMode::AIE;
172 if (s == "oie") return gpr::schema::NebMode::OIE;
173 if (s == "gp_aie") return gpr::schema::NebMode::GP_AIE;
174 if (s == "gp_oie") return gpr::schema::NebMode::GP_OIE;
175 throw std::invalid_argument("Unknown band.mode: " + s);
176}
177
178gpr::schema::AcquisitionType parseAcquisitionToml(const std::string& s)
179{
180 if (s == "ucb") return gpr::schema::AcquisitionType::UCB;
181 if (s == "imspe") return gpr::schema::AcquisitionType::IMSPE;
182 if (s == "ei") return gpr::schema::AcquisitionType::EXPECTED_IMPROVEMENT;
183 if (s == "max_variance") return gpr::schema::AcquisitionType::MAX_VARIANCE;
184 if (s == "max_force") return gpr::schema::AcquisitionType::MAX_FORCE;
185 if (s == "thompson") return gpr::schema::AcquisitionType::THOMPSON_SAMPLING;
186 if (s == "priorityCascade" || s == "priority_cascade")
187 return gpr::schema::AcquisitionType::PRIORITY_CASCADE;
188 if (s == "tpe") return gpr::schema::AcquisitionType::TPE;
189 if (s == "psbax") return gpr::schema::AcquisitionType::PSBAX;
190 throw std::invalid_argument("Unknown acquisition.kind: " + s);
191}
192
193gpr::schema::UncertaintyMode parseUncertaintyModeToml(const std::string& s)
194{
195 if (s == "laplace") return gpr::schema::UncertaintyMode::LAPLACE;
196 if (s == "laplace-slice" || s == "laplace_slice")
197 return gpr::schema::UncertaintyMode::LAPLACE_SLICE;
198 if (s == "eb") return gpr::schema::UncertaintyMode::EB;
199 if (s == "svgd") return gpr::schema::UncertaintyMode::SVGD;
200 if (s == "bma") return gpr::schema::UncertaintyMode::BMA;
201 if (s == "map") return gpr::schema::UncertaintyMode::MAP;
202 throw std::invalid_argument("Unknown uncertainty.mode: " + s);
203}
204
205// Collapses the --use-psis-laplace / --use-psis-deterministic /
206// --use-delta-method triplet into the VarianceArm enum. Mirrors the
207// CLI vocabulary: "psis" (random draws) / "psis-deterministic"
208// (default) / "delta" / "none".
209gpr::schema::VarianceArm parseVarianceArmToml(const std::string& s)
210{
211 if (s == "psis" || s == "psis-random" || s == "psis_random")
212 return gpr::schema::VarianceArm::PSIS_RANDOM;
213 if (s == "delta" || s == "delta-method" || s == "delta_method")
214 return gpr::schema::VarianceArm::DELTA_METHOD;
215 if (s == "none") return gpr::schema::VarianceArm::NONE;
216 if (s == "psis-deterministic" || s == "psis_deterministic")
217 return gpr::schema::VarianceArm::PSIS_DETERMINISTIC;
218 throw std::invalid_argument("Unknown uncertainty.variance_arm: " + s);
219}
220
221gpr::schema::HyperparameterWorkflowMode parseHyperparameterModeToml(
222 const std::string& s)
223{
224 if (s == "map_lbfgs" || s == "lbfgs" || s == "bb")
225 return gpr::schema::HyperparameterWorkflowMode::MAP_LBFGS;
226 if (s == "scg") return gpr::schema::HyperparameterWorkflowMode::SCG;
227 if (s == "inla") return gpr::schema::HyperparameterWorkflowMode::INLA;
228 throw std::invalid_argument("Unknown gp.hyperparameter_mode: " + s);
229}
230
231gpr::schema::HyperparameterObjective parseHyperparameterObjectiveToml(
232 const std::string& s)
233{
234 if (s == "loo" || s == "loocv" || s == "loo_cv")
235 return gpr::schema::HyperparameterObjective::LOO;
236 if (s == "blockLoo" || s == "block_loo" || s == "local-loo" ||
237 s == "local_loo")
238 return gpr::schema::HyperparameterObjective::BLOCK_LOO;
239 if (s == "nlml") return gpr::schema::HyperparameterObjective::NLML;
240 throw std::invalid_argument("Unknown gp.hyperparameter_objective: " + s);
241}
242
243gpr::schema::DistanceMetric parseDistanceMetricToml(const std::string& s)
244{
245 if (s == "max1dlog" || s == "max_1d_log")
246 return gpr::schema::DistanceMetric::MAX1_D_LOG;
247 if (s == "rmsd") return gpr::schema::DistanceMetric::RMSD;
248 if (s == "emd") return gpr::schema::DistanceMetric::EMD;
249 throw std::invalid_argument("Unknown trust.metric: " + s);
250}
251
252gpr::schema::MetatomicSo3Policy parseSo3PolicyToml(std::string s)
253{
254 std::transform(s.begin(), s.end(), s.begin(),
255 [](unsigned char c) { return std::tolower(c); });
256 if (s == "raw") return gpr::schema::MetatomicSo3Policy::RAW;
257 if (s == "always") return gpr::schema::MetatomicSo3Policy::ALWAYS;
258 if (s == "adaptive") return gpr::schema::MetatomicSo3Policy::ADAPTIVE;
259 throw std::invalid_argument("Unknown oracle.metatomic.so3_policy: " + s);
260}
261
262void populateBand(const toml::table& root, gpr::schema::NebParams::Builder neb)
263{
264 const auto* band = tableAt(root, "band");
265 if (!band) return;
266 rejectUnknownKeys(*band,
267 {"nimages",
268 "mode",
269 "converged_force",
270 "convergence_force_norm",
271 "max_iterations",
272 "max_inner_iter",
273 "spring_constant",
274 "spring_constant_min",
275 "geometric_spring",
276 "climbing_image",
277 "climbing_image_converged_only",
278 "ci_activation_tol",
279 "ci_activation_factor",
280 "idpp",
281 "sidpp",
282 "sidpp_alpha",
283 "sidpp_geodesic",
284 "geodesic_image_prior",
285 "endpoint_assign",
286 "endpoint_assign_kmax",
287 "midrun_realign",
288 "reparam_period",
289 "reparam_tol",
290 "eon_inner_mode",
291 "irc_saddle_hessian",
292 "vibrational_stencil",
293 "lbfgs",
294 "mmf"},
295 "band");
296 setIfPresent<int32_t>(*band, "nimages",
297 [&](const auto& value) { neb.setNImages(value); });
298 setIfPresent<std::string>(*band, "mode", [&](const auto& value) {
299 neb.setMode(parseNebModeToml(value));
300 });
301 setIfPresent<std::string>(
302 *band, "irc_saddle_hessian", [&](const auto& value) {
303 if (value == "measured")
304 neb.setIrcSaddleHessian(
305 gpr::schema::IrcSaddleHessian::MEASURED);
306 else if (value == "model")
307 neb.setIrcSaddleHessian(gpr::schema::IrcSaddleHessian::MODEL);
308 else
309 throw std::invalid_argument(
310 "Unknown band.irc_saddle_hessian: " + value);
311 });
312 setIfPresent<std::string>(
313 *band, "vibrational_stencil", [&](const auto& value) {
314 neb.setVibrationalStencil(parseVibrationalStencilToml(value));
315 });
316 setIfPresent<double>(*band, "converged_force", [&](const auto& value) {
317 neb.setConvergedForce(value);
318 });
319 setIfPresent<std::string>(
320 *band, "convergence_force_norm", [&](const auto& value) {
321 const auto norm = gpr::parseForceNorm(value);
322 auto field = neb.initForceNorm();
323 if (!norm) {
324 field.setAutomatic();
325 return;
326 }
327 switch (*norm) {
329 field.setSelected(
330 gpr::schema::ConvergenceForceNorm::L2_NORM);
331 break;
333 field.setSelected(
334 gpr::schema::ConvergenceForceNorm::LINF_NORM);
335 break;
337 field.setSelected(
338 gpr::schema::ConvergenceForceNorm::MAX_FORCE_ON_ATOM);
339 break;
340 }
341 });
342 setIfPresent<int32_t>(*band, "max_iterations", [&](const auto& value) {
343 neb.setMaxIterations(value);
344 });
345 setIfPresent<int32_t>(*band, "max_inner_iter", [&](const auto& value) {
346 neb.setMaxInnerIter(value);
347 });
348 setIfPresent<double>(*band, "spring_constant", [&](const auto& value) {
349 neb.setSpringConstant(value);
350 });
351 setIfPresent<double>(*band, "spring_constant_min", [&](const auto& value) {
352 neb.setSpringConstantMin(value);
353 });
354 setIfPresent<bool>(*band, "geometric_spring", [&](const auto& value) {
355 neb.setGeometricSpring(value);
356 });
357 setIfPresent<bool>(*band, "climbing_image",
358 [&](const auto& value) { neb.setClimbingImage(value); });
359 setIfPresent<bool>(
360 *band, "climbing_image_converged_only",
361 [&](const auto& value) { neb.setClimbingImageConvergedOnly(value); });
362 setIfPresent<double>(*band, "ci_activation_tol", [&](const auto& value) {
363 neb.setCiActivationTol(value);
364 });
365 setIfPresent<double>(*band, "ci_activation_factor", [&](const auto& value) {
366 neb.setCiActivationFactor(value);
367 });
368 setIfPresent<bool>(*band, "idpp",
369 [&](const auto& value) { neb.setIdpp(value); });
370 setIfPresent<bool>(*band, "sidpp",
371 [&](const auto& value) { neb.setSidpp(value); });
372 setIfPresent<double>(*band, "sidpp_alpha",
373 [&](const auto& value) { neb.setSidppAlpha(value); });
374 setIfPresent<bool>(*band, "sidpp_geodesic",
375 [&](const auto& value) { neb.setSidppGeodesic(value); });
376 // Each seeding key selects its initializer on its own: sidpp = true
377 // and sidpp_geodesic = true turn on the IDPP gate the band builder
378 // reads, and the geodesic key also selects the sequential variant.
379 setIfPresent<bool>(*band, "sidpp", [&](const auto& value) {
380 if (value) neb.setIdpp(true);
381 });
382 setIfPresent<bool>(*band, "sidpp_geodesic", [&](const auto& value) {
383 if (value) {
384 neb.setSidpp(true);
385 neb.setIdpp(true);
386 }
387 });
388 setIfPresent<bool>(*band, "geodesic_image_prior", [&](const auto& value) {
389 neb.setGeodesicImagePrior(value);
390 });
391 setIfPresent<bool>(*band, "endpoint_assign", [&](const auto& value) {
392 neb.setEndpointAssign(value);
393 });
394 setIfPresent<double>(*band, "endpoint_assign_kmax", [&](const auto& value) {
395 neb.setEndpointAssignKmax(value);
396 });
397 setIfPresent<bool>(*band, "midrun_realign",
398 [&](const auto& value) { neb.setMidrunRealign(value); });
399 setIfPresent<int32_t>(*band, "reparam_period", [&](const auto& value) {
400 neb.setReparamPeriod(value);
401 });
402 setIfPresent<double>(*band, "reparam_tol",
403 [&](const auto& value) { neb.setReparamTol(value); });
404 setIfPresent<bool>(*band, "eon_inner_mode",
405 [&](const auto& value) { neb.setEonInnerMode(value); });
406 if (const auto* table = tableAt(*band, "lbfgs")) {
407 rejectUnknownKeys(
408 *table,
409 {"max_move", "memory", "inverse_curvature", "finite_difference",
410 "auto_scale", "angle_reset", "distance_reset", "newton_agreement",
411 "sketch_history", "sketch_seed", "sketch_h0_rank",
412 "sketch_h0_eps"},
413 "band.lbfgs");
414 auto options = neb.getLbfgs();
415 setIfPresent<double>(*table, "max_move", [&](const auto& value) {
416 options.setMaxMove(value);
417 });
418 setIfPresent<int32_t>(*table, "memory", [&](const auto& value) {
419 options.setMemory(value);
420 });
421 setIfPresent<double>(
422 *table, "inverse_curvature",
423 [&](const auto& value) { options.setInverseCurvature(value); });
424 setIfPresent<double>(
425 *table, "finite_difference",
426 [&](const auto& value) { options.setFiniteDifference(value); });
427 setIfPresent<bool>(*table, "auto_scale", [&](const auto& value) {
428 options.setAutoScale(value);
429 });
430 setIfPresent<bool>(*table, "angle_reset", [&](const auto& value) {
431 options.setAngleReset(value);
432 });
433 setIfPresent<bool>(*table, "distance_reset", [&](const auto& value) {
434 options.setDistanceReset(value);
435 });
436 setIfPresent<int32_t>(*table, "sketch_history", [&](const auto& value) {
437 options.setSketchHistory(value);
438 });
439 setIfPresent<uint64_t>(*table, "sketch_seed", [&](const auto& value) {
440 options.setSketchSeed(value);
441 });
442 setIfPresent<int32_t>(*table, "sketch_h0_rank", [&](const auto& value) {
443 options.setSketchH0Rank(value);
444 });
445 setIfPresent<double>(*table, "sketch_h0_eps", [&](const auto& value) {
446 options.setSketchH0Eps(value);
447 });
448 setIfPresent<double>(
449 *table, "newton_agreement", [&](const auto& value) {
451 options.setNewtonAgreement(value);
452 });
453 }
454 if (const auto* table = tableAt(*band, "mmf")) {
455 rejectUnknownKeys(
456 *table,
457 {"use_mmf", "rg_minmode_dimer", "trigger_force", "trigger_factor",
458 "max_steps", "ci_stability_count", "angle_tol", "max_phases",
459 "max_inner_iter", "max_rot_iter", "eval_image1", "perturb",
460 "keep_improving", "imspe_soft_threshold"},
461 "band.mmf");
462 auto options = neb.getMmf();
463 setIfPresent<bool>(*table, "use_mmf", [&](const auto& value) {
464 options.setUseMmf(value);
465 });
466 setIfPresent<bool>(*table, "rg_minmode_dimer", [&](const auto& value) {
467 options.setRgMinmodeDimer(value);
468 });
469 setIfPresent<double>(*table, "trigger_force", [&](const auto& value) {
470 options.setTriggerForce(value);
471 });
472 setIfPresent<double>(*table, "trigger_factor", [&](const auto& value) {
473 options.setTriggerFactor(value);
474 });
475 setIfPresent<int64_t>(*table, "max_steps", [&](const auto& value) {
476 options.setMaxSteps(value);
477 });
478 setIfPresent<int64_t>(
479 *table, "ci_stability_count",
480 [&](const auto& value) { options.setCiStabilityCount(value); });
481 setIfPresent<double>(*table, "angle_tol", [&](const auto& value) {
482 options.setAngleTol(value);
483 });
484 setIfPresent<int32_t>(*table, "max_phases", [&](const auto& value) {
485 options.setMaxPhases(value);
486 });
487 setIfPresent<int32_t>(*table, "max_inner_iter", [&](const auto& value) {
488 options.setMaxInnerIter(value);
489 });
490 setIfPresent<int32_t>(*table, "max_rot_iter", [&](const auto& value) {
491 options.setMaxRotIter(value);
492 });
493 setIfPresent<bool>(*table, "eval_image1", [&](const auto& value) {
494 options.setEvalImage1(value);
495 });
496 setIfPresent<double>(*table, "perturb", [&](const auto& value) {
497 options.setPerturb(value);
498 });
499 setIfPresent<bool>(*table, "keep_improving", [&](const auto& value) {
500 options.setKeepImproving(value);
501 });
502 setIfPresent<double>(
503 *table, "imspe_soft_threshold",
504 [&](const auto& value) { options.setImspeSoftThreshold(value); });
505 }
506}
507
508void populateGp(const toml::table& root,
509 gpr::schema::InputParameters::Builder params)
510{
511 const auto* table = tableAt(root, "gp");
512 if (!table) return;
513 rejectUnknownKeys(*table,
514 {"gp_sigma2",
515 "jitter_sigma2",
516 "noise_sigma2",
517 "no_output_norm",
518 "zbl_prior_mean",
519 "use_rigid_null_deflation",
520 "profile_predict_mean",
521 "profile_energy_split",
522 "profile_gradient_split",
523 "hyperparameter_mode",
524 "hyperparameter_objective",
525 "max_iter",
526 "tol_func",
527 "tol_sol",
528 "ls_prior",
529 "principled_nugget",
530 "kappa_max",
531 "hssvd",
532 "scalapack_block_size",
533 "scalapack_nprow"},
534 "gp");
535 auto model = params.getGpr();
536 setIfPresent<double>(*table, "gp_sigma2",
537 [&](const auto& value) { model.setGpSigma2(value); });
538 setIfPresent<double>(*table, "jitter_sigma2", [&](const auto& value) {
539 model.setJitterSigma2(value);
540 });
541 setIfPresent<double>(*table, "noise_sigma2", [&](const auto& value) {
542 model.setNoiseSigma2(value);
543 });
544 setIfPresent<bool>(*table, "no_output_norm", [&](const auto& value) {
545 model.setDisableOutputNormalization(value);
546 });
547 setIfPresent<bool>(*table, "zbl_prior_mean", [&](const auto& value) {
548 model.setUseZblPriorMean(value);
549 });
550 setIfPresent<bool>(
551 *table, "use_rigid_null_deflation",
552 [&](const auto& value) { model.setUseRigidNullDeflation(value); });
553 setIfPresent<bool>(*table, "profile_predict_mean", [&](const auto& value) {
554 model.setProfilePredictMean(value);
555 });
556 setIfPresent<bool>(*table, "profile_energy_split", [&](const auto& value) {
557 model.setProfileEnergySplit(value);
558 });
559 setIfPresent<bool>(
560 *table, "profile_gradient_split",
561 [&](const auto& value) { model.setProfileGradientSplit(value); });
562 auto optimizer = params.getOptimizer();
563 optimizer.setWorkflowModeExplicit(!!(*table)["hyperparameter_mode"]);
564 optimizer.setObjectiveExplicit(!!(*table)["hyperparameter_objective"]);
565 setIfPresent<std::string>(
566 *table, "hyperparameter_mode", [&](const auto& value) {
567 optimizer.setWorkflowMode(parseHyperparameterModeToml(value));
568 });
569 setIfPresent<std::string>(
570 *table, "hyperparameter_objective", [&](const auto& value) {
571 optimizer.setObjective(parseHyperparameterObjectiveToml(value));
572 });
573 setIfPresent<int32_t>(*table, "max_iter", [&](const auto& value) {
574 optimizer.setMaxIter(value);
575 });
576 setIfPresent<double>(*table, "tol_func", [&](const auto& value) {
577 optimizer.setTolFunc(value);
578 });
579 setIfPresent<double>(*table, "tol_sol", [&](const auto& value) {
580 optimizer.setTolSol(value);
581 });
582 auto priors = optimizer.getLengthScalePriors();
583 setIfPresent<bool>(*table, "ls_prior", [&](const auto& value) {
584 priors.setLengthScalePrior(value);
585 });
586 auto hssvd = params.getHsSvd();
587 setIfPresent<bool>(*table, "principled_nugget", [&](const auto& value) {
588 hssvd.setPrincipledNugget(value);
589 });
590 setIfPresent<double>(*table, "kappa_max",
591 [&](const auto& value) { hssvd.setKappaMax(value); });
592 if (const auto* options = tableAt(*table, "hssvd")) {
593 rejectUnknownKeys(
594 *options,
595 {"use_solver", "use_objective_contractions", "dual_chop_tol",
596 "dual_randomized_sketch", "dual_lapack_rrr",
597 "local_active_set_size", "local_posterior_active_set_size"},
598 "gp.hssvd");
599 setIfPresent<bool>(*options, "use_solver", [&](const auto& value) {
600 hssvd.setUseSolver(value);
601 });
602 setIfPresent<bool>(*options, "use_objective_contractions",
603 [&](const auto& value) {
604 hssvd.setUseObjectiveContractions(value);
605 });
606 setIfPresent<double>(*options, "dual_chop_tol", [&](const auto& value) {
607 hssvd.setDualChopTol(value);
608 });
609 setIfPresent<int32_t>(
610 *options, "dual_randomized_sketch",
611 [&](const auto& value) { hssvd.setDualRandomizedSketch(value); });
612 setIfPresent<bool>(*options, "dual_lapack_rrr", [&](const auto& value) {
613 hssvd.setDualLapackRrr(value);
614 });
615 setIfPresent<int32_t>(
616 *options, "local_active_set_size",
617 [&](const auto& value) { hssvd.setLocalActiveSetSize(value); });
618 setIfPresent<int32_t>(*options, "local_posterior_active_set_size",
619 [&](const auto& value) {
620 hssvd.setLocalPosteriorActiveSetSize(value);
621 });
622 }
623 using Field = gpr::schema::GpInitializationField;
624 std::vector<Field> configured_fields;
625 for (const auto& entry: {std::pair{"gp_sigma2", Field::COVARIANCE_NOISE},
626 std::pair{"jitter_sigma2", Field::JITTER},
627 std::pair{"noise_sigma2", Field::LIKELIHOOD_NOISE},
628 std::pair{"max_iter", Field::MAX_ITERATIONS},
629 std::pair{"tol_func", Field::FUNCTION_TOLERANCE},
630 std::pair{"tol_sol", Field::SOLUTION_TOLERANCE}}) {
631 if ((*table)[entry.first]) configured_fields.push_back(entry.second);
632 }
633 auto fields = params.initGpInitializationFields(configured_fields.size());
634 for (std::size_t i = 0; i < configured_fields.size(); ++i)
635 fields.set(i, configured_fields[i]);
636
637 auto linalg = params.getLinearAlgebra();
638 setIfPresent<int32_t>(
639 *table, "scalapack_block_size",
640 [&](const auto& value) { linalg.setScalapackBlockSize(value); });
641 setIfPresent<int32_t>(*table, "scalapack_nprow", [&](const auto& value) {
642 linalg.setScalapackNprow(value);
643 });
644}
645
646void populateUncertainty(const toml::table& root,
647 gpr::schema::InputParameters::Builder params)
648{
649 const auto* table = tableAt(root, "uncertainty");
650 if (!table) return;
651 rejectUnknownKeys(
652 *table,
653 {"mode", "variance_arm", "rff_features", "rff_force_tol_fraction",
654 "accept_tau", "accept_tau_relative", "inner_unc_relative",
655 "stable_posterior_variance"},
656 "uncertainty");
657 auto options = params.getUncertainty();
658 setIfPresent<std::string>(*table, "mode", [&](const auto& value) {
659 options.setMode(parseUncertaintyModeToml(value));
660 });
661 setIfPresent<std::string>(*table, "variance_arm", [&](const auto& value) {
662 options.setVarianceArm(parseVarianceArmToml(value));
663 });
664 if (const auto node = (*table)["rff_features"]) {
665 if (const auto* text = node.as_string()) {
666 if (text->get() != "auto") {
667 throw std::invalid_argument(
668 "uncertainty.rff_features must be a non-negative integer "
669 "or \"auto\"");
670 }
671 options.setRffFeatures(-1);
672 } else {
673 setIfPresent<int32_t>(
674 *table, "rff_features", [&](const auto& value) {
675 if (value < 0) {
676 throw std::invalid_argument(
677 "uncertainty.rff_features must be a non-negative "
678 "integer or \"auto\"");
679 }
680 options.setRffFeatures(value);
681 });
682 }
683 }
684 setIfPresent<double>(
685 *table, "rff_force_tol_fraction", [&](const auto& value) {
686 if (!std::isfinite(value) || value < 0.0 || value >= 1.0) {
687 throw std::invalid_argument(
688 "uncertainty.rff_force_tol_fraction must be in [0, 1)");
689 }
690 options.setRffForceTolFraction(value);
691 });
692 setIfPresent<double>(*table, "accept_tau", [&](const auto& value) {
693 options.setAcceptTau(value);
694 });
695 setIfPresent<double>(*table, "accept_tau_relative", [&](const auto& value) {
696 options.setAcceptTauRelative(value);
697 });
698 setIfPresent<double>(*table, "inner_unc_relative", [&](const auto& value) {
699 options.setInnerUncRelative(value);
700 });
701 setIfPresent<bool>(
702 *table, "stable_posterior_variance",
703 [&](const auto& value) { options.setStablePosteriorVariance(value); });
704}
705
706void populateAcquisition(const toml::table& root,
707 gpr::schema::NebParams::Builder neb)
708{
709 const auto* table = tableAt(root, "acquisition");
710 if (!table) return;
711 rejectUnknownKeys(*table,
712 {"kind", "three_phase_picker", "seed_full_chain",
713 "oie_evals", "per_image_min_train", "per_image_knn",
714 "imspe_refit_skip_relative_tol", "theta_shift_skip_tol",
715 "theta_shift_skip_auto"},
716 "acquisition");
717 setIfPresent<std::string>(*table, "kind", [&](const auto& value) {
718 neb.setAcquisition(parseAcquisitionToml(value));
719 });
720 setIfPresent<bool>(*table, "three_phase_picker", [&](const auto& value) {
721 neb.setThreePhasePicker(value);
722 });
723 setIfPresent<bool>(*table, "seed_full_chain",
724 [&](const auto& value) { neb.setSeedFullChain(value); });
725 setIfPresent<int32_t>(*table, "oie_evals",
726 [&](const auto& value) { neb.setOieEvals(value); });
727 setIfPresent<int32_t>(
728 *table, "per_image_min_train",
729 [&](const auto& value) { neb.setPerImageMinTrain(value); });
730 setIfPresent<int32_t>(*table, "per_image_knn", [&](const auto& value) {
731 neb.setPerImageKnn(value);
732 });
733 setIfPresent<double>(
734 *table, "imspe_refit_skip_relative_tol",
735 [&](const auto& value) { neb.setImspeRefitSkipRelativeTol(value); });
736 setIfPresent<double>(
737 *table, "theta_shift_skip_tol",
738 [&](const auto& value) { neb.setThetaShiftSkipTol(value); });
739 setIfPresent<bool>(*table, "theta_shift_skip_auto", [&](const auto& value) {
740 neb.setThetaShiftSkipAuto(value);
741 });
742}
743
744void populateTrust(const toml::table& root, gpr::schema::NebParams::Builder neb)
745{
746 const auto* table = tableAt(root, "trust");
747 if (!table) return;
748 rejectUnknownKeys(*table,
749 {"metric", "use_adaptive", "radius", "adaptive_A",
750 "adaptive_floor", "t_min", "delta_explore", "half_life",
751 "ratio_at_limit", "scalefree_trust", "scalefree_tau"},
752 "trust");
753 auto options = neb.getTrust();
754 setIfPresent<std::string>(*table, "metric", [&](const auto& value) {
755 options.setMetric(parseDistanceMetricToml(value));
756 });
757 setIfPresent<bool>(*table, "use_adaptive", [&](const auto& value) {
758 options.setUseAdaptive(value);
759 });
760 setIfPresent<double>(*table, "radius",
761 [&](const auto& value) { options.setRadius(value); });
762 setIfPresent<double>(*table, "adaptive_A", [&](const auto& value) {
763 options.setAdaptiveA(value);
764 });
765 setIfPresent<double>(*table, "adaptive_floor", [&](const auto& value) {
766 options.setAdaptiveFloor(value);
767 });
768 setIfPresent<double>(*table, "t_min",
769 [&](const auto& value) { options.setTMin(value); });
770 setIfPresent<double>(*table, "delta_explore", [&](const auto& value) {
771 options.setDeltaExplore(value);
772 });
773 setIfPresent<int32_t>(*table, "half_life", [&](const auto& value) {
774 options.setHalfLife(value);
775 });
776 setIfPresent<double>(*table, "ratio_at_limit", [&](const auto& value) {
777 options.setRatioAtLimit(value);
778 });
779 setIfPresent<bool>(*table, "scalefree_trust", [&](const auto& value) {
780 neb.setScalefreeTrust(value);
781 });
782 setIfPresent<double>(*table, "scalefree_tau", [&](const auto& value) {
783 neb.setScalefreeTau(value);
784 });
785}
786
787// TOML is an input notation for the schema. Unknown fields and mismatched
788// value types are rejected by the schema rather than silently discarded.
789void populatePotentialStruct(const toml::table& table,
790 capnp::DynamicStruct::Builder output);
791
792// Cap'n Proto 1.4.0 compares a double with the maximum of a 64-bit integer
793// field after rounding that maximum to binary64, so 2^63 or 2^64 reaches an
794// undefined conversion. A number for an integer field therefore goes through
795// checkedValue first. A TOML integer is an int64; giving that to
796// DynamicStruct::set lets a float field drop bits past its mantissa, which
797// node::value<double>() rejects.
798capnp::DynamicValue::Reader potentialScalar(const toml::node& node,
799 capnp::Type type,
800 std::string_view key)
801{
802 if (const auto* value = node.as_boolean()) return value->get();
803 const auto held = [&](auto value) -> capnp::DynamicValue::Reader {
804 if (!value) {
805 throw std::invalid_argument(
806 "Invalid type or range for configuration key: " +
807 std::string(key));
808 }
809 return *value;
810 };
811 switch (type.which()) {
812 case capnp::schema::Type::INT8:
813 return held(checkedValue<int8_t>(node, key));
814 case capnp::schema::Type::INT16:
815 return held(checkedValue<int16_t>(node, key));
816 case capnp::schema::Type::INT32:
817 return held(checkedValue<int32_t>(node, key));
818 case capnp::schema::Type::INT64:
819 return held(checkedValue<int64_t>(node, key));
820 case capnp::schema::Type::UINT8:
821 return held(checkedValue<uint8_t>(node, key));
822 case capnp::schema::Type::UINT16:
823 return held(checkedValue<uint16_t>(node, key));
824 case capnp::schema::Type::UINT32:
825 return held(checkedValue<uint32_t>(node, key));
826 case capnp::schema::Type::UINT64:
827 return held(checkedValue<uint64_t>(node, key));
828 case capnp::schema::Type::FLOAT32:
829 case capnp::schema::Type::FLOAT64:
830 if (const auto* integer = node.as_integer()) {
831 const auto number = integer->get();
832 const int digits = type.which() == capnp::schema::Type::FLOAT32
833 ? std::numeric_limits<float>::digits
834 : std::numeric_limits<double>::digits;
835 const auto limit = std::int64_t{1} << digits;
836 if (number < -limit || number > limit) {
837 throw std::invalid_argument(
838 "Invalid type or range for configuration key: " +
839 std::string(key));
840 }
841 return static_cast<double>(number);
842 }
843 if (const auto* floating = node.as_floating_point())
844 return floating->get();
845 break;
846 default:
847 break;
848 }
849 if (const auto* value = node.as_integer()) return value->get();
850 if (const auto* value = node.as_floating_point()) return value->get();
851 if (const auto* value = node.as_string())
852 return capnp::Text::Reader(value->get());
853 throw std::invalid_argument(
854 "Potential settings require scalar values, tables or arrays");
855}
856
857void populatePotentialList(const toml::array& values, std::string_view key,
858 capnp::DynamicList::Builder output)
859{
860 for (std::size_t i = 0; i < values.size(); ++i) {
861 const auto& value = values[i];
862 if (const auto* table = value.as_table())
863 populatePotentialStruct(*table,
864 output[i].as<capnp::DynamicStruct>());
865 else if (const auto* list = value.as_array())
866 populatePotentialList(
867 *list, key,
868 output.init(i, list->size()).as<capnp::DynamicList>());
869 else
870 output.set(i, potentialScalar(
871 value, output.getSchema().getElementType(), key));
872 }
873}
874
875void populatePotentialStruct(const toml::table& table,
876 capnp::DynamicStruct::Builder output)
877{
878 bool union_selected = false;
879 for (const auto& [key, value]: table) {
880 std::string field_name;
881 bool upper = false;
882 for (char c: key.str()) {
883 if (c == '_') {
884 upper = true;
885 continue;
886 }
887 field_name += upper ? static_cast<char>(std::toupper(
888 static_cast<unsigned char>(c)))
889 : c;
890 upper = false;
891 }
892 auto field = output.getSchema().getFieldByName(field_name.c_str());
893 if (field.getProto().getDiscriminantValue() !=
894 capnp::schema::Field::NO_DISCRIMINANT) {
895 if (union_selected)
896 throw std::invalid_argument(
897 "Select one potential configuration arm");
898 union_selected = true;
899 }
900 if (const auto* nested = value.as_table()) {
901 populatePotentialStruct(
902 *nested, output.init(field).as<capnp::DynamicStruct>());
903 } else if (const auto* list = value.as_array()) {
904 populatePotentialList(
905 *list, key.str(),
906 output.init(field, list->size()).as<capnp::DynamicList>());
907 } else {
908 output.set(field,
909 potentialScalar(value, field.getType(), key.str()));
910 }
911 }
912}
913
914void populateOracle(const toml::table& root,
915 gpr::schema::InputParameters::Builder params)
916{
917 const auto* oracle = tableAt(root, "oracle");
918 if (!oracle) return;
919 rejectUnknownKeys(
920 *oracle, {"potential", "parameters", "metatomic", "plugin"}, "oracle");
921 setIfPresent<std::string>(*oracle, "potential", [&](const auto& value) {
922 params.setPotential(value.c_str());
923 });
924 if (const auto* parameters = tableAt(*oracle, "parameters"))
925 populatePotentialStruct(*parameters,
926 capnp::toDynamic(params.initPotentialConfig()));
927 if (const auto* plugin = tableAt(*oracle, "plugin")) {
928 rejectUnknownKeys(*plugin,
929 {"plugin_name", "library_path", "params_path"},
930 "oracle.plugin");
931 auto fields = params.initOraclePlugin();
932 setIfPresent<std::string>(
933 *plugin, "plugin_name",
934 [&](const auto& value) { fields.setPluginName(value.c_str()); });
935 setIfPresent<std::string>(
936 *plugin, "library_path",
937 [&](const auto& value) { fields.setLibraryPath(value.c_str()); });
938 setIfPresent<std::string>(
939 *plugin, "params_path",
940 [&](const auto& value) { fields.setParamsPath(value.c_str()); });
941 if (fields.getLibraryPath().size() == 0)
942 throw std::invalid_argument("oracle.plugin needs library_path");
943 }
944 const auto* table = tableAt(*oracle, "metatomic");
945 if (!table) return;
946 rejectUnknownKeys(*table,
947 {"model", "device", "rotations", "so3_probe",
948 "so3_policy", "uncertainty_threshold"},
949 "oracle.metatomic");
950 setIfPresent<std::string>(*table, "model", [&](const auto& value) {
951 params.setModel(value.c_str());
952 });
953 setIfPresent<std::string>(*table, "device", [&](const auto& value) {
954 params.setDevice(value.c_str());
955 });
956 auto options = params.getMetatomic();
957 setIfPresent<int32_t>(*table, "rotations", [&](const auto& value) {
958 options.setRotations(value);
959 });
960 setIfPresent<bool>(*table, "so3_probe",
961 [&](const auto& value) { options.setSo3Probe(value); });
962 setIfPresent<std::string>(*table, "so3_policy", [&](const auto& value) {
963 options.setSo3Policy(parseSo3PolicyToml(value));
964 });
965 setIfPresent<double>(
966 *table, "uncertainty_threshold",
967 [&](const auto& value) { options.setUncertaintyThreshold(value); });
968}
969
970void populateRun(const toml::table& root,
971 gpr::schema::InputParameters::Builder params,
972 gpr::schema::NebParams::Builder neb)
973{
974 const auto* table = tableAt(root, "run");
975 if (!table) return;
976 rejectUnknownKeys(
977 *table,
978 {"reactant", "product", "output", "con_output", "seed",
979 "max_iterations", "converged_force", "trace_band_history",
980 "trace_con_output", "use_prune", "gp_init"},
981 "run");
982 setIfPresent<std::string>(*table, "reactant", [&](const auto& value) {
983 params.setReactant(value.c_str());
984 });
985 setIfPresent<std::string>(*table, "product", [&](const auto& value) {
986 params.setProduct(value.c_str());
987 });
988 setIfPresent<std::string>(*table, "output", [&](const auto& value) {
989 params.setOutput(value.c_str());
990 });
991 setIfPresent<std::string>(*table, "gp_init", [&](const auto& value) {
992 params.setGpInit(value.c_str());
993 });
994 setIfPresent<std::string>(*table, "con_output", [&](const auto& value) {
995 params.setConOutput(value.c_str());
996 });
997 setIfPresent<uint32_t>(*table, "seed",
998 [&](const auto& value) { params.setSeed(value); });
999 setIfPresent<int32_t>(*table, "max_iterations", [&](const auto& value) {
1000 neb.setMaxIterations(value);
1001 });
1002 setIfPresent<double>(*table, "converged_force", [&](const auto& value) {
1003 neb.setConvergedForce(value);
1004 });
1005 auto trace = params.getTrace();
1006 setIfPresent<bool>(*table, "trace_band_history",
1007 [&](const auto& value) { trace.setBandHistory(value); });
1008 setIfPresent<std::string>(*table, "trace_con_output",
1009 [&](const auto& value) {
1010 trace.setTraceConPath(value.c_str());
1011 trace.setGeometriesConV2(!value.empty());
1012 });
1013 setIfPresent<bool>(*table, "use_prune", [&](bool value) {
1014 (void)value;
1015 params.getPruning().setUsePrune(false);
1016 std::cerr << "warning: run.use_prune is deprecated and ignored; "
1017 "use gp.adaptive_prune for bounded active sets\n";
1018 });
1019}
1020
1021// [linalg]: the gprn --linalg-mode, --linalg-threads and
1022// --training-product-library options.
1023void populateLinalg(const toml::table& root,
1024 gpr::schema::InputParameters::Builder params)
1025{
1026 const auto* table = tableAt(root, "linalg");
1027 if (!table) return;
1028 rejectUnknownKeys(*table, {"mode", "threads", "training_product"},
1029 "linalg");
1030 auto linalg = params.getLinearAlgebra();
1031 setIfPresent<std::string>(*table, "mode", [&](const auto& value) {
1032 if (value == "reproducible")
1033 linalg.setMode(gpr::schema::LinalgMode::REPRODUCIBLE);
1034 else if (value == "library")
1035 linalg.setMode(gpr::schema::LinalgMode::LIBRARY);
1036 else
1037 throw std::invalid_argument("Unknown linalg.mode: " + value);
1038 });
1039 setIfPresent<int32_t>(*table, "threads", [&](const auto& value) {
1040 if (value < 1)
1041 throw std::invalid_argument("linalg.threads must be at least 1");
1042 linalg.setThreads(value);
1043 });
1044 setIfPresent<std::string>(
1045 *table, "training_product", [&](const auto& value) {
1046 linalg.setTrainingProductLibrary(value.c_str());
1047 });
1048}
1049
1050} // namespace
1051
1052void loadInputParametersFromToml(const std::string& path,
1053 capnp::MallocMessageBuilder& message)
1054{
1055 toml::table root;
1056 try {
1057 root = toml::parse_file(path);
1058 } catch (const toml::parse_error& error) {
1059 throw std::runtime_error("Could not parse TOML configuration '" + path +
1060 "': " + std::string(error.description()));
1061 }
1062 rejectUnknownKeys(root,
1063 {"band", "gp", "uncertainty", "acquisition", "trust",
1064 "oracle", "run", "linalg"},
1065 "");
1066 auto params = message.initRoot<gpr::schema::InputParameters>();
1067 params.setSchemaVersion(gpr::schema::CURRENT_SCHEMA_VERSION);
1068 auto neb = params.getMethod().initNeb();
1069 populateLinalg(root, params);
1070 populateBand(root, neb);
1071 populateGp(root, params);
1072 populateUncertainty(root, params);
1073 populateAcquisition(root, neb);
1074 populateTrust(root, neb);
1075 populateOracle(root, params);
1076 populateRun(root, params, neb);
1077}
1078
1079} // namespace gpr::io
1080#endif
GP-accelerated NEB: AIE and OIE variants.
eon_relax_band_t * band
std::pair< std::string, std::string > Field
std::optional< ConvergenceNormType > parseForceNorm(std::string_view name)
Definition ForceNorm.h:16
static void requireLbfgsNewtonAgreement(double value)
Definition GPNEB.h:1025