Loading...
Searching...
No Matches
gpr::io Namespace Reference

Classes

class  ErrorManager
 Responsible for errors handling. More...
class  FileManager
 Responsible for generic IO operations. More...
struct  FrameEnergyForces
struct  GpInitializationOverrides
class  LogManager
 Responsible for logging. More...
struct  MetatomicConfigFields
struct  NebDriverConfig
struct  TrainedGpState

Functions

void loadParametersFromCapnp (const std::string &binary_filename, gpr::InputParameters &parameters)
 Loads parameters by reading a memory-mapped Cap'n Proto binary file.
bool readerIsLegacyDimer (capnp::MessageReader &reader)
 Whether reader is a gprd_params.capnp message rather than a params.capnp message.
void overlayLegacyDimerReader (capnp::MessageReader &reader, gpr::schema::InputParameters::Builder unified)
 Copy a gprd_params.capnp reader onto a unified builder.
GpInitializationOverrides readGpInitializationOverrides (gpr::schema::InputParameters::Reader params)
void applyDimerConfigFromCapnp (gpr::schema::InputParameters::Reader params, gpr::InputParameters &parameters)
 Project the dimer arm of a unified configuration into the runtime parameter record.
void loadNebConfigFromCapnp (const std::string &binary_filename, gpr::neb::GPNEBConfig &config)
 Load the NEB-chain knobs from a unified-schema (params.capnp) Cap'n Proto binary into a gpr::neb::GPNEBConfig.
void applyNebConfigFromCapnp (gpr::schema::InputParameters::Reader params, gpr::neb::GPNEBConfig &config, bool validate_rigid_deflation=true)
 Materialize a gpr::neb::GPNEBConfig from an already-open unified-schema message. Reader-based counterpart of loadNebConfigFromCapnp with additional driver, GP and uncertainty controls for a file baseline. The filename-based adapter retains the established binary override subset. Unset scalar fields use the unified schema defaults.
void applyOciConfigFromCapnp (gpr::schema::InputParameters::Reader params, gpr::neb::OCINEBConfig &config)
 Materialize a gpr::neb::OCINEBConfig (the –use-mmf / –mmf-* family, plus the dimer posterior-variance accept-tau gate carried on Uncertainty) from an already-open unified-schema message.
void applyMetatomicConfigFromCapnp (gpr::schema::InputParameters::Reader params, MetatomicConfigFields &metatomic)
 Materialize the metatomic oracle knobs (model/device live on the top-level InputParameters; rotations/so3-policy/uncertainty threshold live on InputParameters.metatomic) from an already-open unified-schema message.
void applyDriverConfigFromCapnp (gpr::schema::InputParameters::Reader params, NebDriverConfig &driver)
 Materialize the driver-level knobs (endpoint paths, run I/O, image count, seed, endpoint assignment / pruning switches) from an already-open unified-schema message.
void loadOciMmfConfigFromCapnp (const std::string &filename, gpr::neb::OCINEBConfig &config)
 Load the binary MMF override subset, preserving uncertainty controls.
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.
TrainedGpState loadTrainedGpState (const std::string &path)
TrainedGpState observationState (const Observation &observations)
 A state that carries observations and no pair kernel.
bool applyTrainedGpState (GaussianProcessRegression &gp, const TrainedGpState &state, const AtomsConfiguration &atoms, bool require_identity)
void refuseNonFiniteSeedRows (const Observation &observations, Eigen::Index expected_cols)
void noteLocalKernel (neb::ActiveLearningSession &session, const TrainedGpState &state)
int seedSession (neb::ActiveLearningSession &session, const TrainedGpState &state, bool require_identity, Eigen::Index expected_cols)
std::string resolveGpStatePath (const std::string &spec, bool restart)
std::string outputDirectory (const std::string &output_path)
 Directory of an output path, or . when the path has no directory.
void loadEnvironmentAtomTypes (std::istream &input, gpr::AtomsConfiguration &atoms_config, const gpr::InputParameters &parameters)
void loadEnvironmentAtomTypes (const std::string &path, gpr::AtomsConfiguration &atoms_config, const gpr::InputParameters &parameters)
void initializeAtomsConfiguration (const gpr::Coord &R_init, const gpr::InputParameters &parameters, const std::unordered_map< std::string, gpr::Index_t > &atomtypes, gpr::AtomsConfiguration &atoms_config)
std::array< double, 9 > cellMatrixFromLengthsAndAngles (const std::array< double, 3 > &cell, const std::array< double, 3 > &angles)
void setCellDimensionsFromLengthsAndAngles (const std::array< double, 3 > &cell, const std::array< double, 3 > &angles, gpr::InputParameters &parameters)
static void requireUsableFrame (const readcon::CFrame &frame, const char *role)
template<class To, class From>
static To checkedNarrow (From value, const char *field)
void loadAtomsConfigurationFromFrame (const readcon::CFrame &frame, gpr::AtomsConfiguration &atoms_config, gpr::Coord &R_init, gpr::InputParameters &parameters, const readcon::CFrame *product, std::vector< int > *reactive_atoms)
template<typename Type, typename AtomicNr>
std::vector< Type > elementAtomTypes (const AtomicNr *atomic_nrs, std::size_t n_atoms)
double maxAtomicForce (const double *forces, std::size_t n_atoms) noexcept
 Largest atomic force norm. NaN when any component is non-finite.
int addAtomWithOptionalForce (readcon::RKRConFrameBuilder *builder, const char *symbol, double x, double y, double z, bool fixed, std::uint64_t atom_id, double mass, const double *force)
 Add one atom. force is three doubles, or null when the atom has none.
FrameEnergyForces frameEnergyForces (const readcon::RKRConFrame *frame, const readcon::CFrame &parsed)
std::string seedKernelAtomsIdentity (const AtomsConfiguration &atoms)
 Atomic descriptor identity; moving positions belong to the observations.
std::string seedKernelIdentity (const GaussianProcessRegression &gp, const AtomsConfiguration &atoms)
bool readSeedKernelAtomTypes (std::istream &input, AtomsConfiguration &atoms, const InputParameters &parameters)
 Restore the archived type map after checking physical atom identity.
void writeSeedKernel (std::ostream &out, const GaussianProcessRegression &gp, const AtomsConfiguration &atoms)
 Write fitted covariance parameters, output units, and descriptor identity.
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.

Function Documentation

◆ addAtomWithOptionalForce()

int gpr::io::addAtomWithOptionalForce ( readcon::RKRConFrameBuilder * builder,
const char * symbol,
double x,
double y,
double z,
bool fixed,
std::uint64_t atom_id,
double mass,
const double * force )
inline

Add one atom. force is three doubles, or null when the atom has none.

Definition at line 99 of file ReadConLoader.h.

103{
104 return readcon::rkr_frame_add_atom_full(builder, symbol, x, y, z, fixed,
105 fixed, fixed, atom_id, mass,
106 nullptr, force);
107}
@ z
Definition Enums.h:28
@ x
Definition Enums.h:28
@ y
Definition Enums.h:28

◆ applyDimerConfigFromCapnp()

void gpr::io::applyDimerConfigFromCapnp ( gpr::schema::InputParameters::Reader params,
gpr::InputParameters & parameters )

Project the dimer arm of a unified configuration into the runtime parameter record.

The reader may be backed by either a params.capnp binary or TOML through UnifiedConfigMessage. The message must select InputParameters.method.dimer.

Definition at line 358 of file CapnProtoNebLoader.cpp.

