First NEB band: Berry pseudorotation of a Lennard-Jones pentamer¶
Run a Gaussian-process nudged elastic band (GP-NEB) for five atoms bound by a Lennard-Jones potential. The trigonal bipyramid exchanges its two axial atoms with two equatorial ones through a square-pyramidal saddle, a Berry pseudorotation. You write the two endpoints, run one GP-accelerated band and one band on the oracle alone, compare the barrier and the number of oracle calls, and check the energies against the potential.
Energy along the band that gprn returns for the pentamer. The endpoints and the climbing image carry oracle energies, the other images the surrogate’s.¶
Oracle call counts and timings can vary with the build and machine.
What you need¶
Set GPRIDGE_ROOT to the path of your source checkout.
A built
gprn. The documentation CI builds it withbash scripts/install_cbindgen_pixi.sh, thenmeson setup builddir -Dwith_tests=true -Duse_readcon=true -Duse_anneal=enabled --buildtype=releaseandmeson compile -C builddir gprn gprd(.github/workflows/docbuilder.yml, jobexamples). The Installation page lists the other routes. The commands below call the program asgprn; putbuilddiron yourPATHor write./builddir/gprn.A build with readcon-db (
-Duse_readcon_db, defaultauto, on when the wrap resolves). The commands below keep the default--gp-observation-archive auto. Without readcon-db,gprnprints--gp-observation-archive requested but this build has no readcon-dband exits with status 2. Add--gp-observation-archive offto every command if your build lacks it.uv for the Python binding example and the plots. The scripts declare their dependencies inline.
Some familiarity with
gprn. The quickstart explains the log lines using the same cluster and prepared endpoint files.
Work in a fresh directory:
mkdir -p lj-pentamer
cd lj-pentamer
Step 1: check the build¶
gprn --list-potentials | grep -E '^lj[[:space:]]'
The command prints one row, lj with the backend compiled, when this binary has the Lennard-Jones oracle built in.
If the shell reports that gprn is not found, put the build directory on PATH.
Step 2: use the two supplied endpoints¶
The reactant is the relaxed bipyramid with its axis along \(z\); the product is the same bipyramid with its axis along \(y\), after atoms 0 and 1 have moved into the equatorial plane and atoms 3 and 4 onto the axis. Atom 2 is the pivot and stays put.
The oracle is a 12-6 Lennard-Jones potential with \(\epsilon = 1\) eV and \(\sigma = 1\) Angstrom for every pair, shifted to zero at a 15 Angstrom cutoff (the defaults in subprojects/rgpot/CppCore/rgpot/LennardJones/LJPot.hpp).
The element label is therefore arbitrary for the oracle.
The files use Ne.
The label does reach gprn’s element-dependent settings, so the call counts below belong to Ne labels.
Labelling the same atoms Ar also converges (ArgonPentamerAcquiresAndConverges in tests/gpr/GprnLennardJonesTest.cpp asserts it).
In the run that checked this page, Ar labels gave a barrier of 0.623209 eV and took 28 oracle calls instead of 17.
The repository includes both endpoints as CON files. GPRidge reads them through ReadCon. The 30 Å cell gives the cluster room on every side, and all five atoms can move.
examples="$GPRIDGE_ROOT/examples/lj-pentamer"
cp "$examples/reactant.con" "$examples/product.con" .
Step 3: run the GP-accelerated band¶
--potential lj selects the Lennard-Jones oracle.
--nimages 7 puts seven movable images between the endpoints, a band of nine.
--gp-model-profile gprd_zbl selects the GP model profile that the published UMA Baker runs use; the default is extended.
--output gp/neb.h5 names the HDF5 result, and because --gp-observation-archive defaults to auto, the archive of every oracle evaluation goes to gp/obs-archive, next to it.
--write-con stores the final band, one frame per image with its energy in the frame header.
mkdir -p gp
gprn --reactant reactant.con --product product.con \
--potential lj --nimages 7 --gp-model-profile gprd_zbl \
--output gp/neb.h5 --write-con gp/band.con > gp/gprn.log 2>&1
grep -E '^(Oracle calls:|Barrier energy|Converged:|Certified:|Outer relaxation iterations)' gp/gprn.log
awk '/^Barrier energy/ { b = $4 } END { exit !(b > 0.622 && b < 0.625) }' gp/gprn.log
The run on the machine that produced this page took 11 to 14 s and printed
Outer relaxation iterations: <n> across 1 attempt(s)
Oracle calls: <n> (neb=<n>, dimer=0, certificate=0, transition=0)
Barrier energy (eV): <s> (forward: E_saddle - E_reactant)
Converged: yes
Certified: yes
The IRC certificate file is written by the rgmin connectivity walk.
test -f gp/obs-archive/irc_certificate.txt
The awk line asserts the barrier to 1e-3 eV around 0.6232 eV, the tolerance that tests/gpr/GprnLennardJonesTest.cpp uses for this system.
The lines mean:
Oracle callscounts evaluations of the Lennard-Jones potential: 2 for the endpoints and 15 chosen by the search. This count is the cost the surrogate tries to minimise.Barrier energyis the energy of the highest image above the reactant, evaluated on the oracle.Converged: yessays that the true force on the climbing image fell below--converged-force(0.05 eV/Angstrom by default).Certified: yessays that the IRC certificate (--irc-certificate, on by default) walked downhill from the saddle in both directions and reached the reactant and the product. The record is ingp/obs-archive/irc_certificate.txt, and the log lineIRC certificate record:prints its path. See Saddle-point certificates for what the check tests.
The exit status follows the same rule: gprn exits with 0 when the search converged (or when --max-iterations 0 requested band setup only, which builds the initial band without relaxing it, skips the IRC walk and logs setup only (max-iterations 0): band built, not relaxed) and the oracle stencil check, if requested, passed, with 2 when it did not (also when the observation archive is misconfigured), and with 1 on an error such as an unreadable input file or a negative --max-iterations.
A job script can branch on it.
Wall time says little here.
The log’s Oracle time line reports the oracle’s share of the run, which is far below a millisecond for 17 Lennard-Jones evaluations, so almost all of the 11 to 14 s is the surrogate.
The saving appears with an oracle that costs seconds per call.
The log also carries a line Band discretization certificate: FAILS with a leak and a residual.
It compares the chord-discretisation leak and the chord-perpendicular residual at the climbing image’s neighbours with the force tolerance.
The run above printed FAILS and still ended Converged: yes and Certified: yes, because the leak is only a requirement with --band-leak-bound true (default false).
Step 4: compare with a true-force band¶
--nebmode standard runs the same band with the oracle alone, no surrogate.
It gets its own directory.
A run adopts the rows that are already in the observation archive next to its --output file, so a second run in gp/ would start from the first run’s points and its call count would no longer be a cost.
In the run that checked this page, the standard band took 86 calls in gp/ and 93 in a fresh directory.
mkdir -p standard
gprn --reactant reactant.con --product product.con \
--potential lj --nimages 7 --nebmode standard \
--output standard/neb.h5 --write-con standard/band.con \
> standard/gprn.log 2>&1
grep -E '^(Oracle calls:|Barrier energy|Converged:)' standard/gprn.log
gp=$(sed -n 's/^Oracle calls: \([0-9]*\) .*/\1/p' gp/gprn.log)
std=$(sed -n 's/^Oracle calls: \([0-9]*\) .*/\1/p' standard/gprn.log)
test "$gp" -lt "$std"
awk '/^Barrier energy/ { b = $4 } END { exit !(b > 0.622 && b < 0.625) }' standard/gprn.log
Oracle calls: 93 (neb=93, dimer=0, certificate=0, transition=0)
Barrier energy (eV): 0.623232 (forward: E_saddle - E_reactant)
Converged: yes
The two barriers differ by 5e-6 eV.
The GP band asked the oracle 17 times, the true-force band 93 times.
The block asserts that the GP band used fewer calls and that both barriers lie within 1e-3 eV of 0.6232 eV.
The Search time: line of standard/gprn.log reads under 0.01 s against 12 s for the GP band: a Lennard-Jones call costs microseconds, so the surrogate is overhead here and the saving is in calls only.
Run the same reaction through a binding¶
Choose Python, C++, C or Fortran. Each program runs both bands with the same endpoints and force tolerance, keeps all nine images, checks a forward barrier of 0.6232 eV within 1 meV, and verifies that the GP band uses fewer oracle calls. The bindings use the analytical Lennard-Jones function, with gradients converted to forces at the oracle boundary. The CLI uses a cutoff with a constant energy shift. All ten pairs stay within that cutoff, so the shift cancels in the barrier.
The Python tab opens both CON files with ReadCon. For the native examples, use the same ReadCon reader to prepare a coordinate stream. Each output line contains one atom’s coordinate triplet in Å.
uv run --script - "$GPRIDGE_ROOT/examples/lj-pentamer" > endpoints.dat <<'PY'
# /// script
# requires-python = ">=3.11"
# dependencies = ["numpy", "readcon-chemfiles>=0.23.2,<0.24"]
# ///
import sys
from pathlib import Path
import numpy as np
import readcon
examples = Path(sys.argv[1])
for name in ("reactant.con", "product.con"):
frame = readcon.read_first_frame(str(examples / name))
np.savetxt(sys.stdout, frame.coords_array().reshape(-1, 3))
PY
The Python tab uses uv to install the Python package for the script.
The native tabs use the installed shared library and its pkg-config file.
The C and C++ programs check GPR_ABI_CHECK() against GPR_SUCCESS.
Fortran makes the same check through gpr_check_abi.
See Installation for both.
The source files are in examples/lj-pentamer.
sample="$GPRIDGE_ROOT/examples/lj-pentamer"
uv run --script "$sample/band.py" "$sample/reactant.con" "$sample/product.con"
# /// script
# requires-python = ">=3.11"
# dependencies = ["ase", "gpridge", "numpy", "readcon-chemfiles>=0.23.2,<0.24"]
# ///
"""Run the LJ pentamer GP and standard bands from two CON files."""
import argparse
import numpy as np
import readcon
from gpridge import (
GPNEBConfig,
NEBMode,
PotentialWrapper,
neb_search_potential,
potential_lj,
)
def forces(positions, atomic_numbers, cell):
energy, gradient = potential_lj(positions.ravel(), len(atomic_numbers))
return energy, -gradient.reshape(positions.shape)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("reactant")
parser.add_argument("product")
args = parser.parse_args()
reactant = readcon.read_first_frame(args.reactant).to_ase()
product = readcon.read_first_frame(args.product).to_ase()
numbers = reactant.numbers.astype(np.int32)
if len(numbers) != 5 or not np.array_equal(numbers, product.numbers):
parser.error("use the supplied five-atom endpoints with matching atom order")
endpoints = reactant.positions.ravel(), product.positions.ravel()
potential = PotentialWrapper.from_rgpot(forces)
# The search is isolated, regardless of the storage cell in the CON files.
cell = np.zeros((3, 3))
calls = {}
for name, mode, iterations in (
("standard", NEBMode.Standard, 2000),
("gp", NEBMode.GP_OIE, 200),
):
config = GPNEBConfig()
config.mode = mode
config.conv_tol = 0.05
config.max_outer_iter = iterations
config.verbose = False
band = neb_search_potential(potential, numbers, cell, *endpoints, 7, config)
energies = band.image_energies()
positions = np.stack([band.image_positions(i) for i in range(len(energies))])
barrier = band.barrier_energy
if not band.converged or len(energies) != 9 or abs(barrier - 0.6232) > 0.001:
raise SystemExit(f"{name}: unexpected band or barrier {barrier:.6f} eV")
np.savetxt(f"{name}.dat", np.column_stack((energies, positions)))
calls[name] = band.oracle_calls
print(f"{name}: barrier {barrier:.4f} eV, {band.oracle_calls} oracle calls")
if calls["gp"] >= calls["standard"]:
raise SystemExit("GP band did not reduce oracle calls")
if __name__ == "__main__":
main()
c++ -std=c++20 "$GPRIDGE_ROOT/examples/lj-pentamer/band.cpp" \
$(pkg-config --cflags --libs gpridge) -o band
./band < endpoints.dat
// SPDX-License-Identifier: MIT
#include <array>
#include <cmath>
#include <fstream>
#include <gpr/capi/gpridge.hpp>
#include <iomanip>
#include <iostream>
#include <stdexcept>
#include <string>
namespace {
constexpr int atoms = 5;
constexpr int coords = 3 * atoms;
using Positions = std::array<double, coords>;
void lj(long n, const double* x, const int*, double* forces, double* energy,
double* noise, const double*, void*)
{
if (noise) *noise = 0.0;
if (gpr_potential_lj(x, static_cast<int>(n), 1.0, 1.0, energy, forces) !=
GPR_SUCCESS) {
*energy = NAN;
return;
}
for (long i = 0; i < 3 * n; ++i)
forces[i] = -forces[i];
}
int run(const gpr::capi::Potential& potential, const Positions& reactant,
const Positions& product, gpr_neb_mode_t mode, int iterations,
const std::string& name)
{
const std::array<int, atoms> numbers{10, 10, 10, 10, 10};
const std::array<double, 9> cell{};
auto config = gpr_neb_config_defaults();
config.mode = mode;
config.conv_tol = 0.05;
config.max_outer_iter = iterations;
config.verbose = 0;
const auto band = gpr::capi::neb_search_potential(
potential, numbers.data(), cell.data(), reactant.data(), product.data(),
coords, 7, config);
const auto energies = band.all_energies();
if (!band.converged() || energies.size() != 9)
throw std::runtime_error(name + " band did not converge");
const double barrier = band.barrier();
if (std::abs(barrier - 0.6232) > 0.001)
throw std::runtime_error(name + " barrier outside tolerance");
std::ofstream output(name + ".dat");
output.exceptions(std::ios::failbit | std::ios::badbit);
output << std::setprecision(17);
for (int i = 0; i < band.n_images(); ++i) {
output << energies[i];
for (double x: band.image_positions(i, coords))
output << ' ' << x;
output << '\n';
}
output.close();
std::cout << name << ": barrier " << std::fixed << std::setprecision(4)
<< barrier << " eV, " << band.oracle_calls() << " oracle calls\n";
return band.oracle_calls();
}
} // namespace
int main()
try {
std::array<Positions, 2> endpoints{};
for (auto& endpoint: endpoints)
for (double& x: endpoint)
if (!(std::cin >> x)) throw std::runtime_error("invalid endpoints");
if (GPR_ABI_CHECK() != GPR_SUCCESS)
throw std::runtime_error(gpr_last_error_message());
const auto potential = gpr::capi::Potential::from_force(lj);
const int standard = run(potential, endpoints[0], endpoints[1],
GPR_NEB_STANDARD, 2000, "standard");
const int gp =
run(potential, endpoints[0], endpoints[1], GPR_NEB_GP_OIE, 200, "gp");
return gp < standard ? 0 : 1;
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
cc -std=c11 "$GPRIDGE_ROOT/examples/lj-pentamer/band.c" \
$(pkg-config --cflags --libs gpridge) -o band
./band < endpoints.dat
/* SPDX-License-Identifier: MIT */
#include <gpr/capi/gpridge_c.h>
#include <math.h>
#include <stdio.h>
enum { atoms = 5, coords = 3 * atoms, images = 9 };
static void lj(long n, const double* x, const int* numbers, double* forces,
double* energy, double* noise, const double* cell, void* data)
{
(void)numbers;
(void)cell;
(void)data;
if (noise) *noise = 0.0;
if (gpr_potential_lj(x, (int)n, 1.0, 1.0, energy, forces) != GPR_SUCCESS) {
*energy = NAN;
return;
}
for (long i = 0; i < 3 * n; ++i)
forces[i] = -forces[i];
}
static int run(gpr_potential_t potential, const double* reactant,
const double* product, gpr_neb_mode_t mode, int iterations,
const char* name, const char* filename)
{
const int numbers[atoms] = {10, 10, 10, 10, 10};
const double cell[9] = {0};
gpr_neb_config_t config = gpr_neb_config_defaults();
config.mode = mode;
config.conv_tol = 0.05;
config.max_outer_iter = iterations;
config.verbose = 0;
gpr_neb_t band =
gpr_neb_search_potential(potential, numbers, cell, reactant, product,
coords, images - 2, &config);
if (!band) {
fprintf(stderr, "%s\n", gpr_last_error_message());
return -1;
}
int calls = -1;
double energies[images];
if (gpr_neb_result_converged(band) &&
gpr_neb_result_n_images(band) == images &&
gpr_neb_result_all_energies(band, energies, images) == GPR_SUCCESS) {
const double barrier = gpr_neb_result_barrier(band);
if (fabs(barrier - 0.6232) <= 0.001) {
FILE* output = fopen(filename, "w");
if (output) {
calls = gpr_neb_result_oracle_calls(band);
for (int image = 0; image < images; ++image) {
double x[coords];
if (gpr_neb_result_image_positions(band, image, x,
coords) != GPR_SUCCESS) {
calls = -1;
break;
}
fprintf(output, "%.17g", energies[image]);
for (int i = 0; i < coords; ++i)
fprintf(output, " %.17g", x[i]);
fputc('\n', output);
}
if (fclose(output) != 0) calls = -1;
if (calls >= 0)
printf("%s: barrier %.4f eV, %d oracle calls\n", name,
barrier, calls);
}
}
}
if (calls < 0)
fprintf(stderr, "%s: could not write a converged band\n", name);
gpr_neb_result_destroy(band);
return calls;
}
int main(void)
{
double endpoints[2][coords];
for (int j = 0; j < 2; ++j)
for (int i = 0; i < coords; ++i)
if (scanf("%lf", &endpoints[j][i]) != 1) return 1;
if (GPR_ABI_CHECK() != GPR_SUCCESS) {
fprintf(stderr, "%s\n", gpr_last_error_message());
return 1;
}
gpr_potential_t potential = gpr_potential_from_force(lj, NULL);
if (!potential) {
fprintf(stderr, "%s\n", gpr_last_error_message());
return 1;
}
const int standard =
run(potential, endpoints[0], endpoints[1], GPR_NEB_STANDARD, 2000,
"standard", "standard.dat");
const int gp = run(potential, endpoints[0], endpoints[1], GPR_NEB_GP_OIE,
200, "gp", "gp.dat");
gpr_potential_destroy(potential);
if (gp >= 0 && gp < standard) return 0;
fprintf(stderr, "GP band did not reduce oracle calls\n");
return 1;
}
gfortran "$GPRIDGE_ROOT/fortran/gpridge.f90" \
"$GPRIDGE_ROOT/examples/lj-pentamer/band.f90" \
$(pkg-config --libs gpridge) -o band
./band < endpoints.dat
! SPDX-License-Identifier: MIT
module pentamer_oracle
use, intrinsic :: iso_c_binding
use, intrinsic :: ieee_arithmetic, only: ieee_value, ieee_quiet_nan
use gpridge, only: gpr_lj_energy, GPR_SUCCESS
implicit none
contains
subroutine lj(n_atoms, positions, numbers, forces, energy, noise, cell, data) bind(C)
integer(c_long), value :: n_atoms
real(c_double), intent(in) :: positions(3 * n_atoms)
integer(c_int), intent(in) :: numbers(n_atoms)
real(c_double), intent(out) :: forces(3 * n_atoms), energy
type(c_ptr), value :: noise, cell, data
real(c_double), pointer :: energy_noise
integer :: stat
if (c_associated(noise)) then
call c_f_pointer(noise, energy_noise)
energy_noise = 0.0_c_double
end if
call gpr_lj_energy(positions, int(n_atoms), 1.0_c_double, 1.0_c_double, energy, forces, stat)
if (stat /= GPR_SUCCESS) then
energy = ieee_value(energy, ieee_quiet_nan)
return
end if
forces = -forces
end subroutine lj
end module pentamer_oracle
program pentamer_band
use, intrinsic :: iso_fortran_env, only: input_unit
use, intrinsic :: iso_c_binding, only: c_double, c_int
use gpridge
use pentamer_oracle, only: lj
implicit none
integer, parameter :: n_atoms = 5, n_coords = 3 * n_atoms
real(c_double) :: reactant(n_coords), product(n_coords)
integer :: gp, standard, stat
character(len=256) :: message
read (input_unit, *) reactant
read (input_unit, *) product
call gpr_check_abi(stat, message)
if (stat /= GPR_SUCCESS) error stop trim(message)
standard = run(GPR_NEB_STANDARD, 2000, 'standard')
gp = run(GPR_NEB_GP_OIE, 200, 'gp')
if (gp >= standard) error stop 'GP band did not reduce oracle calls'
contains
integer function run(mode, iterations, name) result(calls)
integer(c_int), intent(in) :: mode
integer, intent(in) :: iterations
character(len=*), intent(in) :: name
integer, parameter :: numbers(n_atoms) = 10
type(NEBConfig) :: config
type(NEBResult) :: band
real(c_double), allocatable :: energies(:)
real(c_double) :: x(n_coords), barrier
integer :: i, unit, stat
config = NEBConfig()
config%mode = mode
config%conv_tol = 0.05_c_double
config%max_outer_iter = iterations
config%verbose = 0
call gpr_neb_search_potential(lj, numbers, reactant, product, 7, config, band, stat, message)
if (stat /= GPR_SUCCESS) error stop trim(message)
if (.not. band%converged() .or. band%n_images() /= 9) error stop 'unexpected band'
call band%energies(energies, stat, message)
if (stat /= GPR_SUCCESS) error stop trim(message)
barrier = band%barrier()
if (abs(barrier - 0.6232_c_double) > 0.001_c_double) error stop 'unexpected barrier'
open (newunit=unit, file=name // '.dat', status='replace')
do i = 1, band%n_images()
call band%image_positions(i - 1, x, n_coords, stat)
if (stat /= GPR_SUCCESS) error stop 'cannot read image positions'
write (unit, '(es25.16,15(1x,es25.16))') energies(i), x
end do
close (unit)
calls = band%oracle_calls()
print '(a,f6.4,a,i0,a)', name // ': barrier ', barrier, ' eV, ', calls, ' oracle calls'
end function run
end program pentamer_band
All four programs write gp.dat and standard.dat.
Each row holds an image’s energy in eV followed by its 15 Cartesian coordinates in Å.
Run one tab per working directory to retain the results from multiple languages.
In one run all four bindings reported 0.6232 eV and 93 oracle calls for the standard band and 0.6227 eV and 13 calls for the GP band.
Step 5: plot the band¶
ChemParsePlot draws the 1D energy profile and colors the 2D trajectory by energy. RgPyCrumbs computes the two interatomic distances used in the 2D view. At the reactant, atoms 0 and 1 occupy the axial sites. At the product, atoms 3 and 4 occupy them. Using those two distances keeps the atom identities visible as the pairs exchange roles. The 2D panel shows the sampled band in these coordinates.
The plot script declares its dependencies inline.
uv resolves them when the script runs, including the readcon import supplied by readcon-chemfiles.
MPLBACKEND=Agg uv run --script "$GPRIDGE_ROOT/examples/lj-pentamer/plot_band.py" gp/band.con --output figures
From any of the four binding examples, pass gp.dat in place of gp/band.con.
To plot the standard band, pass standard.dat or standard/band.con and give it a different output directory.
The script writes profile.png and path-2d.png.
The first and last points are the equivalent trigonal bipyramids. The distance between each numbered pair shows how the two pairs exchange axial sites through the saddle.¶
The endpoints and climbing image carry oracle energies in the GP band. The other six are the surrogate’s estimates. ReadCon supplies the geometries to ASE, which independently evaluates the three oracle energies with the same shifted Lennard-Jones potential.
import readcon
from ase.calculators.lj import LennardJones
calculator = LennardJones(epsilon=1.0, sigma=1.0, rc=15.0)
for frame in readcon.read_con("lj-pentamer/gp/band.con"):
role = frame.metadata["role"]
if role in ("reactant", "climbing", "product"):
atoms = frame.to_ase()
atoms.pbc = False
atoms.calc = calculator
direct = atoms.get_potential_energy()
print(f"{role:9s} stored {frame.energy:.6f} direct {direct:.6f} eV")
assert abs(frame.energy - direct) < 1e-6
The reactant energy of −9.1038 eV is the bipyramid’s. The climbing image at −8.4806 eV is the square pyramid, 0.6232 eV above it.
What to try next¶
Use GPRidge with the SciMap tools follows the band from the oracle to analysis and plotting.
Run a GP-NEB band covers the acquisition and trust options that decide which image the oracle evaluates next.
The command-line reference lists every
gprnflag, and the TOML keys give the same settings in a file.The first GP dimer search refines a saddle from Python.
The UMA HCN band runs the same driver with a machine-learned potential.