8#include <capnp/dynamic.h>
14#include <initializer_list>
21#include <toml++/toml.hpp>
29#include "schema/params.capnp.h"
33ConfigValueRangeError::ConfigValueRangeError(std::string key, Reason reason)
34 : std::invalid_argument(
35 std::string(reason == Reason::NotFinite ?
"Non-finite"
36 : reason == Reason::NotIntegral ?
"Fractional"
38 " value for integer configuration key: " + key),
46const toml::table* tableAt(
const toml::table& parent, std::string_view key)
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: " +
55std::size_t editDistance(std::string_view left, std::string_view right)
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)
61 for (std::size_t i = 1; i <= left.size(); ++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);
67 std::min({previous[j] + 1, current[j - 1] + 1, substitution});
69 std::swap(previous, current);
71 return previous.back();
76void rejectUnknownKeys(
const toml::table& table,
77 std::initializer_list<std::string_view> allowed,
78 std::string_view context)
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())
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);
91 const std::size_t shorter =
92 closest == allowed.end()
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);
98 closest != allowed.end() &&
99 editDistance(key, *closest) <= suggestion_limit
100 ? std::string(
"; did you mean '") + std::string(*closest) +
"'?"
102 throw std::invalid_argument(
103 "Unknown configuration key: " +
104 (context.empty() ? std::string() : std::string(context) +
".") +
105 std::string(key) + hint);
114std::optional<T> checkedValue(
const toml::node& node, std::string_view key)
116 if constexpr (!std::is_integral_v<T> || std::is_same_v<T, bool>) {
117 return node.value<T>();
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),
124 return static_cast<T
>(integer->get());
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),
131 if (std::trunc(value) != value)
132 throw ConfigValueRangeError(std::string(key),
133 Reason::NotIntegral);
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),
140 return static_cast<T
>(value);
142 return node.value<T>();
146template <
class T,
class Setter>
147void setIfPresent(
const toml::table& table, std::string_view key, Setter setter)
149 const auto node = table[key];
151 const auto value = checkedValue<T>(*node.node(), key);
153 throw std::invalid_argument(
154 "Invalid type or range for configuration key: " + std::string(key));
159gpr::schema::VibrationalStencil parseVibrationalStencilToml(
160 const std::string& value)
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);
168gpr::schema::NebMode parseNebModeToml(
const std::string& s)
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);
178gpr::schema::AcquisitionType parseAcquisitionToml(
const std::string& s)
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);
193gpr::schema::UncertaintyMode parseUncertaintyModeToml(
const std::string& s)
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);
209gpr::schema::VarianceArm parseVarianceArmToml(
const std::string& s)
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);
221gpr::schema::HyperparameterWorkflowMode parseHyperparameterModeToml(
222 const std::string& s)
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);
231gpr::schema::HyperparameterObjective parseHyperparameterObjectiveToml(
232 const std::string& s)
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" ||
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);
243gpr::schema::DistanceMetric parseDistanceMetricToml(
const std::string& s)
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);
252gpr::schema::MetatomicSo3Policy parseSo3PolicyToml(std::string s)
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);
262void populateBand(
const toml::table& root, gpr::schema::NebParams::Builder neb)
264 const auto*
band = tableAt(root,
"band");
266 rejectUnknownKeys(*
band,
270 "convergence_force_norm",
274 "spring_constant_min",
277 "climbing_image_converged_only",
279 "ci_activation_factor",
284 "geodesic_image_prior",
286 "endpoint_assign_kmax",
291 "irc_saddle_hessian",
292 "vibrational_stencil",
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));
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);
309 throw std::invalid_argument(
310 "Unknown band.irc_saddle_hessian: " + value);
312 setIfPresent<std::string>(
313 *
band,
"vibrational_stencil", [&](
const auto& value) {
314 neb.setVibrationalStencil(parseVibrationalStencilToml(value));
316 setIfPresent<double>(*
band,
"converged_force", [&](
const auto& value) {
317 neb.setConvergedForce(value);
319 setIfPresent<std::string>(
320 *
band,
"convergence_force_norm", [&](
const auto& value) {
322 auto field = neb.initForceNorm();
324 field.setAutomatic();
330 gpr::schema::ConvergenceForceNorm::L2_NORM);
334 gpr::schema::ConvergenceForceNorm::LINF_NORM);
338 gpr::schema::ConvergenceForceNorm::MAX_FORCE_ON_ATOM);
342 setIfPresent<int32_t>(*
band,
"max_iterations", [&](
const auto& value) {
343 neb.setMaxIterations(value);
345 setIfPresent<int32_t>(*
band,
"max_inner_iter", [&](
const auto& value) {
346 neb.setMaxInnerIter(value);
348 setIfPresent<double>(*
band,
"spring_constant", [&](
const auto& value) {
349 neb.setSpringConstant(value);
351 setIfPresent<double>(*
band,
"spring_constant_min", [&](
const auto& value) {
352 neb.setSpringConstantMin(value);
354 setIfPresent<bool>(*
band,
"geometric_spring", [&](
const auto& value) {
355 neb.setGeometricSpring(value);
357 setIfPresent<bool>(*
band,
"climbing_image",
358 [&](
const auto& value) { neb.setClimbingImage(value); });
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);
365 setIfPresent<double>(*
band,
"ci_activation_factor", [&](
const auto& value) {
366 neb.setCiActivationFactor(value);
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); });
379 setIfPresent<bool>(*
band,
"sidpp", [&](
const auto& value) {
380 if (value) neb.setIdpp(
true);
382 setIfPresent<bool>(*
band,
"sidpp_geodesic", [&](
const auto& value) {
388 setIfPresent<bool>(*
band,
"geodesic_image_prior", [&](
const auto& value) {
389 neb.setGeodesicImagePrior(value);
391 setIfPresent<bool>(*
band,
"endpoint_assign", [&](
const auto& value) {
392 neb.setEndpointAssign(value);
394 setIfPresent<double>(*
band,
"endpoint_assign_kmax", [&](
const auto& value) {
395 neb.setEndpointAssignKmax(value);
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);
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")) {
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",
414 auto options = neb.getLbfgs();
415 setIfPresent<double>(*table,
"max_move", [&](
const auto& value) {
416 options.setMaxMove(value);
418 setIfPresent<int32_t>(*table,
"memory", [&](
const auto& value) {
419 options.setMemory(value);
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);
430 setIfPresent<bool>(*table,
"angle_reset", [&](
const auto& value) {
431 options.setAngleReset(value);
433 setIfPresent<bool>(*table,
"distance_reset", [&](
const auto& value) {
434 options.setDistanceReset(value);
436 setIfPresent<int32_t>(*table,
"sketch_history", [&](
const auto& value) {
437 options.setSketchHistory(value);
439 setIfPresent<uint64_t>(*table,
"sketch_seed", [&](
const auto& value) {
440 options.setSketchSeed(value);
442 setIfPresent<int32_t>(*table,
"sketch_h0_rank", [&](
const auto& value) {
443 options.setSketchH0Rank(value);
445 setIfPresent<double>(*table,
"sketch_h0_eps", [&](
const auto& value) {
446 options.setSketchH0Eps(value);
448 setIfPresent<double>(
449 *table,
"newton_agreement", [&](
const auto& value) {
451 options.setNewtonAgreement(value);
454 if (
const auto* table = tableAt(*
band,
"mmf")) {
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"},
462 auto options = neb.getMmf();
463 setIfPresent<bool>(*table,
"use_mmf", [&](
const auto& value) {
464 options.setUseMmf(value);
466 setIfPresent<bool>(*table,
"rg_minmode_dimer", [&](
const auto& value) {
467 options.setRgMinmodeDimer(value);
469 setIfPresent<double>(*table,
"trigger_force", [&](
const auto& value) {
470 options.setTriggerForce(value);
472 setIfPresent<double>(*table,
"trigger_factor", [&](
const auto& value) {
473 options.setTriggerFactor(value);
475 setIfPresent<int64_t>(*table,
"max_steps", [&](
const auto& value) {
476 options.setMaxSteps(value);
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);
484 setIfPresent<int32_t>(*table,
"max_phases", [&](
const auto& value) {
485 options.setMaxPhases(value);
487 setIfPresent<int32_t>(*table,
"max_inner_iter", [&](
const auto& value) {
488 options.setMaxInnerIter(value);
490 setIfPresent<int32_t>(*table,
"max_rot_iter", [&](
const auto& value) {
491 options.setMaxRotIter(value);
493 setIfPresent<bool>(*table,
"eval_image1", [&](
const auto& value) {
494 options.setEvalImage1(value);
496 setIfPresent<double>(*table,
"perturb", [&](
const auto& value) {
497 options.setPerturb(value);
499 setIfPresent<bool>(*table,
"keep_improving", [&](
const auto& value) {
500 options.setKeepImproving(value);
502 setIfPresent<double>(
503 *table,
"imspe_soft_threshold",
504 [&](
const auto& value) { options.setImspeSoftThreshold(value); });
508void populateGp(
const toml::table& root,
509 gpr::schema::InputParameters::Builder params)
511 const auto* table = tableAt(root,
"gp");
513 rejectUnknownKeys(*table,
519 "use_rigid_null_deflation",
520 "profile_predict_mean",
521 "profile_energy_split",
522 "profile_gradient_split",
523 "hyperparameter_mode",
524 "hyperparameter_objective",
532 "scalapack_block_size",
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);
541 setIfPresent<double>(*table,
"noise_sigma2", [&](
const auto& value) {
542 model.setNoiseSigma2(value);
544 setIfPresent<bool>(*table,
"no_output_norm", [&](
const auto& value) {
545 model.setDisableOutputNormalization(value);
547 setIfPresent<bool>(*table,
"zbl_prior_mean", [&](
const auto& value) {
548 model.setUseZblPriorMean(value);
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);
556 setIfPresent<bool>(*table,
"profile_energy_split", [&](
const auto& value) {
557 model.setProfileEnergySplit(value);
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));
569 setIfPresent<std::string>(
570 *table,
"hyperparameter_objective", [&](
const auto& value) {
571 optimizer.setObjective(parseHyperparameterObjectiveToml(value));
573 setIfPresent<int32_t>(*table,
"max_iter", [&](
const auto& value) {
574 optimizer.setMaxIter(value);
576 setIfPresent<double>(*table,
"tol_func", [&](
const auto& value) {
577 optimizer.setTolFunc(value);
579 setIfPresent<double>(*table,
"tol_sol", [&](
const auto& value) {
580 optimizer.setTolSol(value);
582 auto priors = optimizer.getLengthScalePriors();
583 setIfPresent<bool>(*table,
"ls_prior", [&](
const auto& value) {
584 priors.setLengthScalePrior(value);
586 auto hssvd = params.getHsSvd();
587 setIfPresent<bool>(*table,
"principled_nugget", [&](
const auto& value) {
588 hssvd.setPrincipledNugget(value);
590 setIfPresent<double>(*table,
"kappa_max",
591 [&](
const auto& value) { hssvd.setKappaMax(value); });
592 if (
const auto* options = tableAt(*table,
"hssvd")) {
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"},
599 setIfPresent<bool>(*options,
"use_solver", [&](
const auto& value) {
600 hssvd.setUseSolver(value);
602 setIfPresent<bool>(*options,
"use_objective_contractions",
603 [&](
const auto& value) {
604 hssvd.setUseObjectiveContractions(value);
606 setIfPresent<double>(*options,
"dual_chop_tol", [&](
const auto& value) {
607 hssvd.setDualChopTol(value);
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);
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);
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);
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]);
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);
646void populateUncertainty(
const toml::table& root,
647 gpr::schema::InputParameters::Builder params)
649 const auto* table = tableAt(root,
"uncertainty");
653 {
"mode",
"variance_arm",
"rff_features",
"rff_force_tol_fraction",
654 "accept_tau",
"accept_tau_relative",
"inner_unc_relative",
655 "stable_posterior_variance"},
657 auto options = params.getUncertainty();
658 setIfPresent<std::string>(*table,
"mode", [&](
const auto& value) {
659 options.setMode(parseUncertaintyModeToml(value));
661 setIfPresent<std::string>(*table,
"variance_arm", [&](
const auto& value) {
662 options.setVarianceArm(parseVarianceArmToml(value));
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 "
671 options.setRffFeatures(-1);
673 setIfPresent<int32_t>(
674 *table,
"rff_features", [&](
const auto& value) {
676 throw std::invalid_argument(
677 "uncertainty.rff_features must be a non-negative "
678 "integer or \"auto\"");
680 options.setRffFeatures(value);
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)");
690 options.setRffForceTolFraction(value);
692 setIfPresent<double>(*table,
"accept_tau", [&](
const auto& value) {
693 options.setAcceptTau(value);
695 setIfPresent<double>(*table,
"accept_tau_relative", [&](
const auto& value) {
696 options.setAcceptTauRelative(value);
698 setIfPresent<double>(*table,
"inner_unc_relative", [&](
const auto& value) {
699 options.setInnerUncRelative(value);
702 *table,
"stable_posterior_variance",
703 [&](
const auto& value) { options.setStablePosteriorVariance(value); });
706void populateAcquisition(
const toml::table& root,
707 gpr::schema::NebParams::Builder neb)
709 const auto* table = tableAt(root,
"acquisition");
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"},
717 setIfPresent<std::string>(*table,
"kind", [&](
const auto& value) {
718 neb.setAcquisition(parseAcquisitionToml(value));
720 setIfPresent<bool>(*table,
"three_phase_picker", [&](
const auto& value) {
721 neb.setThreePhasePicker(value);
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);
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);
744void populateTrust(
const toml::table& root, gpr::schema::NebParams::Builder neb)
746 const auto* table = tableAt(root,
"trust");
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"},
753 auto options = neb.getTrust();
754 setIfPresent<std::string>(*table,
"metric", [&](
const auto& value) {
755 options.setMetric(parseDistanceMetricToml(value));
757 setIfPresent<bool>(*table,
"use_adaptive", [&](
const auto& value) {
758 options.setUseAdaptive(value);
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);
765 setIfPresent<double>(*table,
"adaptive_floor", [&](
const auto& value) {
766 options.setAdaptiveFloor(value);
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);
773 setIfPresent<int32_t>(*table,
"half_life", [&](
const auto& value) {
774 options.setHalfLife(value);
776 setIfPresent<double>(*table,
"ratio_at_limit", [&](
const auto& value) {
777 options.setRatioAtLimit(value);
779 setIfPresent<bool>(*table,
"scalefree_trust", [&](
const auto& value) {
780 neb.setScalefreeTrust(value);
782 setIfPresent<double>(*table,
"scalefree_tau", [&](
const auto& value) {
783 neb.setScalefreeTau(value);
789void populatePotentialStruct(
const toml::table& table,
790 capnp::DynamicStruct::Builder output);
798capnp::DynamicValue::Reader potentialScalar(
const toml::node& node,
800 std::string_view key)
802 if (
const auto* value = node.as_boolean())
return value->get();
803 const auto held = [&](
auto value) -> capnp::DynamicValue::Reader {
805 throw std::invalid_argument(
806 "Invalid type or range for configuration key: " +
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: " +
841 return static_cast<double>(number);
843 if (
const auto* floating = node.as_floating_point())
844 return floating->get();
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");
857void populatePotentialList(
const toml::array& values, std::string_view key,
858 capnp::DynamicList::Builder output)
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(
868 output.init(i, list->size()).as<capnp::DynamicList>());
870 output.set(i, potentialScalar(
871 value, output.getSchema().getElementType(), key));
875void populatePotentialStruct(
const toml::table& table,
876 capnp::DynamicStruct::Builder output)
878 bool union_selected =
false;
879 for (
const auto& [key, value]: table) {
880 std::string field_name;
882 for (
char c: key.str()) {
887 field_name += upper ?
static_cast<char>(std::toupper(
888 static_cast<unsigned char>(c)))
892 auto field = output.getSchema().getFieldByName(field_name.c_str());
893 if (field.getProto().getDiscriminantValue() !=
894 capnp::schema::Field::NO_DISCRIMINANT) {
896 throw std::invalid_argument(
897 "Select one potential configuration arm");
898 union_selected =
true;
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(
906 output.init(field, list->size()).as<capnp::DynamicList>());
909 potentialScalar(value, field.getType(), key.str()));
914void populateOracle(
const toml::table& root,
915 gpr::schema::InputParameters::Builder params)
917 const auto* oracle = tableAt(root,
"oracle");
920 *oracle, {
"potential",
"parameters",
"metatomic",
"plugin"},
"oracle");
921 setIfPresent<std::string>(*oracle,
"potential", [&](
const auto& value) {
922 params.setPotential(value.c_str());
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"},
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");
944 const auto* table = tableAt(*oracle,
"metatomic");
946 rejectUnknownKeys(*table,
947 {
"model",
"device",
"rotations",
"so3_probe",
948 "so3_policy",
"uncertainty_threshold"},
950 setIfPresent<std::string>(*table,
"model", [&](
const auto& value) {
951 params.setModel(value.c_str());
953 setIfPresent<std::string>(*table,
"device", [&](
const auto& value) {
954 params.setDevice(value.c_str());
956 auto options = params.getMetatomic();
957 setIfPresent<int32_t>(*table,
"rotations", [&](
const auto& value) {
958 options.setRotations(value);
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));
965 setIfPresent<double>(
966 *table,
"uncertainty_threshold",
967 [&](
const auto& value) { options.setUncertaintyThreshold(value); });
970void populateRun(
const toml::table& root,
971 gpr::schema::InputParameters::Builder params,
972 gpr::schema::NebParams::Builder neb)
974 const auto* table = tableAt(root,
"run");
978 {
"reactant",
"product",
"output",
"con_output",
"seed",
979 "max_iterations",
"converged_force",
"trace_band_history",
980 "trace_con_output",
"use_prune",
"gp_init"},
982 setIfPresent<std::string>(*table,
"reactant", [&](
const auto& value) {
983 params.setReactant(value.c_str());
985 setIfPresent<std::string>(*table,
"product", [&](
const auto& value) {
986 params.setProduct(value.c_str());
988 setIfPresent<std::string>(*table,
"output", [&](
const auto& value) {
989 params.setOutput(value.c_str());
991 setIfPresent<std::string>(*table,
"gp_init", [&](
const auto& value) {
992 params.setGpInit(value.c_str());
994 setIfPresent<std::string>(*table,
"con_output", [&](
const auto& value) {
995 params.setConOutput(value.c_str());
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);
1002 setIfPresent<double>(*table,
"converged_force", [&](
const auto& value) {
1003 neb.setConvergedForce(value);
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());
1013 setIfPresent<bool>(*table,
"use_prune", [&](
bool 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";
1023void populateLinalg(
const toml::table& root,
1024 gpr::schema::InputParameters::Builder params)
1026 const auto* table = tableAt(root,
"linalg");
1028 rejectUnknownKeys(*table, {
"mode",
"threads",
"training_product"},
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);
1037 throw std::invalid_argument(
"Unknown linalg.mode: " + value);
1039 setIfPresent<int32_t>(*table,
"threads", [&](
const auto& value) {
1041 throw std::invalid_argument(
"linalg.threads must be at least 1");
1042 linalg.setThreads(value);
1044 setIfPresent<std::string>(
1045 *table,
"training_product", [&](
const auto& value) {
1046 linalg.setTrainingProductLibrary(value.c_str());
1052void loadInputParametersFromToml(
const std::string& path,
1053 capnp::MallocMessageBuilder& message)
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()));
1062 rejectUnknownKeys(root,
1063 {
"band",
"gp",
"uncertainty",
"acquisition",
"trust",
1064 "oracle",
"run",
"linalg"},
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);
GP-accelerated NEB: AIE and OIE variants.
std::pair< std::string, std::string > Field
std::optional< ConvergenceNormType > parseForceNorm(std::string_view name)
static void requireLbfgsNewtonAgreement(double value)