Python API: a first dimer search¶
A first-order saddle point is the top of the lowest barrier between two minima.
Finding one takes many energy and force evaluations of the true potential.
GPDimer needs fewer of them because it fits a Gaussian-process (GP) surrogate to the evaluations it has already made and searches on the surrogate between evaluations.
This tutorial runs GPDimer on a two-atom potential defined in the script, then on a gold adatom hopping on an Al(100) slab with ASE’s effective medium theory (EMT) calculator.
It then checks the saddle against a GP-NEB band between the same two minima and records every evaluation of the true potential in a log and a trajectory file.
Nothing here needs an input file, a model download or a GPU.
What you need¶
The Python bindings of
gpridgeand ASE 3.23 or newer. Build or install them as described in Installation.The
readconPython package for the trajectory step. It is the only optional piece, and that step is skipped when it is missing.
Check the build:
python -m gpridge.wheel_smoke
The command prints one line that starts with gpridge and the library version.
If it fails with an ImportError, the extension module has not been built for this Python; see Installation.
Step 1: a potential for the search to call¶
The dimer search asks a calculator (the oracle) for the energy and forces of a geometry. Any ASE calculator can be the oracle. Here the oracle is a double-well along the distance \(r\) between two atoms,
It has a minimum with \(V = 0\) at each of \(r_1\) and \(r_2\) and a barrier top at \(r = 1.5\ \mathrm{\AA}\) with \(V = 0.25\ \mathrm{eV}\). A correct search ends there.
import numpy as np
from ase import Atoms
from ase.calculators.calculator import Calculator, all_changes
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])
oracle = DoubleWell()
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)
ASE forces point downhill, so the force is the negative gradient. The code expects forces in eV/Å and energies in eV. The start geometry has the atoms 1.35 Å apart, on the slope between the \(r_1\) minimum and the barrier top.
Step 2: run the search¶
from gpridge import GaussianProcess
from gpridge.dimer import GPDimer
gp = GaussianProcess(uncertainty="map")
dimer = GPDimer(atoms, oracle=oracle, gp=gp, verbose=False)
converged = dimer.run(fmax=0.05, steps=100)
separation = np.linalg.norm(dimer.atoms.positions[1] - dimer.atoms.positions[0])
print(converged, dimer.termination_reason, dimer.oracle_calls)
print(f"bond length at the saddle: {separation:.3f} A")
assert converged and dimer.termination_reason == "force_converged"
assert abs(separation - 1.5) < 0.01
assert gp.n_observations == dimer.oracle_calls
The call counts and the bond length below are from one run. The counts can differ by a few with another build or BLAS library.
True force_converged <n>
bond length at the saddle: 1.495 A
The pieces of that call:
GaussianProcess(uncertainty”map”)= is the surrogate.mapis the plain choice; Tune the Gaussian-process surrogate lists the other uncertainty modes and the remaining options.GPDimer(atoms, oracle…, gp=…)= takes a copy ofatoms, so the start geometry is not modified.verbose=Falsesilences the progress log that the C++ search writes to standard error (about ninety lines for this system with the defaultverbose=True).run(fmax=0.05, steps=100)stops when the L2 norm of the force on the dimer midpoint is belowfmax(eV/Å).stepslimits the outer iterations, that is the alternations between the surrogate and the oracle. At that stop it measures the Cartesian index stencil of the midpoint, one true gradient on each side of each coordinate. It returnsTrueonly when the force criterion was reached and the stencil found exactly one negative mode.dimer.termination_reasonsays why the search stopped. The strings are listed in Python bindings. A value other thanforce_convergedmeans the search did not reach a saddle."uncertified_force_stop"is a force stop that the stencil refused, at a minimum or on a flat region.dimer.oracle_callscounts evaluations of the true potential, the stencil included: 12 of the 24 here.vibrational_stencil”vibrational”= measures only the bond stretch, 2 of 8 calls, and can call a borderline mode resolved where the full stencil leaves it unresolved. The surrogate is not counted.gp.n_observationsis the same number here because each call adds one observation.
Step 3: read the energy¶
dimer.atoms holds the saddle geometry, without a calculator attached.
Energies inside the dimer search are measured from the energy at the first oracle call, which is the start geometry.
dimer.energy_eV is therefore the saddle energy minus the start energy, not the absolute energy.
Add the start energy to get the absolute value.
saddle_energy = oracle.get_potential_energy(dimer.atoms)
start_energy = oracle.get_potential_energy(atoms)
print(f"saddle {saddle_energy:.4f} eV, start {start_energy:.4f} eV, "
f"relative {dimer.energy_eV:.4f} eV")
assert abs(saddle_energy - 0.25) < 1e-3
assert abs(start_energy + dimer.energy_eV - saddle_energy) < 1e-3
saddle 0.2500 eV, start 0.2070 eV, relative 0.0430 eV
Step 4: a surface hop with a frozen slab¶
The same driver handles periodic cells and fixed atoms.
The system is one Au adatom on a 2 x 2 x 2 Al(100) slab, evaluated with ASE’s EMT.
Everything but the adatom is frozen with FixAtoms.
GPDimer supports FixAtoms and rejects any other constraint with a ValueError.
The adatom starts in a four-fold hollow site. The dimer starts 0.6 hollow-to-hollow spacings along \(x\), which is 0.1 spacings past the bridge site between two hollows.
from ase.build import add_adsorbate, fcc100
from ase.calculators.emt import EMT
from ase.constraints import FixAtoms
slab = fcc100("Al", size=(2, 2, 2), vacuum=6.0)
add_adsorbate(slab, "Au", 1.9, "hollow")
slab.pbc = [True, True, False]
slab.set_constraint(FixAtoms(indices=range(len(slab) - 1)))
spacing = slab.cell[0, 0] / 2 # hollow-to-hollow distance along x
start = slab.copy()
start.positions[-1, 0] += 0.6 * spacing
hop = GPDimer(start, oracle=EMT(), gp=GaussianProcess(uncertainty="map"),
verbose=False)
converged = hop.run(fmax=0.05, steps=60)
shift = hop.atoms.positions[-1, 0] - slab.positions[-1, 0]
print(converged, hop.termination_reason, hop.oracle_calls)
print(f"adatom {shift:.2f} A from the hollow; the bridge site is {spacing / 2:.2f} A")
assert converged
assert abs(shift - spacing / 2) < 0.05
assert np.array_equal(hop.atoms.positions[:-1], start.positions[:-1])
True force_converged 16
adatom 1.43 A from the hollow; the bridge site is 1.43 A
The saddle is at the bridge site, half a spacing from the hollow. The last assertion checks that the frozen atoms come back with the coordinates they went in with.
Step 5: check the saddle with a GP-NEB band¶
GPNEB searches between two minima instead of from one geometry.
It takes a list of ASE Atoms (reactant, intermediate images, product) and the same oracle and gp arguments.
The intermediate images are only placeholders until interpolate fills them.
The band below runs from the starting hollow to the next one along \(x\), through seven images in total.
from gpridge.neb import GPNEB
product = slab.copy()
product.positions[-1, 0] += spacing
images = [slab.copy() for _ in range(7)]
images[-1] = product
band = GPNEB(images, oracle=EMT(), gp=GaussianProcess(uncertainty="map"),
use_idpp=True, verbose=False)
band.interpolate("idpp")
ok = band.run(fmax=0.05, steps=100)
saddle = hop.atoms.copy()
saddle.calc = EMT()
hollow = slab.copy()
hollow.calc = EMT()
dimer_barrier = saddle.get_potential_energy() - hollow.get_potential_energy()
print(ok, band.max_energy_image)
print(f"band barrier {band.barrier_eV:.3f} eV, dimer barrier {dimer_barrier:.3f} eV")
assert ok
assert band.max_energy_image == 3
assert abs(band.barrier_eV - dimer_barrier) < 0.01
True 3
band barrier 0.344 eV, dimer barrier 0.344 eV
The highest image is the middle one (index 3 of 0 to 6), and the barrier height from the band agrees with the dimer saddle to within 0.01 eV.
Each driver counts its own oracle calls, so band.oracle_calls and hop.oracle_calls are separate numbers for separate searches.
See Python usage for the options of GPNEB and for reading the band energies and images.
Step 6: record each oracle call¶
GPDimer can write a log and a trajectory of the geometries at which the true potential was evaluated.
logfile takes a file name, "-" for standard output, or an open text file.
trajectory takes a file name, which is written in the readcon .con format and needs the readcon package.
Without it, the driver raises an ImportError that names the package.
ASE does not read .con files on its own unless the readcon-con ASE plugin is installed, so the block below reads the file with readcon.
Each frame carries the energy and forces of that oracle call.
The attach observer runs after every oracle call.
import readcon
energies = []
with GPDimer(atoms, oracle=oracle, gp=GaussianProcess(uncertainty="map"),
verbose=False, logfile="dimer.log", trajectory="dimer.con") as logged:
logged.attach(lambda: energies.append(logged.last_atoms.get_potential_energy()))
logged.run(fmax=0.05, steps=100)
frames = [frame.to_ase()
for frame in readcon.ConTrajectory("dimer.con", write_index=False)]
with open("dimer.log") as log:
last_row = log.read().splitlines()[-1].split()
print(len(frames), logged.nsteps, len(energies))
print("last log row:", last_row[0], last_row[1], last_row[3], last_row[4])
assert len(frames) == len(energies) == logged.nsteps == logged.oracle_calls
assert abs(frames[-1].get_potential_energy() - energies[-1]) < 1e-6
saddle_frame = min(frames, key=lambda frame:
np.linalg.norm(frame.positions - logged.atoms.positions))
assert np.max(np.abs(saddle_frame.positions - logged.atoms.positions)) < 1e-8
assert abs(saddle_frame.get_potential_energy()
- (frames[0].get_potential_energy() + logged.energy_eV)) < 1e-6
<n> <n> <n>
last log row: GPDimer: <n> <s> <s>
The log has a header and one row per oracle call: the call number, the wall-clock time, the absolute energy in eV and fmax, the largest force magnitude on any single atom in eV/Å.
The last 12 rows are the index stencil around the saddle, 0.01 Å from it.
With vibrational_stencil”vibrational”= those are the last 2 rows.
The trajectory frames are the same geometries in the same order, and the energy stored in each frame matches the observer’s value.
The last recorded frame can belong to the validation stencil.
The final assertion selects the frame at the returned saddle geometry and checks its absolute energy against the starting energy plus energy_eV.
Step 7: change the oracle¶
The oracle is an argument, so a different potential needs no other change.
The block below uses the PET-MAD machine-learned potential through the metatomic ASE calculator.
It does not run in the documentation build: it needs the metatomic-torch Python package and a model file.
Install
metatomic-torch. It is not part of thepythonpixi environment. Thescalapackandgpu-cudaenvironments inpixi.tomllist it, and a plain environment can usepip install "metatomic-torch>=0.1.2,<0.2"(the version range thatpixi.tomlpins).Fetch the model file. In the
petmad-assetspixi environment,pixi run -e petmad-assets prepare-petmad-modelwritesbench_data/petmad/pet-mad-s-v1.5.0.pt(seescripts/prepare_petmad_assets.py).
from metatomic.torch.ase_calculator import MetatomicCalculator
# start is an ase.Atoms for your own system, with its cell and constraints.
oracle = MetatomicCalculator("bench_data/petmad/pet-mad-s-v1.5.0.pt",
device="cpu")
gp = GaussianProcess(uncertainty="map") # a new surrogate for a new system
dimer = GPDimer(start, oracle=oracle, gp=gp, verbose=False)
dimer.run(fmax=0.05, steps=100)
Use a new GaussianProcess for each system and each oracle.
A surrogate that has already seen observations from another potential would start from the wrong energies.
Engine integrations shows how to connect other engines (for example LAMMPS or a Python callback) as oracles.
Where to go next¶
Python usage: recipes for the drivers, observers and warm starts.
Tune the Gaussian-process surrogate: the options of
GaussianProcess.Python API: the functional dimer interface: the same search through
gpridge.run_dimer.A periodic Pt(111) Morse band: a band on a periodic slab, run through
GPLocalBand.Python bindings: the full public surface, error classes and termination reasons.
The surrogate loop and derivative observations and How GPRidge finds a saddle: why the surrogate works as it does.