Python bindings

The gpridge package has two layers. gpridge._core is a compiled nanobind extension that exposes the C++ objects. The Python modules above it provide the classes that work with ASE: GaussianProcess, GPDimer, GPNEB, GPNEBSession, GPLocalBand and Surrogate. This page lists the public surface by module and states what every call shares: units, sign conventions, errors, arrays and threads. It does not repeat signatures or docstrings.

The Python API reference is generated from the source and has the signature and docstring of every class, method and function.

Five pages show the package in use:

Install the package as described in Installation.

Package layout

Module

Contents

gpridge

Re-exports the names on this page, __version__ and the error classes

gpridge.dimer

GPDimer

gpridge.neb

GPNEB, GPLocalBand, search_local

gpridge.session

GPNEBSession, PreparedGPNEB, GPNEBSessionResult, map_acquisition

gpridge.gp

GaussianProcess, Prediction, TrainingSet, NoiseReport, FitDiagnostics

gpridge.surrogate

Surrogate, the builder that configures the GP posterior

gpridge.errors

GPRidgeError and its subclasses; imports nothing compiled

gpridge.ase_bridge

Conversions between ASE Atoms, flat path matrices and the core objects

gpridge.baker_board

Settings of the Baker-24 board runs

gpridge.pyeon_bridge

Optional pyeonclient.Matter overlay; see ASE and eOn

gpridge.ase_active_gp, gpridge.engine

ActiveGPCalculator and ActiveGPEngine, which call libgpr_engine through ctypes; see ASE and eOn

gpridge.integrations

Oracles for ASE, LAMMPS, OpenMM, PLUMED and GROMACS quantities; see Engine oracles

gpridge.instanton

Experimental instanton Gaussian-process helpers; see Active learning for the spectral instanton

gpridge.wheel_smoke

python -m gpridge.wheel_smoke runs a Muller-Brown dimer search as an install check

gpridge._core

The extension: the C++ classes, the runtime switches and the version

Names that start with an underscore (_core, _api, _adapters, _calculator, _observers) are implementation modules, but the package re-exports their public contents, so from gpridge import run_dimer works. GPRCalculator in _calculator is a learn-on-the-fly calculator written in Python against an absolute variance threshold. ActiveGPCalculator runs that loop in libgpr_engine, the library that eOn uses, with a gate in multiples of the model’s likelihood noise.

The compiled extension is optional for the engine and the ASE calculator. When _core fails to import, import gpridge still works, and the first use of a name that needs the extension raises AttributeError chained to the original ImportError.

The first block checks that the package and the extension report the same version and imports GPRidge’s Muller-Brown potential for the later blocks.

import numpy as np

import gpridge
from gpridge import _core
from gpridge import potential_muller_brown as muller_brown

assert gpridge.__version__ == _core.__version__

Conventions

Units and signs

Positions are in angstrom (Å), energies in electronvolt (eV), forces and gradients in eV/Å, spring constants in eV/Å^2. The classes that take ASE objects (GPDimer, GPNEB, GPNEBSession, GPLocalBand, GaussianProcess) take and return ASE forces, which point downhill. The core stores gradients, the negative of the forces:

  • Observation.G and the gradient that a gp_neb or search_local oracle returns are gradients.

  • AtomicDimer.get_final_gradient_at_mid_point() returns a gradient. Its older name, get_final_force_at_mid_point(), returns the same gradient, not a force, and emits a DeprecationWarning; use the gradient name.

  • The potential callback of PotentialWrapper, as built by ase_potential, fills its forces argument with ASE forces and returns the energy; the core converts them.

A flat coordinate vector lists the atoms in order, x1, y1, z1, x2, ..., so Observation.R has shape (n_obs, 3N), E has shape (n_obs, 1) and G has shape (n_obs, 3N). GPDimer works on the moving atoms only, so its observations have three columns per moving atom.

A dimer search measures energies from the energy of its first oracle call, which is the start geometry. GPDimer.energy_eV and AtomicDimer.get_final_energy() are therefore relative to that zero level; AtomicDimer.get_energy_zero_level() returns the offset in eV. The log and trajectory files that GPDimer writes hold absolute energies.

Constraints

Use atoms.set_constraint(FixAtoms(indices``[0, 1]))= to freeze atoms with ASE. You can also pass a Boolean ``mask or use negative indices counted from the end. GPDimer raises ValueError for other constraint types or when every atom is fixed. GPLocalBand holds an atom fixed when a FixAtoms constraint fixes it in both endpoints. The fixed positions must match at both endpoints.

GPNEB and GPNEBSession hold the atoms named by FixAtoms at their reference positions throughout the search. Use the same fixed atom indices and positions in every image. The ASE calculator receives the full geometry, and the native band optimizes only the moving coordinates.

For constraints such as FixCartesian or Hookean, use an ASE optimizer with GPRCalculator attached to the ASE Atoms object. ASE applies the constraint when it requests the forces or energy, and the GP learns the underlying calculator’s unconstrained surface.

Searches

GPDimer

GPDimer(atoms, oracle, gp=)= searches for a first-order saddle point from atoms, which can be any structure near it, with the C++ AtomicDimer on the surrogate in gp. run(fmax=0.05, steps=200, max_oracle_calls=None) returns whether the force criterion was met. The constructor copies atoms; the final midpoint is in GPDimer.atoms after run.

