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:
Use a trained GP as a potential trains, inspects, minimizes, and compares one GP through its position, ASE, and rgpot interfaces.
Python API: a first dimer search runs
GPDimer,GPNEBandGaussianProcess.Python API: the functional dimer interface runs
run_dimerand reads theAtomicDimergetters.A periodic Pt(111) Morse band runs
GPLocalBandon a periodic slab.Python usage has short recipes: limits, observers, a failing oracle, and handing a surrogate from a band to a saddle search.
Install the package as described in Installation.
Package layout¶
Module |
Contents |
|---|---|
|
Re-exports the names on this page, |
|
|
|
|
|
|
|
|
|
|
|
|
|
Conversions between ASE |
|
Settings of the Baker-24 board runs |
|
Optional |
|
|
|
Oracles for ASE, LAMMPS, OpenMM, PLUMED and GROMACS quantities; see Engine oracles |
|
Experimental instanton Gaussian-process helpers; see Active learning for the spectral instanton |
|
|
|
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.Gand the gradient that agp_neborsearch_localoracle 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 aDeprecationWarning; use the gradient name.The potential callback of
PotentialWrapper, as built byase_potential, fills itsforcesargument 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 |
|
Band |
|
Acquisition and model |
|
Climbing-image dimer |
|
GP refit gate |
|
Observation |
|
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 |
|
|
|
|---|---|---|---|
Converged |
|
|
|
Why it stopped |
|
|
|
Energy, eV |
|
|
|
Highest image |
not applicable |
|
|
Oracle calls |
|
|
|
Outer iterations |
|
|
|
Wall time, 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 |
|---|---|
|
The two endpoint evaluations |
|
The initial design |
|
The outer loop; one iteration can measure several geometries |
|
The final validation of the band, including the index certificate |
|
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 |
|---|---|
|
The force on the midpoint met the criterion |
|
The limit on outer phases ( |
|
The |
|
30 consecutive probes added no distinct observation, so the surrogate could not move the dimer |
|
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 |
|
The final stencil refused a midpoint that lies within one dimer separation of a complete measured expansion with no negative curvature |
|
Three consecutive phases ended with non-negative surrogate curvature after a true image evaluation each |
|
The dimer axis fell out of alignment with its reference |
|
The shortest interatomic distance of the measured midpoint fell below |
|
The deadline set with |
|
The force criterion was met but the index stencil did not certify one negative mode |
|
The dimer separation is not positive; |
|
The atoms configuration has no moving-atom set; |
|
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 |
|---|---|
|
A |
|
|
|
Add the INLA-Delta variance estimator; needs |
|
PSIS correction of the Laplace-slice path (on by default for |
|
Random Fourier features for the mean prediction; 0 turns them off. |
|
|
|
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. |
|
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 |
|---|---|
|
Add a geometry; values come from the arguments or from |
|
The two forms of |
|
Fit the hyperparameters on the stored observations; |
|
|
|
A |
|
Predictive energy variance in eV^2. |
|
The stored rows as a core |
|
Number of stored observations; True once |
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 |
|---|---|
|
Build an |
|
A new dictionary of every input parameter with the settings |
|
|
|
The GP-relevant parameters with their defaults. |
|
A potential callback for |
|
Wrap an rgpot-style surface as a |
|
An |
|
The same, fully initialised for |
|
An |
|
ASE images to a |
|
The image list that |
|
The |
|
Write a |
|
Map an acquisition name to |
|
The settings of the Baker-24 board runs ( |
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 |
|---|---|---|
|
0.01 |
Distance from the midpoint to each dimer image, in Å; must be finite and positive |
|
|
Rotation and translation methods |
|
|
Translation step length and its maximum, in Å |
|
0.1 |
Force convergence threshold on the midpoint, in eV/Å (L2 norm of the full gradient) |
|
0.0873 |
Rotation-angle threshold of the initial rotations, in rad (about 5 degrees); must lie in (0, pi) |
|
6 |
Maximum number of initial rotations; 0 skips them |
|
0.01 |
Rotation-angle threshold during a relaxation phase, in rad; must lie in (0, pi) |
|
10 |
A relaxation phase converges at the smallest accurate force so far divided by this value, but not below |
|
0.5 |
Largest distance of the midpoint from the nearest observation, in Å; a value below |
|
2/3 |
Ratio below 1 of inter-atomic distances to the nearest observation at which a phase stops |
|
300 |
Maximum outer iterations (new pairs of observations) |
|
200 |
Maximum inner iterations per relaxation phase |
|
30.3 |
Activation distance in Å for pairs of a moving and a frozen atom; a float or an integer, and reported as a float |
|
|
Metric and threshold (Å for EMD) of the early-stopping trust test of a relaxation phase; the effective threshold is the smaller of |
|
400, 1e-3, 1e-3 |
Iteration limit and tolerances of the hyperparameter optimiser |
|
1 |
Verbosity of the C++ report on standard error; 0 writes none of it |
|
0 |
Norm that |
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 |
|
|
|
|---|---|---|---|
|
0.1 |
0.1 |
0.001 |
|
300 |
3 |
20 |
|
200 |
50 |
200 |
|
400 |
100 |
800 |
|
1e-3 |
1e-3 |
1e-6 |
|
1e-3 |
1e-3 |
1e-6 |
|
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 |
|
GP model |
|
Priors |
|
Band |
|
Other enumerations |
|
Band functions |
|
Dimer functions |
|
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 |
|---|---|
|
True when the final force criterion is met; the curvature is not checked |
|
A name from the termination table above |
|
Flat midpoint coordinates in Å |
|
Flat gradient at the midpoint in eV/Å, the negative of the force |
|
Deprecated alias of |
|
Energy of the midpoint in eV, relative to the zero level |
|
The zero level in eV: the first measured energy |
|
Curvature along the dimer axis in eV/Å^2 |
|
Evaluations of the true potential |
|
Evaluations of the surrogate |
|
Outer iterations (relaxation phases) completed |
|
Budget of true evaluations; 0 or less removes it. The search stops before a call that would exceed it |
|
The surrogate of the search, or |
|
The three steps that |
|
Switch the dimer phase timing output |
|
Times the active frozen set grew, and its current size |
|
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 |
|---|---|
|
|
|
|
|
|
|
Raises |
|
The compiled linear-algebra backend, such as |
|
One |
|
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 |
|
|
Also derives from |
Raised by the Python package |
|---|---|---|---|---|
|
-1 |
|
|
no; the C API and the core use it |
|
-2 |
|
|
yes: unknown parameter key, wrong array size, a rejected argument |
|
-3 |
|
|
yes: |
|
-4 |
|
|
yes: |
|
-5 |
|
|
yes: |
|
-6 |
|
|
no; the C API reports it |
|
-7 |
|
|
no; the C API reports it |
|
-8 |
|
|
yes: |
|
-9 |
|
|
no; a failing Python oracle gives |
|
-10 |
|
|
no; the C API reports it |
|
-11 |
|
|
yes: |
|
-12 |
|
|
yes: a derivative query past |
|
-13 |
|
|
yes: |
|
-99 |
|
|
yes: any other |
|
0 |
|
|
yes: a failed |
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.