C API¶
The C API is the header gpr/capi/gpridge_c.h and the shared library
libgpridge. It has three tiers. Tier 1 runs the dimer, NEB,
GP-accelerated NEB, local-band, periodic-band, OCINEB and minimizer
searches with a C callback as the oracle. Tier 2 trains a Gaussian process
or Student-t process and predicts from it. Tier 3 holds three analytical
test potentials. The header compiles as C99 and as C++, and
abi/gpridge_c.symbols lists every function it exports.
The page gives two complete examples, then the reference for the shared conventions (ownership, errors, threads, versioning) and for each group of functions. The function reference lists every function with its purpose, units, ownership and failure codes. The generated declaration reference for every function and struct is in the Doxygen pages:
The library converts no units. The header states the default of each configuration field next to it, and the periodic-band record states its lengths in Angstrom and its force in eV/Angstrom.
Scalar GP and Bayesian quadrature (ABI 1.17)¶
gpr_bq_config_defaults initializes gpr_bq_config_t, including its kernel
and hyperparameter treatment. gpr_bq_create constructs a scalar GP/BQ
handle, gpr_bq_reset reconfigures it, and gpr_bq_destroy releases it.
gpr_bq_dimension, gpr_bq_n_observations, and
gpr_bq_n_lengthscales query its current shape and training set.
Training uses gpr_bq_train_checked, which infers the integration box from
the training extrema, or gpr_bq_train_bounded_checked, which stores an
explicit box that refits and appended rows keep. gpr_bq_append_checked
appends rows and optionally refits. gpr_bq_fit_hyperparameters_checked fills gpr_bq_fit_report_t, the
marginal-likelihood fields plus failed_trials, and returns the fitted length
scales. failed_trials counts the optimizer trial points whose posterior could
not be built (a covariance that did not factor, or a non-positive leave-one-out
precision); each scored as an infinite objective. It is 0 for an ordinary fit,
and a fit in which every trial failed returns GPR_ERR_OPTIMIZER instead of a
report. Length scales are read
and changed with gpr_bq_get_lengthscales_checked and
gpr_bq_set_lengthscales_checked. The signal variance accessors are
gpr_bq_get_magn_sigma2 and gpr_bq_set_magn_sigma2; the additional nugget
accessors are gpr_bq_get_extra_sigma2 and gpr_bq_set_extra_sigma2.
gpr_bq_set_basis selects no, constant, or affine Bayes–Sard moments, or
GPR_BQ_BASIS_FOLLOW_CONFIG to follow use_prior_mean, and gpr_bq_get_basis
reports the active selection. The selected basis governs every integral, the
cumulative covariance, candidate ranking, batch selection, leave-one-out
calibration, prediction, and the posterior itself. A quadratic basis is not
provided.
gpr_bq_predict_batch_checked predicts scalar posterior means and variances.
For box measures, gpr_bq_kernel_mean_checked evaluates kernel means and
gpr_bq_kernel_double_integral_checked evaluates the kernel double integral.
gpr_bq_integrate_checked returns an integral mean and variance, while
gpr_bq_integrate_report_checked returns their full decomposition.
gpr_bq_integrate_measure_checked integrates against a Lebesgue box, the
uniform probability on a box, or a Gaussian measure, and
gpr_bq_integrate_uncertainty_checked does the same with the uncertainty
split by source. A product Matern kernel under a Gaussian measure with a
non-diagonal covariance is integrated as a joint mixture over the active scale
nodes. That mixture has a limit of 200000 joint nodes, which allows two
dimensions; a larger problem returns GPR_ERR_UNSUPPORTED and the caller
chooses another kernel or a diagonal covariance. The reported numerical
tolerance includes the error of the Matern scale mixture.
gpr_bq_integrate_cumulative_checked computes correlated cumulative
integrals, and gpr_bq_sample_cumulative_checked draws from that joint
posterior.
Active quadrature can rank points with
gpr_bq_candidate_variance_reduction_checked or greedily choose a batch with
gpr_bq_select_batch_candidates_checked. gpr_bq_calibrate_loo_checked
returns the leave-one-out calibration summary;
gpr_bq_calibrate_loo_scores_checked additionally writes every standardized
LOO score and reports how many were written.
A gpr_bq_t has one writer at a time. The writers are gpr_bq_reset, the
train, append and fit functions, every set function and gpr_bq_destroy. A
writer must not overlap any other call on the same handle, because the
library takes no lock on the handle. Calls on distinct handles may run on
different threads. A query function clears status and error on NULL and
preserves any prior error state on a live handle; a destroyed handle gives
GPR_ERR_NULL_HANDLE from a status function and 0 from a query function.
gpr_bq_destroy clears status and error on NULL or a live handle while
preserving a pending GPR_ERR_ORACLE, and a second gpr_bq_destroy sets
GPR_ERR_INVALID_ARG in gpr_last_status. When hyperparameter inference
fails, the call returns GPR_ERR_OPTIMIZER and the model keeps its previous
state. No other treatment is substituted.
Free-energy surrogate on collective variables (ABI 1.23)¶
A gpr_fes_t is a Gaussian process over a free energy \(F(s)\) on a
dimension-dimensional collective-variable space. gpr_fes_create builds
it from a gpr_model_config_t (NULL selects gpr_model_config_defaults)
and a gpr_fes_config_t (NULL selects gpr_fes_config_init), copying
both; gpr_fes_destroy releases it, and gpr_fes_dimension and
gpr_fes_n_observations report its shape. The prior is the
squared-exponential kernel of the scaled distance, with one length scale or,
when ard is 1, one per coordinate, around a constant mean equal to the mean
of the observed \(F\). Another kernel returns GPR_ERR_UNSUPPORTED, as do
const_sigma2 and the ZBL and force-field prior means. sigma2 and
jitter_sigma2 add to every \(F\) noise variance, in the unit of \(F\)
squared. Gradient components get their own added variance, one per
coordinate in the unit of \(F\) squared per unit of that coordinate
squared: the grad_noise_var argument of gpr_fes_create, or by default
(sigma2 + jitter_sigma2) over the squared standard deviation of the
training points along the coordinate, so a change of unit of one coordinate
leaves the predictions unchanged. magn_sigma2 > 0
fixes the signal variance, and SCG fits the signal variance and length
scales with max_iter, tol_func and tol_sol. The function it minimises
is the negative log marginal likelihood plus a maximum a posteriori
penalty: a half-Cauchy prior on the signal standard deviation, a
half-Student-t prior on each length scale over the standard deviation of
the training points along its coordinates, and a log barrier on a fitted
signal variance, weighted by \(\min(10^{-4} + 10^{-3} n, 0.5)\) for \(n\)
training rows.
gpr_fes_train_checked takes \(F\) at n_obs points with one noise
variance each, and optionally the gradient of \(F\) with per-component
noise variances and one presence flag per row. The surrogate does not see a
bias potential: a metadynamics bias, an umbrella restraint or an unweighted
histogram must be converted to \(F\) before training.
gpr_fes_predict_batch_checked returns the posterior mean of \(F\), its
gradient, and the latent posterior variance of \(F\), which excludes
observation noise. gpr_fes_noise_from_weights_checked turns relative
sample weights into noise variances that scale as the inverse weight, an
approximation that ignores correlation between samples.
gpr_fes_rate_path_checked estimates the overdamped Kramers-Langer rate
from path point reactant_index to product_index, with \(\kappa\) the
negative eigenvalue of \(\beta D H_\ddagger\) and \(D\) the diagonal
diffusion tensor whose dimension entries the call takes, each in the
squared unit of its variable per time. The saddle is the
stationary point of the posterior mean with one negative Hessian
eigenvalue. The search starts at the interior path point with the highest
mean and follows Hessian eigenvectors, uphill along the lowest mode and
downhill along the others, until the gradient in length-scale units falls
below saddle_tolerance times the prior standard deviation. When it does
not converge, or the stationary point it reaches has another inertia or
lies more than one length scale from the path or beyond either end, the
call returns GPR_ERR_NOT_CONVERGED. Each posterior draw then samples
\(F\) and its Hessian at the reactant and the saddle jointly, so the barrier
\(\Delta F = F_\ddagger - F_A\) carries the covariance between the two
values rather than the sum of their variances. A mean barrier that is not
positive returns GPR_ERR_UNSUPPORTED. A draw counts only when its barrier
is positive, \(H_A\) is positive definite and \(H_\ddagger\) has exactly
one negative eigenvalue \(\lambda_-\); when fewer than 90% of the draws
count, the call returns GPR_ERR_UNSUPPORTED and writes no report. The report holds means,
sample standard deviations and equal-tailed intervals over the accepted
draws, which come from a seeded SplitMix64 stream.
gpr_fes_config_t, gpr_fes_rate_config_t and gpr_fes_rate_report_t
begin with struct_size. gpr_fes_config_init and
gpr_fes_rate_config_init write the first min(out_size, sizeof) bytes of
the defaults and set struct_size to that count, and a call reads or writes
only the first struct_size bytes, so a caller built against a shorter
structure keeps working when fields are appended.
A gpr_fes_t has one writer at a time: gpr_fes_train_checked and
gpr_fes_destroy must not overlap another call on the same handle. A failed
train keeps the previous posterior. GPR_ERR_CHOLESKY means the training
covariance does not factor at the fitted hyperparameters and
GPR_ERR_OPTIMIZER that the fit diverged.
Example: a Muller-Brown band in C¶
The program below runs a nudged elastic band between two minima of the
Muller-Brown surface, with the surface as the oracle. The oracle receives
the coordinates and writes the energy and the gradient; the Muller-Brown
energy and coordinates are dimensionless. The same file is
examples/capi_neb_muller_brown.c, which the test suite builds and runs
as example_capi_neb_muller_brown.
/* SPDX-License-Identifier: MIT
* A nudged elastic band on the Muller-Brown surface through the C API.
*
* Build against an installed library:
* cc capi_neb_muller_brown.c $(pkg-config --cflags --libs gpridge) -lm
*/
#include <gpr/capi/gpridge_c.h>
#include <stdio.h>
/* The oracle: energy and gradient at x. A failed evaluation would write a
* non-finite energy; the search then rejects that trial. */
static void oracle(int n_coords, const double* x, double* energy,
double* gradient, void* user_data)
{
int* calls = (int*)user_data;
(void)n_coords;
++*calls;
gpr_potential_muller_brown(x, energy, gradient);
}
int main(void)
{
const double reactant[2] = {-0.558224, 1.441726};
const double product[2] = {0.623499, 0.028038};
double energies[9];
int calls = 0;
int i;
gpr_neb_config_t config;
gpr_neb_t path;
if (GPR_ABI_CHECK() != GPR_SUCCESS) {
fprintf(stderr, "%s\n", gpr_last_error());
return 1;
}
printf("gpridge %s, linear algebra: %s (%s)\n", gpr_version(),
gpr_backend_name(), gpr_linalg_mode());
config = gpr_neb_config_defaults();
config.mode = GPR_NEB_STANDARD;
config.verbose = 0;
config.max_outer_iter = 400;
config.conv_tol = 0.5;
path = gpr_neb_search(oracle, &calls, reactant, product, 2, 7, &config);
if (!path) {
fprintf(stderr, "NEB failed (%s): %s\n",
gpr_status_name(gpr_last_status()), gpr_last_error());
return 1;
}
gpr_neb_result_all_energies(path, energies, 9);
for (i = 0; i < gpr_neb_result_n_images(path); ++i)
printf("image %d E = %9.3f\n", i, energies[i]);
printf("converged %d after %d oracle calls, barrier %.2f\n",
gpr_neb_result_converged(path), calls, gpr_neb_result_barrier(path));
gpr_neb_result_destroy(path);
return 0;
}
To build it against an installed library, use the pkg-config file, which supplies the include path and the library:
cc examples/capi_neb_muller_brown.c $(pkg-config --cflags --libs gpridge) -lm
./a.out
The first line shows the installed library version, the linear-algebra
backend and the linear-algebra mode. The band has seven intermediate
images and two endpoints, so nine energies follow, then the convergence
flag, the number of oracle calls and the barrier. Use
gpr_neb_result_barrier(result) to get the forward barrier, the reported
saddle image energy relative to the reactant. The default Eigen build
produces this output:
gpridge X.Y.Z, linear algebra: eigen (reproducible)
image 0 E = -146.700
image 1 E = -93.589
image 2 E = -40.665
image 3 E = -45.294
image 4 E = -72.125
image 5 E = -79.414
image 6 E = -72.418
image 7 E = -89.835
image 8 E = -108.167
converged 1 after 163 oracle calls, barrier 106.03
The listing is the output of the block above on the Eigen build; the number of oracle calls and the last digits of the energies can differ on another backend. The block asserts only that the band converged with a barrier near 106. Image 2 sits on the saddle near (-0.82, 0.62), at -40.66, so the barrier above minimum A (-146.70) is 106.03. Image 5 lies next to the intermediate minimum near (-0.05, 0.47), at -80.77.
Example: a GP model in C¶
The Tier 2 functions train a Gaussian process on energies and gradients
and predict from it. The program trains on six points of a Lennard-Jones
pair (two atoms, six coordinates), predicts the energy, gradient and
variance at a seventh separation, appends one observation with
gpr_model_update, and checks the Hessian action against the Hessian. It
asserts each claim it prints.
#include <assert.h>
#include <gpr/capi/gpridge_c.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#define N_ATOMS 2
#define N_COORDS (3 * N_ATOMS)
#define N_OBS 6
/* Energy and gradient of a Lennard-Jones pair at the given separation. */
static void lj_pair(double separation, double* r, double* energy, double* g)
{
memset(r, 0, N_COORDS * sizeof *r);
r[3] = separation;
gpr_potential_lj(r, N_ATOMS, 1.0, 1.0, energy, g);
}
int main(void)
{
const double separations[N_OBS] = {0.95, 1.05, 1.15, 1.3, 1.5, 1.8};
double R[N_OBS * N_COORDS], E[N_OBS], G[N_OBS * N_COORDS];
double query[N_COORDS], g_exact[N_COORDS], e_exact;
double e_pred, g_pred[N_COORDS], var_e, var_g[N_COORDS];
double var_inside, var_far;
gpr_atoms_t atoms;
gpr_model_t model;
gpr_model_config_t config;
int i;
if (GPR_ABI_CHECK() != GPR_SUCCESS) return 1;
for (i = 0; i < N_OBS; ++i)
lj_pair(separations[i], R + i * N_COORDS, E + i, G + i * N_COORDS);
atoms = gpr_atoms_create_simple(N_ATOMS);
model = gpr_model_create(GPR_MODEL_GP);
if (!atoms || !model) {
fprintf(stderr, "%s\n", gpr_last_error_message());
return 1;
}
config = gpr_model_config_defaults();
config.report_level = 0;
if (gpr_model_init(model, &config, atoms) != GPR_SUCCESS ||
gpr_model_train(model, R, E, G, N_OBS, N_COORDS) != GPR_SUCCESS) {
fprintf(stderr, "%s\n", gpr_last_error_message());
return 1;
}
printf("observations %d, lengthscales %d, fit stop: %s\n",
gpr_model_n_observations(model), gpr_model_n_lengthscales(model),
gpr_model_fit_stop_reason(model));
lj_pair(1.2, query, &e_exact, g_exact);
gpr_model_predict(model, query, &e_pred, g_pred, N_COORDS);
gpr_model_predict_variance(model, query, &var_inside, var_g, N_COORDS);
printf("E exact %.5f predicted %.5f variance %.2e\n", e_exact, e_pred,
var_inside);
printf("dE/dx2 exact %.5f predicted %.5f\n", g_exact[3], g_pred[3]);
assert(fabs(e_pred - e_exact) < 1e-2);
lj_pair(3.0, query, &e_exact, g_exact);
gpr_model_predict_variance(model, query, &var_far, var_g, N_COORDS);
printf("variance at separation 3.0: %.2e\n", var_far);
assert(var_far > var_inside);
lj_pair(1.2, query, &e_exact, g_exact);
if (gpr_model_update(model, query, &e_exact, g_exact, 1, N_COORDS) !=
GPR_SUCCESS) {
fprintf(stderr, "%s\n", gpr_last_error_message());
return 1;
}
gpr_model_predict_full(model, query, &e_pred, g_pred, &var_e, var_g,
N_COORDS);
printf("after update: %d observations, variance at 1.2 %.2e\n",
gpr_model_n_observations(model), var_e);
assert(var_e < var_inside);
{
double H[N_COORDS * N_COORDS], v[N_COORDS], Hv[N_COORDS], dot;
int j;
for (i = 0; i < N_COORDS; ++i) v[i] = (i == 3) ? 1.0 : 0.0;
if (gpr_model_predict_hessian(model, query, H, N_COORDS) !=
GPR_SUCCESS ||
gpr_model_predict_hessian_action(model, query, v, Hv, N_COORDS) !=
GPR_SUCCESS) {
fprintf(stderr, "%s\n", gpr_last_error_message());
return 1;
}
for (i = 0; i < N_COORDS; ++i) {
dot = 0.0;
for (j = 0; j < N_COORDS; ++j) dot += H[i * N_COORDS + j] * v[j];
assert(fabs(dot - Hv[i]) < 1e-8);
}
printf("d2E/dx2^2 %.3f (H v = Hv checked)\n", H[3 * N_COORDS + 3]);
}
gpr_model_destroy(model);
gpr_atoms_destroy(atoms);
return 0;
}
A run prints the lines below. The energy prediction at separation 1.2 is within 0.01 of the exact value (the assertion), the variance grows far from the data, and the extra observation lowers the variance at its own point. The values come from this program on the Eigen build.
observations 6, lengthscales 1, fit stop: <reason>
E exact -0.89097 predicted -0.89697 variance 1.44e-04
dE/dx2 exact 2.21169 predicted 2.27691
variance at separation 3.0: 4.87e+00
after update: 7 observations, variance at 1.2 1.32e-04
d2E/dx2^2 9.668 (H v = Hv checked)
The library prints a diagnostic line starting with [hssvd] on standard
error during a train; it does not affect the result.
gpr_model_fit_iterations returns the optimizer iterations of the last
train. The count is rgmin’s SCG steps plus the L-BFGS fallback steps that
finish a stalled rgmin SCG fit. After a restarted marginal-likelihood fit the
count covers both passes. gpr_model_fit_stop_reason names why the fit
stopped: “budget” when an rgmin fit exhausts its iteration budget,
“library” when it does not, “restored scg point” when a rejected L-BFGS
fallback restores the SCG point, “wall-clock limit” when the wall is
already spent, “non-finite marginal likelihood” when a failed fit keeps
a non-finite input marginal likelihood, “unset” before any train, and
“missing” for a NULL handle.
Marginal likelihood, residual calibration and fixed-parameter appends¶
ABI 1.13 adds a complete low-level workflow for reproducible GP studies.
gpr_model_train_marginal_likelihood_checked fits the signal variance and
descriptor length scales by the Gaussian negative log marginal likelihood
alone. It uses every supplied row and disables hyperparameter-prior and
barrier terms; positivity remains the parameter domain, not a tuned prior.
The report returns the selected objective and its log-determinant and
quadratic components in physical output coordinates, together with physical
signal and noise variances, optimizer iteration count and number of length
scales. The iteration count is rgmin’s SCG steps plus the L-BFGS fallback
steps that finish a stalled rgmin SCG fit. The caller supplies
the length-scale output buffer and its extent.
gpr_model_calibrate_forces_checked takes positions and true held-out energy
gradients that were not used for training. For each Cartesian force component
it forms
The empirical coverage is the fraction with
abs(z) below the central-normal quantile for the requested nominal
probability. The calibration scale is exactly
sqrt(mean(z*z)), computed only from these held-out standardized residuals;
there is no floor, cap, prior or training-residual contribution. The report
also gives coverage after scaling posterior standard deviations by this
value. posterior_variance_scale records the model’s existing
training-residual variance multiplier, which this held-out calculation
removes from the public posterior variance before forming \(z_i\). Components
with exactly zero latent variance and exactly zero residual are deterministic
and carry no calibration information, so components excludes them. The call
does not introduce a variance floor.
gpr_model_calibrate_loo_checked evaluates every fitted energy and gradient
channel without an explicit holdout split. With \(\alpha=K^{-1}y\) and
\(q_i=[K^{-1}]_{ii}\), Rasmussen and Williams section 5.4.2 gives
\(y_i-\mu_{-i}=\alpha_i/q_i\), \(v_{-i}=1/q_i\), and therefore
\(z_i=\alpha_i/\sqrt{q_i}\). The implementation supports both the Cholesky
and HS-SVD posteriors and performs no oracle calls or model updates.
Both calibration calls fill gpr_calibration_report_t. In addition to the
same residual moments, scale and coverage fields, it reports mean Gaussian
log predictive density in physical output units. LOO sets
posterior_variance_scale to one because it uses the fitted covariance
directly. Both calls require a Gaussian-process model; Student-t models are
rejected because their predictive calibration is not Gaussian. The nominal
probability must also have a representable central Gaussian quantile.
gpr_model_append_fixed_checked appends complete energy-gradient rows while
holding the selected hyperparameters fixed. It accepts the append only when
the live Cholesky factor represents the old prefix and can be extended by the
block identity
It neither reruns hyperparameter optimization nor silently performs a full
factorization. An ineligible model returns GPR_ERR_UNSUPPORTED. Every
buffer-taking ABI 1.13 entry point takes the extent of each caller-owned
array.
Example: a local band and a periodic band¶
gpr_neb_search_local runs GPR_NEB_GP_LOCAL. The result is the same
opaque handle as the other band entries. A failure returns NULL and
leaves the reason in gpr_last_error_message(), which is the same string
as gpr_last_error(). gpr_local_band_config_defaults() supplies the
local knobs. The band report’s certified, index and
n_certificate_calls describe the index certificate;
n_certificate_calls is not part of oracle_calls_to_convergence.
/* SPDX-License-Identifier: MIT
* A local band on a one-atom bowl through the C API.
*
* Build against an installed library:
* cc capi_local_band.c $(pkg-config --cflags --libs gpridge) -lm
*/
#include <gpr/capi/gpridge_c.h>
#include <stdio.h>
static void oracle(int n_coords, const double* x, double* energy,
double* gradient, void* user_data)
{
int* calls = (int*)user_data;
int i;
double e = 0.0;
++*calls;
for (i = 0; i < n_coords; ++i) {
e += 0.5 * x[i] * x[i];
gradient[i] = x[i];
}
*energy = e;
}
int main(void)
{
const double reactant[3] = {0.4, 0.0, 0.0};
const double product[3] = {-0.2, 0.0, 0.0};
gpr_neb_config_t config;
gpr_local_band_config_t local;
gpr_neb_report_t report;
gpr_neb_t path;
int calls = 0;
if (GPR_ABI_CHECK() != GPR_SUCCESS) {
fprintf(stderr, "%s\n", gpr_last_error_message());
return 1;
}
printf("gpridge %s, local band\n", gpr_version());
config = gpr_neb_config_defaults();
config.verbose = 0;
config.max_outer_iter = 2;
config.conv_tol = 1.0;
local = gpr_local_band_config_defaults();
local.initial_sweep = 0;
local.inner_max = 1;
local.refit_iters = 0;
path = gpr_neb_search_local(oracle, &calls, NULL, NULL, reactant, product,
3, 1, &config, &local);
if (!path) {
fprintf(stderr, "local band failed (%s): %s\n",
gpr_status_name(gpr_last_status()), gpr_last_error_message());
return 1;
}
report.struct_size = sizeof report;
if (gpr_neb_result_report(path, &report) != GPR_SUCCESS) {
fprintf(stderr, "%s\n", gpr_last_error_message());
gpr_neb_result_destroy(path);
return 1;
}
printf("images %d oracle %ld certificate %ld index %d certified %d\n",
gpr_neb_result_n_images(path), report.oracle_calls,
report.n_certificate_calls, report.index, report.certified);
gpr_neb_result_destroy(path);
return report.oracle_calls >= report.oracle_calls_to_convergence +
report.n_certificate_calls
? 0
: 1;
}
The suite builds and runs this program as example_capi_local_band.
gpr_neb_search_periodic is that local band on a slab: uniform springs, a
linear path, and the whole band under the force tolerance, which is how
GPLocalBand runs. gpr_periodic_band_config_defaults() is that record.
The local knobs stay on gpr_local_band_config_t, and the cell is the
box argument. The search does not certify. Call
gpr_neb_request_index_certificate first when the index is wanted; the
report then carries certified, index and n_certificate_calls.
/* SPDX-License-Identifier: MIT
* A periodic local band through the C API: one atom slides across a
* frozen neighbour in an orthorhombic cell. The search itself does not
* certify; the report's certificate fields stay at zero unless
* gpr_neb_request_index_certificate was called first.
*
* Build against an installed library:
* cc capi_periodic_band.c $(pkg-config --cflags --libs gpridge) -lm
*/
#include <gpr/capi/gpridge_c.h>
#include <stdio.h>
#define N_ATOMS 2
#define N_COORDS (3 * N_ATOMS)
#define N_IMAGES 3
/* Not the 25 A vacuum box the library treats as isolated. */
static const double kCell[9] = {8.0, 0.0, 0.0, 0.0, 8.0, 0.0, 0.0, 0.0, 8.0};
/* A bowl. The cell is the band's periodic cell; this oracle is the same
* quadratic the local-band example uses, so the two languages agree. */
static void oracle(int n_coords, const double* x, double* energy,
double* gradient, void* user_data)
{
int i;
double e = 0.0;
(void)user_data;
for (i = 0; i < n_coords; ++i) {
e += 0.5 * x[i] * x[i];
gradient[i] = x[i];
}
*energy = e;
}
int main(void)
{
/* The second atom is fixed. The first slides from one side of it to
* the other, through the periodic cell. */
const double reactant[N_COORDS] = {0.4, 0.0, 0.0, 0.2, 0.0, 0.0};
const double product[N_COORDS] = {-0.3, 0.0, 0.0, 0.2, 0.0, 0.0};
const int frozen[N_ATOMS] = {0, 1};
const int numbers[N_ATOMS] = {1, 1};
gpr_atoms_config_t atoms_cfg;
gpr_atoms_t atoms;
gpr_periodic_band_config_t band;
gpr_neb_report_t report;
gpr_neb_t path;
double energies[N_IMAGES + 2];
double image[N_COORDS];
int i;
if (GPR_ABI_CHECK() != GPR_SUCCESS) {
fprintf(stderr, "%s\n", gpr_last_error_message());
return 1;
}
printf("gpridge %s, periodic band\n", gpr_version());
atoms_cfg = gpr_atoms_config_defaults();
atoms_cfg.n_atoms_total = N_ATOMS;
atoms_cfg.is_frozen = frozen;
atoms_cfg.atomic_nrs = numbers;
atoms = gpr_atoms_create(&atoms_cfg);
if (!atoms) {
fprintf(stderr, "%s\n", gpr_last_error_message());
return 1;
}
band = gpr_periodic_band_config_defaults();
band.verbose = 0;
band.fmax = 0.05;
band.steps = 40;
band.convergence_norm = GPR_NORM_L2;
path = gpr_neb_search_periodic(oracle, NULL, atoms, kCell, reactant,
product, N_COORDS, N_IMAGES, &band, NULL);
if (!path) {
fprintf(stderr, "periodic band failed (%s): %s\n",
gpr_status_name(gpr_last_status()), gpr_last_error_message());
gpr_atoms_destroy(atoms);
return 1;
}
report.struct_size = sizeof report;
if (gpr_neb_result_report(path, &report) != GPR_SUCCESS ||
gpr_neb_result_all_energies(path, energies, N_IMAGES + 2) !=
GPR_SUCCESS) {
fprintf(stderr, "%s\n", gpr_last_error_message());
gpr_neb_result_destroy(path);
gpr_atoms_destroy(atoms);
return 1;
}
for (i = 0; i < gpr_neb_result_n_images(path); ++i) {
printf("image %d E = %9.4f\n", i, energies[i]);
if (gpr_neb_result_image_positions(path, i, image, N_COORDS) !=
GPR_SUCCESS) {
fprintf(stderr, "%s\n", gpr_last_error_message());
gpr_neb_result_destroy(path);
gpr_atoms_destroy(atoms);
return 1;
}
/* The frozen atom stays on the reactant. */
if (image[3] != product[3] || image[4] != product[4] ||
image[5] != product[5]) {
fprintf(stderr, "frozen atom moved on image %d\n", i);
gpr_neb_result_destroy(path);
gpr_atoms_destroy(atoms);
return 1;
}
}
printf(
"converged %d oracle %ld certificate %ld index %d certified %d "
"barrier %.4f\n",
gpr_neb_result_converged(path), report.oracle_calls,
report.n_certificate_calls, report.index, report.certified,
report.barrier);
gpr_neb_result_destroy(path);
gpr_atoms_destroy(atoms);
/* The search was not asked to certify. */
return report.n_certificate_calls == 0 && report.certified == 0 ? 0 : 1;
}
The suite builds and runs this program as example_capi_periodic_band.
Reference¶
Conventions¶
Arrays are flat and row-major. A coordinate vector for \(N\) atoms is
[x1, y1, z1, x2, ...]with \(3N\) entries. A set of \(n\) observations is an \(n \times\)n_coordsarray, one row per observation.n_coordsis three times the number of moving atoms.gpr_model_trainchecks it against the atoms handle: a mismatch isGPR_ERR_INVALID_ARGwith the message “n_coords must equal three times the moving atom count”. The other model functions check it against the value of the training call.In
gpr_atoms_config_t,atom_typesholds dense type indices (0, 1, …) that are smaller thann_atoms_total; atomic numbers belong inatomic_nrs. An index that is negative or not belown_atoms_totalis rejected withGPR_ERR_INVALID_ARG.A gradient callback (
gpr_oracle_fn) writes the energy and the gradient. A force callback (gpr_force_fn,gpr_force_with_uncertainty_fn) writes the force and also receives the atomic numbers and the cell.Handles are opaque pointers:
gpr_model_t,gpr_atoms_t,gpr_neb_tandgpr_potential_t. In Fortran they aretype(c_ptr).
Ownership and lifecycle¶
Each constructor has a matching destroy call that accepts NULL.
Created by |
Destroyed by |
|---|---|
|
|
|
|
|
|
any NEB search entry point |
|
Outputs are caller-allocated arrays whose sizes the header states. The
library copies what it keeps: gpr_model_init copies the atoms
descriptor, and gpr_model_train and gpr_model_update copy the
observations, so the caller may free its arrays after the call. A
gpr_atoms_config_t passed to gpr_atoms_create is read during that call;
its is_frozen and atom_types arrays belong to the caller.
gpr_atoms_simple(n) returns the descriptor for n identical moving atoms
with one pair type, and gpr_atoms_create_simple(n) creates the handle from it.
A GP model goes through these steps: created, initialised
(gpr_model_init, which can be called again to reconfigure: the model is
rebuilt, so it is untrained and fits from the library defaults like a fresh
one), trained (gpr_model_train, which replaces the training data) and
updated (gpr_model_update, which appends observations and
optimises the hyperparameters again on the whole set; it is not a rank-one
update of the factorisation). A call out of order returns
GPR_ERR_INVALID_ARG (train before init) or GPR_ERR_NOT_TRAINED
(predict or update before train).
Errors¶
A function whose result is a status returns GPR_SUCCESS (0) or a
negative code, and a constructor returns NULL. The accessors that return
a count, a flag or a rank return that value instead: gpr_atoms_n_moving,
gpr_atoms_n_pairtypes, gpr_model_n_observations,
gpr_model_n_lengthscales, gpr_model_fit_iterations,
gpr_neb_result_converged, gpr_neb_result_n_images,
gpr_neb_result_oracle_calls, gpr_neb_result_outer_iterations,
gpr_neb_result_max_energy_image, gpr_backend_requires_mpi, gpr_mpi_initialized, gpr_mpi_world_rank,
gpr_mpi_world_size, gpr_omp_max_threads, gpr_training_product_configured.
A status-returning call, a constructor, a NULL-handle call to a
usable_or_null accessor, or a destroy call on NULL or a live handle
clears the thread’s message and status at entry (except that all destroy
calls preserve a pending GPR_ERR_ORACLE during cleanup), so after a
failure gpr_last_error_message() (the same string as gpr_last_error())
and gpr_last_status() describe that failure until the next such call;
a successful call to a count, flag or rank accessor on a live handle leaves
the thread’s status and message untouched. A NULL from a constructor
leaves its reason the same way. Both are thread-local.
No call aborts the process: C++ exceptions stop at the boundary and become a
status.
Status |
Value |
Meaning |
|---|---|---|
|
0 |
The call succeeded |
|
-1 |
A NULL or dead model or NEB-result handle, a dead atoms or potential handle, a NULL potential in the two force evaluators, or a NEB result with no path. A required NULL atoms or potential argument of a search is |
|
-2 |
A pointer, size or value is out of range |
|
-3 |
The model has no training data |
|
-4 |
Memory allocation failed |
|
-5 |
A covariance factor or Schur certificate failed, or a |
|
-6 |
A marginal-likelihood fit threw a |
|
-7 |
|
|
-8 |
The problem exceeds an index limit (LP64 ScaLAPACK, MKL) |
|
-9 |
The oracle failed past the bound the search tolerates |
|
-10 |
A feature, library, provider or CPU extension is missing |
|
-11 |
Header and library ABI versions disagree |
|
-12 |
A query’s posterior energy std exceeds the caller’s |
|
-13 |
Inputs that must share a unit were computed in different ones: |
|
-99 |
Any other failure; the message names it |
GPR_ERR_NULL_HANDLE is a direct return, never an exception mapping.
Which pointer produces it depends on the family.
Model status calls go through
guard_model, which returnsGPR_ERR_NULL_HANDLEfor aNULLmodel and for a model that is not in the live set.gpr_model_predict_energy_variance_intervalandgpr_model_get_noise_floor_reportare the exception: each returnsGPR_ERR_NULL_HANDLEfor aNULLmodel and does not test liveness.gpr_model_initreturnsGPR_ERR_INVALID_ARGfor aNULLatoms handle andGPR_ERR_NULL_HANDLEwhen the atoms handle is not live.guard_nebreturnsGPR_ERR_NULL_HANDLEfor aNULLNEB result and for one that is not live.gpr_neb_result_reportuses it.gpr_neb_result_image_positions,gpr_neb_result_image_energyandgpr_neb_result_all_energiesuse it and also returnGPR_ERR_NULL_HANDLEwhen the live result has no path.gpr_potential_forceandgpr_potential_force_with_uncertaintyreturnGPR_ERR_NULL_HANDLEfor aNULLpotential and for one that is not live.reject_dead_atomsandreject_dead_potentialreturnGPR_ERR_NULL_HANDLEonly for a non-null handle that is not live. ANULLatoms or potential argument is left to the caller. Where that argument is required, the dimer, minimizer and NEB searches then returnGPR_ERR_INVALID_ARG.gpr_neb_search_local,gpr_neb_search_periodicand their potential variants allow aNULLatoms handle (every coordinate moves).The accessors that return a count, a flag or a rank use
usable_or_null. PassingNULLclearsgpr_last_status()andgpr_last_error()toGPR_SUCCESSand returns the sentinel (0, -1,"missing"orGPR_MODEL_GP); passing a live handle preserves any prior status and error message. A handle that is not live setsGPR_ERR_NULL_HANDLEand returns that sentinel.The destroy calls return nothing. Destroying
NULLor a live handle clearsgpr_last_status()andgpr_last_error()toGPR_SUCCESS, while preserving a pendingGPR_ERR_ORACLEduring cleanup. Destroying a handle that is not live frees nothing and setsGPR_ERR_INVALID_ARGingpr_last_status().
gpr_status_name(status) gives the
name of a code. gpr_last_error_copy(buf, n) copies the message into a
caller buffer with snprintf semantics: the copy is terminated when
n > 0, and a return value of at least n means it was cut.
Exceptions. A function that returns a status, and a constructor that
returns NULL, runs inside one handler that turns a C++ exception into a
status (status_from_exception in gpr/capi/gpridge_c.cpp). The
handler tries the types in the order below and the first match wins. The
message is the exception’s what() string, except for std::bad_alloc and a
non-standard exception, whose messages are fixed.
Exception thrown |
Status |
Message |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
any other |
|
|
any other |
|
|
any other |
|
|
anything not derived from |
|
|
“Any other std::exception” includes std::runtime_error,
std::out_of_range, std::logic_error and every other class not listed
above. No exception maps to GPR_ERR_NULL_HANDLE, GPR_ERR_NOT_TRAINED or
GPR_ERR_ABI; the functions return those directly after their own checks.
GPR_ERR_UNSUPPORTED is also a direct return everywhere except in the six
functions listed below, which turn a caught exception into it. An oracle
failure is a C callback that writes a non-finite value. The adapter throws a
std::runtime_error and sets a flag (throw_oracle_failure).
When an exception leaves a search that ran with that flag set, the search
wrapper marks the calling thread (run_search), and
the handler then reports any std::exception that is not one of the first
six rows as GPR_ERR_ORACLE (the std::exception clause of
status_from_exception).
The two Bayesian quadrature rows apply to the gpr_bq_* functions that build
a posterior: gpr_bq_train_checked, gpr_bq_train_bounded_checked,
gpr_bq_append_checked and gpr_bq_fit_hyperparameters_checked, and on a
trained model gpr_bq_set_lengthscales_checked, gpr_bq_set_magn_sigma2,
gpr_bq_set_extra_sigma2 and gpr_bq_set_basis. GPR_ERR_CHOLESKY means
that the covariance did not factor at the hyperparameters the call uses.
GPR_ERR_OPTIMIZER means that hyperparameter inference failed in another
way, as when every optimizer trial failed. Either way the model keeps its
previous state.
Nine functions have a try block of their own ahead of the common
handler. Each catches the types in its row, in the order shown, and returns
the status with the exception’s what() as the message. An exception that
it does not catch, including one that is not derived from std::exception,
leaves the block and reaches the common handler, so it follows the table
above. None of the nine consults the oracle mark: a fit, a factor, a library
load, a package check or a Bayesian quadrature call does not run through the
search wrapper.
Function (the |
Catches |
Status |
|---|---|---|
|
|
|
|
any other |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
as the table above |
|
any other |
|
|
|
|
|
any other |
|
Four details of the table. First, the interval function’s try block
covers only the call to tryGateEnergyVarianceInterval,
and a std::bad_alloc thrown inside
it is caught by the std::exception clause and gives GPR_ERR_INTERNAL,
not GPR_ERR_ALLOC. Second, the noise-floor function catches only
std::runtime_error, so a std::domain_error thrown there (a
std::logic_error, not a std::runtime_error) reaches the common handler
and gives GPR_ERR_INVALID_ARG; the interval function maps the same type to
GPR_ERR_CHOLESKY. Third, gpr_check_model_package sends
std::invalid_argument and std::length_error to GPR_ERR_UNSUPPORTED,
where gpr_set_training_product rethrows them. Fourth, the other
GPR_ERR_UNSUPPORTED returns of the interval and noise-floor functions
(the GPR_ERR_UNSUPPORTED returns before those catches) are direct returns for a model
without the HS-SVD MAP factor, not caught exceptions.
For gpr_model_train_marginal_likelihood_checked, the try block holds the
hyperparameter setup and the marginal-likelihood fit. A fit that returns
without throwing but with a non-finite objective, or with a different number
of length scales than the model has, also returns GPR_ERR_OPTIMIZER
(the check of fitted.objective and fitted.length_scales after
optimizeMarginalLikelihood). Every other exception from that fit
falls through to the table above: std::bad_alloc gives GPR_ERR_ALLOC,
std::length_error gives GPR_ERR_SIZE_LIMIT, std::invalid_argument and
std::domain_error give GPR_ERR_INVALID_ARG, and the other
std::logic_error classes and non-standard exceptions give
GPR_ERR_INTERNAL. A fit never gives GPR_ERR_ORACLE. No other function
returns GPR_ERR_OPTIMIZER. The gpr_bq_* functions that build a posterior
also return it when hyperparameter inference fails.
Three other places in the file catch an exception without turning it into a
status. run_search sets the oracle mark
and rethrows. set_error keeps an empty
message when the copy of the message itself fails to allocate.
gpr_model_n_lengthscales returns a
count, not a status, and returns 0 for any exception.
The program below runs each of these on the library. It asserts what it prints.
#include <assert.h>
#include <gpr/capi/gpridge_c.h>
#include <math.h>
#include <stdio.h>
typedef struct {
int calls;
gpr_lj_params_t lj;
} flaky_state;
/* A Lennard-Jones oracle that fails on its third call. */
static void flaky(int n_coords, const double* x, double* energy,
double* gradient, void* user_data)
{
flaky_state* state = (flaky_state*)user_data;
gpr_oracle_lj(n_coords, x, energy, gradient, &state->lj);
if (++state->calls == 3) *energy = NAN;
}
int main(void)
{
char copy[64];
size_t length;
int status, converged, n_calls;
flaky_state state = {0, {2, 1.0, 1.0}};
const double r0[6] = {0, 0, 0, 0, 0, 1.3};
double r_final[6], e_final, g_final[6];
gpr_atoms_t atoms;
gpr_minimize_config_t config;
/* A status-returning call reports through its result. */
status = gpr_model_train(NULL, NULL, NULL, NULL, 0, 0);
printf("%s (%d): %s\n", gpr_status_name(status), status,
gpr_last_error_message());
assert(status == GPR_ERR_NULL_HANDLE);
assert(gpr_last_status() == status);
/* A constructor returns NULL and leaves its reason in the same place. */
atoms = gpr_atoms_create(NULL);
printf("gpr_atoms_create(NULL): %s, %s\n", atoms ? "handle" : "NULL",
gpr_status_name(gpr_last_status()));
assert(atoms == NULL && gpr_last_status() == GPR_ERR_INVALID_ARG);
/* The copy is cut to the buffer and always terminated. */
length = gpr_last_error_copy(copy, 16);
printf("message length %zu, copied \"%s\"\n", length, copy);
assert(length > 15);
/* The next call that returns a status clears message and status. */
atoms = gpr_atoms_create_simple(2);
assert(atoms != NULL && gpr_last_status() == GPR_SUCCESS);
assert(gpr_last_error_message()[0] == '\0');
/* gpr_minimize stops at the first failed evaluation. */
config = gpr_minimize_config_defaults();
status = gpr_minimize(flaky, &state, r0, 6, atoms, &config, r_final,
&e_final, g_final, &converged, &n_calls);
printf("gpr_minimize: %s after %d oracle calls\n",
gpr_status_name(status), state.calls);
assert(status == GPR_ERR_ORACLE && state.calls == 3);
gpr_atoms_destroy(atoms);
return 0;
}
Oracle failures¶
A callback reports a failed evaluation by writing a non-finite energy or
any non-finite force or gradient component. The dimer and NEB searches
treat it as a rejected trial: no training row, a shorter next step. More
than eight consecutive failures, or a failure the search cannot step
around (an endpoint or an image of the initial band, which have no
measured state to fall back to), returns GPR_ERR_ORACLE. gpr_minimize
has no rejected-trial path and returns GPR_ERR_ORACLE at the first
failure, as the program above shows. A call to gpr_potential_force on a
handle whose callback fails returns GPR_ERR_ORACLE as well.
Threads¶
A handle is used by one thread at a time; distinct handles may be used
from different threads at once. The error message and status are
thread-local. The runtime configuration calls (Runtime configuration
below) are process-wide: make them before a search starts and not while
one runs. The oracle of a search may run on a thread other than the
caller’s, so a callback keeps its state behind user_data and does not
use thread-local state of the calling thread.
Searches¶
Entry point |
Callback |
Outcome |
|---|---|---|
|
|
|
|
|
curvature and call counts |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
final point, converged flag, calls |
A dimer search that stops without meeting the force criterion returns
GPR_SUCCESS with converged 0; stop says why (GPR_DIMER_STOP_*).
gpr_potential_from_force turns a gpr_force_fn into a potential handle
for the report entry point.
The dimer entry points take a gpr_dimer_config_t. gpr_dimer_config_defaults()
returns one with the library defaults, which you then edit; its
es_use_adaptive_threshold field (default 0) selects a fixed EMD trust
threshold (es_threshold, default 1.2) or the adaptive one
(es_t_min, es_delta_explore, es_half_life, es_adaptive_A and
es_adaptive_floor).
gpr_potential_force evaluates a potential handle once and writes the
force and the energy. gpr_potential_force_with_uncertainty does the same
and also returns energy_noise_rms and force_noise_rms; either may be
NULL.
gpr_minimize uses the gradient the GP predicts only to propose a stop.
converged is set when an actual oracle evaluation at that exact position
has gradient norm under conv_tol. On success R_final, E_final and
G_final are always an exact oracle evaluation at R_final (never a
surrogate prediction or an averaged near-coincident row): the converged
point, or the lowest-energy oracle evaluation when the search did not
converge. config.max_iter bounds outer surrogate-relaxation cycles, each
running up to 200 inner surrogate steps, or up to the cap that
gpr_minimize_request_max_inner_steps (ABI 1.18) set for the next call on
the calling thread. The C entry calls
gpr::optim::gp_minimize with no training policy, so the initial point
is measured before any surrogate step, and a point is measured before it
is reported. G_final, converged and n_oracle_calls may be NULL;
R_final and E_final may not.
Reports¶
Both report structs are versioned by size. Zero the struct, then set
struct_size to sizeof the struct before the call; the library writes
only the fields that fit in the size the caller gave.
gpr_dimer_report_t report;
memset(&report, 0, sizeof report);
report.struct_size = sizeof report;
report.max_oracle_calls = 200; /* an input: the budget, 0 for none */
gpr_dimer_report_t.max_oracle_calls is read as a budget before the
search starts and is never exceeded. A force stop is reported converged only
after a Cartesian stencil at the stopped midpoint measures exactly one
negative mode; otherwise converged is 0 and stop is
GPR_DIMER_STOP_UNCERTIFIED_FORCE_STOP (ABI 1.10). The certificate_step
field (ABI 1.5) is an input: the stencil displacement, with 0 for the
library step. The report carries certified and n_certificate_calls.
gpr_neb_result_convergence_status distinguishes a band that met the
force tolerance from one that stopped at the resolution of its model.
gpr_neb_result_image_positions and gpr_neb_result_image_energy return
the positions and the energy of one image, and gpr_neb_result_all_energies
returns every image energy. gpr_neb_result_report fills a gpr_neb_report_t
from any NEB result:
convergence, whether a GP ran (gp_used), the band’s oracle calls with and
without the validation pass, every callback evaluation (callback_calls),
hyperparameter refits, both barriers, the OCINEB dimer accounting and, from
ABI 1.6, the index certificate (certified, index, n_certificate_calls).
ABI 1.25 appends prior_observations, the rows loaded from a seed. They are
not part of oracle_calls. A caller that sets struct_size from an older
header still receives the fields that fit.
GP-accelerated NEB and OCINEB¶
gpr_neb_search and gpr_neb_search_potential run GPR_NEB_STANDARD,
GPR_NEB_AIE and GPR_NEB_OIE without a surrogate. GPR_NEB_GP_OIE and
GPR_NEB_GP_AIE, including the mode from gpr_neb_config_defaults, run
when n_coords is a multiple of 3. gpr_neb_search builds all-moving
atoms with gpr_atoms_create_simple and calls gpr_neb_search_gp, using
the gprn GP settings. It rejects a GP mode only when n_coords is not
a multiple of 3, returning NULL with GPR_ERR_INVALID_ARG and the
message kGpModeWithoutGp. gpr_neb_search_potential requires a positive
multiple of 3 for every mode, and a non-null box and atomic_nrs; a GP
mode then builds all-moving atoms from atomic_nrs, with one atom type per
element in order of first appearance as the gprn NEB reader assigns them,
and calls gpr_neb_search_gp_potential. Both reject GPR_NEB_GP_LOCAL with
GPR_ERR_INVALID_ARG and the message kLocalModeEntry. On the potential
entry the length check runs first, so a local mode whose length is not a
multiple of 3 fails that check instead.
GPR_NEB_STANDARD, GPR_NEB_AIE and GPR_NEB_OIE on gpr_neb_search
accept any positive n_coords, including a length that is not a multiple
of three. The plain entries used to refuse every GP mode. Passing
GPR_NEB_GP_OIE with a multiple of three now runs the search. That change
added no C symbol and no struct field, so it did not itself raise the ABI
minor.
gpr_neb_search_gp is the entry that takes an atoms handle and a
gpr_model_config_t:
int is_frozen[N] = {1, 1, /* ... */ 0}; /* the last atom moves */
gpr_atoms_config_t desc = gpr_atoms_config_defaults();
desc.n_atoms_total = N;
desc.is_frozen = is_frozen;
gpr_atoms_t atoms = gpr_atoms_create(&desc);
gpr_neb_config_t config = gpr_neb_config_defaults();
config.mode = GPR_NEB_GP_OIE;
gpr_neb_t band = gpr_neb_search_gp(oracle, &state, atoms, NULL, R_initial,
R_final, 3 * N, 5, &config);
gpr_neb_report_t report;
memset(&report, 0, sizeof report);
report.struct_size = sizeof report;
gpr_neb_result_report(band, &report); /* report.gp_used == 1 */
The coordinates hold every atom of the handle: the oracle receives and
returns \(3N\) values, frozen atoms stay at their R_initial positions, the
band moves the others, and gpr_neb_result_image_positions returns full
images. atom_types sets the kernel’s pair types, frozen atoms within
actdist_fro enter the kernel (0 selects 30.3 Angstrom), and atomic
numbers, when given, key the band’s contact floor. A NULL model selects
the GP settings of the gprn NEB driver (sigma2 and jitter_sigma2
1e-4); a model config replaces them field by field, so start it from
gpr_model_config_defaults(), which uses those same noise defaults.
When use_idpp is nonzero on gpr_neb_config_t, sequential IDPP is the
library default, matching GPNEBConfig::use_sidpp. Call
gpr_neb_request_sidpp(0) before a search to select classic IDPP, or pass 1
to select SIDPP explicitly. The thread-local request is consumed by that
search even when its arguments fail validation. The request has no effect on
gpr_neb_search_periodic or gpr_neb_search_periodic_potential: a periodic
band takes its initializer from gpr_periodic_band_config_t::initial alone,
and those searches still consume the request. Values other than 0 or 1 fail
the request with GPR_ERR_INVALID_ARG.
gpr_neb_search_gp_potential takes a potential handle and an optional
box; a periodic box also sets the band’s and the kernel’s minimum-image
lattice. gpr_ocineb_search runs the same band with the minimum-mode dimer
bursts on the climbing image that gprn hands over to (gpr_ocineb_config_t,
from gpr_ocineb_config_defaults()). The suite runs all three on a
Lennard-Jones adatom hopping between hollows of a frozen layer
(test_capi_gp_neb, test_fortran_gp_neb): each converges on the bridge
saddle in fewer oracle calls than plain climbing-image NEB.
GP model¶
Tier 2 is the model of the second example. The functions group as follows.
Group |
Functions |
|---|---|
Lifecycle |
|
Training |
|
Prediction |
|
Noise floor |
|
Extent-checked |
|
Calibration |
|
Derivatives |
|
Kernel support |
|
Random features |
|
Rigid-null deflation |
|
Prediction parts |
|
Hyperparameters |
|
Timing |
|
Rules that the functions share:
gpr_model_config_defaults()is the starting point of agpr_model_config_t.gpr_model_initrejectsGPR_OPT_FACTORIZED, which names no optimiser the library implements, withGPR_ERR_INVALID_ARG.GPR_MODEL_GPandGPR_MODEL_TP(Student-t process) share the functions.gpr_model_tp_prefactoris specific to the Student-t model and valid after training.gpr_model_predict_varianceandgpr_model_predict_fullreturn the variance of the energy and of each gradient component.gpr_model_predict_batchtakesn_queriesrows and acceptsNULLfor both variance outputs to skip them.The plain training and prediction calls cannot see how long a caller’s buffers are: a buffer shorter than
n_obs * n_coords(orn_coords, orn_queries * n_coords) is read or written past its end. The_checkedforms (ABI 1.11) take the length of each buffer in doubles after its pointer and returnGPR_ERR_INVALID_ARGwith the buffer named ingpr_last_error()when the call would pass it, without writing. The needs are \(n_{\mathrm{obs}} n_{\mathrm{coords}}\) forRandG, \(n_{\mathrm{obs}}\) forE,n_coordsfor a query, its gradient and variance gradient, \(n_{\mathrm{queries}} n_{\mathrm{coords}}\) for the batchR_queries,G_outandvar_G_out, andn_queriesfor the batchE_outandvar_E_out. ANULLpointer is not measured and its length is ignored; otherwise a call behaves as the unchecked call of the same name. The FortranGPModeltype calls the checked forms.gpr_model_predict_hessianfills a symmetric row-major \(n_{\mathrm{coords}} \times n_{\mathrm{coords}}\) matrix with the dense posterior-mean Hessian.gpr_model_predict_hessian_actionapplies that operator to one vector. A model whose mean Hessian is refused returnsGPR_ERR_UNSUPPORTED. The checked formgpr_model_predict_hessian_checked(ABI 1.24) measuresR_queryandH_outbefore writing the matrix.gpr_model_prediction_supportedreturns the same correlation-support decision used by the GP active-learning loops. It adds no distance or uncertainty threshold. An untrained model reports zero. The checked form measures the query before writing the result.gpr_model_get_alphaneeds a buffer of at least \(n_{\mathrm{obs}} (1 + n_{\mathrm{coords}})\) doubles and writes nothing to a smaller one.gpr_model_fit_stop_reasonreturns a static string:budgetwhen an rgmin fit exhausts its iteration budget,librarywhen it does not,restored scg pointwhen a rejected L-BFGS fallback restores the SCG point,wall-clock limitwhen the wall is already spent,non-finite marginal likelihoodwhen a failed fit keeps a non-finite input marginal likelihood,unsetbefore any train andmissingfor aNULLhandle. The example above stops withlibrary.gpr_train_phase_resetzeroes the train-phase wall times. The next train or predict accumulates into a fresh sample, andgpr_train_phase_readandgpr_train_phase_read_leavesread it; any output pointer may beNULL.gpr_set_library_serial(1)selects Eigen’s factor and triangular solves for the next train and0the OpenMP panel kernels; a scaling measurement reports the two serial timings together.The oracle adapters
gpr_oracle_lj,gpr_oracle_muller_brownandgpr_oracle_lepswrap the analytical potentialsgpr_potential_lj,gpr_potential_muller_brownandgpr_potential_lepsasgpr_oracle_fn.gpr_oracle_ljtakes agpr_lj_params_tasuser_data.
The Python class GaussianProcess and the C++ class
gpr::GaussianProcessRegression expose the same model with more
configuration than the C struct carries.
Posterior derivatives and harmonic prefactors¶
ABI 1.20 adds batched derivatives of a trained model’s posterior and the harmonic (Vineyard) rate prefactor built on them. The rate prefactor how-to shows both in use.
Group |
Functions |
|---|---|
Derivative options |
|
Mean derivatives |
|
Uncertainty |
|
Refinement |
|
Prefactor halves |
|
Prefactors of searches |
|
Rules that the functions share:
The units are those of the training data.
energy_unitandlength_unitare tags the report echoes; nothing is converted and the derivative primitives apply no mass weighting.Hessians are raw unless
project_rigidis set. The residuals ofgpr_model_mean_hessian_batchmeasure how far the raw Hessian is from rigid invariance at each point.Every failure is a typed status, never a NaN.
GPR_ERR_OUT_OF_SUPPORT(-12) means a point lies outside the training support by the caller’smax_energy_std; the report carries the largest posterior standard deviation.Variances and covariances are probabilistic estimates under the fitted GP, not bounds.
ln_sum_stdis the root-sum-square, over the positive modes with a component outside the oracle-measured directions, of \(\sqrt{v_i} / (2\lambda_i)\): the standard deviation of \(\ln\nu_i\) from the mode’s diagonal curvature variance \(v_i\). Covariance between modes is not included.Searches do not compute prefactors until
gpr_request_prefactoropts this thread in. Setenabled = 1.NULLdoes so and requests the surrogate, at no extra oracle call, for every NEB search (gpr_neb_search*, including local and periodic bands) andgpr_minimize. The NEB saddle half uses the index certificate’s measured stencil whengpr_neb_request_index_certificateis on. A later call selects the refined or measured mode, or turns the halves off withenabled = 0. A half that cannot be formed is stored with statusGPR_HTST_UNAVAILABLE. Nothing is dropped or replaced.
Runtime configuration¶
These are the gprd and gprn options of the same names, process-wide;
set them before a search starts.
Call |
CLI option |
|---|---|
|
|
|
|
|
|
|
the check |
gpr_set_training_product accepts "" (native), a scheme2: specification
(:moduli=N :bits=B :provider=mkl|onednn|builtin|cuda :library=PATH) or the
path of a library implementing the v1 training-product ABI. A malformed
specification is GPR_ERR_INVALID_ARG; a library or provider that cannot
load is GPR_ERR_UNSUPPORTED, and the previous selection stays.
The program below asserts the GPR_ERR_UNSUPPORTED of a library that
cannot load, and the GPR_ERR_INVALID_ARG of an unreadable package path,
which gpr_check_model_package returns before its try block. The
exceptions each function maps to GPR_ERR_UNSUPPORTED are in the table
under Exceptions above.
gpr_backend_name, gpr_mpi_* and gpr_omp_max_threads describe the
build and the process.
#include <assert.h>
#include <gpr/capi/gpridge_c.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
int major, minor;
if (GPR_ABI_CHECK() != GPR_SUCCESS) {
fprintf(stderr, "%s\n", gpr_last_error_message());
return 1;
}
gpr_abi_version(&major, &minor);
printf("library ABI %d.%d, header ABI %d.%d\n", major, minor,
GPR_C_ABI_MAJOR, GPR_C_ABI_MINOR);
assert(major == GPR_C_ABI_MAJOR && minor >= GPR_C_ABI_MINOR);
/* Process-wide settings: set them before a search, not during one. */
assert(gpr_set_linalg_mode("library") == GPR_SUCCESS);
assert(strcmp(gpr_linalg_mode(), "library") == 0);
assert(gpr_set_linalg_mode("fast") == GPR_ERR_INVALID_ARG);
assert(strcmp(gpr_linalg_mode(), "library") == 0); /* unchanged */
assert(gpr_set_linalg_mode("reproducible") == GPR_SUCCESS);
assert(gpr_set_linalg_threads(2) == GPR_SUCCESS);
assert(gpr_set_linalg_threads(0) == GPR_ERR_INVALID_ARG);
assert(gpr_set_training_product("") == GPR_SUCCESS);
assert(gpr_training_product_configured() == 0);
assert(gpr_set_training_product("scheme2:fp99") == GPR_ERR_INVALID_ARG);
/* A library that cannot load throws std::runtime_error, which
gpr_set_training_product maps to GPR_ERR_UNSUPPORTED. */
assert(gpr_set_training_product("/nonexistent/libproduct.so") ==
GPR_ERR_UNSUPPORTED);
assert(gpr_last_error_message()[0] != '\0');
assert(gpr_training_product_configured() == 0); /* unchanged */
/* An unreadable package path is a direct return before the try block. */
assert(gpr_check_model_package("/nonexistent/model.pt2") ==
GPR_ERR_INVALID_ARG);
assert(gpr_check_model_package(NULL) == GPR_ERR_INVALID_ARG);
printf("backend %s, mode %s\n", gpr_backend_name(), gpr_linalg_mode());
return 0;
}
ABI and versioning¶
GPR_C_ABI_MAJOR and GPR_C_ABI_MINOR in the header give the ABI it
declares; gpr_abi_version gives the ABI of the loaded library. Call
GPR_ABI_CHECK() once at start. It fails with GPR_ERR_ABI, naming both
versions in the message, when the library has another major version or a
lower minor version than the header. The release version of the library
is gpr_version() as a string and gpr_version_components(&major, &minor, &patch) as integers; any pointer may be NULL.
The rules:
A minor version counts additions: a function, a struct field at the end of a size-versioned struct, an enumerator. A caller built against an older header keeps working with a newer library.
gpr_model_config_tis not size-versioned: ABI 1.19 appendsuse_hssvd_backend, which preserves all preceding field offsets but growssizeof(gpr_model_config_t). Callers compiled against an older header must recompile before passing that struct togpr_model_init. The field is tri-state:GPR_HSSVD_BACKEND_DEFAULT(0) leaves the library default, which is HS-SVD, so a zero-initialized config keeps that solver;GPR_HSSVD_BACKEND_HSSVD(1) selects it explicitly;GPR_HSSVD_BACKEND_CHOLESKY(2) selects Cholesky.gpr_model_config_defaultsstores HSSVD.gpr_model_set_hssvd_backendtakes the same three values and rejects any other; the getter returns that value.A major version changes when an existing declaration changes in a way that breaks a compiled caller: a struct layout, a signature or a removed symbol.
gpr_dimer_report_tandgpr_neb_report_tcarrystruct_sizeso that they can grow within a major version.abi/gpridge_c.symbolsrecords the version and every function. The suite (test_capi_abi_symbols, which runsscripts/check_c_abi.py) fails when the header, that record and the library disagree.
What each minor version added, from the header and the history of the repository:
Minor |
Added |
|---|---|
1.1 |
The Section 12 runtime calls, |
1.2 |
|
1.3 |
|
1.4 |
|
1.5 |
The certificate fields of |
1.6 |
|
1.7 |
|
1.8 |
|
1.9 |
|
1.10 |
|
1.11 |
The six extent-checked model calls |
1.12 |
|
1.13 |
Prior-free marginal-likelihood fitting, held-out true-force and closed-form LOO calibration through a shared report, and fixed-hyperparameter Cholesky append. Buffer-taking calls are extent-checked, the Fortran |
1.14 |
|
1.15 |
|
1.16 |
|
1.17 |
Bayesian quadrature model lifecycle, hyperparameters, prediction, scalar and cumulative integration, seeded cumulative sampling, candidate reduction, batch selection, and LOO diagnostics. |
1.18 |
|
1.19 |
|
1.20 |
Posterior derivatives and harmonic prefactor APIs. |
1.21 |
|
1.22 |
|
1.23 |
Free-energy surrogate on collective variables: |
1.24 |
|
1.25 |
|
1.26 |
Scalar surrogate for a noisy oracle and ask-and-tell parameter search: |
The symbol list was brought up to date in the 1.6 revision, so the rows for 1.3 to 1.5 come from the header changes that raised the minor version. The Julia package pins minor 26. The R package and the Rust crate check the library against the header version they were built with.
Contract fix in ABI 1.17 (without a minor bump): every \*_destroy function
(gpr_atoms_destroy, gpr_model_destroy, gpr_potential_destroy,
gpr_neb_result_destroy, gpr_bq_destroy) and every NULL call to a
usable_or_null accessor now clears gpr_last_status() and
gpr_last_error() to GPR_SUCCESS instead of leaving prior non-oracle error
state behind, while all five destroy calls preserve a pending
GPR_ERR_ORACLE during cleanup and successful live-handle accessors leave
any existing error state intact. No symbols or struct layouts changed, so
GPR_C_ABI_MINOR remains 17.
Building against the library¶
pkg-config --cflags --libs gpridge # -I<prefix>/include -L<prefix>/lib -lgpridge
pkg-config --variable=c_abi_minor gpridge
The header compiles as C99 and as C++; the suite builds its C tests with
-Wall -Wextra -Wpedantic -Werror. test_install_consumer installs the
build into a staging root and compiles the C example, a C++ consumer and
the Fortran example against the staged gpridge.pc
(tests/cinstall/smoke.sh). CMake consumers use
find_package(gpridge REQUIRED CONFIG) and the target
gpridge::gpridge; Native packages
describes both contracts and the installation check in
packaging/native/cmake/.