360{
361 if (!params.getMethod().isDimer())
362 throw std::runtime_error(
363 "Unified configuration does not select method.dimer");
364
365 const auto dimer = params.getMethod().getDimer();
366 parameters.actdist_fro.value = dimer.getActdistFro();
367 parameters.dimer_sep.value = dimer.getDimerSep();
368 parameters.method_rot.value = "LBFGS_alg";
369 parameters.method_trans.value = "LBFGS_alg";
370 const auto translation = dimer.getParamTrans();
371 parameters.param_trans.value[0] = translation.getStepLength();
372 parameters.param_trans.value[1] = translation.getMaxStepLength();
374 translation.getRotremThresh();
375 parameters.T_dimer.value = dimer.getFinalConvergenceForce();
376
377 const auto initial = dimer.getInitialRotations();
378 parameters.num_iter_initrot.value =
379 static_cast<int>(initial.getMaxIterations());
380 parameters.initrot_nogp.value = initial.getUseGpr() ? 0 : 1;
381 parameters.T_anglerot_init.value = initial.getConvergenceAngle();
382 const auto relaxation = dimer.getRelaxation();
383 parameters.num_bigiter.value =
384 static_cast<int>(relaxation.getMaxOuterIterations());
385 parameters.num_iter.value =
386 static_cast<int>(relaxation.getMaxInnerIterations());
387 parameters.num_iter_rot_gp.value =
388 static_cast<int>(relaxation.getMaxRotationIterations());
389 parameters.num_bigiter_initloc.value =
390 static_cast<int>(relaxation.getWarmupFromInitialLocation());
391 parameters.num_bigiter_initparam.value =
392 static_cast<int>(relaxation.getWarmupFromInitHyperparameters());
393 parameters.islarge_num_iter.value =
394 relaxation.getAssumeManyIterations() ? 1 : 0;
395 parameters.T_anglerot_gp.value = relaxation.getConvergence().getAngle();
396 parameters.divisor_T_dimer_gp.value = dimer.getDivisorTdimerGP();
397 parameters.disp_max.value = dimer.getMidpointMaxDisp();
398 parameters.ratio_at_limit.value = dimer.getRatioAtLimit();
399 switch (dimer.getConvergenceForceNorm()) {
400 case gpr::schema::ConvergenceForceNorm::L2_NORM:
401 parameters.convergence_force_norm.value = 0;
402 break;
403 case gpr::schema::ConvergenceForceNorm::LINF_NORM:
404 parameters.convergence_force_norm.value = 1;
405 break;
406 case gpr::schema::ConvergenceForceNorm::MAX_FORCE_ON_ATOM:
407 parameters.convergence_force_norm.value = 2;
408 break;
409 }
410
411 const auto run = params.getRunSelector();
412 parameters.i_dist.value = run.getIDist();
413 parameters.i_run.value = run.getIRun();
414 const auto separations = run.getSepDists();
415 for (std::size_t i = 0; i < separations.size() && i < 4; ++i)
416 parameters.dist_sp.value[i] = separations[i];
417
418 const auto gp = params.getGpr();
419 parameters.gp_sigma2.value = gp.getGpSigma2();
420 parameters.jitter_sigma2.value = gp.getJitterSigma2();
421 parameters.sigma2.value = gp.getNoiseSigma2();
422 parameters.use_alpha_k_predict_mean.value = gp.getUseAlphaKPredictMean();
423 parameters.use_alpha_k_laplace_mean.value = gp.getUseAlphaKLaplaceMean();
424 parameters.laplace_skip_scg_threshold.value = gp.getSkipScgThreshold();
426 gp.getUseTrainingGeometryHandle();
427 parameters.profile_predict_mean.value = gp.getProfilePredictMean();
428 parameters.profile_energy_split.value = gp.getProfileEnergySplit();
429 parameters.profile_gradient_split.value = gp.getProfileGradientSplit();
430 parameters.use_rigid_null_deflation.value = gp.getUseRigidNullDeflation();
431 gpr::detail::validateRigidNullDeflationConfiguration(
433 params.getHsSvd().getPrincipledNugget());
434 parameters.log_training_geometry.value = gp.getLogTrainingGeometry();
435 parameters.log_rank_block_cholesky.value = gp.getLogRankBlockCholesky();
436 // Schema version 5 and later read an omitted prior as the published
437 // defaults. A writer from an earlier schema, including a version 4
438 // oraclePlugin message, that omitted it meant zeros, so that message
439 // keeps reading as zeros, which GP initialization rejects by name.
440 if (params.getSchemaVersion() < kPublishedPriorSchemaVersion &&
441 !gp.hasPrior()) {
442 parameters.prior_mu.value = 0.0;
443 parameters.prior_nu.value = 0.0;
444 parameters.prior_s2.value = 0.0;
445 } else {
446 const auto prior = gp.getPrior();
447 parameters.prior_mu.value = prior.getMu();
448 parameters.prior_nu.value = prior.getNu();
449 parameters.prior_s2.value = prior.getS2();
450 }
451
452 const auto early = params.getEarlyStopping();
453 parameters.es_dist_metric.value = mapDistanceMetric(early.getDistMetric());
454 parameters.es_threshold.value = early.getThreshold();
456 early.getUseAdaptiveThreshold();
457 parameters.es_adaptive_A.value = early.getAdaptiveA();
458 parameters.es_adaptive_floor.value = early.getAdaptiveFloor();
459 parameters.es_t_min.value = early.getTMin();
460 parameters.es_delta_explore.value = early.getDeltaExplore();
461 parameters.es_half_life.value = early.getHalfLife();
462
463 const auto optimizer = params.getOptimizer();
464 parameters.check_derivative.value =
465 optimizer.getCheckDerivative() ? "true" : "false";
466 parameters.max_iter.value = optimizer.getMaxIter();
467 parameters.tolerance_func.value = optimizer.getTolFunc();
468 parameters.tolerance_sol.value = optimizer.getTolSol();
469 if (optimizer.isScg()) {
470 parameters.optimization_alg.value = "SCG_opt";
471 const auto scg = optimizer.getScg();
472 parameters.lambda_limit.value = scg.getLambdaLimit();
473 parameters.lambda.value = scg.getLambda();
474 switch (scg.getCurvatureMode()) {
475 case gpr::schema::ScgCurvatureMode::EXACT:
476 parameters.curvature_mode.value = "exact";
477 break;
478 case gpr::schema::ScgCurvatureMode::NLML_HESSIAN_VECTOR:
479 parameters.curvature_mode.value = "nlml_hessian_vector";
480 break;
481 default:
482 parameters.curvature_mode.value = "finite_difference";
483 break;
484 }
485 } else {
486 parameters.optimization_alg.value = "ADAM_opt";
487 const auto adam = optimizer.getAdam();
488 parameters.learning_rate.value = adam.getLr();
489 parameters.learning_rate_decay.value = adam.getLrd();
490 parameters.beta1.value = adam.getB1();
491 parameters.beta2.value = adam.getB2();
492 parameters.epsilon.value = adam.getEps();
493 parameters.weight_decay.value = adam.getWeightDecay();
494 parameters.amsgrad.value = adam.getAmsgrad();
495 }
496
497 const auto pruning = params.getPruning();
498 parameters.use_prune.value = pruning.getUsePrune();
499 parameters.start_prune_at.value = pruning.getPruneBegin();
500 parameters.nprune_vals.value = pruning.getPruneNVals();
501 parameters.prune_threshold.value = pruning.getPruneThreshold();
502 const auto debug = params.getDebug();
503 parameters.report_level.value = debug.getReportLevel();
504 parameters.debug_level.value = debug.getDebugLevel();
505 parameters.debug_output_dir.value = debug.getDebugOutDir().cStr();
506 parameters.debug_output_file_R.value = debug.getDebugPosFile().cStr();
507 parameters.debug_output_file_E.value = debug.getDebugEnergyFile().cStr();
508 parameters.debug_output_file_G.value = debug.getDebugGradFile().cStr();
510 debug.getDebugOutExt().cStr();
512 debug.getDebugOffsetMidPoint();
513 parameters.debug_dy.value = debug.getDebugDy();
514 parameters.debug_dz.value = debug.getDebugDz();
515 parameters.profile_dimer_times.value = debug.getProfileDimerTimes();
516
517 const auto linalg = params.getLinearAlgebra();
518 parameters.scalapack_block_size.value = linalg.getScalapackBlockSize();
519 parameters.scalapack_nprow.value = linalg.getScalapackNprow();
520 parameters.cutlass_plugin_path.value = linalg.getCutlassPluginPath().cStr();
521 const auto cell = params.getCellDimensions();
522 for (std::size_t i = 0; i < cell.size() && i < 9; ++i)
523 parameters.cell_dimensions.value[i] = cell[i];
524}
KeyValuePair< double[2]> param_trans
Definition Structures.h:440
KeyValuePair< bool > log_rank_block_cholesky
Definition Structures.h:635
KeyValuePair< double > T_anglerot_gp
Definition Structures.h:484
KeyValuePair< double > prior_s2
Definition Structures.h:650
KeyValuePair< double > es_t_min
Definition Structures.h:659
KeyValuePair< double > laplace_skip_scg_threshold
Definition Structures.h:623
KeyValuePair< std::string > debug_output_file_G
Definition Structures.h:589
KeyValuePair< int > max_iter
Definition Structures.h:674
KeyValuePair< int > i_dist
Definition Structures.h:371
KeyValuePair< int > initrot_nogp
Definition Structures.h:467
KeyValuePair< DistanceMetricType > es_dist_metric
Definition Structures.h:652
KeyValuePair< bool > use_rigid_null_deflation
Definition Structures.h:627
KeyValuePair< std::string > optimization_alg
Definition Structures.h:614
KeyValuePair< bool > es_use_adaptive_threshold
Definition Structures.h:655
KeyValuePair< double[9]> cell_dimensions
Definition Structures.h:605
KeyValuePair< double > dimer_sep
Definition Structures.h:425
KeyValuePair< int > start_prune_at
Definition Structures.h:571
KeyValuePair< int > islarge_num_iter
Definition Structures.h:544
KeyValuePair< double > lambda
Definition Structures.h:678
KeyValuePair< double > prior_nu
Definition Structures.h:649
KeyValuePair< int > report_level
Definition Structures.h:673
KeyValuePair< double > rotation_removal_projection_threshold
Definition Structures.h:667
KeyValuePair< double > T_anglerot_init
Definition Structures.h:474
KeyValuePair< double > learning_rate_decay
Definition Structures.h:681
KeyValuePair< int > scalapack_nprow
Definition Structures.h:638
KeyValuePair< double > jitter_sigma2
Definition Structures.h:613
KeyValuePair< std::string > debug_output_dir
Definition Structures.h:584
KeyValuePair< int > scalapack_block_size
Definition Structures.h:637
KeyValuePair< double > ratio_at_limit
Definition Structures.h:512
KeyValuePair< int > debug_level
Definition Structures.h:597
KeyValuePair< std::string > method_trans
Definition Structures.h:435
KeyValuePair< double > weight_decay
Definition Structures.h:685
KeyValuePair< double > beta2
Definition Structures.h:683
KeyValuePair< double > debug_dz
Definition Structures.h:596
KeyValuePair< double > prune_threshold
Definition Structures.h:581
KeyValuePair< double > beta1
Definition Structures.h:682
KeyValuePair< double > es_delta_explore
Definition Structures.h:660
KeyValuePair< int > nprune_vals
Definition Structures.h:576
KeyValuePair< int > num_bigiter_initloc
Definition Structures.h:519
KeyValuePair< int > convergence_force_norm
Definition Structures.h:461
KeyValuePair< bool > use_training_geometry_handle
Definition Structures.h:625
KeyValuePair< bool > profile_gradient_split
Definition Structures.h:631
KeyValuePair< double > actdist_fro
Definition Structures.h:379
KeyValuePair< double > epsilon
Definition Structures.h:684
KeyValuePair< int > num_bigiter_initparam
Definition Structures.h:527
KeyValuePair< std::string > method_rot
Definition Structures.h:430
KeyValuePair< bool > use_prune
Definition Structures.h:562
KeyValuePair< int > divisor_T_dimer_gp
Definition Structures.h:498
KeyValuePair< double > learning_rate
Definition Structures.h:680
KeyValuePair< int > num_iter
Definition Structures.h:537
KeyValuePair< int > num_iter_initrot
Definition Structures.h:479
KeyValuePair< double > lambda_limit
Definition Structures.h:677
KeyValuePair< double > debug_offset_from_mid_point
Definition Structures.h:593
KeyValuePair< double > disp_max
Definition Structures.h:505
KeyValuePair< double > tolerance_func
Definition Structures.h:675
KeyValuePair< std::string > check_derivative
Definition Structures.h:672
KeyValuePair< bool > profile_dimer_times
Definition Structures.h:633
KeyValuePair< std::string > cutlass_plugin_path
Definition Structures.h:639
KeyValuePair< std::string > debug_output_file_E
Definition Structures.h:587
KeyValuePair< double[4]> dist_sp
Definition Structures.h:374
KeyValuePair< double > es_adaptive_A
Definition Structures.h:657
KeyValuePair< bool > profile_energy_split
Definition Structures.h:630
KeyValuePair< int > es_half_life
Definition Structures.h:661
KeyValuePair< bool > log_training_geometry
Definition Structures.h:634
KeyValuePair< bool > use_alpha_k_laplace_mean
Definition Structures.h:621
KeyValuePair< bool > use_alpha_k_predict_mean
Definition Structures.h:619
KeyValuePair< std::string > debug_output_file_extension
Definition Structures.h:591
KeyValuePair< double > tolerance_sol
Definition Structures.h:676
KeyValuePair< double > prior_mu
Definition Structures.h:648
KeyValuePair< int > num_bigiter
Definition Structures.h:532
KeyValuePair< double > sigma2
Definition Structures.h:616
KeyValuePair< std::string > curvature_mode
Definition Structures.h:679
KeyValuePair< bool > profile_predict_mean
Definition Structures.h:629
KeyValuePair< int > i_run
Definition Structures.h:372
KeyValuePair< bool > amsgrad
Definition Structures.h:686
KeyValuePair< double > es_threshold
Definition Structures.h:654
KeyValuePair< double > debug_dy
Definition Structures.h:595
KeyValuePair< std::string > debug_output_file_R
Definition Structures.h:585
KeyValuePair< double > gp_sigma2
Definition Structures.h:612
KeyValuePair< double > es_adaptive_floor
Definition Structures.h:658
KeyValuePair< double > T_dimer
Definition Structures.h:453
KeyValuePair< int > num_iter_rot_gp
Definition Structures.h:490

◆ applyDriverConfigFromCapnp()

void gpr::io::applyDriverConfigFromCapnp ( gpr::schema::InputParameters::Reader params,
NebDriverConfig & driver )

Materialize the driver-level knobs (endpoint paths, run I/O, image count, seed, endpoint assignment / pruning switches) from an already-open unified-schema message.

Definition at line 613 of file CapnProtoNebLoader.cpp.

615{
616 if (params.getReactant().size() > 0)
617 driver.reactant = params.getReactant().cStr();
618 if (params.getProduct().size() > 0)
619 driver.product = params.getProduct().cStr();
620 driver.potential = params.getPotential().cStr();
621 driver.output = params.getOutput().cStr();
622 if (params.getConOutput().size() > 0)
623 driver.con_output = params.getConOutput().cStr();
624 driver.seed = params.getSeed();
625
626 auto neb = requireNeb(params, "applyDriverConfigFromCapnp");
627 driver.n_images = neb.getNImages();
628 driver.endpoint_assign = neb.getEndpointAssign();
629 driver.endpoint_assign_kmax = neb.getEndpointAssignKmax();
630 driver.midrun_realign = neb.getMidrunRealign();
631
632 driver.use_prune = false;
633 if (params.getPruning().getUsePrune()) {
634 std::cerr << "warning: usePrune is deprecated and ignored; use "
635 "adaptivePrune for bounded active sets\n";
636 }
637
638 auto trace = params.getTrace();
639 driver.trace_band_history = trace.getBandHistory();
640 if (trace.getTraceConPath().size() > 0)
641 driver.trace_con_output = trace.getTraceConPath().cStr();
642
643 auto linalg = params.getLinearAlgebra();
644 driver.linalg_threads = linalg.getThreads();
645 driver.training_product_library = linalg.getTrainingProductLibrary().cStr();
646
647 driver.irc_saddle_hessian =
648 neb.getIrcSaddleHessian() == gpr::schema::IrcSaddleHessian::MODEL
649 ? "model"
650 : "measured";
651 if (params.getGpInit().size() > 0)
652 driver.gp_init = params.getGpInit().cStr();
653 driver.vibrational_stencil =
654 neb.getVibrationalStencil() ==
655 gpr::schema::VibrationalStencil::VIBRATIONAL
656 ? "vibrational"
657 : "full";
658}
Dense and structured linear algebra behind the GP: Cholesky and eigen solvers, linear operators,...
The nudged elastic band: path, GP-NEB driver, configuration and result, acquisition,...
std::string training_product_library
Scheme II specification or product library path; empty for native.
std::string gp_init
gp-state.npz to load before the search. Empty starts from no seed.
int linalg_threads
Dense linear-algebra threads; 0 leaves the CLI default.
std::string irc_saddle_hessian
IRC saddle step: "measured" or "model".
std::string vibrational_stencil
Oracle stencil: "full" or "vibrational".

◆ applyMetatomicConfigFromCapnp()

void gpr::io::applyMetatomicConfigFromCapnp ( gpr::schema::InputParameters::Reader params,
MetatomicConfigFields & metatomic )

Materialize the metatomic oracle knobs (model/device live on the top-level InputParameters; rotations/so3-policy/uncertainty threshold live on InputParameters.metatomic) from an already-open unified-schema message.

Definition at line 601 of file CapnProtoNebLoader.cpp.

603{
604 metatomic.model_path = params.getModel().cStr();
605 metatomic.device = params.getDevice().cStr();
606 auto meta = params.getMetatomic();
607 metatomic.n_symmetry_rotations = meta.getRotations();
608 metatomic.so3_probe_scatter = meta.getSo3Probe();
609 metatomic.so3_policy = mapSo3Policy(meta.getSo3Policy());
610 metatomic.uncertainty_threshold = meta.getUncertaintyThreshold();
611}
gpr::neb::MetatomicSO3Policy so3_policy

◆ applyNebConfigFromCapnp()

void gpr::io::applyNebConfigFromCapnp ( gpr::schema::InputParameters::Reader params,
gpr::neb::GPNEBConfig & config,
bool validate_rigid_deflation = true )

Materialize a gpr::neb::GPNEBConfig from an already-open unified-schema message. Reader-based counterpart of loadNebConfigFromCapnp with additional driver, GP and uncertainty controls for a file baseline. The filename-based adapter retains the established binary override subset. Unset scalar fields use the unified schema defaults.

