Python usage

Short recipes for the gpridge Python package: train and query the Gaussian-process surrogate, limit and observe a search, recover from a failing oracle, hand a surrogate from a band to a saddle search, and use the low-level objects. Every block runs in the documentation test, in order, in one Python session, so a block can use the names that earlier blocks define.

For a first search from start to finish, read Python API: a first dimer search. The classes, errors and termination reasons are listed in Python bindings. Install the package as described in Installation.

Set up

The recipes use two oracles. ASE’s EMT calculator gives a copper dimer for the surrogate recipes. The search recipes need a potential with a known saddle, so they use a double well along the distance \(r\) between two atoms, \(V(r) = a\,(r - r_1)^2 (r - r_2)^2\) with \(a = 4\ \mathrm{eV/\AA^4}\), \(r_1 = 1\ \mathrm{\AA}\) and \(r_2 = 2\ \mathrm{\AA}\). Its minima are at \(r_1\) and \(r_2\) and its saddle point is at \(r = 1.5\ \mathrm{\AA}\) with a barrier of \(0.25\ \mathrm{eV}\). The class is the one from the first tutorial.

import numpy as np
from ase import Atoms
from ase.calculators.calculator import Calculator, all_changes
from ase.calculators.emt import EMT

import gpridge
from gpridge import (GaussianProcess, GPDimer, GPNEB, GPNEBSession,
                       GPRidgeError, Surrogate)


class DoubleWell(Calculator):
    implemented_properties = ["energy", "forces"]

    def __init__(self, a=4.0, r1=1.0, r2=2.0, **kwargs):
        super().__init__(**kwargs)
        self.a, self.r1, self.r2 = a, r1, r2

    def calculate(self, atoms=None, properties=("energy",),
                  system_changes=all_changes):
        super().calculate(atoms, properties, system_changes)
        d = atoms.positions[1] - atoms.positions[0]
        r = np.linalg.norm(d)
        u = (r - self.r1) * (r - self.r2)
        dv = 2.0 * self.a * u * (2.0 * r - self.r1 - self.r2)
        f1 = -dv * d / r
        self.results["energy"] = self.a * u * u
        self.results["forces"] = np.array([-f1, f1])


def pair(distance):
    return Atoms("H2", positions=[[0, 0, 0], [distance, 0, 0]],
                 cell=[10, 10, 10], pbc=False)


def cu2(distance):
    return Atoms("Cu2", positions=[[0, 0, 0], [distance, 0, 0]],
                 cell=[10, 10, 10], pbc=False)


oracle = DoubleWell()
emt = EMT()

Train a surrogate and query it

GaussianProcess is a trainable model and an ASE calculator. Add oracle evaluations with observe, fit the hyperparameters with fit, and query it with predict, predict_with_uncertainty or as atoms.calc.

Fit on oracle evaluations

observe(atoms) calls atoms.get_potential_energy() and atoms.get_forces() on the geometry, so the oracle must be attached first. The GP stores the observation and negates the forces, because the core works with gradients.

gp = GaussianProcess(uncertainty="map")
for distance in (2.3, 2.6, 3.0):
    atoms = cu2(distance)
    atoms.calc = emt
    gp.observe(atoms)
print(gp)
gp.fit()
print(gp)

query = cu2(2.7)
prediction = gp.predict_with_uncertainty(query)
query.calc = emt
true_energy = query.get_potential_energy()
true_forces = query.get_forces()
print(f"GP {prediction.energy:.4f} eV, oracle {true_energy:.4f} eV")
print(f"largest force error {np.abs(prediction.forces - true_forces).max():.4f} eV/A")
assert abs(prediction.energy - true_energy) < 0.05
assert np.abs(prediction.forces - true_forces).max() < 0.1
GaussianProcess(chain='map', n_obs=3, fit=False)
GaussianProcess(chain='map', n_obs=3, fit=True)
GP 4.3299 eV, oracle 4.3347 eV
largest force error 0.0247 eV/A

fit rebuilds the underlying C++ model from all stored observations. After observe adds a point, call fit again before the next query. is_fit stays True, and a query then ignores the new point until fit runs.

Use the fitted GP as the calculator of a geometry to read the posterior mean through ASE’s get_potential_energy and get_forces:

surrogate_atoms = cu2(2.7)
surrogate_atoms.calc = gp
assert abs(surrogate_atoms.get_potential_energy() - prediction.energy) < 1e-9
assert surrogate_atoms.get_forces().shape == (2, 3)