The optional constructor arguments are orient (initial orientation, shape (n_atoms, 3); default: a random direction over the moving atoms scaled to norm 0.01 Å, drawn from seed), seed (default 42), verbose, model_profile, logfile, trajectory and convergence_force_norm. verbose=False selects report level 0, which writes none of the progress report to standard error (a one-shot [hssvd] conditioning diagnostic that the library prints with fprintf is not part of that report). logfile takes a file name or any os.PathLike, "-" for standard output or an object with write. convergence_force_norm is None (the default, the L2 norm of the whole force vector), "l2", "linf" (the largest absolute component), "max_force_on_atom" (the largest per-atom force magnitude) or a ConvergenceNorm member; fmax is compared with that norm. trajectory takes a file name, which needs the readcon package, or an object with write.

If gp already holds observations, for example after a GPNEB run, the dimer starts from them. GPDimer uses the canonical sigma2 and jitter_sigma2 defaults (both 1e-4) for the GP inside the search and refits gp on all observations when it finishes.

run stops before an oracle call that would exceed max_oracle_calls, so oracle_calls never ends above it. converged is True only when the true force met fmax and the index stencil at the final midpoint measured exactly one negative mode; its oracle calls are part of oracle_calls.

GPNEB and GPNEBSession

GPNEB(images, oracle, gp=)= relaxes a band of ASE images with the GP-NEB loop, optionally with a climbing-image dimer burst. GPNEBSession is the same object split into steps: interpolate, prepare, compute and apply, with the summary in session.result. GPNEB is a facade over the session that keeps the images as a list. Prefer the session when you compose steps or start from pyeonclient endpoints (from_matters). Both classes build the image list from two endpoints with from_endpoints(reactant, product, n_intermediate). The path methods of interpolate and from_endpoints are "linear" (the default), "idpp", "idpp_collective", "sidpp" and "sidpp_geodesic".

The constructor options fall into groups. The generated reference gives the defaults.

Group

Options

Required

images, oracle, gp

Band

climb, spring_constant (eV/Å^2), geometric_spring, use_sidpp, sidpp_alpha

Acquisition and model

acquisition, model_profile, seed, verbose

Climbing-image dimer

use_mmf (master switch), rg_minmode_dimer, rgsaddle_library, dimer_max_rot_iter, dimer_eval_image1, dimer_variance_tau_rel, dimer_variance_tau_abs, dimer_imspe_soft_threshold

GP refit gate

theta_shift_skip_tol, theta_shift_skip_auto

Observation

logfile, trajectory

acquisition selects the rule that picks the next image to measure: "ucb", "max_variance", "max_force", "thompson_sampling", "expected_improvement", "imspe", "tpe" or "psbax". Short forms such as "maxvar", "ts" and "ei" and the names of the AcquisitionType members are also accepted, and an unknown name raises ValueError. model_profile is None (the library profile), "gprd_zbl", "chemgp", "extended" or a GPModelProfile.

use_idpp chooses the path method where the session builds the interior images: interpolate and from_endpoints (or from_matters) without an explicit method or path_method use "idpp" when use_idpp is true, and "linear" when it is false, the default. interpolate("idpp") uses IDPP even when use_idpp is false, and interpolate("linear") uses a linear path even when use_idpp is true. The constructor still treats an explicit path_method as a conflict with an explicit flag when the two disagree: an IDPP-family method ("idpp", "idpp_collective", "sidpp", "sidpp_geodesic") with use_idpp=False, or any other method with use_idpp=True, raises ValueError. The constructor searches the band in images as given, and prepare sets GPNEBConfig.use_idpp to False whatever the argument says.

The run options of run, prepare and compute are fmax (eV/Å, default 0.05), steps (outer iterations, default 200), the band stepper settings (lbfgs_*, band_engine, max_inner_iter_gp, inner_conv_tol), the reparametrisation settings (oie_hook_reparam, reparam_period, reparam_tol) and, for prepare and compute, use_ocineb (default True; GPNEB.run always runs the climbing-image controller). compute also takes prepared, apply and fit_gp.

GPLocalBand and search_local

GPLocalBand(reactant, product, calculator) relaxes a band between two periodic endpoints with the local band mode, the Python form of gpr_neb_search_local. It handles fixed atoms, takes the minimum image in the endpoints’ cell and starts from a linear, "idpp" or "sidpp" path. GPLocalBand.from_con reads .con endpoints with readcon, which keeps the cell, the periodicity and the fixed atoms. n_images is the number of images between the endpoints, so the band has n_images + 2 images. Any further keyword is a GPNEBConfig field by name. run(fmax=None, steps=None, norm=None) returns whether the band converged; fmax, steps and the options left at None take the shared periodic-band defaults, _core.periodic_band_defaults(). norm is "l2" (over the moving atoms), "linf" or "max_force_on_atom". The index certificate is off unless you pass force_stop_certificate=True in the keywords; without it certified stays False. The Pt(111) tutorial runs the band.

search_local(oracle, initial, final, n_images=8, fmax=0.05, steps=50) is the function form for a Python oracle on flat moving coordinates. It sets the mode of its GPNEBConfig to NEBMode.GP_LOCAL and returns a GPNEBResult.

Results and oracle-call counts

Quantity

GPDimer

GPNEB attributes, GPNEBSession.result

GPLocalBand; GPNEBResult from search_local