Exceptions
std::runtime_errorif the message carries no NebParams (method union not set to neb).

Definition at line 526 of file CapnProtoNebLoader.cpp.

529{
530 applyCoreNebConfig(params, config, validate_rigid_deflation);
531
532 // --- Uncertainty / variance arm ----------------------------------------
533 auto uncertainty = params.getUncertainty();
534 config.uncertainty_mode = mapUncertaintyMode(uncertainty.getMode());
535 applyVarianceArm(uncertainty.getVarianceArm(), config);
536 config.rff_features = uncertainty.getRffFeatures();
537 config.rff_force_tol_fraction = uncertainty.getRffForceTolFraction();
538 config.inner_unc_relative = uncertainty.getInnerUncRelative();
539 config.stable_posterior_variance = uncertainty.getStablePosteriorVariance();
540
541 // --- Shared GP conditioning blocks -----------------------------------
542 auto hssvd = params.getHsSvd();
544 hssvd.getUseObjectiveContractions();
545 config.hssvd_dual_chop_tol = hssvd.getDualChopTol();
546 config.hssvd_dual_randomized_sketch = hssvd.getDualRandomizedSketch();
547 config.hssvd_dual_lapack_rrr = hssvd.getDualLapackRrr();
548 config.hssvd_local_active_set_size = hssvd.getLocalActiveSetSize();
550 hssvd.getLocalPosteriorActiveSetSize();
551
552 auto optimizer = params.getOptimizer();
553 if (optimizer.getWorkflowModeExplicit() ||
554 optimizer.getWorkflowMode() !=
555 gpr::schema::HyperparameterWorkflowMode::INLA) {
556 config.hyperparameter_mode =
557 mapHyperparameterWorkflowMode(optimizer.getWorkflowMode());
558 }
559 if (optimizer.getObjectiveExplicit() ||
560 optimizer.getObjective() !=
561 gpr::schema::HyperparameterObjective::NLML) {
563 mapHyperparameterObjective(optimizer.getObjective());
565 }
566
567 auto gpr_model = params.getGpr();
569 gpr_model.getDisableOutputNormalization();
570 config.use_zbl_prior_mean = gpr_model.getUseZblPriorMean();
571 config.use_rigid_null_deflation = gpr_model.getUseRigidNullDeflation();
572
573 auto linalg = params.getLinearAlgebra();
574 config.scalapack_block_size = linalg.getScalapackBlockSize();
575 config.scalapack_nprow = linalg.getScalapackNprow();
576 config.linalg_mode =
577 linalg.getMode() == gpr::schema::LinalgMode::LIBRARY
580
581 // --- Trace ---------------------------------------------------------
582 auto trace = params.getTrace();
583 config.record_band_trace = trace.getBandHistory();
585 trace.getBandHistory() && trace.getGeometriesConV2();
586}
gpr::HyperparameterOptimizationMode hyperparameter_mode
Definition GPNEB.h:800
gpr::linalg::DistributedFactorization linalg_mode
Definition GPNEB.h:782
gpr::UncertaintyMode uncertainty_mode
Definition GPNEB.h:559
bool disable_output_normalization
Definition GPNEB.h:569
bool hssvd_dual_lapack_rrr
Definition GPNEB.h:766
double inner_unc_relative
Definition GPNEB.h:1140
bool hyperparameter_objective_explicit
Definition GPNEB.h:808
int hssvd_local_active_set_size
Definition GPNEB.h:767
double rff_force_tol_fraction
Definition GPNEB.h:754
int hssvd_local_posterior_active_set_size
Definition GPNEB.h:768
bool record_band_trace_geometry
Definition GPNEB.h:520
gpr::HyperparameterObjectiveMode hyperparameter_objective
Definition GPNEB.h:802
bool stable_posterior_variance
Definition GPNEB.h:786
bool use_rigid_null_deflation
Definition GPNEB.h:730
int hssvd_dual_randomized_sketch
Definition GPNEB.h:765
bool use_hssvd_objective_contractions
Definition GPNEB.h:760
double hssvd_dual_chop_tol
Definition GPNEB.h:764

◆ applyOciConfigFromCapnp()

void gpr::io::applyOciConfigFromCapnp ( gpr::schema::InputParameters::Reader params,
gpr::neb::OCINEBConfig & config )

Materialize a gpr::neb::OCINEBConfig (the –use-mmf / –mmf-* family, plus the dimer posterior-variance accept-tau gate carried on Uncertainty) from an already-open unified-schema message.

Exceptions
std::runtime_errorif the message carries no NebParams.

Definition at line 588 of file CapnProtoNebLoader.cpp.

590{
591 applyCoreOciConfig(params, config);
592
593 auto uncertainty = params.getUncertainty();
594 const double accept_tau = uncertainty.getAcceptTau();
595 const double accept_tau_relative = uncertainty.getAcceptTauRelative();
596 if (accept_tau > 0.0) config.dimer_variance_tau_abs = accept_tau;
597 if (accept_tau_relative >= 0.0)
598 config.dimer_variance_tau_rel = accept_tau_relative;
599}

◆ applyTrainedGpState()

bool gpr::io::applyTrainedGpState ( GaussianProcessRegression & gp,
const TrainedGpState & state,
const AtomsConfiguration & atoms,
bool require_identity )

Install the saved hyperparameters. Raw float64 values overwrite the text kernel, so a load/apply round trip keeps the bits. Returns false when the kernel does not match this model.

Definition at line 564 of file GpState.cpp.

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}
void setConstSigma2(const double _constSigma2)
Set the constSigma2 value.
void restoreOutputTransform(double mean, double scale, bool frozen_mean)
Restore output coordinates alongside a kernel represented in them.
void setSigma2(const double value)
Set sigma2 value.
void setMagnSigma2(double value)
Definition SexpatCF.inl:19
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.
std::string kernel_text
Definition GpState.h:36
FieldMatrixd atomistic_length_scale
Definition GpState.h:24
FieldMatrixd length_scale
Definition GpState.h:23
bool has_atomistic_length_scale
Definition GpState.h:25

◆ cellMatrixFromLengthsAndAngles()

std::array< double, 9 > gpr::io::cellMatrixFromLengthsAndAngles ( const std::array< double, 3 > & cell,
const std::array< double, 3 > & angles )

Full 3x3 cell matrix (row-major; rows are the lattice vectors a, b, c) from .con lengths + angles (degrees, order alpha, beta, gamma). Lower-triangular convention: a along x, b in the xy plane.

Definition at line 239 of file ReadConLoader.cpp.

241{
242 // An angle that compares equal to 90 is an exact zero cosine, so
243 // the 25 A Baker box stays the diagonal cellIsVacuumBox recognises.
244 mi_cell box{};
245 if (minimage_cell_from_con_box_exact(cell.data(), angles.data(), &box) !=
246 0) {
247 const char* msg = minimage_last_error();
248 throw std::invalid_argument(msg ? std::string(msg)
249 : "minimage: con box failed");
250 }
251 return {box.ax, box.ay, box.az, box.bx, box.by,
252 box.bz, box.cx, box.cy, box.cz};
253}

◆ checkedNarrow()

template<class To, class From>
To gpr::io::checkedNarrow ( From value,
const char * field )
static

Definition at line 282 of file ReadConLoader.cpp.

283{
284 if (value > static_cast<From>(std::numeric_limits<To>::max())) {
285 throw std::invalid_argument(std::string(field) +
286 " is out of range for this build");
287 }
288 return static_cast<To>(value);
289}

◆ elementAtomTypes()

template<typename Type, typename AtomicNr>
std::vector< Type > gpr::io::elementAtomTypes ( const AtomicNr * atomic_nrs,
std::size_t n_atoms )
nodiscard

Dense atom types for n_atoms atomic numbers: one type per element, numbered in order of first appearance.

Definition at line 43 of file ReadConLoader.h.

45{
46 std::vector<AtomicNr> elements;
47 std::vector<Type> types(n_atoms);
48 for (std::size_t i = 0; i < n_atoms; ++i) {
49 const auto seen =
50 std::find(elements.begin(), elements.end(), atomic_nrs[i]);
51 types[i] = static_cast<Type>(seen - elements.begin());
52 if (seen == elements.end()) elements.push_back(atomic_nrs[i]);
53 }
54 return types;
55}

◆ frameEnergyForces()

FrameEnergyForces gpr::io::frameEnergyForces ( const readcon::RKRConFrame * frame,
const readcon::CFrame & parsed )
inlinenodiscard

Definition at line 117 of file ReadConLoader.h.

119{
121 const auto n = parsed.num_atoms;
122 if (frame == nullptr || n == 0 || !parsed.has_forces) return out;
123 out.forces.assign(3 * n, 0.0);
124 for (std::size_t atom = 0; atom < n; ++atom) {
125 const auto& site = parsed.atoms[atom];
126 if (!site.has_forces) return FrameEnergyForces{};
127 out.forces[3 * atom] = site.fx;
128 out.forces[3 * atom + 1] = site.fy;
129 out.forces[3 * atom + 2] = site.fz;
130 }
131 out.energy = readcon::rkr_frame_energy(frame);
132 out.complete = std::isfinite(out.energy) &&
133 std::isfinite(maxAtomicForce(out.forces.data(), n));
134 if (!out.complete) return FrameEnergyForces{};
135 return out;
136}
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
double maxAtomicForce(const double *forces, std::size_t n_atoms) noexcept
Largest atomic force norm. NaN when any component is non-finite.

◆ initializeAtomsConfiguration()

void gpr::io::initializeAtomsConfiguration ( const gpr::Coord & R_init,
const gpr::InputParameters & parameters,
const std::unordered_map< std::string, gpr::Index_t > & atomtypes,
gpr::AtomsConfiguration & atoms_config )

Definition at line 163 of file ReadConLoader.cpp.

167{
168 aux::ProblemSetUp problem_setup;
169 const gpr::Index_t number_of_mov_atoms = atoms_config.countMovingAtoms();
170 const gpr::Index_t number_of_fro_atoms =
171 static_cast<gpr::Index_t>(atoms_config.is_frozen.size()) -
172 number_of_mov_atoms;
173 const bool use_legacy_cuh2_types =
174 atomtypes.count("H2") && atomtypes.count("Cu");
175
176 atoms_config.atoms_mov.resize(number_of_mov_atoms);
177 atoms_config.atoms_froz_inactive.resize(number_of_fro_atoms);
178 atoms_config.atoms_mov.type.resize(1, number_of_mov_atoms);
179 atoms_config.atoms_froz_inactive.type.resize(1, number_of_fro_atoms);
180
181 if (use_legacy_cuh2_types) {
182 atoms_config.atoms_mov.type.setConstant(atomtypes.at("H2"));
183 atoms_config.atoms_froz_inactive.type.setConstant(atomtypes.at("Cu"));
184 }
185
186 gpr::Index_t counter_f = 0, counter_m = 0;
187 for (Eigen::Index n = 0; n < atoms_config.is_frozen.size(); ++n) {
188 if (*(atoms_config.is_frozen.data() + n) == MOVING_ATOM) {
189 gpr::coord::set(atoms_config.atoms_mov.positions, 0, counter_m,
190 gpr::coord::at(atoms_config.positions,
191 static_cast<gpr::Index_t>(n)));
192 if (!use_legacy_cuh2_types)
193 atoms_config.atoms_mov.type(0, counter_m) =
194 atoms_config.type(0, n);
195 ++counter_m;
196 } else {
198 counter_f,
199 gpr::coord::at(atoms_config.positions,
200 static_cast<gpr::Index_t>(n)));
201 if (!use_legacy_cuh2_types)
202 atoms_config.atoms_froz_inactive.type(0, counter_f) =
203 atoms_config.type(0, n);
204 ++counter_f;
205 }
206 }
207
208 atoms_config.pairtype.resize((gpr::Index_t)atomtypes.size(),
209 (gpr::Index_t)atomtypes.size());
210 atoms_config.pairtype.setConstant(EMPTY);
211 atoms_config.n_pt = 0;
212
213 problem_setup.setPairtypeForMovingAtoms(
214 atoms_config.atoms_mov.type, atoms_config.n_pt, atoms_config.pairtype);
215
216 // Active-frozen-set policy from the input parameters.
217 atoms_config.evict_frozen = parameters.evict_frozen.value != 0;
218 atoms_config.nn_frozen =
219 static_cast<gpr::Index_t>(parameters.nn_frozen.value);
220 atoms_config.nn_auto = parameters.nn_auto.value != 0;
221
222 // Selection and covariance features use the same periodic lattice.
223 std::fill(std::begin(atoms_config.cell), std::end(atoms_config.cell), 0.0);
224 if (!parameters.gp_nonperiodic.value)
225 geometry::copyMicLattice(atoms_config.cell,
226 parameters.cell_dimensions.value);
227 geometry::zeroOpenAxes(atoms_config.cell,
228 {parameters.cell_periodic.value[0] != 0,
229 parameters.cell_periodic.value[1] != 0,
230 parameters.cell_periodic.value[2] != 0});
231 problem_setup.activateFrozenAtoms(R_init, parameters.actdist_fro.value,
232 atoms_config);
233 // Default policy: hold the active set at the radius-seeded size with the
234 // nearest-neighbour rule (no effect for molecular systems with no frozen
235 // atoms, or when nn_frozen / eviction were set explicitly).
236 atoms_config.seedNearestNeighbourFromActive();
237}
@ MOVING_ATOM
Definition Enums.h:35
#define EMPTY
Definition Macros.h:39
Set up the GP-dimer problem.
bool activateFrozenAtoms(const gpr::Coord &R, const double activation_distance, gpr::AtomsConfiguration &atoms_config)
Update the active frozen-atom set for one or more configurations.
void setPairtypeForMovingAtoms(const gpr::FieldMatrixIdx &atomtype_mov, gpr::Index_t &n_pt, gpr::FieldMatrixi &pairtype)
Set pairtype indices for moving+moving atom pairs and gives the updated number of active pairtypes.
Eigen::Vector3d at(const FieldMatrixd &mat, Index_t i)
void set(FieldMatrixd &mat, Index_t i, const Eigen::Vector3d &vec)
void zeroOpenAxes(double cell[9], const std::array< bool, 3 > &periodic) noexcept
Definition MinImage.h:136
bool copyMicLattice(double dest[9], const double src[9]) noexcept
Copy src onto dest only when src is a MIC lattice.
Definition MinImage.h:68
uint32_t Index_t
Definition Macros.h:17
void seedNearestNeighbourFromActive()
Seed the fixed-N nearest-neighbour set from the current active (radius-activated) frozen count....
Definition Structures.h:890
AtomsPositionAndType atoms_froz_inactive
Info on inactive frozen atoms.
Definition Structures.h:843
FieldMatrixU8 is_frozen
Indicates whether atom is frozen or not.
Definition Structures.h:834
AtomsPositionAndType atoms_mov
Info on moving atoms.
Definition Structures.h:844
FieldMatrixIdx type
Type of each atom.
Definition Structures.h:839
Coord positions
Positions of all atoms in the system.
Definition Structures.h:833
void resize(const Index_t num_atoms)
Definition Structures.h:814
KeyValuePair< int > nn_frozen
Definition Structures.h:381
KeyValuePair< int > gp_nonperiodic
Definition Structures.h:603
KeyValuePair< int > nn_auto
Definition Structures.h:382
KeyValuePair< int > evict_frozen
Definition Structures.h:380