Before the first fit, a query raises RuntimeError. predict returns (energy, forces), and predict_with_uncertainty returns a Prediction with the same two values plus energy_variance (eV:math:^2), force_variance (eV:math:^2/\(\mathrm{\AA}^2\)) and energy_std (eV).

Pass oracle values that already exist

When the energy and forces come from a run you did earlier, pass them to observe. The GP does not query a calculator in that case, and the geometry does not need one. Give energy and forces together. Passing only one raises ValueError.

extra = cu2(2.45)
extra.calc = emt
extra_energy = extra.get_potential_energy()
extra_forces = extra.get_forces()

fresh = cu2(2.45)
gp.observe(fresh, energy=extra_energy, forces=extra_forces)
gp.fit()
print(gp.n_observations)
assert gp.n_observations == 4

try:
    gp.observe(fresh, energy=extra_energy)
except ValueError as error:
    print("ValueError:", error)
4
ValueError: energy and forces must be supplied together

Read the uncertainty

uncertainty(atoms) and get_variance(atoms) return the predictive variance of the energy in eV:math:^2. It is small near the training geometries and grows away from them.

near = gp.uncertainty(cu2(2.6))
far = gp.uncertainty(cu2(4.5))
print(f"variance at a training point {near:.2e} eV^2, far away {far:.2e} eV^2")
assert far > 10 * near
assert gp.get_variance(cu2(4.5)) == far
variance at a training point 1.43e-04 eV^2, far away 4.71e-02 eV^2

The numbers depend on the fitted hyperparameters, so they change when the training set changes. The ordering does not.

Choose the uncertainty arm

The constructor options select how the GP computes its posterior. The default is the maximum a posteriori fit (uncertainty”map”=). The table lists the options. Tune the Gaussian-process surrogate explains when each one pays off.

Option

Values

Default

uncertainty

"map", "laplace", "bma", "eb", "svgd"

"map"

use_delta

True adds the INLA-Delta variance correction

False

psis

PSIS correction inside the Laplace-slice path

on with "laplace"

psis_deterministic

deterministic axial-grid PSIS sampler

True

rff_features

number of random Fourier features, 0 is off, "auto" selects the count

0

rff_force_tol_fraction

share of the force tolerance that "auto" may spend, 0 derives it

0.0

hyperparameters

"scg" or "inla"

"scg"

"laplace-slice", "slice" and "production" are accepted spellings of "laplace". use_delta, psis and a positive rff_features need the Laplace arm. A combination the arm cannot honour raises ValueError, and so does an unknown uncertainty name. Instead of the options, pass a Surrogate (see Python bindings) as chain; mixing chain with the options raises ValueError.

laplace = GaussianProcess(uncertainty="laplace", psis=True,
                          psis_deterministic=True, use_delta=True,
                          rff_features=512, hyperparameters="inla")
print(laplace)
print(GaussianProcess(chain=Surrogate.laplace_slice().delta()))

for options in ({"uncertainty": "nope"}, {"use_delta": True},
                {"rff_features": 16}, {"chain": Surrogate.map(),
                                       "uncertainty": "laplace"}):
    try:
        GaussianProcess(**options)
    except ValueError as error:
        print("ValueError:", error)
    else:
        raise AssertionError(options)
GaussianProcess(chain='lapslice+psis+delta+rff512', n_obs=0, fit=False)
GaussianProcess(chain='lapslice+psis+delta', n_obs=0, fit=False)
ValueError: unknown uncertainty mode 'nope'; use 'map', 'laplace', 'bma', 'eb', or 'svgd'
ValueError: delta() requires Surrogate.laplace_slice() base
ValueError: rff() requires Surrogate.laplace_slice() base
ValueError: pass either chain= or uncertainty/use_delta/psis/rff_features/hyperparameters options, not both

Handle an oracle that fails

An exception in the oracle surfaces as InternalError, a subclass of GPRidgeError and RuntimeError. The message holds the Python traceback of the original error, so the cause stays visible. Where the failure happens decides how the search reacts.

  • At the start geometry the search has nothing to fall back to and raises at once.

  • At a later trial geometry the search rejects the trial and goes on from the last accepted geometry. After more than 8 failures in a row it raises.

class Unreachable(DoubleWell):
    def calculate(self, atoms=None, properties=("energy",),
                  system_changes=all_changes):
        raise RuntimeError("licence server unreachable")