Converged

converged

converged

converged

Why it stopped

termination_reason

GPNEBSession.result.neb_result.convergence_status

GPNEBResult.convergence_status

Energy, eV

energy_eV (relative)

barrier_eV

barrier; GPNEBResult.barrier_energy

Highest image

not applicable

max_energy_image

max_energy_image

Oracle calls

oracle_calls

oracle_calls and the parts below

oracle_calls; the parts through GPNEBResult

Outer iterations

outer_iterations

outer_iterations

GPNEBResult.outer_iterations

Wall time, s

elapsed_s

elapsed_s

not recorded

converged is True when the force criterion fmax was met. It does not test the curvature: a stationary point with zero force that is not a saddle can report True, so read the final geometry and, for a dimer, termination_reason. The energy of GPDimer is relative to the first oracle call (see above). The barrier of a band is the energy of the highest image minus the energy of the reactant. max_energy_image counts the reactant as 0.

Oracle calls are evaluations of the true potential. The surrogate is not counted. For a band, oracle_calls is the sum of four parts:

Attribute

Counts

oracle_calls_endpoints

The two endpoint evaluations

oracle_calls_initial

The initial design

oracle_calls_outer

The outer loop; one iteration can measure several geometries

oracle_calls_validation

The final validation of the band, including the index certificate

oracle_calls_to_convergence

Endpoints, initial and outer calls, without validation

GPLocalBand.n_certificate_calls and GPNEBResult.n_certificate_calls give the evaluations that the index certificate spent. They are part of oracle_calls and not of oracle_calls_to_convergence. GPNEB also records dimer_oracle_calls and mmf_bursts for the climbing-image dimer.

The next block runs a Muller-Brown band with seven intermediate images through _core.gp_neb and checks the accounting. The band converges on the force tolerance. The printed call count comes from the single-process Eigen backend. The surface’s coordinates, energies and barrier are dimensionless. The C API page runs the same band and prints the same barrier and call count.

config = gpridge.GPNEBConfig()
config.mode = gpridge.NEBMode.Standard
config.verbose = False
config.max_outer_iter = 400
config.conv_tol = 0.5

reactant = np.array([-0.558224, 1.441726])
product = np.array([0.623499, 0.028038])
result = _core.gp_neb(muller_brown, reactant, product, 7, config)
print(f"barrier {result.barrier_energy:.2f} after {result.oracle_calls} calls, "
      f"{result.convergence_status}")
assert result.converged and result.convergence_status == "force_tolerance"
assert abs(result.barrier_energy - 106.03) < 0.05
parts = (result.oracle_calls_endpoints, result.oracle_calls_initial,
         result.oracle_calls_outer, result.oracle_calls_validation)
print("endpoints, initial, outer, validation:", *parts)
assert sum(parts) == result.oracle_calls
assert result.oracle_calls_to_convergence == sum(parts[:3])
barrier 106.03 after 163 calls, force_tolerance
endpoints, initial, outer, validation: 2 7 154 0

Termination reasons

GPDimer.termination_reason and AtomicDimer.get_termination_reason() return one of these names. A GPDimer reports "not_run" before run. The checks behind alignment_loss and interatomic_collapse are off in the core and Python has no switch for them. Only the dimers that a band run starts turn them on, so a standalone GPDimer does not report these two.

Name

Meaning

force_converged

The force on the midpoint met the criterion

iteration_budget

The limit on outer phases (steps, num_bigiter) was reached

oracle_budget

The max_oracle_calls budget was spent; checked before each phase

degenerate_probe

30 consecutive probes added no distinct observation, so the surrogate could not move the dimer

measured_non_descent

The measured force stopped improving: the surrogate reached a fixed point above the tolerance, a stationary candidate was refused by the measured-energy ceiling, or a recovery burst measured a larger force than its reference

measured_index_zero

The final stencil refused a midpoint that lies within one dimer separation of a complete measured expansion with no negative curvature

uninformative_rotation

Three consecutive phases ended with non-negative surrogate curvature after a true image evaluation each

alignment_loss

The dimer axis fell out of alignment with its reference

interatomic_collapse

The shortest interatomic distance of the measured midpoint fell below ratio_at_limit times that of the start

wall_clock_limit

The deadline set with AtomicDimer.set_max_wall_seconds passed; the search returns the best measured state, not converged

uncertified_force_stop

The force criterion was met but the index stencil did not certify one negative mode

invalid_parameters

The dimer separation is not positive; execute raises InvalidArgumentError instead

invalid_atoms_configuration

The atoms configuration has no moving-atom set; execute raises InvalidArgumentError for this case

unspecified

No reason was recorded

Only force_converged sets converged to True. Every other reason leaves it False, so check the reason before you use the geometry. oracle_budget and iteration_budget are the two limits you set.

The Gaussian process

GaussianProcess and Prediction

GaussianProcess is the trainable surrogate and an ASE calculator for the properties energy and forces. It takes keyword arguments only.

Argument

Meaning

chain

A Surrogate that fixes the whole configuration; the default is Surrogate.map().

uncertainty

"map" (default; also "fast", "none"), "laplace" (also "laplace-slice", "slice", "production"), "bma", "eb" or "svgd". Any other value raises ValueError.

use_delta

Add the INLA-Delta variance estimator; needs uncertainty”laplace”=.

psis, psis_deterministic