◆ loadAtomsConfigurationFromFrame()

void gpr::io::loadAtomsConfigurationFromFrame ( const readcon::CFrame & frame,
gpr::AtomsConfiguration & atoms_config,
gpr::Coord & R_init,
gpr::InputParameters & parameters,
const readcon::CFrame * product = nullptr,
std::vector< int > * reactive_atoms = nullptr )

Fill the configuration from a readcon frame: positions, frozen flags, ids, atomic numbers, one atom type per element, the cell, then the moving/frozen split and pair types. With a product frame of the same atoms, every atom whose covalent bond set differs between the two frames is moved to its element's reactive type (gpr::geometry::assignReactiveAtomTypes) before the pair types are built, so the reactive pairs get their own kernel length scales; reactive_atoms receives their indices.

Definition at line 291 of file ReadConLoader.cpp.

297{
298 requireUsableFrame(frame, "frame");
299 const int n_atoms = static_cast<int>(frame.num_atoms);
300 atoms_config.clear();
301
302 atoms_config.positions.resize(1, 3 * n_atoms);
303 atoms_config.is_frozen.resize(1, n_atoms);
304 atoms_config.id.resize(1, n_atoms);
305 atoms_config.atomicNrs.resize(1, n_atoms);
306 atoms_config.atomic_masses.resize(n_atoms);
307 atoms_config.type.resize(1, n_atoms);
308
309 std::vector<std::uint64_t> atomic_nrs(static_cast<std::size_t>(n_atoms));
310 for (int i = 0; i < n_atoms; ++i)
311 atomic_nrs[static_cast<std::size_t>(i)] = frame.atoms[i].atomic_number;
312 const auto element_types =
313 elementAtomTypes<gpr::Index_t>(atomic_nrs.data(), atomic_nrs.size());
314 std::unordered_map<std::string, gpr::Index_t> atomtypes;
315 for (std::size_t i = 0; i < atomic_nrs.size(); ++i)
316 atomtypes["Z" + std::to_string(atomic_nrs[i])] = element_types[i];
317
318 int n_partially_fixed = 0;
319 for (int i = 0; i < n_atoms; ++i) {
320 atoms_config.positions(0, 3 * i) = frame.atoms[i].x;
321 atoms_config.positions(0, 3 * i + 1) = frame.atoms[i].y;
322 atoms_config.positions(0, 3 * i + 2) = frame.atoms[i].z;
323 // CAtom.is_fixed is true when ANY axis is fixed; gpr's
324 // is_frozen is all-or-nothing, so a partially fixed atom
325 // becomes fully frozen here. Count and warn below rather than
326 // silently over-constraining.
327 atoms_config.is_frozen(0, i) =
328 frame.atoms[i].is_fixed ? FROZEN_ATOM : MOVING_ATOM;
329 if (frame.atoms[i].is_fixed &&
330 !(frame.atoms[i].fixed_x && frame.atoms[i].fixed_y &&
331 frame.atoms[i].fixed_z))
332 ++n_partially_fixed;
333 atoms_config.id(0, i) =
334 checkedNarrow<gpr::Index_t>(frame.atoms[i].atom_id, "atom_id");
335 atoms_config.atomicNrs(0, i) = checkedNarrow<gpr::Index_t>(
336 frame.atoms[i].atomic_number, "atomic_number");
337 atoms_config.atomic_masses(i) = frame.atoms[i].mass;
338 atoms_config.type(0, i) = element_types[static_cast<std::size_t>(i)];
339 }
340 if (n_partially_fixed > 0)
341 std::cerr << "ReadConLoader: " << n_partially_fixed
342 << " atom(s) carry per-axis fixed flags; gpr supports "
343 "only fully frozen atoms and treats them as frozen "
344 "on all axes\n";
345 if (frame.has_velocities)
346 std::cerr << "ReadConLoader: frame declares a velocities section; "
347 "the GP drivers are static (dimer / NEB) and the "
348 "velocity data is not used\n";
349
350 R_init = atoms_config.positions;
352 {frame.cell[0], frame.cell[1], frame.cell[2]},
353 {frame.angles[0], frame.angles[1], frame.angles[2]}, parameters);
354
355 if (reactive_atoms) reactive_atoms->clear();
356 if (product) {
357 requireUsableFrame(*product, "product frame");
358 if (static_cast<int>(product->num_atoms) != n_atoms) {
359 std::cerr << "ReadConLoader: product frame has "
360 << product->num_atoms << " atoms, reactant " << n_atoms
361 << "; reactive atom types skipped\n";
362 } else {
363 bool same_elements = true;
364 std::vector<int> Z(static_cast<std::size_t>(n_atoms));
365 std::vector<gpr::Index_t> types(static_cast<std::size_t>(n_atoms));
366 Eigen::VectorXd x_react(3 * n_atoms), x_prod(3 * n_atoms);
367 for (int i = 0; i < n_atoms; ++i) {
368 Z[static_cast<std::size_t>(i)] = checkedNarrow<int>(
369 frame.atoms[i].atomic_number, "atomic_number");
370 same_elements =
371 same_elements && product->atoms[i].atomic_number ==
372 frame.atoms[i].atomic_number;
373 types[static_cast<std::size_t>(i)] = atoms_config.type(0, i);
374 x_react.segment<3>(3 * i) << frame.atoms[i].x, frame.atoms[i].y,
375 frame.atoms[i].z;
376 x_prod.segment<3>(3 * i) << product->atoms[i].x,
377 product->atoms[i].y, product->atoms[i].z;
378 }
379 if (!same_elements) {
380 std::cerr << "ReadConLoader: product elements differ from "
381 "the reactant; reactive atom types skipped\n";
382 } else {
383 std::array<double, 9> cell{};
384 if (!parameters.gp_nonperiodic.value)
385 std::copy(std::begin(parameters.cell_dimensions.value),
386 std::begin(parameters.cell_dimensions.value) + 9,
387 cell.begin());
388 const auto reactive = gpr::geometry::assignReactiveAtomTypes(
389 x_react, x_prod, Z, types, atomtypes, cell);
390 for (int i = 0; i < n_atoms; ++i)
391 atoms_config.type(0, i) =
392 reactive.types[static_cast<std::size_t>(i)];
393 atomtypes = reactive.atomtypes;
394 if (reactive_atoms) *reactive_atoms = reactive.reactive_atoms;
395 }
396 }
397 }
398
399 initializeAtomsConfiguration(R_init, parameters, atomtypes, atoms_config);
400}
@ FROZEN_ATOM
Definition Enums.h:36
ReactiveAtomTypes assignReactiveAtomTypes(const Eigen::VectorXd &reactant, const Eigen::VectorXd &product, const std::vector< int > &atomic_numbers, const std::vector< Index_t > &types, const std::unordered_map< std::string, Index_t > &atomtypes, const std::array< double, 9 > &cell)
void setCellDimensionsFromLengthsAndAngles(const std::array< double, 3 > &cell, const std::array< double, 3 > &angles, gpr::InputParameters &parameters)
static To checkedNarrow(From value, const char *field)
static void requireUsableFrame(const readcon::CFrame &frame, const char *role)
std::vector< Type > elementAtomTypes(const AtomicNr *atomic_nrs, std::size_t n_atoms)
void initializeAtomsConfiguration(const gpr::Coord &R_init, const gpr::InputParameters &parameters, const std::unordered_map< std::string, gpr::Index_t > &atomtypes, gpr::AtomsConfiguration &atoms_config)
FieldMatrixi atomicNrs
Atomic Number of each atom.
Definition Structures.h:836
FieldMatrixIdx id
ID of each atom (we do not use it).
Definition Structures.h:835
Eigen::VectorXd atomic_masses
Per-atom input masses; empty selects unit masses.
Definition Structures.h:838

◆ loadEnvironmentAtomTypes() [1/2]

void gpr::io::loadEnvironmentAtomTypes ( const std::string & path,
gpr::AtomsConfiguration & atoms_config,
const gpr::InputParameters & parameters )

Definition at line 152 of file ReadConLoader.cpp.

155{
156 std::ifstream input(path);
157 if (!input)
158 throw std::invalid_argument("could not open environment types: " +
159 path);
160 loadEnvironmentAtomTypes(input, atoms_config, parameters);
161}
void loadEnvironmentAtomTypes(std::istream &input, gpr::AtomsConfiguration &atoms_config, const gpr::InputParameters &parameters)

◆ loadEnvironmentAtomTypes() [2/2]

void gpr::io::loadEnvironmentAtomTypes ( std::istream & input,
gpr::AtomsConfiguration & atoms_config,
const gpr::InputParameters & parameters )

Load fixed environment classes from rows: atom index, atomic number, type, and optionally the base type (element and reaction role) the class refines, which fills pair_type_parent for tied length scales. Validate every row before replacing types and rebuilding moving/frozen pairs.

Definition at line 27 of file ReadConLoader.cpp.