class FailsAfterThree(DoubleWell):
    calls = 0

    def calculate(self, atoms=None, properties=("energy",),
                  system_changes=all_changes):
        type(self).calls += 1
        if type(self).calls > 3:
            raise RuntimeError("licence server unreachable")
        super().calculate(atoms, properties, system_changes)


for broken in (Unreachable(), FailsAfterThree()):
    search = GPDimer(pair(1.35), oracle=broken,
                     gp=GaussianProcess(uncertainty="map"), verbose=False)
    try:
        search.run(fmax=0.05, steps=10)
    except GPRidgeError as error:
        first_line = str(error).splitlines()[0]
        print(type(error).__name__, isinstance(error, RuntimeError), "|", first_line[:78])
        assert "licence server unreachable" in str(error)
    else:
        raise AssertionError("the search should have raised")
InternalError True | the oracle failed at the start geometry: Traceback (most recent call last):
InternalError True | the oracle failed at 9 consecutive trial geometries, past the bound of 8; last

An oracle that returns a non-finite energy or force at the start geometry also raises. The Python bindings page lists every error class.

Watch the oracle calls

GPDimer, GPNEB and GPNEBSession step once per oracle evaluation, so the ASE-style observers act on oracle calls. attach(function, interval) calls function after every interval-th evaluation. nsteps counts the evaluations, and last_atoms is a copy of the most recent evaluated geometry whose calculator holds that evaluation’s energy and forces.

dimer = GPDimer(pair(1.35), oracle=oracle,
                gp=GaussianProcess(uncertainty="map"), verbose=False)
seen = []
dimer.attach(lambda: seen.append(dimer.nsteps), interval=3)
dimer.run(fmax=0.05, steps=100)
print(seen[:3], dimer.nsteps == dimer.oracle_calls)
assert seen == list(range(3, dimer.nsteps + 1, 3))
assert dimer.nsteps == dimer.oracle_calls

last = dimer.last_atoms
print(f"{last.get_potential_energy():.4f} eV", last.get_forces().shape)
[3, 6, 9] True
0.2500 eV (2, 3)

Those counts are the default full stencil, one gradient on each side of each coordinate. vibrational_stencil”vibrational”= on the dimer measures only the bond stretch: 6 oracle calls, of which 2 are the stencil. That resolution can call a borderline mode resolved where the full stencil leaves it unresolved.

The same driver writes a log file and a trajectory, and a with block closes them. The first tutorial shows both outputs. The log and trajectory energies are the oracle’s absolute values. dimer.energy_eV is relative to the energy at the first oracle call.

Tune the dimer trust gate

The functional interface, gpridge.run_dimer, takes a parameter dictionary. The part of it that governs how far a surrogate step may go from measured geometries is the es_* group. default_parameters() holds these values:

params = gpridge.default_parameters()
gate = {key: params[key] for key in sorted(params) if key.startswith("es_")}
print({key: str(value) for key, value in gate.items()})
assert gate["es_threshold"] == 1.2 and gate["es_use_adaptive_threshold"] is False
assert gate["es_dist_metric"] == gpridge.DistanceMetricType.EMD
assert params["disp_max"] == 0.5
{'es_adaptive_A': '1.3', 'es_adaptive_floor': '0.25', 'es_delta_explore': '0.35', 'es_dist_metric': 'DistanceMetricType.EMD', 'es_half_life': '50', 'es_t_min': '0.15', 'es_threshold': '1.2', 'es_use_adaptive_threshold': 'False'}