PSIS correction of the Laplace-slice path (on by default for "laplace"; the deterministic sampler is the default). Both need "laplace".

rff_features

Random Fourier features for the mean prediction; 0 turns them off.

hyperparameters

"scg" (default) or "inla".

template_atoms

Reference structure for the model. A periodic model keeps its cell; every observation and query must keep its atomic numbers, order, periodicity and the cell vectors of its periodic axes.

gpr_params

Override of the underlying parameter dictionary.

Pass either chain or the option arguments: giving both raises ValueError. Choose GP settings explains which settings to choose.

The methods:

Method

Purpose

observe(atoms, energy=None, forces=None)

Add a geometry; values come from the arguments or from atoms’ calculator. Pass both or neither.

add_observation(atoms), add_evaluated_observation(atoms, energy, forces)

The two forms of observe, with forces in eV/Å (ASE sign).

fit(atoms_list=None), fit_from_atoms(atoms_list)

Fit the hyperparameters on the stored observations; fit raises RuntimeError when none are stored.

predict(atoms)

(energy, forces); raises RuntimeError before the first fit.

predict_with_uncertainty(atoms)

A Prediction.

uncertainty(atoms), get_variance(atoms)

Predictive energy variance in eV^2.

to_observation()

The stored rows as a core Observation.

n_observations, is_fit

Number of stored observations; True once fit has run.

An observation whose atomic numbers or order differ from the template raises ValueError. Prediction is a frozen dataclass with energy (eV), forces (eV/Å, ASE sign), energy_variance (eV^2) and force_variance, which are None when no variance was computed, and the property energy_std (eV).

Surrogate

Surrogate is an immutable builder. Surrogate.map() is the default. The methods Surrogate.laplace_slice(), psis(), delta(), rff(n), hssvd() and with_hyperparameter_mode(mode) each return a new Surrogate, and label names the chain, for example "lapslice+psis+delta". A method that needs a base the chain lacks raises ValueError: delta() needs a Laplace-slice base and psis() needs one too. GaussianProcess builds the same chains from its option arguments.

Functional interface

The functions below work on the core objects directly. The functional dimer tutorial runs them in order.

Function

Purpose

run_dimer(params, initial_obs, mid_point_obs, orientation, atoms_config, potential_fn)

Build an AtomicDimer, run it and return it. Check get_converged() and get_termination_reason().

default_parameters()

A new dictionary of every input parameter with the settings gprd runs with.

preset_parameters(name)

default_parameters() with the values of the preset "default", "fast" or "accurate". Any other name raises ValueError.

default_gpr_parameters()

The GP-relevant parameters with their defaults.

ase_potential(atoms)

A potential callback for atoms, which needs a calculator (ValueError otherwise) and ASE (ImportError). It updates atoms in place on every call.

from_rgpot(pot)

Wrap an rgpot-style surface as a PotentialWrapper.

atoms_config_from_ase(atoms, frozen_indices=None)

An AtomsConfiguration; every atom moves unless listed.

make_atoms_configuration(atoms, *, gp_params=None, frozen_indices=None)

The same, fully initialised for gp_neb and the dimer.

observation_from_ase(atoms_list)

An Observation with R, E and G; G is the negative of the ASE forces.

path_matrix_from_images(images), apply_path_matrix(images, path, energies=None)

ASE images to a (n_images, 3N) matrix and back.

images_from_endpoints(reactant, product, n_intermediate, ...)

The image list that from_endpoints builds.

neb_oracle_from_calculator(template, calculator, ...)

The (positions) -> (energy, gradient) oracle for gp_neb and run_ocineb.

apply_gpneb_result(images, result)

Write a GPNEBResult into ASE images.

map_acquisition(name)

Map an acquisition name to AcquisitionType.

production_baker_gpneb_config(), production_baker_high_level_kwargs(), production_baker_nimages()

The settings of the Baker-24 board runs (gprd_zbl profile, "max_variance" acquisition, no minimum-mode following, 8 images).

Parameter dictionary

The keys are the names of the gprd parameters. A key that the extension does not know raises InvalidArgumentError with the message Unknown parameter key, and an array with the wrong length raises it too. Array-valued keys take NumPy arrays of the stated size. default_parameters() already carries the dimer settings gprd uses, which _core.canonical_dimer_parameters() also returns.

These keys control a dimer search:

Key

Default

Meaning

dimer_sep

0.01

Distance from the midpoint to each dimer image, in Å; must be finite and positive

method_rot, method_trans

"LBFGS_alg"

Rotation and translation methods

param_trans

[0.1, 0.05]

Translation step length and its maximum, in Å

T_dimer

0.1

Force convergence threshold on the midpoint, in eV/Å (L2 norm of the full gradient)

T_anglerot_init

0.0873

Rotation-angle threshold of the initial rotations, in rad (about 5 degrees); must lie in (0, pi)

num_iter_initrot

6

Maximum number of initial rotations; 0 skips them

T_anglerot_gp

0.01

Rotation-angle threshold during a relaxation phase, in rad; must lie in (0, pi)

divisor_T_dimer_gp

10

A relaxation phase converges at the smallest accurate force so far divided by this value, but not below T_dimer divided by 10; 0 uses T_dimer divided by 10

disp_max

0.5

Largest distance of the midpoint from the nearest observation, in Å; a value below es_threshold also becomes the trust threshold