30{
31 const Eigen::Index n = atoms_config.atomicNrs.size();
32 if (n <= 0 || atoms_config.positions.size() != 3 * n ||
33 atoms_config.is_frozen.size() != n) {
34 throw std::invalid_argument(
35 "environment types require a complete atomic configuration");
36 }
37 std::vector<long long> labels;
38 std::vector<long long> bases;
39 std::map<long long, int> elements;
40 std::map<long long, long long> base_of_label;
41 std::string line;
42 while (std::getline(input, line)) {
43 line.erase(line.find('#') == std::string::npos ? line.size()
44 : line.find('#'));
45 std::istringstream row(line);
46 row >> std::ws;
47 if (row.eof()) continue;
48 long long atom, atomic_number, label;
49 long long base = -1;
50 std::string extra;
51 if (!(row >> atom >> atomic_number >> label) ||
52 atom != static_cast<long long>(labels.size()) || atom >= n ||
53 label < 0 || atomic_number != atoms_config.atomicNrs(0, atom)) {
54 throw std::invalid_argument(
55 "environment types require one ordered index, atomic number, "
56 "and nonnegative type per atom");
57 }
58 // An optional fourth column names the base type (element and
59 // reaction role) the environment type refines. Trailing text that
60 // is not that integer is rejected; a failed extraction must not
61 // look like an absent column.
62 row >> std::ws;
63 if (row.eof()) {
64 base = -1;
65 } else if (!(row >> base) || base < 0 || (row >> extra)) {
66 throw std::invalid_argument(
67 "environment types take one optional nonnegative base "
68 "type per atom");
69 }
70 if (!bases.empty() && (bases.back() < 0) != (base < 0))
71 throw std::invalid_argument(
72 "environment types either all carry a base type or none");
73 const auto [it, inserted] =
74 elements.emplace(label, static_cast<int>(atomic_number));
75 if (!inserted && it->second != atomic_number) {
76 throw std::invalid_argument(
77 "an environment type cannot contain different elements");
78 }
79 if (base >= 0) {
80 const auto [bit, binserted] = base_of_label.emplace(label, base);
81 if (!binserted && bit->second != base)
82 throw std::invalid_argument(
83 "an environment type cannot refine two base types");
84 }
85 labels.push_back(label);
86 bases.push_back(base);
87 }
88 if (input.bad() || static_cast<Eigen::Index>(labels.size()) != n) {
89 throw std::invalid_argument(
90 "environment types do not cover every atom");
91 }
92
93 std::map<long long, gpr::Index_t> compact;
94 std::unordered_map<std::string, gpr::Index_t> names;
95 for (const auto& [label, element]: elements) {
96 const auto type = static_cast<gpr::Index_t>(compact.size());
97 compact.emplace(label, type);
98 names.emplace(
99 "Z" + std::to_string(element) + ":env" + std::to_string(label),
100 type);
101 }
102 gpr::AtomsConfiguration typed;
103 typed.copy(atoms_config);
104 typed.type.resize(1, n);
105 for (Eigen::Index atom = 0; atom < n; ++atom)
106 typed.type(0, atom) =
107 compact.at(labels[static_cast<std::size_t>(atom)]);
108 typed.atoms_froz_active.clear();
109 initializeAtomsConfiguration(typed.positions, parameters, names, typed);
110 typed.pair_type_parent.clear();
111 typed.n_base_pt = 0;
112 if (!bases.empty() && bases.front() >= 0) {
113 // Base pair types in order of first appearance over the pair types.
114 std::map<std::pair<long long, long long>, gpr::Index_t> base_pairs;
115 typed.pair_type_parent.assign(static_cast<std::size_t>(typed.n_pt),
116 static_cast<gpr::Index_t>(0));
117 std::vector<char> seen(static_cast<std::size_t>(typed.n_pt), 0);
118 std::vector<long long> base_of_type(compact.size(), -1);
119 for (const auto& [label, type]: compact)
120 base_of_type[static_cast<std::size_t>(type)] =
121 base_of_label.at(label);
122 for (gpr::Index_t a = 0; a < typed.pairtype.rows(); ++a) {
123 for (gpr::Index_t b = a; b < typed.pairtype.cols(); ++b) {
124 const auto k = typed.pairtype(a, b);
125 if (k == EMPTY || k < 0 || k >= typed.n_pt) continue;
126 const long long ba = base_of_type[static_cast<std::size_t>(a)];
127 const long long bb = base_of_type[static_cast<std::size_t>(b)];
128 const auto key =
129 std::make_pair(std::min(ba, bb), std::max(ba, bb));
130 const auto found = base_pairs.find(key);
131 const gpr::Index_t parent =
132 found != base_pairs.end()
133 ? found->second
134 : base_pairs
135 .emplace(key, static_cast<gpr::Index_t>(
136 base_pairs.size()))
137 .first->second;
138 if (seen[static_cast<std::size_t>(k)] &&
139 typed.pair_type_parent[static_cast<std::size_t>(k)] !=
140 parent)
141 throw std::invalid_argument(
142 "a pair type cannot refine two base pair types");
143 typed.pair_type_parent[static_cast<std::size_t>(k)] = parent;
144 seen[static_cast<std::size_t>(k)] = 1;
145 }
146 }
147 typed.n_base_pt = static_cast<gpr::Index_t>(base_pairs.size());
148 }
149 atoms_config.copy(typed);
150}
std::vector< Index_t > pair_type_parent
Definition Structures.h:854
AtomsPositionAndType atoms_froz_active
Info on active frozen atoms.
Definition Structures.h:841
Index_t n_base_pt
Number of base pair types (0: none).
Definition Structures.h:855
void copy(const AtomsConfiguration &other)
Definition Structures.h:959

◆ loadNebConfigFromCapnp()

void gpr::io::loadNebConfigFromCapnp ( const std::string & binary_filename,
gpr::neb::GPNEBConfig & config )

Load the NEB-chain knobs from a unified-schema (params.capnp) Cap'n Proto binary into a gpr::neb::GPNEBConfig.

Reads the InputParameters.method.neb branch (NebParams) plus the shared GP conditioning blocks (HsSvd.principledNugget/kappaMax, optimizer.lengthScalePriors.lengthScalePrior) and maps them onto the GP-OIE config. The 9-way acquisition switch mirrors the DistMetric / ScgCurvatureMode switch pattern in loadParametersFromCapnp. Fields absent from the message keep their GPNEBConfig defaults (capnp supplies schema defaults). This is the gprn (NEB) counterpart to loadParametersFromCapnp, which serves the dimer driver via the legacy gprd_params.capnp schema.

Parameters
binary_filenamePath to the unified-schema Cap'n Proto binary.
configThe GP-NEB config to populate (NEB knobs only).
Exceptions
std::runtime_errorif the file is missing/empty or carries no NebParams (method union not set to neb).

Definition at line 660 of file CapnProtoNebLoader.cpp.

662{
663 UnifiedConfigMessage message(filename);
664 applyCoreNebConfig(message.reader(), config);
665}

◆ loadOciMmfConfigFromCapnp()

void gpr::io::loadOciMmfConfigFromCapnp ( const std::string & filename,
gpr::neb::OCINEBConfig & config )

Load the binary MMF override subset, preserving uncertainty controls.

Definition at line 667 of file CapnProtoNebLoader.cpp.

669{
670 UnifiedConfigMessage message(filename);
671 applyCoreOciConfig(message.reader(), config);
672}

◆ loadParametersFromCapnp()

void gpr::io::loadParametersFromCapnp ( const std::string & binary_filename,
gpr::InputParameters & parameters )

Loads parameters by reading a memory-mapped Cap'n Proto binary file.

This function replaces the manual text parsing of FileManager::readInputFile. It opens the binary file, maps it to memory, and populates the legacy gpr::InputParameters struct.

Parameters
binary_filenameThe path to the Cap'n Proto binary file (e.g., "capnp_params.bin").
parametersThe legacy C++ parameters struct to be filled.

Definition at line 20 of file CapnProtoManager.cpp.

22{
23 int fd = open(binary_filename.c_str(), O_RDONLY);
24 if (fd < 0) {
25 throw std::runtime_error("Error: Could not open file: " +
26 binary_filename);
27 }
28
29 struct stat file_stats;
30 if (fstat(fd, &file_stats) < 0) {
31 close(fd);
32 throw std::runtime_error("Error: Could not get file stats for: " +
33 binary_filename);
34 }
35 off_t size = file_stats.st_size;
36
37 if (size == 0) {
38 close(fd);
39 throw std::runtime_error("Error: Input file is empty: " +
40 binary_filename);
41 }
42 const void* mapped_ptr = mmap(nullptr, size, PROT_READ, MAP_SHARED, fd, 0);
43 if (mapped_ptr == MAP_FAILED) {
44 close(fd);
45 throw std::runtime_error("Error: Could not mmap file: " +
46 binary_filename);
47 }
48
49 kj::ArrayPtr<const capnp::word> wordPtr(
50 reinterpret_cast<const capnp::word*>(mapped_ptr),
51 size / sizeof(capnp::word));
52 capnp::FlatArrayMessageReader reader(wordPtr);
53 auto paramsReader = reader.getRoot<::InputParameters>();
54
55 // --- Adapt from Cap'n Proto reader to gpr::InputParameters ---
56
57 // --- Run Selector ---
58 auto runSelectorReader = paramsReader.getRunSelector();
59 parameters.i_dist.value = runSelectorReader.getIDist();
60 parameters.i_run.value = runSelectorReader.getIRun();
61 auto sepDistsReader = runSelectorReader.getSepDists();
62 for (size_t i = 0; i < sepDistsReader.size() && i < 4; ++i) {
63 parameters.dist_sp.value[i] = sepDistsReader[i];
64 }
65
66 // --- Problem Group ---
67 auto problemReader = paramsReader.getProblem();
68 parameters.actdist_fro.value = problemReader.getActdistFro();
69 parameters.dimer_sep.value = problemReader.getDimerSep();
70 if (problemReader.getMethodRot() == DimerOptimizer::LBFGS)
71 parameters.method_rot.value = "LBFGS_alg";
72 if (problemReader.getMethodTrans() == DimerOptimizer::LBFGS)
73 parameters.method_trans.value = "LBFGS_alg";
74
75 auto paramTransReader = problemReader.getParamTrans();
76 parameters.param_trans.value[0] = paramTransReader.getStepLength();
77 parameters.param_trans.value[1] = paramTransReader.getMaxStepLength();
79 paramTransReader.getRotremThresh();
80
81 // Final convergence on the true PES
82 parameters.T_dimer.value = problemReader.getFinalConvergenceForce();
83
84 // Initial rotations phase
85 auto initialRotationsReader = problemReader.getInitialRotations();
86 parameters.num_iter_initrot.value =
87 initialRotationsReader.getMaxIterations();
88 // Note the inversion: initrot_nogp=1 means NO GP, so useGpr=false
89 parameters.initrot_nogp.value = initialRotationsReader.getUseGpr() ? 0 : 1;
90 parameters.T_anglerot_init.value =
91 initialRotationsReader.getConvergenceAngle();
92
93 // Main relaxation phase
94 auto relaxationReader = problemReader.getRelaxation();
95 parameters.num_bigiter.value = relaxationReader.getMaxOuterIterations();
96 parameters.num_iter.value = relaxationReader.getMaxInnerIterations();
97 parameters.num_iter_rot_gp.value =
98 relaxationReader.getMaxRotationIterations();
99 parameters.num_bigiter_initloc.value =
100 relaxationReader.getWarmupFromInitialLocation();
101 parameters.num_bigiter_initparam.value =
102 relaxationReader.getWarmupFromInitHyperparameters();
103 parameters.islarge_num_iter.value =
104 relaxationReader.getAssumeManyIterations() ? 1 : 0;
105 // 'inittrans_nogp' has no gpr::InputParameters field.
106
107 auto relaxationConvergenceReader = relaxationReader.getConvergence();
108 parameters.T_anglerot_gp.value = relaxationConvergenceReader.getAngle();
109 // gpr::InputParameters uses T_dimer for the relaxation force criterion.
110
111 // Other problem parameters
112 parameters.divisor_T_dimer_gp.value = problemReader.getDivisorTdimerGP();
113 parameters.disp_max.value = problemReader.getMidpointMaxDisp();
114 parameters.ratio_at_limit.value = problemReader.getRatioAtLimit();
115
116 // Convergence force norm
117 switch (problemReader.getConvergenceForceNorm()) {
118 case (::ConvergenceForceNorm::L2_NORM):
119 parameters.convergence_force_norm.value = 0;
120 break;
121 case (::ConvergenceForceNorm::LINF_NORM):
122 parameters.convergence_force_norm.value = 1;
123 break;
124 case (::ConvergenceForceNorm::MAX_FORCE_ON_ATOM):
125 parameters.convergence_force_norm.value = 2;
126 break;
127 }
128
129 // --- GPR Model ---
130 auto gprReader = paramsReader.getGpr();
131 parameters.gp_sigma2.value = gprReader.getGpSigma2();
132 parameters.jitter_sigma2.value = gprReader.getJitterSigma2();
133 parameters.sigma2.value = gprReader.getNoiseSigma2();
135 gprReader.getUseAlphaKPredictMean();
137 gprReader.getUseAlphaKLaplaceMean();
139 gprReader.getSkipScgThreshold();
141 gprReader.getUseTrainingGeometryHandle();
142 parameters.profile_predict_mean.value = gprReader.getProfilePredictMean();
143 parameters.profile_energy_split.value = gprReader.getProfileEnergySplit();
144 parameters.profile_gradient_split.value =
145 gprReader.getProfileGradientSplit();
146 parameters.log_training_geometry.value = gprReader.getLogTrainingGeometry();
147 parameters.log_rank_block_cholesky.value =
148 gprReader.getLogRankBlockCholesky();
149 // A gprd_params message predates the published prior defaults. One that
150 // omits gpr.prior meant zeros and keeps reading as zeros, which GP
151 // initialization rejects by name; the schema default is not applied.
152 if (gprReader.hasPrior()) {
153 auto priorReader = gprReader.getPrior();
154 parameters.prior_mu.value = priorReader.getMu();
155 parameters.prior_nu.value = priorReader.getNu();
156 parameters.prior_s2.value = priorReader.getS2();
157 } else {
158 parameters.prior_mu.value = 0.0;
159 parameters.prior_nu.value = 0.0;
160 parameters.prior_s2.value = 0.0;
161 }
162
163 // --- Early stopping
164 auto earlyStoppingReader = paramsReader.getEarlyStopping();
165 switch (earlyStoppingReader.getDistMetric()) {
166 case (::DistanceMetric::MAX1_D_LOG): {
168 break;
169 }
170 case (::DistanceMetric::RMSD): {
172 break;
173 }
174 case (::DistanceMetric::EMD): {
176 break;
177 }
178 default:
179 throw("Shouldn't be here");
180 }
181 parameters.es_threshold.value = earlyStoppingReader.getThreshold();
183 earlyStoppingReader.getUseAdaptiveThreshold();
184 parameters.es_adaptive_A.value = earlyStoppingReader.getAdaptiveA();
185 parameters.es_adaptive_floor.value = earlyStoppingReader.getAdaptiveFloor();
186 parameters.es_t_min.value = earlyStoppingReader.getTMin();
187 parameters.es_delta_explore.value = earlyStoppingReader.getDeltaExplore();
188 parameters.es_half_life.value = earlyStoppingReader.getHalfLife();
189
190 // --- Hyperparameter Optimizer ---
191 auto optimizerReader = paramsReader.getOptimizer();
192 parameters.check_derivative.value =
193 optimizerReader.getCheckDerivative() ? "true" : "false";
194 parameters.max_iter.value = optimizerReader.getMaxIter();
195 parameters.tolerance_func.value = optimizerReader.getTolFunc();
196 parameters.tolerance_sol.value = optimizerReader.getTolSol();
197
198 switch (optimizerReader.getAlgorithm()) {
199 case HyperparameterOptimizer::SCG: {
200 parameters.optimization_alg.value = "SCG_opt";
201 auto scgReader = optimizerReader.getScg();
202 parameters.lambda_limit.value = scgReader.getLambdaLimit();
203 parameters.lambda.value = scgReader.getLambda();
204 switch (scgReader.getCurvatureMode()) {
206 parameters.curvature_mode.value = "exact";
207 break;
209 parameters.curvature_mode.value = "finite_difference";
210 break;
212 parameters.curvature_mode.value = "nlml_hessian_vector";
213 break;
214 }
215 break;
216 }
217 case HyperparameterOptimizer::ADAM: {
218 parameters.optimization_alg.value = "ADAM_opt";
219 auto adamReader = optimizerReader.getAdam();
220 parameters.learning_rate.value = adamReader.getLr();
221 parameters.learning_rate_decay.value = adamReader.getLrd();
222 parameters.beta1.value = adamReader.getB1();
223 parameters.beta2.value = adamReader.getB2();
224 parameters.epsilon.value = adamReader.getEps();
225 parameters.weight_decay.value = adamReader.getWeightDecay();
226 parameters.amsgrad.value = adamReader.getAmsgrad();
227 break;
228 }
229 }
230
231 // --- Pruning ---
232 auto pruningReader = paramsReader.getPruning();
233 parameters.use_prune.value = pruningReader.getUsePrune();
234 parameters.start_prune_at.value = pruningReader.getPruneBegin();
235 parameters.nprune_vals.value = pruningReader.getPruneNVals();
236 parameters.prune_threshold.value = pruningReader.getPruneThreshold();
237
238 // --- Debug ---
239 auto debugReader = paramsReader.getDebug();
240 parameters.report_level.value = debugReader.getReportLevel();
241 parameters.debug_level.value = debugReader.getDebugLevel();
242 parameters.debug_output_dir.value = debugReader.getDebugOutDir().cStr();
243 parameters.debug_output_file_R.value = debugReader.getDebugPosFile().cStr();
244 parameters.debug_output_file_E.value =
245 debugReader.getDebugEnergyFile().cStr();
246 parameters.debug_output_file_G.value =
247 debugReader.getDebugGradFile().cStr();
249 debugReader.getDebugOutExt().cStr();
251 debugReader.getDebugOffsetMidPoint();
252 parameters.debug_dy.value = debugReader.getDebugDy();
253 parameters.debug_dz.value = debugReader.getDebugDz();
254 parameters.profile_dimer_times.value = debugReader.getProfileDimerTimes();
255
256 // --- Linear algebra ---
257 auto linalgReader = paramsReader.getLinearAlgebra();
258 parameters.scalapack_block_size.value =
259 linalgReader.getScalapackBlockSize();
260 parameters.scalapack_nprow.value = linalgReader.getScalapackNprow();
261 parameters.cutlass_plugin_path.value =
262 linalgReader.getCutlassPluginPath().cStr();
263
264 // --- Cell Dimensions ---
265 auto cellDimsReader = paramsReader.getCellDimensions();
266 for (size_t i = 0; i < cellDimsReader.size() && i < 9; ++i) {
267 parameters.cell_dimensions.value[i] = cellDimsReader[i];
268 }
269
270 // Cleanup
271 munmap(const_cast<void*>(mapped_ptr), size);
272 close(fd);
273}