The gate compares the distance of a proposed geometry from the nearest observation with a threshold. With the default permutation-aware metric (DistanceMetricType.EMD), the distance is in Å: for each element, the mean displacement under the best matching of like atoms, and the largest of those means. The threshold follows from the keys:

  • With es_use_adaptive_threshold off (the default), the threshold is es_threshold (1.2 Å), lowered to disp_max (0.5 Å by default) when disp_max is positive and finite.

  • With it on, the threshold is the smaller of two numbers. The first is \(t_\mathrm{min} + \Delta\,(1 - e^{-n \ln 2 / n_{1/2}})\) with \(t_\mathrm{min}\) = es_t_min, \(\Delta\) = es_delta_explore, \(n_{1/2}\) = es_half_life and \(n\) the number of stored observations. It has grown by half of \(\Delta\) when \(n = n_{1/2}\), and it approaches \(t_\mathrm{min} + \Delta\) only as \(n\) grows. The second is \(\max(`=es\_adaptive\_floor=:math:\),`=es_adaptive_A=:math:/sqrt{N}) for \(N\) moving atoms. disp_max is not read.

  • For the EMD and RMSD metrics, the threshold is then raised to the shortest kernel length scale of the GP when the recent force and energy errors of the model are inside their scales.

The source of these rules is evaluateInterAtomicTrustDistance in gpr/AtomicDimer.cpp and the initialisation in gpr/AtomicDimerInit.cpp. The function below writes the adaptive formula out for a given observation count. It does not call the library.

def adaptive_threshold(n_obs, n_atoms, p):
    earned = p["es_t_min"] + p["es_delta_explore"] * (
        1.0 - np.exp(-np.log(2.0) * n_obs / p["es_half_life"]))
    limit = max(p["es_adaptive_floor"], p["es_adaptive_A"] / np.sqrt(n_atoms))
    return min(earned, limit)


half = adaptive_threshold(params["es_half_life"], 4, params)
print(f"{adaptive_threshold(0, 4, params):.3f} {half:.3f} "
      f"{adaptive_threshold(1000, 4, params):.3f}")
assert abs(half - (params["es_t_min"] + params["es_delta_explore"] / 2)) < 1e-12
0.150 0.325 0.500

For four atoms the limit is \(\max(0.25, 1.3/2) = 0.65\ \mathrm{\AA}\), so the earned value of 0.5 Å at 1000 observations is not capped.

Use the low-level Gaussian process

GaussianProcessRegression is the nanobind-bound C++ model that GaussianProcess wraps. It takes explicit Observation and AtomsConfiguration objects, and it works with gradients, not forces. The block trains it on five points of the double well and predicts a sixth.

params = gpridge.default_gpr_parameters()
# This analytic pair data is noiseless; use a correspondingly low noise floor
# so the force interpolation assertion tests the binding rather than the
# production observation-noise model.
params["gp_sigma2"] = 1e-8
params["sigma2"] = 1e-8
params["jitter_sigma2"] = 1e-5
params["tolerance_func"] = 1e-4
params["tolerance_sol"] = 1e-4
atoms_config = gpridge.make_atoms_configuration(pair(1.0), gp_params=params)

distances = [1.1, 1.3, 1.5, 1.7, 1.9]
R = np.zeros((len(distances), 6))
E = np.zeros((len(distances), 1))
G = np.zeros((len(distances), 6))
for row, distance in enumerate(distances):
    atoms = pair(distance)
    atoms.calc = oracle
    R[row] = atoms.positions.reshape(-1)
    E[row, 0] = atoms.get_potential_energy()
    G[row] = -atoms.get_forces().reshape(-1)

obs = gpridge.Observation()
obs.R, obs.E, obs.G = R, E, G

model = gpridge.GaussianProcessRegression()
model.initialize(params, atoms_config)
model.set_hyperparameters(obs, atoms_config)
model.optimize(obs)

probe = pair(1.6)
probe.calc = oracle
energy, gradient = model.predict(probe.positions.reshape(1, -1))
energy_variance, gradient_variance = model.predict_variance(
    probe.positions.reshape(1, -1))
print(energy.shape, gradient.shape, energy_variance.shape, gradient_variance.shape)
print(f"GP {energy[0, 0]:.4f} eV, oracle {probe.get_potential_energy():.4f} eV")
assert abs(energy[0, 0] - probe.get_potential_energy()) < 0.01
assert np.allclose(-gradient.reshape(2, 3), probe.get_forces(), atol=0.01)
assert not model.failed_optimizer

alpha = model.get_alpha()
print(model.get_jitter(), alpha.shape)
assert alpha.shape == (5 * (1 + 6),)
(1, 1) (1, 6) (1, 1) (1, 6)
GP 0.2301 eV, oracle 0.2304 eV
1e-05 (35,)

get_jitter() is the configured diagonal jitter, and get_alpha() returns an owned copy of the posterior weights, whose length is \(n_\mathrm{obs}\,(1 + 3N)\). Writing to the copy does not change the model. The core prints a few progress lines to standard error while it fits.

Observation layout

The rows of an Observation are observations, and the columns of R and G are the Cartesian coordinates of the moving atoms.

Field

Shape

Unit

Description

R

(n_obs, 3 * n_moving)

Å

Coordinates of moving atoms

E

(n_obs, 1)

eV

Energies

G

(n_obs, 3 * n_moving)

eV/Å

Gradients, not forces

ASE forces are the negative of G, which the example above applies in both directions.