ratio_at_limit

2/3

Ratio below 1 of inter-atomic distances to the nearest observation at which a phase stops

num_bigiter

300

Maximum outer iterations (new pairs of observations)

num_iter

200

Maximum inner iterations per relaxation phase

actdist_fro

30.3

Activation distance in Å for pairs of a moving and a frozen atom; a float or an integer, and reported as a float

es_dist_metric, es_threshold

DistanceMetricType.EMD, 1.2

Metric and threshold (Å for EMD) of the early-stopping trust test of a relaxation phase; the effective threshold is the smaller of es_threshold and a positive disp_max

max_iter, tolerance_func, tolerance_sol

400, 1e-3, 1e-3

Iteration limit and tolerances of the hyperparameter optimiser

report_level

1

Verbosity of the C++ report on standard error; 0 writes none of it

convergence_force_norm

0

Norm that T_dimer is compared with: 0 L2, 1 L-infinity, 2 largest force on one atom

es_dist_metric is an enumeration member and does not accept a string. A value of the wrong type for any key raises InvalidArgumentError (a ValueError) whose message names the key, the expected type and the type given, for example parameter 'T_dimer': expected float, got str. A key that is not a string raises the same error. convergence_force_norm outside 0 to 2 is refused. GPDimer(convergence_force_norm…)= sets it. GPDimer.run sets T_dimer from fmax, num_bigiter from steps and keeps the canonical sigma2 and jitter_sigma2 defaults.

The presets change a few of these keys:

Key

default

fast

accurate

T_dimer

0.1

0.1

0.001

num_bigiter

300

3

20

num_iter

200

50

200

max_iter

400

100

800

tolerance_func

1e-3

1e-3

1e-6

tolerance_sol

1e-3

1e-3

1e-6

report_level

1

0

1

Every other key keeps its default in all three presets. The next block asserts this table and the defaults above, so that the page fails when a value drifts.

default = gpridge.default_parameters()
fast = gpridge.preset_parameters("fast")
accurate = gpridge.preset_parameters("accurate")
changed = {
    #                  default  fast   accurate
    "T_dimer":        (0.1,     0.1,   0.001),
    "num_bigiter":    (300,     3,     20),
    "num_iter":       (200,     50,    200),
    "max_iter":       (400,     100,   800),
    "tolerance_func": (1e-3,    1e-3,  1e-6),
    "tolerance_sol":  (1e-3,    1e-3,  1e-6),
    "report_level":   (1,       0,     1),
}
for key, (d, f, a) in changed.items():
    assert (default[key], fast[key], accurate[key]) == (d, f, a), key
for key in default:
    if key not in changed:
        assert str(fast[key]) == str(accurate[key]) == str(default[key]), key
assert str(gpridge.preset_parameters("default")) == str(default)

canonical = _core.canonical_dimer_parameters()
documented = {
    "dimer_sep": 0.01, "method_rot": "LBFGS_alg", "method_trans": "LBFGS_alg",
    "T_dimer": 0.1, "T_anglerot_init": 0.0873, "num_iter_initrot": 6,
    "T_anglerot_gp": 0.01, "divisor_T_dimer_gp": 10, "disp_max": 0.5,
    "num_bigiter": 300, "num_iter": 200, "actdist_fro": 30.3, "es_threshold": 1.2,
}
for key, value in documented.items():
    assert default[key] == value, key
    if key in canonical:
        assert canonical[key] == value, key
assert list(default["param_trans"]) == [0.1, 0.05]
assert abs(default["ratio_at_limit"] - 2 / 3) < 1e-12
assert default["es_dist_metric"] == _core.DistanceMetricType.EMD
assert "convergence_force_norm" not in default

try:
    gpridge.preset_parameters("slow")
except ValueError as error:
    print(error)


def initialize(parameters):
    _core.AtomicDimer().initialize(parameters, _core.Observation(),
                                   _core.Observation(), np.zeros((1, 3)),
                                   _core.AtomsConfiguration())


for bad in (dict(default, no_such_key=1), dict(default, param_trans=np.zeros(3)),
            dict(default, dimer_sep=0.0)):
    try:
        initialize(bad)
    except gpridge.InvalidArgumentError as error:
        print(error)
    else:
        raise AssertionError("the bad parameter was accepted")
Unknown preset: 'slow'. Use 'default', 'fast', or 'accurate'.
Unknown parameter key: no_such_key
parameter 'param_trans': expected array of size 2, got 3
dimer_sep must be finite and positive

The extension layer

gpridge._core is imported by the Python modules and re-exported by gpridge, so gpridge.AtomicDimer and gpridge._core.AtomicDimer are the same class. These groups cover everything it exports:

Group

Names

Dimer

AtomicDimer, AtomsConfiguration, Observation, PotentialWrapper, FrozenAndMovingAtoms

GP model

GaussianProcessRegression, StudentTProcessRegression, GPModelProfile, UncertaintyMode, HyperparameterOptimizationMode, HyperparameterObjectiveMode, OptimizationAlgorithms, LinalgMode

Priors

PriorBase, PriorGaussian, PriorLogNormal, PriorLogUnif, PriorSqrtt, PriorT, PriorUnif

Band

NEBPath, Image, GPNEBConfig, GPNEBResult, OCINEBConfig, OCINEBResult, PeriodicBandDefaults, NEBMode, ConvergenceNorm, BandEngineKind, AcquisitionType

