R and Julia bindings¶
The packages in r/gpridge and julia/GPRidge.jl call the installed
libgpridge through its C API. They implement no search
themselves: each function converts its arguments, calls the C entry point
and converts the result. Both packages expose the ABI 1.26 binding surface
summarized below. Neither is on a package registry; build the library,
select its
installation and install the package as described in
Native packages and downstream bindings.
The function tables come from r/gpridge/NAMESPACE, r/gpridge/R/gpridge.R,
julia/GPRidge.jl/src/capi.jl and the package tests. The examples are the
calls those tests make. The documentation test installs the library into a
scratch prefix, installs the R package from this checkout, and runs every R
and Julia block on this page against that prefix where Rscript and julia
are on the PATH; without an installed prefix the blocks are skipped.
Install and load¶
gpr_libdir=$(pkg-config --define-prefix --variable=libdir gpridge)
export LD_LIBRARY_PATH="$gpr_libdir${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
R CMD build --no-build-vignettes --no-manual "$GPRIDGE_ROOT/r/gpridge"
R CMD INSTALL --library="$R_LIBS_USER" gpridge_*.tar.gz
Rscript -e 'library(gpridge); stopifnot(abi_check()); cat("gpridge loaded, library", gpr_version(), "\n")'
GPRIDGE_ROOT is the source checkout and R_LIBS_USER the R library to
install into; the documentation test sets both, the second to a scratch
directory. R CMD build packs the package into gpridge_X.Y.Z.tar.gz in the
working directory, so the install does not write src/Makevars or object
files into the checkout.
R 4.0.0 or later is required (DESCRIPTION). The package’s configure
script gets the compiler flags and libraries from pkg-config gpridge.
Loading the package calls the ABI check (.onLoad), so a library whose ABI
does not match the header the package was built with stops library(gpridge).
gpr_version() returns the version string of the loaded library.
julia --project="$GPRIDGE_ROOT/julia/GPRidge.jl" \
-e 'using GPRidge; abi_check(); println("GPRidge loaded, library ", GPRidge.version())'
The package needs no installation step: --project points julia at the
package directory, and its only dependency is the standard library Libdl.
julia --project=julia/GPRidge.jl -e 'using Pkg; Pkg.test()' runs the
package tests.
Julia 1.10 or later is required (Project.toml). using GPRidge finds the
library in this order: the file named by GPRIDGE_LIBRARY, then the
libdir that pkg-config --define-prefix --variable=libdir gpridge
reports (libgpridge.so, .dylib or gpridge.dll in that directory).
It loads librgpot from the same directory first, then the library, and then
runs the ABI check. GPRidge.jl/src/capi.jl hard-codes the C ABI major and
minor it was written against (GPR_C_ABI_MAJOR, GPR_C_ABI_MINOR). The
check accepts a library with the same major and an equal or higher minor.
Functions¶
Purpose |
R |
Julia |
C entry point |
|---|---|---|---|
Library version |
|
|
|
ABI check |
|
|
|
Last error text, status name |
|
|
|
Backend, linear-algebra mode |
|
|
|
Atoms descriptor |
|
|
|
Atom counts |
|
same names |
|
GP model |
|
|
|
Prediction |
|
same names |
|
Model state |
|
same names |
|
Posterior solver (ABI 1.19) |
|
|
|
Rigid-null deflation (ABI 1.22) |
|
|
|
Test potentials |
|
|
|
Nudged elastic band |
|
|
|
Local band |
|
|
|
Periodic local band |
|
|
|
Dimer search |
|
|
|
R passes n_images and the other numbers as positional or named arguments
(neb_search(oracle, reactant, product, n_images, ...)). Julia takes
n_images and every option as a keyword (neb_search(oracle, reactant, product; n_images, ...)). An option left at NULL in R or nothing in Julia
keeps the library default from the matching \*_config_defaults call.
The posterior solver is a gpr_hssvd_backend_t value:
GPR_HSSVD_BACKEND_DEFAULT (0) keeps the library default, HS-SVD;
GPR_HSSVD_BACKEND_HSSVD (1) selects HS-SVD; GPR_HSSVD_BACKEND_CHOLESKY (2)
selects Cholesky. R reads the constants from gpr_constants(), Julia exports
them. model_init and model_set_hssvd_backend pass a whole number to the C
API unchanged, so -1, 3 or any other value outside the enum raises a
gpridge_error or a GPRidgeError with GPR_ERR_INVALID_ARG and leaves the
model as it was. TRUE / true selects HSSVD and FALSE / false selects
CHOLESKY, not DEFAULT. R refuses NA, a fraction, a string or a vector before
the call. model_hssvd_backend is FALSE / false only for CHOLESKY.
The packages also wrap gpr_minimize and its inner-step request
gpr_minimize_request_max_inner_steps (ABI 1.18; Julia’s minimize also takes
it as the max_inner_steps keyword), the GP-accelerated bands and their
potential variants, gpr_ocineb_search, model setters and updaters, runtime
configuration, and the index-certificate request. See the package exports
for the complete callable surface.
Modes, norms and results¶
R names the NEB modes as strings: "standard", "aie", "oie", "gp_aie",
"gp_oie" and "gp_local". Julia uses NEB_STANDARD, NEB_AIE,
NEB_OIE, NEB_GP_AIE, NEB_GP_OIE and NEB_GP_LOCAL. The convergence
norm of the periodic band is "l2", "linf" or "max_atom" in R and
NORM_L2, NORM_LINF or NORM_MAX_ATOM in Julia.
neb_search runs gp_aie and gp_oie when the coordinate length is
three times an atom count. Every atom moves and the model is the library
default. A length that is not a multiple of three is refused: the C entry
returns GPR_ERR_INVALID_ARG with a message that names
gpr_neb_search_gp, and the binding raises it as a gpridge_error (R) or
a GPRidgeError (Julia). gp_local is refused the same way and names
gpr_neb_search_local. Run a local band with neb_search_local.
The three band functions return the same fields: converged,
convergence_status, n_images (endpoints included), energies,
positions (one vector per image), barrier, oracle_calls,
oracle_calls_to_convergence, n_certificate_calls, index, certified
and outer_iterations. barrier is the energy of the highest image minus
the energy of the first image, in the energy unit of the oracle. index is
the negative-mode count of the stored index certificate, 0 when none was
stored (gpr_neb_report_t). dimer_search returns converged, stop,
stop_name, curvature, final_force_norm, n_force_calls, n_gp_calls,
n_iterations, energy, energy_zero_level, positions and
orientation.
Callbacks¶
A band oracle takes the coordinate vector and returns the energy and the
gradient dE/dR. In R it returns list(energy = e, gradient = g); in Julia it
returns the tuple (e, g). A dimer force function takes the coordinates and
the atomic numbers and returns the energy and the forces, which are -dE/dR.
In R it returns list(energy = e, forces = f); in Julia it returns
(e, f). The gradient or the forces have the length of the coordinate
vector. Use one energy unit and one length unit for the oracle, the
positions and the tolerances; the library does not convert.
An error in the callback, or a return value of the wrong shape, ends the
search. The binding then raises an ordinary R error or a Julia
ErrorException with the callback’s message. It is not a gpridge_error or
a GPRidgeError, because the failure is in the caller’s code. The R
wrapper checks that the energy is a single number and that the gradient has
the right length before it hands the values to C.
Errors¶
A failed library call raises gpridge_error in R. The condition is an R
error with the elements message (the C gpr_last_error_message()),
status and status_name (for example "GPR_ERR_INVALID_ARG"). In Julia
the exception is GPRidgeError with the fields status, status_name and
message. A negative actdist_fro in atoms_create, and a GP mode in
neb_search, are two calls that raise it; the package tests check both.
library(gpridge)
err <- tryCatch(
atoms_create(4L, actdist_fro = -1),
gpridge_error = function(e) e
)
err$status_name # "GPR_ERR_INVALID_ARG"
conditionMessage(err) # the text of last_error_message()
using GPRidge
err = try
atoms_create(; n_atoms=4, actdist_fro=-1.0)
catch caught
caught
end
println(err isa GPRidgeError) # true
println(err.status_name) # GPR_ERR_INVALID_ARG
Examples¶
The first block is the Muller-Brown band of r/gpridge/tests/testthat/test-capi.R.
The test expects converged to be true, nine images, and a barrier within 12
of 106 energy units.
library(gpridge)
oracle <- function(x) {
pot <- muller_brown(x)
list(energy = pot$energy, gradient = pot$gradient)
}
result <- neb_search(
oracle,
c(-0.558224, 1.441726), # reactant
c(0.623499, 0.028038), # product
n_images = 7L,
mode = "standard",
max_outer_iter = 400L,
conv_tol = 0.5,
verbose = 0L
)
stopifnot(result$n_images == 9L, abs(result$barrier - 106) < 12)
result$converged
result$barrier
The same band in Julia, from julia/GPRidge.jl/test/runtests.jl:
using GPRidge
oracle = function (x)
pot = muller_brown(x)
return pot.energy, pot.gradient
end
result = neb_search(
oracle,
[-0.558224, 1.441726],
[0.623499, 0.028038];
n_images=7,
mode=NEB_STANDARD,
max_outer_iter=400,
conv_tol=0.5,
verbose=0,
)
@assert result.n_images == 9 && abs(result.barrier - 106) < 12
println("converged ", result.converged, ", barrier ", result.barrier)
A GP model trained on Lennard-Jones pair energies and gradients. The package tests train on four geometries of a two-atom system and expect the prediction at the first training point to match its energy to 1e-2:
library(gpridge)
n_coords <- 6L
positions <- matrix(0, 4, n_coords)
energies <- numeric(4)
gradients <- matrix(0, 4, n_coords)
for (i in 1:4) {
x <- numeric(n_coords)
x[4] <- 1 + 0.15 * (i - 1)
x[5] <- 0.05 * (i - 1)
pot <- lennard_jones(x, 2L)
positions[i, ] <- x
energies[i] <- pot$energy
gradients[i, ] <- pot$gradient
}
model <- model_create("gp")
model_init(model, atoms_simple(2L), max_iter = 200L, report_level = 0L)
model_train(model, positions, energies, gradients)
stopifnot(abs(model_predict(model, positions[1, ])$energy - energies[1]) < 1e-2)
model_predict(model, positions[1, ])$energy
using GPRidge
positions = zeros(4, 6); energies = zeros(4); gradients = zeros(4, 6)
for i in 1:4
x = zeros(6)
x[4] = 1 + 0.15 * (i - 1)
x[5] = 0.05 * (i - 1)
pot = lennard_jones(x; n_atoms=2)
positions[i, :] = x
energies[i] = pot.energy
gradients[i, :] = pot.gradient
end
model = model_create(GPR_MODEL_GP)
model_init(model, atoms_simple(2); max_iter=200, report_level=0)
model_train(model, positions, energies, gradients)
prediction = model_predict(model, positions[1, :]).energy
@assert abs(prediction - energies[1]) < 1e-2
println("prediction ", prediction, ", observed ", energies[1])
A dimer search on the bond energy \(E = d^4/4 - d^2/2\) with
\(d = r - 3\), whose top is at \(r = 3\). The tests start at \(r = 3.3\) and expect
converged to be true, stop_name to be force_converged, a negative
curvature and a final bond length within 0.02 of 3:
library(gpridge)
force <- function(positions, atomic_numbers) {
dx <- positions[4] - positions[1]
dy <- positions[5] - positions[2]
dz <- positions[6] - positions[3]
r <- sqrt(dx * dx + dy * dy + dz * dz)
d <- r - 3
dE <- d^3 - d
scale <- -dE / r
list(
energy = 0.25 * d^4 - 0.5 * d^2,
forces = c(-scale * c(dx, dy, dz), scale * c(dx, dy, dz))
)
}
result <- dimer_search(
force, atoms_simple(2L),
positions = c(0, 0, 0, 0, 0, 3.3),
orientation = c(0, 0, -sqrt(0.5), 0, 0, sqrt(0.5)),
force_tol = 1e-3,
report_level = 0L
)
stopifnot(result$converged, result$curvature < 0)
result$stop_name
using GPRidge
function force(positions, atomic_numbers)
d3 = positions[4:6] .- positions[1:3]
r = sqrt(sum(abs2, d3))
d = r - 3
scale = -(d^3 - d) / r
return 0.25 * d^4 - 0.5 * d^2, vcat(-scale .* d3, scale .* d3)
end
result = dimer_search(
force, atoms_simple(2), [0.0, 0, 0, 0, 0, 3.3],
[0.0, 0, -sqrt(0.5), 0, 0, sqrt(0.5)];
force_tol=1e-3, report_level=0,
)
@assert result.converged && result.curvature < 0
println(result.stop_name)
Handles and threads¶
atoms_* and model_* return handles that wrap C objects. A finalizer
destroys each one when it is collected, and a call on a finalized handle
raises an error. Use a handle from one thread at a time and do not share one
model, atoms descriptor or result between simultaneous operations; the
C API page states the rule for the library.