Run a GP model through its C lifecycle

This guide follows one GP model from gpr_model_create to gpr_model_destroy. It shows who owns each handle, which status code each mistake returns, how to change the noise of a trained model, and how to add data and calibrate it. Every block runs in the documentation test.

Status: implemented. The functions are the Tier 2 model calls of ABI 1.13. The C API page has one longer program and the conventions. The function reference lists every function with its units, ownership and failure codes.

The order of calls

A model passes through four states.

State

How it is reached

What works

created

gpr_model_create

gpr_model_type, gpr_model_destroy

initialised

gpr_model_init

settings, gpr_model_get_sigma2

trained

gpr_model_train (or the checked form)

predictions, variance, Hessian, update, calibration

updated

gpr_model_update, gpr_model_append_fixed_checked

the same as trained

A prediction before training returns GPR_ERR_NOT_TRAINED. Training before gpr_model_init returns GPR_ERR_INVALID_ARG. A NULL model handle, and a model handle that is not live, returns GPR_ERR_NULL_HANDLE from the status calls (guard_model). gpr_model_predict_energy_variance_interval and gpr_model_get_noise_floor_report return that code for a NULL model and do not test liveness. A NULL atoms argument of gpr_model_init returns GPR_ERR_INVALID_ARG; an atoms handle that is not live returns GPR_ERR_NULL_HANDLE. Constructors return NULL and leave the reason in gpr_last_error_message().

Ownership

The caller owns every handle and every buffer it passes in. The library copies what it keeps. gpr_model_init copies the atoms descriptor, so the caller may destroy the atoms handle after it. gpr_model_train and gpr_model_update copy the observations, so the caller may free or reuse R, E and G afterwards. A function that fills an output buffer writes only the extent that its documentation names. The _checked forms take the length of each buffer and return GPR_ERR_INVALID_ARG for a short one before they write anything. Each destroy call accepts NULL and clears gpr_last_status() and gpr_last_error() to GPR_SUCCESS on both NULL and live handles while preserving any pending GPR_ERR_ORACLE during cleanup; destroying a handle that is already retired sets GPR_ERR_INVALID_ARG. Count/flag/rank accessors clear status on NULL, preserve any existing error state on live handles, and set GPR_ERR_NULL_HANDLE on retired handles. This status-clearing contract is a behavioral fix in ABI 1.17 without a minor bump (no symbols or struct layouts changed). Calling gpr_model_init again reconfigures the model and leaves it untrained.

The program

Units are those of the oracle: positions in the length unit of the potential, energies and gradients in its energy unit. The oracle here is the built-in Lennard-Jones pair with \(\sigma=\epsilon=1\), so every number is in reduced units. The coordinates are n_coords = 3 * n_atoms = 6 and each observation is one row of R and G and one entry of E.

#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