Other enumerations

DistanceMetricType, DebugLevels, _core.HssvdBackend

Band functions

gp_neb, run_ocineb, neb_linear_path, neb_idpp_path, neb_idpp_collective_path, neb_sidpp_path, neb_sidpp_geodesic_path, periodic_band_defaults

Dimer functions

canonical_dimer_parameters, initialize_atoms_config

Runtime

The functions in the next section

_core.HssvdBackend is not one of those re-exports. No public function or model config takes it.

gp_neb(oracle, initial, final_state, n_images, config, gp_params=, atoms_config=)= takes flat coordinates of the reactant and the product and the number of intermediate images. The oracle is callable(positions) -> (energy, gradient). run_ocineb takes the same arguments plus an OCINEBConfig and adds the climbing-image dimer bursts; it returns an OCINEBResult. canonical_dimer_parameters(report_level=1) returns the dimer settings of gprd.

AtomicDimer

Construct an AtomicDimer without arguments, call initialize(parameters, initial_data, middle_point, initial_orientation, atoms_config), then execute(potential). execute releases the GIL. It raises InvalidArgumentError when the atoms configuration has no moving-atom set or when dimer_sep is not finite and positive.

Method

Returns

get_converged()

True when the final force criterion is met; the curvature is not checked

get_termination_reason()

A name from the termination table above

get_final_coord_of_mid_point()

Flat midpoint coordinates in Å

get_final_gradient_at_mid_point()

Flat gradient at the midpoint in eV/Å, the negative of the force

get_final_force_at_mid_point()

Deprecated alias of get_final_gradient_at_mid_point(): the same gradient, with a DeprecationWarning

get_final_energy()

Energy of the midpoint in eV, relative to the zero level

get_energy_zero_level()

The zero level in eV: the first measured energy

get_final_curvature()

Curvature along the dimer axis in eV/Å^2

get_total_force_calls()

Evaluations of the true potential

get_total_gpr_force_calls()

Evaluations of the surrogate

get_iterations()

Outer iterations (relaxation phases) completed

set_max_oracle_calls(n)

Budget of true evaluations; 0 or less removes it. The search stops before a call that would exceed it

get_gpr_model()

The surrogate of the search, or None

restart_along_weak_mode, refine_saddle_from_measured_hessian, restart_from_higher_order_point

The three steps that gprd takes from a converged midpoint whose full stencil shows a weak or a second negative mode. The stencil certificate itself is the --weak-mode-continuations loop of gprd

set_profile_dimer_times(on), get_profile_dimer_times()

Switch the dimer phase timing output

get_active_set_change_count(), get_active_frozen_count()

Times the active frozen set grew, and its current size

atoms_config

Read/write access to the atoms configuration

Runtime configuration

These module functions mirror options of gprn. They act on the whole process.

Function

CLI option or purpose

set_linalg_mode(mode), linalg_mode()

--linalg-mode: "reproducible" (default) or "library"; another name raises InvalidArgumentError. GPNEBConfig.linalg_mode sets it per NEB

set_linalg_threads(n)

--linalg-threads; call it before building models. It also sets the OpenMP team. A value below 1 raises InvalidArgumentError

set_training_product(spec), training_product_configured()

--training-product-library: "”= (native), "scheme2:fp64[...]", "scheme2:int8[...]" or a library path. A malformed specification raises ValueError, a missing library RuntimeError

check_model_package(path)

Raises RuntimeError when an AOTInductor package needs a CPU extension the host lacks

backend_name()

The compiled linear-algebra backend, such as "eigen" or "scalapack"

abi_report(), check_abi()

One [startup] abi line per native library; check_abi() raises ABIError naming both stamps when a loaded library does not match its header

__version__, _core.__version__

The library version, from the meson project version

A failing oracle

An oracle that raises or returns a non-finite energy or force is a failed evaluation. A failure at an endpoint or in the initial band stops the run at once with an InternalError. A failure at a later trial geometry is a refused measurement: the geometry is remembered and not requested again, and more than 8 consecutive failures stop the run. The dimer has the same bound of 8. The error carries the oracle’s own message, with the Python traceback when the oracle raised.

The next block shows both immediate cases and the runtime switches. Each abi line gives the stamp of the header that gpridge was built against, the stamp of the loaded library and a status; the block prints the status of the gpridge line.

calls = 0


def flaky(x):
    global calls
    calls += 1
    if calls > 4:
        raise FloatingPointError("surface unavailable")
    return muller_brown(x)


try:
    _core.gp_neb(flaky, reactant, product, 7, config)
except gpridge.InternalError as error:
    lines = str(error).splitlines()
    print(type(error).__name__, "-", lines[0].split(":")[0])
    print(lines[-1])
    assert isinstance(error, RuntimeError)
    assert not isinstance(error, gpridge.OracleError)
    assert lines[-1] == "FloatingPointError: surface unavailable"
else:
    raise AssertionError("the failing oracle did not stop the band")


def not_a_number(x):
    return float("nan"), np.array([float("nan"), float("nan")])


try:
    _core.gp_neb(not_a_number, reactant, product, 7, config)
except gpridge.InternalError as error:
    print(error)
else:
    raise AssertionError("a NaN endpoint did not stop the band")

