Python API: the functional dimer interface

This tutorial runs one dimer search through the function-style interface, gpridge.run_dimer, instead of the GPDimer class. The function takes the inputs of the C++ AtomicDimer directly (a parameter dictionary, two Observation objects, an orientation, an AtomsConfiguration and a potential callback) and returns the bound AtomicDimer, whose getters give the final midpoint, force, curvature and counters. Use it when you need those getters or need to build the Observation inputs yourself. GPDimer calls the same AtomicDimer for you and also handles frozen atoms, the shared GaussianProcess and logging; Python API: a first dimer search covers it.

The system is the two-atom double well of the first tutorial, defined again here because every page runs on its own.

What you need

  • The Python bindings of gpridge and ASE 3.23 or newer. See Installation.

  • No input files.

Step 1: the oracle and its callback

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

import gpridge


class DoubleWell(Calculator):
    """V(r) = a (r - r1)^2 (r - r2)^2 in eV, forces in eV/Angstrom."""

    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 = (self.r1 - r) * (self.r2 - r)
        dV_dr = 2.0 * self.a * u * (2.0 * r - self.r1 - self.r2)
        force_on_second = -dV_dr * d / r
        self.results["energy"] = self.a * u * u
        self.results["forces"] = np.array([-force_on_second, force_on_second])


atoms = Atoms("H2", positions=[[0.0, 0.0, 0.0], [1.35, 0.0, 0.0]],
              cell=[10.0, 10.0, 10.0], pbc=False)
atoms.calc = DoubleWell()
pot_fn = gpridge.ase_potential(atoms)
start_energy = atoms.get_potential_energy()

ase_potential wraps atoms in a callback of the form fn(positions, atomic_numbers, forces, box) -> energy. On each call it overwrites the positions and cell of atoms, runs the calculator, writes the ASE forces into the forces array unchanged (eV/Å, pointing downhill) and returns the energy (eV). The C++ core converts the forces to gradients itself. After the search atoms holds the last geometry the callback evaluated, which is not necessarily the saddle.

Step 2: parameters

params = gpridge.default_parameters()
params["T_dimer"] = 0.05
params["sigma2"] = 1e-7
params["jitter_sigma2"] = 0.0

default_parameters() returns a dictionary of every InputParameters field. Its dimer keys (separation, rotation and translation methods, step settings) carry the values that gprd runs with, and the remaining keys are neutral placeholders. The three assignments set:

  • T_dimer, the force convergence criterion in eV/Å. The default is 0.1 and GPDimer.run uses 0.05.

  • sigma2 and jitter_sigma2, the two GP noise settings (fields of GPRSetup in structures/Structures.h). Both default to 1e-4 in default_parameters() and GPDimer. This functional-interface tutorial explicitly pins the lower-noise settings above to preserve its reference trajectory and call count; they are example settings, not library defaults.

preset_parameters("fast") and preset_parameters("accurate") return the same dictionary with a different iteration budget and tolerance. The reference lists the keys that each preset changes.

Step 3: initial data

The dimer needs the energy and gradient at the start point, an empty set of earlier observations, an orientation and a description of the atoms.

init_middle = gpridge.Observation()
init_middle.R = atoms.get_positions().reshape(1, -1)
init_middle.E = np.array([[atoms.get_potential_energy()]])
init_middle.G = -atoms.get_forces().reshape(1, -1)

init_obs = gpridge.Observation()
init_obs.clear()

orient = np.array([[-1.0, 0.0, 0.0, 1.0, 0.0, 0.0]])
orient /= np.linalg.norm(orient)

atoms_config = gpridge.make_atoms_configuration(atoms)

assert init_middle.R.shape == init_middle.G.shape == orient.shape == (1, 6)
assert init_middle.E.shape == (1, 1)

An Observation stores one geometry per row: R and G have shape (n_obs, 3 * n_atoms) and E has shape (n_obs, 1). G is the gradient of the energy, which is the negative of the ASE force. This is the one place in the functional interface where the sign differs from ASE, and a missing minus sign gives a search that walks uphill. The orientation has shape (1, 3 * n_atoms) and unit length. Here it stretches the bond along \(x\), the direction of negative curvature at the barrier top.

Step 5: energies and the gradient sign

The final energy is relative to a zero level, which is the first measured energy (the start geometry). Add get_energy_zero_level() for the absolute energy. get_final_gradient_at_mid_point() returns the gradient G at the midpoint, so it is the negative of the ASE force. (The older name get_final_force_at_mid_point() returns the same gradient and emits a DeprecationWarning.) The block checks both against the calculator.

saddle = Atoms("H2", positions=midpoint, cell=[10.0, 10.0, 10.0], pbc=False)
saddle.calc = DoubleWell()

absolute_energy = dimer.get_final_energy() + dimer.get_energy_zero_level()
print(f"zero level {dimer.get_energy_zero_level():.4f} eV, "
      f"relative {dimer.get_final_energy():.4f} eV, "
      f"absolute {absolute_energy:.4f} eV")

assert abs(dimer.get_energy_zero_level() - start_energy) < 1e-9
assert abs(absolute_energy - saddle.get_potential_energy()) < 1e-6
final_gradient = np.asarray(dimer.get_final_gradient_at_mid_point()).reshape(2, 3)
assert np.allclose(final_gradient, -saddle.get_forces(), atol=1e-6)
zero level 0.2070 eV, relative 0.0430 eV, absolute 0.2500 eV

What to change for your own system

  • Replace DoubleWell() with the ASE calculator for your system. The calculator must provide get_potential_energy() and get_forces().

  • Build init_middle, orient and atoms_config from your own atoms. The orientation has one entry for each coordinate of each atom. For frozen atoms, use GPDimer: it marks them in the AtomsConfiguration and limits the observations and the orientation to the moving atoms.

  • For other oracles, run_dimer also accepts a PotentialWrapper, including one made by from_rgpot.

The full list of functions, getters and parameter keys is in Python bindings. The next tutorial for the Python API is A periodic Pt(111) Morse band, which runs a periodic band.