#define CHECK(call)                                                      \
    do {                                                                 \
        int status_ = (call);                                            \
        if (status_ != GPR_SUCCESS) {                                    \
            fprintf(stderr, "%s failed: %s (%s)\n", #call,               \
                    gpr_status_name(status_), gpr_last_error_message()); \
            return 1;                                                    \
        }                                                                \
    } while (0)

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], e_new, g_new[N_COORDS];
    double e_pred, g_pred[N_COORDS], var_e, var_g[N_COORDS], var_noisy;
    double sigma2 = 0.0, jitter = 0.0;
    gpr_calibration_report_t report;
    gpr_atoms_t atoms;
    gpr_model_t model, untrained;
    gpr_model_config_t config;
    int i, status;

    CHECK(GPR_ABI_CHECK());
    for (i = 0; i < N_OBS; ++i)
        lj_pair(separations[i], R + i * N_COORDS, E + i, G + i * N_COORDS);

    /* 1. Create and initialise. The atoms handle describes the system. */
    atoms = gpr_atoms_create_simple(N_ATOMS);
    model = gpr_model_create(GPR_MODEL_GP);
    untrained = gpr_model_create(GPR_MODEL_GP);
    if (!atoms || !model || !untrained) {
        fprintf(stderr, "%s\n", gpr_last_error_message());
        return 1;
    }
    config = gpr_model_config_defaults();
    config.report_level = 0;
    CHECK(gpr_model_init(model, &config, atoms));
    CHECK(gpr_model_init(untrained, &config, atoms));

    /* 2. Mistakes and their codes. */
    lj_pair(1.2, query, &e_new, g_new);
    status = gpr_model_predict(untrained, query, &e_pred, g_pred, N_COORDS);
    printf("predict before training: %s\n", gpr_status_name(status));
    status = gpr_model_predict(NULL, query, &e_pred, g_pred, N_COORDS);
    printf("predict on a NULL handle: %s\n", gpr_status_name(status));

    /* 3. Train with the extent-checked call. */
    CHECK(gpr_model_train_checked(model, R, N_OBS * N_COORDS, E, N_OBS, G,
                                  N_OBS * N_COORDS, N_OBS, N_COORDS));
    printf("trained on %d observations\n", gpr_model_n_observations(model));

    /* 4. A short output buffer is refused before anything is written. */
    status = gpr_model_predict_checked(model, query, N_COORDS, &e_pred, g_pred,
                                       N_COORDS - 1, N_COORDS);
    printf("short gradient buffer: %s\n", gpr_status_name(status));

    /* 5. Predict with the variance. */
    CHECK(gpr_model_predict_full_checked(model, query, N_COORDS, &e_pred, g_pred,
                                         N_COORDS, &var_e, var_g, N_COORDS,
                                         N_COORDS));
    printf("E exact %.5f predicted %.5f\n", e_new, e_pred);
    if (fabs(e_pred - e_new) > 1e-2) return 1;

    /* 6. Add the exact observation at the fitted hyperparameters. The call
          needs the dense Cholesky factor that the last fit kept. When it
          has none it returns GPR_ERR_UNSUPPORTED, and the caller falls
          back to gpr_model_update, which refits. This model returns it. */
    status = gpr_model_append_fixed_checked(model, query, N_COORDS, &e_new, 1,
                                            g_new, N_COORDS, 1, N_COORDS);
    printf("append at fixed hyperparameters: %s\n", gpr_status_name(status));
    if (status == GPR_ERR_UNSUPPORTED)
        CHECK(gpr_model_update_checked(model, query, N_COORDS, &e_new, 1, g_new,
                                       N_COORDS, 1, N_COORDS));
    else
        CHECK(status);
    printf("observations now %d\n", gpr_model_n_observations(model));

    /* 7. Raise the noise of the trained model. The variance at a data
          point must grow. */
    CHECK(gpr_model_predict_variance_checked(model, query, N_COORDS, &var_e,
                                             var_g, N_COORDS, N_COORDS));
    CHECK(gpr_model_get_sigma2(model, &sigma2));
    CHECK(gpr_model_get_jitter(model, &jitter));
    CHECK(gpr_model_set_sigma2(model, 100.0 * sigma2));
    CHECK(gpr_model_predict_variance_checked(model, query, N_COORDS, &var_noisy,
                                             var_g, N_COORDS, N_COORDS));
    printf("sigma2 %.1e jitter %.1e variance %.2e -> %.2e\n", sigma2, jitter,
           var_e, var_noisy);
    if (!(var_noisy > var_e)) return 1;
    status = gpr_model_set_sigma2(model, -1.0);
    printf("negative sigma2: %s\n", gpr_status_name(status));

    /* 8. Closed-form leave-one-out calibration of the training channels. */
    CHECK(gpr_model_calibrate_loo_checked(model, 0.95, &report));
    printf("loo components %zu\n", report.components);
    if (report.components == 0) return 1;

    /* 9. Destroy every handle. The atoms were copied by gpr_model_init. */
    gpr_model_destroy(untrained);
    gpr_model_destroy(model);
    gpr_atoms_destroy(atoms);
    printf("lifecycle complete\n");
    return 0;
}
predict before training: GPR_ERR_NOT_TRAINED
predict on a NULL handle: GPR_ERR_NULL_HANDLE
trained on 6 observations
short gradient buffer: GPR_ERR_INVALID_ARG
E exact <s> predicted <s>
append at fixed hyperparameters: GPR_ERR_UNSUPPORTED
observations now 7
sigma2 <s> jitter <s> variance <s> -> <s>
negative sigma2: GPR_ERR_INVALID_ARG
loo components <n>
lifecycle complete

Reading the status codes

The codes this program met are the ones to handle first.

Code

Meaning in this lifecycle

GPR_ERR_NULL_HANDLE

A NULL model handle, or a model handle that is not live, on a status call (guard_model). The energy-variance interval and the noise-floor report return it for a NULL model only. A NULL atoms handle in gpr_model_init is GPR_ERR_INVALID_ARG; an atoms handle that is not live is GPR_ERR_NULL_HANDLE.

GPR_ERR_NOT_TRAINED

A prediction, update or calibration before gpr_model_train.

GPR_ERR_INVALID_ARG

A bad pointer, a short buffer, a non-positive noise or a wrong n_coords.

GPR_ERR_UNSUPPORTED

gpr_model_append_fixed_checked could not extend the factor.

GPR_ERR_CHOLESKY

gpr_model_predict_energy_variance_interval returns it for a std::domain_error from tryGateEnergyVarianceInterval, and gpr_model_get_noise_floor_report returns it for a std::runtime_error from tryBorderedNoiseReport. The checked interval calls the first.

gpr_status_name returns a static string for each code and never returns NULL. gpr_last_error_message() returns the text of the last failure on the calling thread.