◆ loadTrainedGpState()

TrainedGpState gpr::io::loadTrainedGpState ( const std::string & path)
nodiscard

Definition at line 516 of file GpState.cpp.

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}
FieldMatrixd E
Observation observations
Definition GpState.h:22
std::string identity
Definition GpState.h:37

◆ maxAtomicForce()

double gpr::io::maxAtomicForce ( const double * forces,
std::size_t n_atoms )
inlinenodiscardnoexcept

Largest atomic force norm. NaN when any component is non-finite.

Definition at line 82 of file ReadConLoader.h.

84{
85 if (forces == nullptr) return std::numeric_limits<double>::quiet_NaN();
86 double fmax = 0.0;
87 for (std::size_t atom = 0; atom < n_atoms; ++atom) {
88 const double x = forces[3 * atom];
89 const double y = forces[3 * atom + 1];
90 const double z = forces[3 * atom + 2];
91 if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(z))
92 return std::numeric_limits<double>::quiet_NaN();
93 fmax = std::max(fmax, std::sqrt(x * x + y * y + z * z));
94 }
95 return fmax;
96}

◆ noteLocalKernel()

void gpr::io::noteLocalKernel ( neb::ActiveLearningSession & session,
const TrainedGpState & state )

Definition at line 619 of file GpState.cpp.

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}
void noteLocalKernelSeed(double signal_variance, double length_scale) noexcept
Definition Session.h:1307

◆ observationState()

TrainedGpState gpr::io::observationState ( const Observation & observations)
nodiscard

A state that carries observations and no pair kernel.

Definition at line 556 of file GpState.cpp.

557{
558 TrainedGpState state;
559 state.observations = normalizedObservations(observations);
560 state.output_scale = 1.0;
561 return state;
562}

◆ outputDirectory()

std::string gpr::io::outputDirectory ( const std::string & output_path)
nodiscard

Directory of an output path, or . when the path has no directory.

Definition at line 714 of file GpState.cpp.

715{
716 const auto parent = std::filesystem::path(output_path).parent_path();
717 if (parent.empty()) return ".";
718 return parent.string();
719}

◆ overlayLegacyDimerReader()

void gpr::io::overlayLegacyDimerReader ( capnp::MessageReader & reader,
gpr::schema::InputParameters::Builder unified )

Copy a gprd_params.capnp reader onto a unified builder.

The builder's dimer arm must already be initialized. Strings and lists are copied into the builder, so the legacy reader can be destroyed afterwards. Schema defaults of fields the legacy message left unset overwrite the builder, matching loadParametersFromCapnp.

Definition at line 411 of file CapnProtoManager.cpp.

413{
414 const auto legacy = reader.getRoot<::InputParameters>();
415 const auto problem = legacy.getProblem();
416 auto dimer = unified.getMethod().getDimer();
417 dimer.setActdistFro(problem.getActdistFro());
418 dimer.setDimerSep(problem.getDimerSep());
419 dimer.setMethodRot(gpr::schema::DimerOptimizer::LBFGS);
420 dimer.setMethodTrans(gpr::schema::DimerOptimizer::LBFGS);
421 {
422 const auto src = problem.getParamTrans();
423 auto dst = dimer.initParamTrans();
424 dst.setStepLength(src.getStepLength());
425 dst.setMaxStepLength(src.getMaxStepLength());
426 dst.setRotremThresh(src.getRotremThresh());
427 }
428 dimer.setFinalConvergenceForce(problem.getFinalConvergenceForce());
429 {
430 const auto src = problem.getInitialRotations();
431 auto dst = dimer.initInitialRotations();
432 dst.setMaxIterations(src.getMaxIterations());
433 dst.setUseGpr(src.getUseGpr());
434 dst.setConvergenceAngle(src.getConvergenceAngle());
435 }
436 {
437 const auto src = problem.getRelaxation();
438 auto dst = dimer.initRelaxation();
439 dst.setMaxOuterIterations(src.getMaxOuterIterations());
440 dst.setMaxInnerIterations(src.getMaxInnerIterations());
441 dst.setMaxRotationIterations(src.getMaxRotationIterations());
442 dst.setWarmupFromInitialLocation(src.getWarmupFromInitialLocation());
443 dst.setWarmupFromInitHyperparameters(
444 src.getWarmupFromInitHyperparameters());
445 dst.setAssumeManyIterations(src.getAssumeManyIterations());
446 dst.initConvergence().setAngle(src.getConvergence().getAngle());
447 }
448 dimer.setDivisorTdimerGP(problem.getDivisorTdimerGP());
449 dimer.setMidpointMaxDisp(problem.getMidpointMaxDisp());
450 dimer.setRatioAtLimit(problem.getRatioAtLimit());
451 switch (problem.getConvergenceForceNorm()) {
452 case ::ConvergenceForceNorm::LINF_NORM:
453 dimer.setConvergenceForceNorm(
454 gpr::schema::ConvergenceForceNorm::LINF_NORM);
455 break;
456 case ::ConvergenceForceNorm::MAX_FORCE_ON_ATOM:
457 dimer.setConvergenceForceNorm(
458 gpr::schema::ConvergenceForceNorm::MAX_FORCE_ON_ATOM);
459 break;
460 default:
461 dimer.setConvergenceForceNorm(
462 gpr::schema::ConvergenceForceNorm::L2_NORM);
463 break;
464 }
465 {
466 const auto src = legacy.getOrientInit();
467 copyFloats(src, dimer.initOrientInit(src.size()));
468 }
469 {
470 const auto src = legacy.getOrientStart();
471 copyFloats(src, dimer.initOrientStart(src.size()));
472 }
473 {
474 const auto src = legacy.getDisplacedPositions();
475 copyFloats(src, dimer.initDisplacedPositions(src.size()));
476 }
477
478 const auto gpr_src = legacy.getGpr();
479 auto gpr = unified.getGpr();
480 gpr.setGpSigma2(gpr_src.getGpSigma2());
481 gpr.setJitterSigma2(gpr_src.getJitterSigma2());
482 gpr.setNoiseSigma2(gpr_src.getNoiseSigma2());
483 gpr.setUseAlphaKPredictMean(gpr_src.getUseAlphaKPredictMean());
484 gpr.setUseAlphaKLaplaceMean(gpr_src.getUseAlphaKLaplaceMean());
485 gpr.setSkipScgThreshold(gpr_src.getSkipScgThreshold());
486 gpr.setUseTrainingGeometryHandle(gpr_src.getUseTrainingGeometryHandle());
487 gpr.setProfilePredictMean(gpr_src.getProfilePredictMean());
488 gpr.setProfileEnergySplit(gpr_src.getProfileEnergySplit());
489 gpr.setProfileGradientSplit(gpr_src.getProfileGradientSplit());
490 gpr.setLogTrainingGeometry(gpr_src.getLogTrainingGeometry());
491 gpr.setLogRankBlockCholesky(gpr_src.getLogRankBlockCholesky());
492 {
493 // An omitted legacy prior meant zeros. Write them explicitly so
494 // the schema 4 default does not replace them in the converted
495 // message.
496 auto dst = gpr.getPrior();
497 if (gpr_src.hasPrior()) {
498 const auto src = gpr_src.getPrior();
499 dst.setMu(src.getMu());
500 dst.setNu(src.getNu());
501 dst.setS2(src.getS2());
502 } else {
503 dst.setMu(0.0);
504 dst.setNu(0.0);
505 dst.setS2(0.0);
506 }
507 }
508
509 const auto early_src = legacy.getEarlyStopping();
510 auto early = unified.getEarlyStopping();
511 switch (early_src.getDistMetric()) {
512 case ::DistanceMetric::MAX1_D_LOG:
513 early.setDistMetric(gpr::schema::DistanceMetric::MAX1_D_LOG);
514 break;
515 case ::DistanceMetric::RMSD:
516 early.setDistMetric(gpr::schema::DistanceMetric::RMSD);
517 break;
518 default:
519 early.setDistMetric(gpr::schema::DistanceMetric::EMD);
520 break;
521 }
522 early.setThreshold(early_src.getThreshold());
523 early.setUseAdaptiveThreshold(early_src.getUseAdaptiveThreshold());
524 early.setAdaptiveA(early_src.getAdaptiveA());
525 early.setAdaptiveFloor(early_src.getAdaptiveFloor());
526 early.setTMin(early_src.getTMin());
527 early.setDeltaExplore(early_src.getDeltaExplore());
528 early.setHalfLife(early_src.getHalfLife());
529
530 const auto opt_src = legacy.getOptimizer();
531 auto optimizer = unified.getOptimizer();
532 optimizer.setCheckDerivative(opt_src.getCheckDerivative());
533 optimizer.setMaxIter(opt_src.getMaxIter());
534 optimizer.setTolFunc(opt_src.getTolFunc());
535 optimizer.setTolSol(opt_src.getTolSol());
536 if (opt_src.getAlgorithm() == ::HyperparameterOptimizer::ADAM) {
537 optimizer.setAlgorithm(gpr::schema::HyperparameterOptimizer::ADAM);
538 const auto src = opt_src.getAdam();
539 auto dst = optimizer.initAdam();
540 dst.setLr(src.getLr());
541 dst.setLrd(src.getLrd());
542 dst.setB1(src.getB1());
543 dst.setB2(src.getB2());
544 dst.setEps(src.getEps());
545 dst.setWeightDecay(src.getWeightDecay());
546 dst.setAmsgrad(src.getAmsgrad());
547 } else {
548 optimizer.setAlgorithm(gpr::schema::HyperparameterOptimizer::SCG);
549 const auto src = opt_src.getScg();
550 auto dst = optimizer.initScg();
551 dst.setLambdaLimit(src.getLambdaLimit());
552 dst.setLambda(src.getLambda());
553 switch (src.getCurvatureMode()) {
554 case ::ScgCurvatureMode::FINITE_DIFFERENCE:
555 dst.setCurvatureMode(
556 gpr::schema::ScgCurvatureMode::FINITE_DIFFERENCE);
557 break;
558 case ::ScgCurvatureMode::NLML_HESSIAN_VECTOR:
559 dst.setCurvatureMode(
560 gpr::schema::ScgCurvatureMode::NLML_HESSIAN_VECTOR);
561 break;
562 default:
563 dst.setCurvatureMode(gpr::schema::ScgCurvatureMode::EXACT);
564 break;
565 }
566 }
567
568 const auto prune_src = legacy.getPruning();
569 auto pruning = unified.getPruning();
570 pruning.setUsePrune(prune_src.getUsePrune());
571 pruning.setPruneBegin(prune_src.getPruneBegin());
572 pruning.setPruneNVals(prune_src.getPruneNVals());
573 pruning.setPruneThreshold(prune_src.getPruneThreshold());
574
575 const auto debug_src = legacy.getDebug();
576 auto debug = unified.getDebug();
577 debug.setReportLevel(debug_src.getReportLevel());
578 debug.setDebugLevel(debug_src.getDebugLevel());
579 debug.setDebugOutDir(debug_src.getDebugOutDir().cStr());
580 debug.setDebugPosFile(debug_src.getDebugPosFile().cStr());
581 debug.setDebugEnergyFile(debug_src.getDebugEnergyFile().cStr());
582 debug.setDebugGradFile(debug_src.getDebugGradFile().cStr());
583 debug.setDebugOutExt(debug_src.getDebugOutExt().cStr());
584 debug.setDebugOffsetMidPoint(debug_src.getDebugOffsetMidPoint());
585 debug.setDebugDy(debug_src.getDebugDy());
586 debug.setDebugDz(debug_src.getDebugDz());
587 debug.setProfileDimerTimes(debug_src.getProfileDimerTimes());
588
589 const auto linalg_src = legacy.getLinearAlgebra();
590 auto linalg = unified.getLinearAlgebra();
591 linalg.setScalapackBlockSize(linalg_src.getScalapackBlockSize());
592 linalg.setScalapackNprow(linalg_src.getScalapackNprow());
593 linalg.setCutlassPluginPath(linalg_src.getCutlassPluginPath().cStr());
594
595 const auto run_src = legacy.getRunSelector();
596 auto run = unified.getRunSelector();
597 run.setIDist(run_src.getIDist());
598 run.setIRun(run_src.getIRun());
599 {
600 const auto src = run_src.getSepDists();
601 copyFloats(src, run.initSepDists(src.size()));
602 }
603 {
604 const auto src = legacy.getCellDimensions();
605 copyFloats(src, unified.initCellDimensions(src.size()));
606 }
607 unified.setConfigFile(legacy.getConfigFile().cStr());
608}
Structure of the input parameters. All input parameters are pairs of string names and values.
Definition Structures.h:370

