Use GPRidge from ASE and eOn¶
An ASE user wants to hand GPRidge an Atoms object and an ASE calculator.
An eOn user wants to reuse .con files, parameter names and a potential
plugin that eOn already understands. This page lists what the repository
provides for each, runs what can run without eOn, and says which parts
could not be run here. eOn is a separate program. GPRidge implements
interfaces that eOn uses and does not contain eOn code.
This page was written on a host with ASE 3.28 and readcon 0.23, without an
eOn installation and without pyeonclient. Every eOn-side statement below
comes from GPRidge source or from the comments of its tests, and the
blocks marked needs-eon were not run.
What exists¶
Route |
Entry point |
Needs |
|---|---|---|
ASE, searches |
|
Python bindings, an ASE calculator as oracle |
ASE, learning potential |
|
|
Either, files |
|
the |
eOn, names |
five |
nothing beyond the driver |
eOn, plugin |
|
eOn’s engine loader (not in this repository) |
eOn, Python objects |
|
|
eOn, settings |
|
Python standard library |
The reverse direction is not a user feature. gpr/neb/EonRelaxClient.h
loads an eOn relaxation library named by GPR_EON_RELAX_ENGINE. Only
tests construct it. The --neb-band-engine kinds in the CLI help do not
include it.
The search drivers are documented elsewhere. For GPNEB and GPDimer
with a calculator as the oracle, see Python usage and
Python API: a first dimer search. For other oracles see
Engine oracles for saddle and path searches.
Read and write .con files from ASE¶
ReadCon opens multi-frame CON trajectories and converts each frame to
ASE Atoms, preserving cell, fixed atoms, and stored forces. A CON
file carries no periodicity flags. Set atoms.pbc = False for an
isolated cluster before passing it to a search.
Copy the supplied pentamer endpoints, then run gprn on them. GPRidge opens the CON files through ReadCon.
examples="$GPRIDGE_ROOT/examples/lj-pentamer"
cp "$examples/reactant.con" "$examples/product.con" .
gprn --reactant reactant.con --product product.con \
--potential lj --nimages 7 --gp-model-profile gprd_zbl \
--gp-nonperiodic true --gp-observation-archive off \
--output neb.h5 --write-con band.con > gprn.log 2>&1
grep -E '^(Oracle calls \(to convergence\)|Converged:)' gprn.log
Oracle calls (to convergence): 17 (endpoints=2, initial=0, outer=15, dimer=0, certificate=0, transition=0)
Converged: yes
band.con holds the two endpoints and the seven images. ReadCon
exposes the frame roles and energies from the metadata and reads the
forces stored after the coordinates. ConTrajectory creates an
optional band.con.rcidx sidecar to support random access.
import numpy as np
import readcon
band = readcon.ConTrajectory("band.con")
frames = [frame.to_ase() for frame in band]
assert len(frames) == 9 and frames[0].pbc.all()
roles = [frame.metadata["role"] for frame in band]
energies = np.array([frame.energy for frame in band])
print(len(band), "frames:", roles[0], "...", roles[4], "...", roles[-1])
assert len(band) == 9 and roles[0] == "reactant" and roles[-1] == "product"
for name, frame in (("reactant.con", band[0]), ("product.con", band[-1])):
from_input = readcon.ConTrajectory(name)[0].to_ase()
from_band = frame.to_ase()
assert from_input.pbc.all() and from_band.pbc.all()
assert np.abs(from_input.positions - from_band.positions).max() < 1e-5
print("input and band endpoints agree; pbc", from_input.pbc)
print(f"barrier from the band file: {energies.max() - energies[0]:.6f} eV")
9 frames: reactant ... climbing ... product
input and band endpoints agree; pbc [ True True True]
barrier from the band file: 0.623237 eV
Search with an ASE calculator as the oracle¶
The same problem runs from Python. GPNEB.from_endpoints takes the two
Atoms objects, the number of intermediate images and an ASE calculator.
The calculator below is ASE’s LennardJones with \(\epsilon = \sigma = 1\)
and rc=None, which ASE reads as a cutoff of 3 \(\sigma\). A subclass
counts the evaluations. The call sets the model profile gprd_zbl, as
the CLI call did, and the endpoints are made an isolated cluster with
pbc = False.
import readcon
from ase.calculators.lj import LennardJones
from gpridge import GPNEB, GaussianProcess
def isolated(path):
atoms = readcon.ConTrajectory(path)[0].to_ase()
atoms.pbc = False
return atoms
class CountingLJ(LennardJones):
calls = 0
def calculate(self, atoms=None, properties=None, system_changes=None):
type(self).calls += 1
super().calculate(atoms, properties, system_changes)
neb = GPNEB.from_endpoints(
isolated("reactant.con"), isolated("product.con"), 7,
oracle=CountingLJ(sigma=1.0, epsilon=1.0, rc=None),
gp=GaussianProcess(uncertainty="map"), path_method="idpp",
model_profile="gprd_zbl", verbose=False,
)
converged = neb.run(fmax=0.0514, steps=100)
# 0.001 eV is the agreement window asserted below. The oracle count is
# printed and not checked: the same endpoints have taken 21 and 13 calls.
print(converged, f"{neb.barrier_eV:.3f} eV")
print(f"oracle calls {neb.oracle_calls}")
assert converged and neb.oracle_calls == CountingLJ.calls
assert abs(neb.barrier_eV - (energies.max() - energies[0])) < 1e-3
neb.write_con("band_python.con")
assert len(readcon.ConTrajectory("band_python.con")) == 9
offset = {}
for frame in band:
atoms = frame.to_ase()
atoms.pbc = False
atoms.calc = LennardJones(sigma=1.0, epsilon=1.0, rc=None)
offset.setdefault(frame.metadata["role"], []).append(
atoms.get_potential_energy() - frame.energy)
checked = [offset[role][0] for role in ("reactant", "climbing", "product")]
others = offset["intermediate"]
# ASE shifts each pair by 4*eps*((sigma/rc)^12 - (sigma/rc)^6) with rc = 3*sigma.
pair_shift = abs(4.0 * ((1.0 / 3.0) ** 12 - (1.0 / 3.0) ** 6))
n_pairs = 10
offset_eV = n_pairs * pair_shift
print("ASE minus gprn, reactant/climbing/product:", " ".join(f"{d:.4f}" for d in checked), "eV")
print(f"ASE minus gprn, the other 6 frames: {min(others):.4f} to {max(others):.4f} eV")
assert all(abs(d - offset_eV) < pair_shift for d in checked)
span = max(others) - min(others)
assert pair_shift < span < n_pairs * 1.0
True 0.623 eV
ASE minus gprn, reactant/climbing/product: <p> <p> <p> eV
ASE minus gprn, the other 6 frames: <p> to <p> eV
The barrier is printed to 0.001 eV, the window the block asserts against
the barrier read from the gprn band. Six decimals are not stable across
builds: the run that first listed this page printed 0.623250 eV and the
standard pixi env prints 0.623228 eV. The oracle count is not listed.
The CLI run above used 17 evaluations, and Python has used 21 and 13 on
these endpoints; the two calls do not set every option alike.
neb.oracle_calls is the count the driver reports and
CountingLJ.calls is the count of calculator evaluations; the block
asserts they are equal. GPNEB.write_con writes the band with readcon,
as gprn --write-con does.
The block also compares the energies in band.con with ASE’s own
LennardJones on the same geometries. Two things follow.
The absolute values differ by a constant of 0.0548 eV on the reactant, the climbing image and the product. ASE’s
LennardJoneswithrc=Noneuses a cutoff of 3 \(\sigma\) and shifts every pair energy by \(4\epsilon[(\sigma/r_c)^{12} - (\sigma/r_c)^{6}]\), which is -0.00548 eV per pair for these parameters. The five-atom cluster has 10 pairs, which gives 0.0548 eV, sogprn’sljenergies behave as an unshifted sum on these frames. Compare energy differences, such as the barrier, and not absolute energies.The other six frames differ from ASE by 0.06 to 0.31 eV, which is not a constant, and the largest force stored with each of them differs from ASE’s as well. The run made 17 oracle calls for nine images, so not every image was evaluated. The page did not trace where
gprntakes those frame energies from, so treat only the three frames that agree as oracle values.
Use the learning engine as an ASE calculator¶
ActiveGPCalculator wraps an inner ASE calculator. It answers from the
GP where the posterior is resolved and calls the inner calculator
elsewhere. The policy lives in libgpr_engine.so, the library that
eOn’s loader opens (see the next section), so an ASE run and an eOn run
share one implementation. Set certify_below_force to your optimizer’s
fmax or a little above it. The engine then forces a ground-truth call
before a driver can stop on a force that came from the model.
The block relaxes a four-atom copper cluster with ASE’s EMT and BFGS,
once with EMT directly and once through the calculator. It asserts that
the engine’s oracle-call count equals the number of EMT evaluations and
that the force at the final geometry, evaluated with EMT, is below
fmax. The library is found through GPR_ENGINE_LIBRARY, then the copy a
wheel installs in the package, then the loader’s search path.
import numpy as np
from ase import Atoms
from ase.calculators.emt import EMT
from ase.optimize import BFGS
from gpridge.ase_active_gp import ActiveGPCalculator
class CountingEMT(EMT):
calls = 0
def calculate(self, atoms=None, properties=None, system_changes=None):
type(self).calls += 1
super().calculate(atoms, properties, system_changes)
def cluster():
rng = np.random.default_rng(0)
base = np.array([[0, 0, 0], [2.5, 0, 0], [1.25, 2.2, 0], [1.25, 0.7, 2.1]], float)
return Atoms("Cu4", positions=base + rng.normal(scale=0.15, size=base.shape))
fmax = 0.02
plain = cluster()
plain.calc = CountingEMT()
BFGS(plain, logfile=None).run(fmax=fmax)
plain_calls = CountingEMT.calls
CountingEMT.calls = 0
learned = cluster()
learned.calc = ActiveGPCalculator(inner_calc=CountingEMT(), certify_below_force=fmax)
try:
BFGS(learned, logfile=None).run(fmax=fmax)
oracle_calls = learned.calc.oracle_calls
finally:
learned.calc.close()
check = learned.copy()
check.calc = EMT()
true_fmax = np.abs(check.get_forces()).max()
print("plain BFGS:", plain_calls, "EMT calls; engine:", oracle_calls, "oracle calls,",
CountingEMT.calls, "EMT calls; true fmax", f"{true_fmax:.4f} eV/A")
assert oracle_calls == CountingEMT.calls and true_fmax < fmax
plain BFGS: 17 EMT calls; engine: 17 oracle calls, 17 EMT calls; true fmax 0.0104 eV/A
On this problem every evaluation reached the oracle: 17 calls with the
engine, 17 for plain BFGS. The engine saved no calls, and this page
does not claim a saving for the calculator. The block shows only that
the final geometry has a true force below fmax. The gate settings
(sigma_lo_factor, sigma_hi_factor, refit_training_revisions) are
constructor arguments. They must satisfy 0 < sigma_lo_factor <=
sigma_hi_factor, and the constructor raises gpridge.errors.EngineError
otherwise.
Connect eOn to the plugin library¶
libgpr_engine.so is built by the Meson target gpr_engine. A wheel build
or do_install installs it. It exports the generic engine C ABI of rgpot
(gpr/potentials/rgpot_engine_c_abi.h, ABI 1.11 with layout revision 1;
positions in Angstrom, energies in eV, forces in eV/Angstrom). The host
chooses the backend by choosing which library it opens. The comments of
tests/gpr/potentials/GprEngineLoaderContractTest.cpp record what eOn’s
GenericEngineLoader (client/potentials/Rgpot/GenericEngineLoader.cpp in
the eOn source, not in this repository) does with the library:
It opens the library with
RTLD_NOW | RTLD_GLOBAL.It resolves
rgpot_engine_abi_version,rgpot_engine_create,rgpot_engine_destroyandrgpot_engine_force.It compares the ABI version with the version in its own copy of the header.
It calls
rgpot_engine_createwith a configuration blob and treats a null return as a hard failure. It never callsrgpot_engine_set_callbacks.
A missing symbol or a different ABI version makes eOn throw an error that reads “engine C ABI missing/mismatch”, before it asks for any force.
rgpot’s own engine loader (EnginePotential::load in rgpot-core) also
resolves rgpot_engine_abi_stamp, which returns the major, the minor and
the layout revision. At the rgpot revision this tree pins, it requires the
same major and the same layout revision, and a plugin minor no greater than
the host minor (11). A library without the symbol is served as 1.0, layout
revision 1, without the later optional symbols. A newer minor, for example
“engine ABI stamp 1.12 (layout 1) cannot serve host stamp 1.11 (layout 1)”,
or a different major or layout, is refused.
The block repeats steps 1 to 4 from Python with ctypes and reads the
stamp. It then passes two other blobs: a valid gate struct and 16 zero
bytes. The engine must accept the first and reject the second with a
message that starts with gpr engine:. The C++ test records why such a
check exists: the contract lives in another repository, so a change here
that dropped a symbol would break eOn only at load time.
import ctypes
import os
path = os.environ.get("GPR_ENGINE_LIBRARY") or "libgpr_engine.so"
lib = ctypes.CDLL(path, mode=os.RTLD_NOW | os.RTLD_GLOBAL)
for name in ("rgpot_engine_abi_version", "rgpot_engine_create",
"rgpot_engine_destroy", "rgpot_engine_force"):
assert hasattr(lib, name), name
lib.rgpot_engine_abi_version.restype = ctypes.c_int
lib.rgpot_engine_create.restype = ctypes.c_void_p
lib.rgpot_engine_create.argtypes = [ctypes.c_void_p, ctypes.c_size_t,
ctypes.c_char_p, ctypes.c_size_t]
lib.rgpot_engine_destroy.argtypes = [ctypes.c_void_p]
assert lib.rgpot_engine_abi_version() == 1
class Stamp(ctypes.Structure):
_fields_ = [("abi_major", ctypes.c_ushort), ("abi_minor", ctypes.c_ushort),
("layout_revision", ctypes.c_ushort)]
lib.rgpot_engine_abi_stamp.restype = Stamp
stamp = lib.rgpot_engine_abi_stamp()
assert (stamp.abi_major, stamp.abi_minor, stamp.layout_revision) == (1, 11, 1)
err = ctypes.create_string_buffer(512)
handle = lib.rgpot_engine_create(None, 0, err, 512)
assert handle, err.value
lib.rgpot_engine_destroy(handle)
print("empty config accepted")
class Gate(ctypes.Structure):
_fields_ = [("magic", ctypes.c_uint), ("version", ctypes.c_uint),
("sigmaLoFactor", ctypes.c_double), ("sigmaHiFactor", ctypes.c_double),
("certifyBelowForce", ctypes.c_double),
("refitTrainingRevisions", ctypes.c_ulonglong)]
gate = Gate(0x47505247, 1, 1.0, 20.0, 0.05, 5)
handle = lib.rgpot_engine_create(ctypes.byref(gate), ctypes.sizeof(gate), err, 512)
assert handle, err.value
lib.rgpot_engine_destroy(handle)
print("gate config accepted")
junk = ctypes.create_string_buffer(16)
assert not lib.rgpot_engine_create(junk, 16, err, 512)
text = err.value.decode()
assert text.startswith("gpr engine:")
print("zero-filled config rejected: gpr engine:")
empty config accepted
gate config accepted
zero-filled config rejected: gpr engine:
The text after the gpr engine: prefix depends on the build. In a build
with Cap’n Proto the source sends any blob whose length is a multiple of 8
bytes, other than the 40-byte gate struct, down a GprParams path first,
and the message for this blob names that path. The listing stops at the
prefix the block asserts.
Three limits matter when eOn loads the engine.
With the empty configuration that eOn passes by default, the force certificate is off. The header defines
certifyBelowForceas “Non-positive disables the certificate”, and its comment on theRgpotEngineGprGatestruct says that a driver’s convergence claim is then “unbacked by ground truth”. The gate struct (magic0x47505247, version 1, the layout in theGateclass above) sets it. The header marks the struct as interim, to be replaced by a Cap’n Proto message.The oracle normally arrives through
rgpot_engine_set_callbacks. A source comment ingpr/potentials/NestedEngineOracle.hsays eOn’s loader does not call it, so a host in that position names the oracle in the configuration instead: aPotentialSpecmessage with an arm for UMA, metatomic, NWChem, CPMD, LAMMPS (and CP2K when the schema has it), or abuiltinarm that names a library. Only a build with Cap’n Proto and rgpot’sPotentials.capnpheader compiles that path. The page did not test it.configureSessionForSysteminGprEngineAbi.cpptreats every atom as moving. The source comment says that is what a host asking for forces means by passing them.
This page did not run eOn against the library.
Convert an eOn config.ini for the dimer¶
schema/eon_ini_to_toml.py reads the [GPR Dimer] and [Optimizer]
sections of an eOn config.ini and prints the TOML tables of the dimer
parameter schema. It needs only the Python standard library (3.10 or
newer, from its type hints). Four things to know before using it:
It reads a fixed list of keys from
[GPR Dimer](theg.getcalls in the script) and one key,converged_force, from[Optimizer]. Every other key in the file is ignored, and a key that is absent takes the default written in the script.Values are copied as text into the TOML without checking them, so an eOn value that is not valid TOML can give a file that TOML parsers reject.
With
--con FILEit takes the box lengths from line 3 of that.confile and writes a 9-elementcellDimensions(row-major, diagonal box). Without it the box is 25 Angstrom on each side.Two settings do not follow the input. It writes
algorithm = "scg"whateverhyperparameter_opt_methodsays (both branches of theifin the script write the same line), and it writesforce = 0.001under[problem.relaxation.convergence].
The key names in the script are the script’s own. This page did not check them against eOn’s documentation. The block below uses these five of its mappings:
|
TOML key |
|---|---|
|
|
|
|
|
|
|
|
|
|
import os
import subprocess
import sys
import tomllib
from pathlib import Path
Path("config.ini").write_text(
"[GPR Dimer]\n"
"dimer_separation = 0.02\n"
"gpr_noise_variance = 1e-6\n"
"es_threshold = 1.5\n"
"max_outer_iterations = 50\n"
"[Optimizer]\n"
"converged_force = 0.02\n"
)
script = Path(os.environ["GPRIDGE_ROOT"]) / "schema" / "eon_ini_to_toml.py"
subprocess.run([sys.executable, str(script), "config.ini", "--con", "reactant.con",
"-o", "run.toml"], check=True)
table = tomllib.loads(Path("run.toml").read_text())
assert table["cellDimensions"] == [30.0, 0, 0, 0, 30.0, 0, 0, 0, 30.0]
assert table["problem"]["dimerSep"] == 0.02
assert table["problem"]["finalConvergenceForce"] == 0.02
assert table["gpr"]["gpSigma2"] == 1e-6
assert table["early_stopping"]["threshold"] == 1.5
assert table["problem"]["relaxation"]["maxOuterIterations"] == 50
print(sorted(table))
['cellDimensions', 'debug', 'early_stopping', 'gpr', 'optimizer', 'problem', 'pruning', 'runSelector']
The next step turns the TOML into a Cap’n Proto file with
schema/gen_capnp_params.py, which gprd --config FILE reads. That script
needs pycapnp 2.1.0, tomli and rich (its header declares them) and
the compiled schema module. Load Cap’n Proto parameters and wrap potentials
gives the commands. This page ran the converter and did not run that step,
so it does not show that the converter’s output loads in gprd.
Use pyeonclient objects¶
gpridge.pyeon_bridge converts a pyeonclient.Matter to ASE Atoms
(matter_to_ase) and back (ase_to_matter). The back direction raises
ImportError unless pyeonclient is importable; the source names the eOn
build option -Dwith_pyeonclient=true. The forward direction uses
pyeonclient.ase_bridge when it exists. Otherwise it reads positions or
get_positions() and atomic_numbers or get_atomic_numbers() from the
object, so any object with that surface works. GPNEBSession.from_matters
and GPNEB.from_matters build a band from two such endpoints. They need
an ASE calculator as the oracle, and they raise TypeError for a
Matter-bound potential, with the advice to convert it with the pyeonclient
ASE bridge first.
from gpridge import GPNEB, GaussianProcess
from ase.calculators.emt import EMT
neb = GPNEB.from_matters(initial_matter, final_matter, 5,
oracle=EMT(), gp=GaussianProcess(uncertainty="map"))
neb.run(fmax=0.05, steps=100)
initial_matter and final_matter stand for pyeonclient.Matter objects
that you hold. The call was not run, and the oracle in it is only a
placeholder for your calculator.
Where eOn names appear in the drivers¶
Five gprn flags mention eOn in their help text. That text is the only
statement of the correspondence in the CLI:
Flag |
Default |
Help text mentions |
|---|---|---|
|
5.0 |
“(eOn)” after the default |
|
0.5 |
the eOn option |
|
0.8 |
the eOn option |
|
true |
“(eOn default)” for sequential IDPP seeding |
|
false |
“the eOn-style inner relaxation loop” |
The block checks that each of the five lines in gprn --help still
mentions eOn. This page did not compare gprn with eOn’s NEB on any
system, so read the table as a map of names and defaults and not as a
claim that the two programs follow the same path.
gprn --help > gprn_help.txt
for flag in --spring-constant --ci-activation-tol --ci-activation-factor --sidpp --neb-eon-inner-mode; do
grep -E -e "^ +$flag " gprn_help.txt | grep -q eOn
done
echo "five flags mention eOn"
five flags mention eOn
The CLI reference lists every flag with its default.