gpridge.set_linalg_mode("library")
assert gpridge.backend_name() in {
    "eigen", "cholmod", "kokkos", "cusolver", "stdpar", "scalapack", "slate"
}
print(gpridge.linalg_mode(), gpridge.backend_name())
gpridge.set_linalg_mode("reproducible")
assert gpridge.linalg_mode() == "reproducible"
try:
    gpridge.set_training_product("scheme2:quad")
except ValueError as error:
    print("refused:", error)
try:
    gpridge.set_linalg_threads(0)
except gpridge.InvalidArgumentError as error:
    print("refused:", error)
assert not gpridge.training_product_configured()
gpridge.check_abi()
report = gpridge.abi_report()
assert report and all(line.startswith("[startup] abi ") for line in report)
line = next(line for line in report if "library=gpridge " in line)
print(line.split()[-1])
assert line.split()[-1] == "status=verified"
InternalError - the oracle failed at image 3 of the initial band
FloatingPointError: surface unavailable
the oracle failed at a band endpoint (the given reactant or product): oracle returned a non-finite energy or force
library <reason>
refused: unknown Scheme II engine quad
refused: linalg threads must be at least 1
status=verified

Errors

Errors that the library raises on purpose derive from gpridge.GPRidgeError. There is one subclass per GPR_ERR_* status of the C API, and status and status_name carry the code. Each subclass also derives from the built-in exception that the same failure raised before the hierarchy existed, so an except ValueError or except RuntimeError keeps working. The classes live in gpridge.errors, which imports nothing compiled.

Class

status

status_name

Also derives from

Raised by the Python package

NullHandleError

-1

GPR_ERR_NULL_HANDLE

ValueError

no; the C API and the core use it

InvalidArgumentError

-2

GPR_ERR_INVALID_ARG

ValueError

yes: unknown parameter key, wrong array size, a rejected argument

NotTrainedError

-3

GPR_ERR_NOT_TRAINED

ValueError

yes: get_alpha() on an untrained model

AllocationError

-4

GPR_ERR_ALLOC

MemoryError

yes: std::bad_alloc

CholeskyError

-5

GPR_ERR_CHOLESKY

RuntimeError

yes: predict_energy_variance_interval on std::domain_error, noise_floor_report on std::runtime_error

OptimizerError

-6

GPR_ERR_OPTIMIZER

RuntimeError

no; the C API reports it

NotConvergedError

-7

GPR_ERR_NOT_CONVERGED

RuntimeError

no; the C API reports it

SizeLimitError

-8

GPR_ERR_SIZE_LIMIT

ValueError

yes: std::length_error, an LP64 index limit

OracleError

-9

GPR_ERR_ORACLE

RuntimeError

no; a failing Python oracle gives InternalError

UnsupportedError

-10

GPR_ERR_UNSUPPORTED

NotImplementedError

no; the C API reports it

ABIError

-11

GPR_ERR_ABI

RuntimeError

yes: check_abi() on mismatched stamps

OutOfSupportError

-12

GPR_ERR_OUT_OF_SUPPORT

ValueError

yes: a derivative query past max_energy_std

UnitMismatchError

-13

GPR_ERR_UNIT_MISMATCH

ValueError

yes: htst_ln_prefactor on halves with different omega_scale

InternalError

-99

GPR_ERR_INTERNAL

RuntimeError

yes: any other std::exception, including a failed oracle

EngineError

0

RGPOT_ENGINE_ERROR

RuntimeError

yes: a failed libgpr_engine call in gpridge.engine; code holds the return value

GPRidgeError itself derives from Exception and is the base of all of them. error_for_status(status) returns the class for a GPR_ERR_* code and InternalError for an unknown code, as the C API reports it.

A C++ exception that leaves a binding and reaches the translator follows the common handler of gpridge_c.cpp (status_from_exception): std::bad_alloc becomes AllocationError, std::length_error becomes SizeLimitError, std::invalid_argument and std::domain_error become InvalidArgumentError, and any other std::exception becomes InternalError. Five C functions catch before that handler, as the C API page tables, and two methods here do the same. predict_energy_variance_interval catches std::domain_error and raises CholeskyError. noise_floor_report catches std::runtime_error and raises CholeskyError. std::out_of_range, std::overflow_error and std::range_error keep nanobind’s IndexError, OverflowError and ValueError. A Python exception from an oracle is not passed through as it is: the search catches it and re-raises it as InternalError when the run stops. No error ends the interpreter.

Two checks sit in the core. An image index outside 0 < i < n_images= raises IndexError in NEBPath.image, NEBPath.neb_force, NEBPath.tangent_at and GPNEBResult.image_positions; the unchecked read used to return garbage or end the process. gp_neb with a GP mode (GP_AIE or GP_OIE, and GP_OIE is the GPNEBConfig default) and no gp_setup raises InvalidArgumentError: a GP mode builds its Gaussian process through that callback, and without it there is nothing to fit. The classes GPNEB, GPNEBSession and GPLocalBand set it. Set config.mode to NEBMode.Standard, AIE or OIE to run a band without a GP.

Pure Python code raises ValueError for the argument checks of the classes (for example a constraint that GPDimer does not support, an unknown acquisition name or a GaussianProcess option conflict) and RuntimeError for GaussianProcess.predict before a fit. The oracles of gpridge.integrations use their own hierarchy; see Engine oracles for saddle and path searches.