◆ readerIsLegacyDimer()

bool gpr::io::readerIsLegacyDimer ( capnp::MessageReader & reader)

Whether reader is a gprd_params.capnp message rather than a params.capnp message.

Cap'n Proto does not store the schema id, so the size of the root's data and pointer sections decides. A gprd_params.capnp message has the root of one of that schema's revisions since its field numbers settled. A params.capnp message has one data word and between the 20 pointers of that schema's first revision and its current count; no root is both. A root between two gprd_params.capnp revisions is refused, since no writer emitted it. A root at least as large as the current params.capnp root is a newer params.capnp message when its schema version is newer than this build, and the caller checks that version. The same size stamped with a version this build knows matches no revision and throws std::runtime_error naming the version and the size. Any other root throws std::runtime_error naming its size.

Definition at line 389 of file CapnProtoManager.cpp.

390{
391 const auto any =
392 reader.getRoot<capnp::AnyPointer>().getAs<capnp::AnyStruct>();
393 const RootShape root{any.getDataSection().size() / sizeof(capnp::word),
394 any.getPointerSection().size()};
395 if (isLegacyRoot(root)) return true;
396 // Versions this build knows wrote a root in [kOldestUnifiedRoot,
397 // kUnifiedRoot]. A writer newer than this build appends to the current
398 // root and stamps a schema version the caller rejects. The same larger
399 // root stamped with a known version matches nothing in that table.
400 if (within(root, kOldestUnifiedRoot, kUnifiedRoot)) return false;
401 if (root.data_words >= kUnifiedRoot.data_words &&
402 root.pointers >= kUnifiedRoot.pointers) {
403 const auto version =
404 reader.getRoot<gpr::schema::InputParameters>().getSchemaVersion();
405 if (version > gpr::schema::CURRENT_SCHEMA_VERSION) return false;
406 throw std::runtime_error(unmatchedRoot(root, std::to_string(version)));
407 }
408 throw std::runtime_error(unmatchedRoot(root, {}));
409}

◆ readGpInitializationOverrides()

GpInitializationOverrides gpr::io::readGpInitializationOverrides ( gpr::schema::InputParameters::Reader params)

Definition at line 325 of file CapnProtoNebLoader.cpp.

327{
329 using Field = gpr::schema::GpInitializationField;
330 for (const auto field: params.getGpInitializationFields()) {
331 switch (field) {
332 case Field::COVARIANCE_NOISE:
333 result.gp_sigma2 = params.getGpr().getGpSigma2();
334 break;
335 case Field::JITTER:
336 result.jitter_sigma2 = params.getGpr().getJitterSigma2();
337 break;
338 case Field::LIKELIHOOD_NOISE:
339 result.sigma2 = params.getGpr().getNoiseSigma2();
340 break;
341 case Field::MAX_ITERATIONS:
342 result.max_iter = params.getOptimizer().getMaxIter();
343 break;
344 case Field::FUNCTION_TOLERANCE:
345 result.tolerance_func = params.getOptimizer().getTolFunc();
346 break;
347 case Field::SOLUTION_TOLERANCE:
348 result.tolerance_sol = params.getOptimizer().getTolSol();
349 break;
350 default:
351 throw std::invalid_argument(
352 "Unknown GP initialization field in configuration");
353 }
354 }
355 return result;
356}
std::optional< double > tolerance_func
std::optional< double > jitter_sigma2
std::optional< double > gp_sigma2
std::optional< double > tolerance_sol

◆ readSeedKernel()

bool gpr::io::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.

Definition at line 310 of file SeedKernel.cpp.

313{
314 if (gp.atomicEnvironmentModelEnabled()) return false;
315 double magnitude = -1.0, constant = -1.0;
316 double source_noise = -1.0;
317 double pair_cutoff = 0.0, pair_cutoff_width = 0.0;
318 double mean = gp.outputMean(), scale = gp.outputScale();
319 int frozen_mean = gp.outputMeanFrozen();
320 std::vector<double> lengths, atomistic_lengths;
321 std::shared_ptr<const geometry::InternalCoordinateChart> chart;
322 std::shared_ptr<const GeodesicHeatEnergyForceKernel> heat;
323 int chart_present = 0, heat_present = 0;
324 std::set<std::string> seen;
325 std::string line, identity;
326 while (std::getline(input, line)) {
327 std::istringstream row(line);
328 std::string key;
329 if (!(row >> key)) continue;
330 if (!seen.insert(key).second) return false;
331 if (key == "identity") {
332 std::getline(row >> std::ws, identity);
333 if (identity.empty()) return false;
334 continue;
335 }
336 if (key == "components") {
337 int version = 0;
338 if (!(row >> version >> chart_present >> heat_present) ||
339 version != 1 || (chart_present != 0 && chart_present != 1) ||
340 (heat_present != 0 && heat_present != 1))
341 return false;
342 } else if (key == "chart") {
343 try {
344 chart =
345 readChart(row, atoms.atoms_mov.type.size(), line.size());
346 } catch (const std::exception&) {
347 return false;
348 }
349 if (!chart) return false;
350 } else if (key == "heat") {
351 try {
352 heat = readHeat(row, atoms, line.size());
353 } catch (const std::exception&) {
354 return false;
355 }
356 if (!heat) return false;
357 } else if (key == "magnSigma2") {
358 row >> magnitude;
359 } else if (key == "constSigma2") {
360 row >> constant;
361 } else if (key == "lengthScale" || key == "atomisticLengthScale") {
362 std::size_t count = 0;
363 row >> count;
364 if (!row || count == 0 || (count != 1 && count != atoms.n_pt))
365 return false;
366 auto& values = key == "lengthScale" ? lengths : atomistic_lengths;
367 values.resize(count);
368 for (auto& length: values)
369 row >> length;
370 } else if (key == "outputTransform") {
371 row >> mean >> scale >> frozen_mean;
372 } else if (key == "sigma2") {
373 row >> source_noise;
374 if (!std::isfinite(source_noise) || source_noise < 0.0)
375 return false;
376 } else if (key == "pairCutoff") {
377 row >> pair_cutoff >> pair_cutoff_width;
378 try {
379 (void)PairCutoff(pair_cutoff, pair_cutoff_width);
380 } catch (const std::invalid_argument&) {
381 return false;
382 }
383 } else {
384 return false;
385 }
386 if (!row) return false;
387 std::string extra;
388 if (row >> extra) return false;
389 }
390 // An absent cutoff record denotes the unbounded descriptor. A seed
391 // changes fitted parameters, not the destination's descriptor domain.
392 const auto& descriptor = gp.getSexpAtCovarianceFunction().getConfInfo();
393 if (pair_cutoff != atoms.pair_cutoff ||
394 pair_cutoff_width != atoms.pair_cutoff_width ||
395 pair_cutoff != descriptor.pair_cutoff ||
396 pair_cutoff_width != descriptor.pair_cutoff_width)
397 return false;
398 const bool components = seen.count("components") != 0;
399 if (static_cast<bool>(chart) != (chart_present != 0) ||
400 static_cast<bool>(heat) != (heat_present != 0) ||
401 (!components && (chart || heat || !atomistic_lengths.empty())) ||
402 (components &&
403 (!seen.count("identity") || !seen.count("outputTransform"))) ||
404 (chart && atomistic_lengths.size() != atoms.n_pt) ||
405 (!chart && !atomistic_lengths.empty()))
406 return false;
407 if (!identity.empty() &&
408 identity != kernelIdentity(gp, atoms, static_cast<bool>(chart),
409 static_cast<bool>(heat), components))
410 return false;
411 if (input.bad() || (require_identity && !seen.count("identity")) ||
412 (seen.count("identity") && !seen.count("outputTransform")) ||
413 lengths.size() != (chart ? 1 : atoms.n_pt) || lengths.empty() ||
414 !std::isfinite(magnitude) || magnitude <= 0.0 ||
415 !std::isfinite(constant) || constant < 0.0 || !std::isfinite(mean) ||
416 !std::isfinite(scale) || scale <= 0.0 ||
417 (frozen_mean != 0 && frozen_mean != 1))
418 return false;
419 for (const double length: lengths)
420 if (!std::isfinite(length) || length <= 0.0) return false;
421 for (const double length: atomistic_lengths)
422 if (!std::isfinite(length) || length <= 0.0) return false;
423
424 // An archive handoff preserves its physical likelihood variance. An
425 // independent fit keeps the destination's configured resolution.
426 const double scale_squared = scale * scale;
427 if (preserve_source_noise &&
428 (!seen.count("sigma2") || !seen.count("outputTransform") ||
429 !(source_noise > 0.0) || !std::isfinite(scale_squared) ||
430 !(scale_squared > 0.0)))
431 return false;
432 const double physical_noise = preserve_source_noise
433 ? source_noise * scale_squared
434 : gp.getLikGaussian().getSigma2() *
435 gp.outputScale() * gp.outputScale();
436 const double training_noise = physical_noise / scale / scale;
437 if (!std::isfinite(physical_noise) || !std::isfinite(training_noise) ||
438 training_noise < 0.0 ||
439 (preserve_source_noise && !(training_noise > 0.0)))
440 return false;
441 auto& covariance = gp.getSexpAtCovarianceFunction();
442 covariance.clearManifoldChart();
444 gp.restoreOutputTransform(mean, scale, frozen_mean != 0);
445 if (preserve_source_noise)
446 (void)gp.setLikelihoodNoiseVariance(physical_noise);
447 else
448 gp.getLikGaussian().setSigma2(training_noise);
449 covariance.setMagnSigma2(magnitude);
451 const auto& pair_lengths = chart ? atomistic_lengths : lengths;
452 covariance.getAtomisticLengthScaleRef().resize(1, pair_lengths.size());
453 std::copy(pair_lengths.begin(), pair_lengths.end(),
454 covariance.getAtomisticLengthScaleRef().data());
455 if (chart) gp.setInternalCoordinateChart(std::move(chart), lengths.front());
456 if (heat) gp.setGeodesicHeatPrior(std::move(heat));
457 // The archive kernel is the band's fitted maximum-evidence kernel for
458 // these rows; the destination starts from a fitted state.
460 return true;
461}
LikelihoodNoiseVarianceUpdate setLikelihoodNoiseVariance(double physical_sigma2, const Observation *full_observation=nullptr)
Set the likelihood noise variance in physical output units.
void setGeodesicHeatPrior(std::shared_ptr< const GeodesicHeatEnergyForceKernel > kernel)
void setInternalCoordinateChart(std::shared_ptr< const geometry::InternalCoordinateChart > chart, double length_scale)
bool atomicEnvironmentModelEnabled() const noexcept
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
const AtomsConfiguration & getConfInfo() const noexcept
Definition SexpatCF.h:678
void clearManifoldChart()
Definition SexpatCF.cpp:513
std::vector< Component > components()
A stable snapshot including the linked ABI dependencies.
std::string line(const std::string &topic, const std::vector< Field > &fields)

◆ readSeedKernelAtomTypes()

bool gpr::io::readSeedKernelAtomTypes ( std::istream & input,
AtomsConfiguration & atoms,
const InputParameters & parameters )

Restore the archived type map after checking physical atom identity.

Restore a saved type map before GP initialization. Physical composition, frozen geometry, cell, and the rebuilt pair ordering must match exactly. Kernel parameters and model-profile compatibility are checked separately by readSeedKernel after the destination GP is initialized.

Definition at line 175 of file SeedKernel.cpp.

177{
178 const Eigen::Index n = atoms.atomicNrs.size();
179 if (n <= 0) return false;
180 std::string line, identity;
181 while (std::getline(input, line)) {
182 std::istringstream row(line);
183 std::string key;
184 if (row >> key && key == "identity") {
185 if (!identity.empty()) return false;
186 std::getline(row >> std::ws, identity);
187 if (identity.empty()) return false;
188 }
189 }
190 if (input.bad() || identity.empty()) return false;
191 std::istringstream row(identity);
192 std::string version;
193 int profile, zbl, ff, manifold, heat = 0;
194 if (!(row >> version >> profile >> zbl >> ff >> manifold) ||
195 (version != "v1" && version != "v2"))
196 return false;
197 if (version == "v2" && (!(row >> heat) || (heat != 0 && heat != 1)))
198 return false;
199 const auto read_matrix = [&](auto& matrix, Eigen::Index max_entries) {
200 Eigen::Index rows, cols;
201 if (!(row >> rows >> cols) || rows < 0 || cols < 0 ||
202 rows > max_entries || cols > max_entries ||
203 (cols > 0 && rows > max_entries / cols))
204 return false;
205 matrix.resize(rows, cols);
206 for (Eigen::Index i = 0; i < rows; ++i)
207 for (Eigen::Index j = 0; j < cols; ++j)
208 if (!(row >> matrix(i, j))) return false;
209 return matrix.allFinite();
210 };
211 AtomsConfiguration archived;
212 FieldMatrixi frozen;
213 if (!read_matrix(archived.atomicNrs, n) || !read_matrix(frozen, n) ||
214 !read_matrix(archived.type, n) ||
215 !read_matrix(archived.atoms_mov.type, n) ||
216 !read_matrix(archived.atoms_froz_active.type, n) ||
217 !read_matrix(archived.atoms_froz_active.positions, 3 * n) ||
218 !read_matrix(archived.pairtype,
219 static_cast<Eigen::Index>(identity.size())))
220 return false;
221 for (double& entry: archived.cell)
222 if (!(row >> entry) || !std::isfinite(entry)) return false;
223 std::string extra;
224 if (row >> extra) return false;
225 const auto same = [](const auto& a, const auto& b) {
226 return a.rows() == b.rows() && a.cols() == b.cols() &&
227 (a.template cast<double>().array() ==
228 b.template cast<double>().array())
229 .all();
230 };
231 if (!same(archived.atomicNrs, atoms.atomicNrs) ||
232 !same(frozen, atoms.is_frozen) || archived.type.rows() != 1 ||
233 archived.type.cols() != n || archived.pairtype.rows() <= 0 ||
234 archived.pairtype.rows() != archived.pairtype.cols())
235 return false;
236 archived.is_frozen = atoms.is_frozen;
237 std::map<int, int> elements;
238 for (Eigen::Index i = 0; i < n; ++i) {
239 const int type = archived.type(0, i);
240 const int element = archived.atomicNrs(0, i);
241 if (type < 0 || type >= archived.pairtype.rows()) return false;
242 const auto [it, inserted] = elements.emplace(type, element);
243 if (!inserted && it->second != element) return false;
244 }
245 std::unordered_map<std::string, Index_t> names;
246 for (Eigen::Index i = 0; i < archived.pairtype.rows(); ++i)
247 names.emplace("seed:" + std::to_string(i), static_cast<Index_t>(i));
248 AtomsConfiguration typed;
249 typed.copy(atoms);
250 typed.type = archived.type;
251 typed.atoms_froz_active.clear();
252 initializeAtomsConfiguration(typed.positions, parameters, names, typed);
253 if (seedKernelAtomsIdentity(typed) != seedKernelAtomsIdentity(archived))
254 return false;
255 atoms.copy(typed);
256 return true;
257}
std::string seedKernelAtomsIdentity(const AtomsConfiguration &atoms)
Atomic descriptor identity; moving positions belong to the observations.
Eigen::Matrix< int, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixi
Definition Macros.h:27

◆ refuseNonFiniteSeedRows()

void gpr::io::refuseNonFiniteSeedRows ( const Observation & observations,
Eigen::Index expected_cols = -1 )

Refuse a seed whose rows are non-finite, the wrong length, or a different width from this search. expected_cols < 0 skips the width check. The message names how many rows would have been kept.

Definition at line 587 of file GpState.cpp.

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}

◆ requireUsableFrame()

void gpr::io::requireUsableFrame ( const readcon::CFrame & frame,
const char * role )
static

Definition at line 267 of file ReadConLoader.cpp.

268{
269 if (frame.num_atoms >
270 static_cast<std::size_t>(std::numeric_limits<int>::max() / 3)) {
271 throw std::invalid_argument(
272 std::string(role) +
273 " atom count does not fit in the coordinate index");
274 }
275 if (frame.num_atoms > 0 && frame.atoms == nullptr) {
276 throw std::invalid_argument(
277 std::string(role) + " declares atoms but the atom pointer is null");
278 }
279}

◆ resolveGpStatePath()

std::string gpr::io::resolveGpStatePath ( const std::string & spec,
bool restart )
nodiscard

--gp-init names the npz file. --restart names a directory or a previous output file; the npz is that directory's gp-state.npz, or the sibling of the output file.

Definition at line 694 of file GpState.cpp.

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}

◆ saveTrainedGpState()

void gpr::io::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 at line 450 of file GpState.cpp.

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}
double getConstSigma2()
GPModelProfile getModelProfile() const noexcept
std::string version()
Definition gpridge.hpp:339
void writeSeedKernel(std::ostream &out, const GaussianProcessRegression &gp, const AtomsConfiguration &atoms)
Write fitted covariance parameters, output units, and descriptor identity.
std::string seedKernelIdentity(const GaussianProcessRegression &gp, const AtomsConfiguration &atoms)

◆ seedKernelAtomsIdentity()

std::string gpr::io::seedKernelAtomsIdentity ( const AtomsConfiguration & atoms)
nodiscard

Atomic descriptor identity; moving positions belong to the observations.

Definition at line 26 of file SeedKernel.cpp.

27{
28 std::ostringstream out;
29 out << std::setprecision(17);
30 const auto matrix = [&](const auto& value) {
31 out << ' ' << value.rows() << ' ' << value.cols();
32 for (Eigen::Index i = 0; i < value.rows(); ++i)
33 for (Eigen::Index j = 0; j < value.cols(); ++j)
34 out << ' ' << +value(i, j);
35 };
36 matrix(atoms.atomicNrs);
37 matrix(atoms.is_frozen);
38 matrix(atoms.type);
39 matrix(atoms.atoms_mov.type);
40 matrix(atoms.atoms_froz_active.type);
41 matrix(atoms.atoms_froz_active.positions);
42 matrix(atoms.pairtype);
43 for (const double entry: atoms.cell)
44 out << ' ' << entry;
45 return out.str();
46}

◆ seedKernelIdentity()

std::string gpr::io::seedKernelIdentity ( const GaussianProcessRegression & gp,
const AtomsConfiguration & atoms )
nodiscard

Definition at line 158 of file SeedKernel.cpp.

160{
162 throw std::invalid_argument(
163 "atomic environment parameters cannot use the pair seed-kernel "
164 "format");
165 const auto& covariance = gp.getSexpAtCovarianceFunction();
166 const bool chart = covariance.usesManifoldChart();
167 const bool heat = covariance.usesGeodesicHeatKernel();
168 return kernelIdentity(gp, atoms, chart, heat, chart || heat);
169}
bool usesManifoldChart() const noexcept
Definition SexpatCF.h:616

◆ seedSession()

int gpr::io::seedSession ( neb::ActiveLearningSession & session,
const TrainedGpState & state,
bool require_identity,
Eigen::Index expected_cols = -1 )

Copy seed rows into the session. They are prior data: append does not count an oracle call. The hook installs hyperparameters once the session builds its GP. expected_cols < 0 skips the width check; a seed with rows of any other width is refused before a column is stored.

Definition at line 638 of file GpState.cpp.

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}
bool applyTrainedGpState(GaussianProcessRegression &gp, const TrainedGpState &state, const AtomsConfiguration &atoms, bool require_identity)
Definition GpState.cpp:564
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
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 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

◆ setCellDimensionsFromLengthsAndAngles()

void gpr::io::setCellDimensionsFromLengthsAndAngles ( const std::array< double, 3 > & cell,
const std::array< double, 3 > & angles,
gpr::InputParameters & parameters )

Definition at line 255 of file ReadConLoader.cpp.

258{
259 const std::array<double, 9> m =
260 cellMatrixFromLengthsAndAngles(cell, angles);
261 std::copy(m.begin(), m.end(), std::begin(parameters.cell_dimensions.value));
262}
std::array< double, 9 > cellMatrixFromLengthsAndAngles(const std::array< double, 3 > &cell, const std::array< double, 3 > &angles)

◆ writeSeedKernel()

void gpr::io::writeSeedKernel ( std::ostream & out,
const GaussianProcessRegression & gp,
const AtomsConfiguration & atoms )

Write fitted covariance parameters, output units, and descriptor identity.

Definition at line 259 of file SeedKernel.cpp.

261{
263 throw std::invalid_argument(
264 "atomic environment parameters cannot use the pair seed-kernel "
265 "format");
266 const auto& covariance = gp.getSexpAtCovarianceFunction();
267 const auto& lengths = covariance.getLengthScaleRef();
268 const auto& chart = covariance.manifoldChart();
269 const auto& heat = covariance.geodesicHeatKernel();
270 out << std::setprecision(17);
271 if (chart || heat)
272 out << "components 1 " << static_cast<bool>(chart) << ' '
273 << static_cast<bool>(heat) << '\n';
274 out << "magnSigma2 " << covariance.getMagnSigma2() << '\n'
275 << "constSigma2 " << gp.getConstantCovarianceFunction().getConstSigma2()
276 << '\n'
277 << "sigma2 " << gp.getLikGaussian().getSigma2() << '\n'
278 << "pairCutoff " << covariance.getConfInfo().pair_cutoff << ' '
279 << covariance.getConfInfo().pair_cutoff_width << '\n'
280 << "lengthScale " << lengths.size();
281 for (Eigen::Index i = 0; i < lengths.size(); ++i)
282 out << ' ' << lengths.data()[i];
283 out << "\noutputTransform " << gp.outputMean() << ' ' << gp.outputScale()
284 << ' ' << gp.outputMeanFrozen() << "\nidentity "
285 << seedKernelIdentity(gp, atoms) << '\n';
286 if (chart) {
287 const auto& pair_lengths = covariance.getAtomisticLengthScaleRef();
288 out << "atomisticLengthScale " << pair_lengths.size();
289 for (Eigen::Index i = 0; i < pair_lengths.size(); ++i)
290 out << ' ' << pair_lengths.data()[i];
291 out << '\n';
292 writeChart(out, *chart);
293 }
294 if (heat) {
295 const auto& metric = heat->atomisticLengthScales();
296 const auto& reference = heat->referencePath();
297 out << "heat " << heat->covarianceWeight() << ' ' << metric.size();
298 for (Eigen::Index i = 0; i < metric.size(); ++i)
299 out << ' ' << metric.data()[i];
300 out << ' ' << reference.rows() << ' ' << reference.cols();
301 for (Eigen::Index i = 0; i < reference.rows(); ++i)
302 for (Eigen::Index j = 0; j < reference.cols(); ++j)
303 out << ' ' << reference(i, j);
304 out << '\n';
305 }
306 if (!out) throw std::runtime_error("could not write seed kernel");
307}
FieldMatrixd & getLengthScaleRef()
Definition SexpatCF.inl:58