The next block asserts the table and shows three of the translations.

from gpridge import errors

table = [
    ("NullHandleError", -1, "GPR_ERR_NULL_HANDLE", ValueError),
    ("InvalidArgumentError", -2, "GPR_ERR_INVALID_ARG", ValueError),
    ("NotTrainedError", -3, "GPR_ERR_NOT_TRAINED", ValueError),
    ("AllocationError", -4, "GPR_ERR_ALLOC", MemoryError),
    ("CholeskyError", -5, "GPR_ERR_CHOLESKY", RuntimeError),
    ("OptimizerError", -6, "GPR_ERR_OPTIMIZER", RuntimeError),
    ("NotConvergedError", -7, "GPR_ERR_NOT_CONVERGED", RuntimeError),
    ("SizeLimitError", -8, "GPR_ERR_SIZE_LIMIT", ValueError),
    ("OracleError", -9, "GPR_ERR_ORACLE", RuntimeError),
    ("UnsupportedError", -10, "GPR_ERR_UNSUPPORTED", NotImplementedError),
    ("ABIError", -11, "GPR_ERR_ABI", RuntimeError),
    ("OutOfSupportError", -12, "GPR_ERR_OUT_OF_SUPPORT", ValueError),
    ("UnitMismatchError", -13, "GPR_ERR_UNIT_MISMATCH", ValueError),
    ("InternalError", -99, "GPR_ERR_INTERNAL", RuntimeError),
]
for name, status, status_name, builtin in table:
    cls = getattr(gpridge, name)
    assert issubclass(cls, gpridge.GPRidgeError) and issubclass(cls, builtin)
    assert (cls.status, cls.status_name) == (status, status_name)
    assert errors.error_for_status(status) is cls
assert errors.error_for_status(12345) is gpridge.InternalError
assert issubclass(gpridge.EngineError, (gpridge.GPRidgeError, RuntimeError))
assert gpridge.EngineError.status_name == "RGPOT_ENGINE_ERROR"

for call in (lambda: _core.GaussianProcessRegression().get_alpha(),
             lambda: initialize(dict(default, dimer_sep=0.0))):
    try:
        call()
    except gpridge.GPRidgeError as error:
        print(f"{type(error).__name__} ({error.status_name}):", error)
    else:
        raise AssertionError("no error")
NotTrainedError (GPR_ERR_NOT_TRAINED): posterior weights are unavailable until the model has been trained
InvalidArgumentError (GPR_ERR_INVALID_ARG): dimer_sep must be finite and positive

Arrays and the GIL

Arguments are NumPy float64 arrays that nanobind’s Eigen casters copy into Eigen objects. Positions and observations are copied once per call, which is small next to a search or a fit. The matrix fields of the plain data classes (Observation.R, E, G, AtomsConfiguration.positions, …) read back as NumPy views of the C++ storage: obs.R[0, 0] = 1.0 changes the observation, and a view keeps its object alive. Assigning a field copies the array in, so later edits to the source array do not reach the object. Reassigning a field with a different size reallocates its storage, so take a fresh view afterwards rather than reusing one taken before.

AtomicDimer.execute, the three AtomicDimer restart methods, gp_neb, run_ocineb, GaussianProcessRegression.optimize, the path-initialisation functions and NEBPath steps, set_training_product and check_model_package release the GIL while the C++ code runs, and an oracle callback takes it again for each call. Other threads run in the meantime. The remaining methods hold the GIL.

Typing

gpridge/_core.pyi types the extension and py.typed marks the package. The test suite fails when _core exports a name that the stub file lacks, or when the stub file declares one that _core does not have. The generated reference reads its _core documentation from the stub file.

Free-threaded Python

_core does not request nanobind’s NB_FREE_THREADED build mode. Nanobind therefore does not declare Py_MOD_GIL_NOT_USED for the extension, including with nanobind 3 where that declaration is supplied by the compiled runtime rather than the NB_MODULE macro. A free-threaded CPython build enables the GIL when it imports _core.

The runtime configuration is process-wide and the search objects are not internally synchronised, so the module cannot promise thread safety without the GIL. The binding tests check the compiled module’s nanobind build flag and, on a free-threaded interpreter, assert that the GIL is enabled after importing _core. Only add the free-threaded build mode after providing synchronization for the module’s shared state and extending that runtime test.

Wheels

pyproject.toml builds wheels with meson-python and cibuildwheel for CPython 3.11 to 3.13 on Linux x86_64 and aarch64 (manylinux_2_28) and on macOS arm64 and x86_64. scripts/vendor_sdist_deps.py downloads the wraps that configure uses and vendors their Cargo crates; the sdist carries those trees, and the wheel build sets CARGO_NET_OFFLINE. auditwheel and delocate vendor OpenBLAS, libgomp or libomp, and libgfortran into the wheel. Windows wheels are not built. Publishing is a separate tag or manual job and stays off until the repository is public.

_core and the engine need two shared libraries, libgpr_canonical_tiles and libgpr_engine. A wheel installs both into the gpridge package directory and finds them through an $ORIGIN (@loader_path) RPATH, so gpridge.engine.ActiveGPEngine needs no GPR_ENGINE_LIBRARY. python/tests/test_wheel.py imports _core without importorskip, so a wheel that lacks native code fails its tests. The wheels target the single-process Eigen backend; MPI builds come from the scalapack pixi environment.