======================================== C API: from a GP model to a saddle point ======================================== This tutorial uses the C API of ``libgpridge`` from start to finish. It creates a Gaussian-process (GP) model, trains it on a handful of energies and gradients, predicts with it, runs a GP-accelerated dimer search to a saddle point, and destroys every handle. It ends by compiling and running the three example programs in ``examples/``. Every program on this page is compiled and run by the documentation test. What you need ------------- - A build tree of GPRidge (``meson setup builddir`` and ``meson compile -C builddir``) or an installed prefix. See :doc:`Installation <../getting-started/installation>`. - A C11 compiler. Against an installed library, compile a program with ``cc -std=c11 program.c $(pkg-config --cflags --libs gpridge) -lm``. Against a build tree, put the source root and ``gpr/capi/`` on the include path and link ``builddir/libgpridge.so``; the last step of this page shows that command. Step 1: a potential with a barrier ---------------------------------- Both the model and the dimer search need an *oracle*: a function that returns the energy and gradient of a geometry. The oracle of this tutorial is one bond between two atoms. With :math:`d = r - 3`, where :math:`r` is the bond length, .. math:: E(r) = \tfrac{1}{4} d^4 - \tfrac{1}{2} d^2 . The minima are at :math:`r = 2` and :math:`r = 4` with :math:`E = -1/4`, and the barrier is at :math:`r = 3` with :math:`E = 0`. The six coordinates are the Cartesian positions of the two atoms, :math:`x_1, y_1, z_1, x_2, y_2, z_2`, in reduced units. The block below writes the header ``bond.h`` that the two programs of this page include. It also defines ``CHECK``, which prints the status name and the error message of a failing call. Every C API function returns ``GPR_SUCCESS`` or a status code, and ``gpr_last_error_message()`` holds the reason of the last failure on the calling thread. .. code:: c #include #include #include #define N_ATOMS 2 #define N_COORDS (3 * N_ATOMS) #define BARRIER_LENGTH 3.0 #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) /* Energy and gradient dE/dR at the six coordinates x. */ static void bond_energy(const double* x, double* energy, double* gradient) { const double dx = x[3] - x[0], dy = x[4] - x[1], dz = x[5] - x[2]; const double r = sqrt(dx * dx + dy * dy + dz * dz); const double d = r - BARRIER_LENGTH; const double dE_dr = d * d * d - d; *energy = 0.25 * d * d * d * d - 0.5 * d * d; gradient[0] = -dE_dr * dx / r; gradient[1] = -dE_dr * dy / r; gradient[2] = -dE_dr * dz / r; gradient[3] = dE_dr * dx / r; gradient[4] = dE_dr * dy / r; gradient[5] = dE_dr * dz / r; } /* The bond along z with the first atom at the origin. */ static void bond_along_z(double r, double* x) { int k; for (k = 0; k < N_COORDS; ++k) x[k] = 0.0; x[5] = r; } Step 2: create, train, predict and destroy a model -------------------------------------------------- The program below goes through the life of one model: 1. ``GPR_ABI_CHECK()`` compares the header the program was compiled with to the library it loaded. Call it once, first. 2. ``gpr_atoms_create_simple(2)`` describes two moving atoms of one type, and ``gpr_model_create(GPR_MODEL_GP)`` makes an empty model. 3. ``gpr_model_init`` applies the settings of ``gpr_model_config_defaults()``. The model copies the atoms descriptor, so the program destroys the descriptor right away. 4. ``gpr_model_train_checked`` fits the hyperparameters and conditions the model on five observations at :math:`r = 2.2, 2.6, 2.9, 3.3, 3.7`. The ``_checked`` form takes the length of every buffer and refuses a short one. 5. ``gpr_model_predict_full_checked`` returns the energy, gradient and their variances at :math:`r = 3`, which is not a training point. ``gpr_model_predict_variance_checked`` returns the variances alone, here at :math:`r = 5`, outside the data. 6. ``gpr_model_destroy`` frees the model. .. code:: c #include "bond.h" #define N_OBS 5 int main(void) { const double lengths[N_OBS] = {2.2, 2.6, 2.9, 3.3, 3.7}; double R[N_OBS * N_COORDS], E[N_OBS], G[N_OBS * N_COORDS]; double query[N_COORDS], e_true, g_true[N_COORDS]; double e_pred, g_pred[N_COORDS], var_e, var_g[N_COORDS], var_far; gpr_model_config_t config; gpr_atoms_t atoms; gpr_model_t model; int i; CHECK(GPR_ABI_CHECK()); printf("gpridge %s, C ABI %d.%d\n", gpr_version(), GPR_C_ABI_MAJOR, GPR_C_ABI_MINOR); for (i = 0; i < N_OBS; ++i) { bond_along_z(lengths[i], R + i * N_COORDS); bond_energy(R + i * N_COORDS, E + i, G + i * N_COORDS); } /* Create: an atoms descriptor and an empty GP model. */ atoms = gpr_atoms_create_simple(N_ATOMS); model = gpr_model_create(GPR_MODEL_GP); if (!atoms || !model) { fprintf(stderr, "create failed: %s\n", gpr_last_error_message()); return 1; } /* Initialise with the default settings. The model copies the atoms. */ config = gpr_model_config_defaults(); config.report_level = 0; CHECK(gpr_model_init(model, &config, atoms)); gpr_atoms_destroy(atoms); /* Train: fit the hyperparameters and condition on the observations. */ 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)); /* Predict at the barrier top, which is not a training point. */ bond_along_z(BARRIER_LENGTH, query); bond_energy(query, &e_true, g_true); 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("r = 3.0: E exact %.4f predicted %.4f\n", e_true, e_pred); if (fabs(e_pred - e_true) > 1e-2) return 1; /* The variance is small between the data and grows away from it. */ bond_along_z(5.0, query); CHECK(gpr_model_predict_variance_checked(model, query, N_COORDS, &var_far, var_g, N_COORDS, N_COORDS)); printf("energy variance at r = 3.0 %.1e, at r = 5.0 %.1e\n", var_e, var_far); if (!(var_far > var_e)) return 1; /* Destroy. */ gpr_model_destroy(model); printf("model destroyed\n"); return 0; } The prediction at the barrier top agrees with the exact energy to within :math:`10^{-2}`, and the energy variance at :math:`r = 5`, two units past the last observation, is more than ten times its value inside the data. The fitted numbers depend slightly on the build: :: gpridge , C ABI . trained on 5 observations r = 3.0: E exact 0.0000 predicted energy variance at r = 3.0 , at r = 5.0 model destroyed :doc:`Run a GP model through its C lifecycle <../howto/capi_lifecycle>` goes further with the same calls: the state of a model after each call, the status code of each misuse, noise changes, updates and calibration. Step 3: find the saddle with a GP dimer --------------------------------------- The dimer search needs a *potential* handle rather than an energy function. ``gpr_potential_from_force`` wraps a callback that returns the energy and the forces :math:`F = -\partial E/\partial R`. The callback here also counts its calls through the ``user_data`` pointer. The search starts at :math:`r = 3.3`, on the far side of the barrier, with the dimer axis along the bond. It builds its own GP from the oracle calls it makes; passing ``NULL`` and ``0`` for the prior observations starts that GP empty. ``gpr_dimer_search_report`` fills a ``gpr_dimer_report_t``. The caller sets ``struct_size`` so that the library fills only the fields this header knows, and may set ``max_oracle_calls`` as a hard budget. .. code:: c #include "bond.h" #include /* The dimer calls a force function: forces are -dE/dR. */ static void bond_force(long n_atoms, const double* R, const int* atomic_nrs, double* F, double* energy, double* energy_noise_rms, const double* box, void* user_data) { long* calls = (long*)user_data; long k; (void)atomic_nrs; (void)box; ++*calls; bond_energy(R, energy, F); for (k = 0; k < 3 * n_atoms; ++k) F[k] = -F[k]; if (energy_noise_rms) *energy_noise_rms = 0.0; } int main(void) { double start[N_COORDS], saddle[N_COORDS], orient_out[N_COORDS]; double orient[N_COORDS] = {0.0}; double e_saddle, dx, dy, dz, r; long calls = 0; gpr_dimer_config_t config; gpr_dimer_report_t report; gpr_potential_t pot; gpr_atoms_t atoms; CHECK(GPR_ABI_CHECK()); /* Create: the atoms descriptor and a potential around the callback. */ atoms = gpr_atoms_create_simple(N_ATOMS); pot = gpr_potential_from_force(bond_force, &calls); if (!atoms || !pot) { fprintf(stderr, "create failed: %s\n", gpr_last_error_message()); return 1; } /* Start 0.3 past the barrier, the dimer axis along the bond. */ bond_along_z(BARRIER_LENGTH + 0.3, start); orient[2] = -sqrt(0.5); orient[5] = sqrt(0.5); config = gpr_dimer_config_defaults(); config.T_dimer = 1e-3; config.report_level = 0; memset(&report, 0, sizeof report); report.struct_size = sizeof report; report.max_oracle_calls = 100; /* Search: no prior observations, so the GP starts empty. */ CHECK(gpr_dimer_search_report(pot, atoms, start, orient, &config, NULL, NULL, NULL, 0, saddle, &e_saddle, orient_out, &report)); dx = saddle[3] - saddle[0]; dy = saddle[4] - saddle[1]; dz = saddle[5] - saddle[2]; r = sqrt(dx * dx + dy * dy + dz * dz); printf("converged %d, stop %s\n", report.converged, report.stop == GPR_DIMER_STOP_FORCE_CONVERGED ? "force" : "other"); printf("saddle r = %.3f, E = %.4f, curvature %.1f\n", r, e_saddle + report.energy_zero_level, report.curvature); printf("%ld oracle calls: %ld in the search, %ld for the certificate\n", calls, report.n_force_calls, report.n_certificate_calls); if (calls != report.n_force_calls + report.n_certificate_calls) return 1; /* Destroy, in any order. */ gpr_potential_destroy(pot); gpr_atoms_destroy(atoms); printf("handles destroyed\n"); return report.converged && fabs(r - BARRIER_LENGTH) < 0.02 && report.curvature < 0.0 ? 0 : 1; } :: converged 1, stop force saddle r = 3.000, E = 0.0000, curvature oracle calls: in the search, for the certificate handles destroyed How to read the report: - ``converged`` is 1 when the true force fell below ``T_dimer`` and the index certificate at that point measured exactly one negative mode. ``stop`` says why the search stopped either way; ``GPR_DIMER_STOP_FORCE_CONVERGED`` is the force criterion. - ``e_saddle`` is relative to the GP's energy zero; adding ``energy_zero_level`` gives the absolute energy, here the barrier top :math:`E = 0`. - ``curvature`` is the curvature along the final dimer axis. The axis is a unit vector in the six coordinates, :math:`(0,0,-1,0,0,1)/\sqrt{2}`, and a unit step along it stretches the bond by :math:`\sqrt{2}`, so the exact value is :math:`2 \times (-1) = -2`. The search reports the GP's estimate, close to it. - ``n_force_calls`` counts the oracle calls of the search and ``n_certificate_calls`` those of the certificate. Their sum is what the callback counted, and both count against ``max_oracle_calls``. Step 4: build the example programs ---------------------------------- ``examples/`` holds three complete C programs. Each states its build command for an installed library in its header comment. The same examples are available in :doc:`language tabs ` with their Fortran counterparts. .. table:: +-----------------------------+-----------------------------------------------------------------------------+ | Program | What it runs | +=============================+=============================================================================+ | ``capi_neb_muller_brown.c`` | A nudged elastic band (NEB) on the Muller-Brown surface, ``gpr_neb_search`` | +-----------------------------+-----------------------------------------------------------------------------+ | ``capi_local_band.c`` | A local band on a one-atom bowl, ``gpr_neb_search_local`` | +-----------------------------+-----------------------------------------------------------------------------+ | ``capi_periodic_band.c`` | A periodic band with a frozen neighbour, ``gpr_neb_search_periodic`` | +-----------------------------+-----------------------------------------------------------------------------+ The block below compiles each one against the build tree of the documentation test and prints the last line of its output: .. code:: bash cc="${CC:-cc}" for example in capi_neb_muller_brown capi_local_band capi_periodic_band; do "$cc" -std=c11 -I"$GPRIDGE_ROOT" -I"$GPRIDGE_ROOT/gpr/capi" \ "$GPRIDGE_ROOT/examples/$example.c" -o "$example" \ -L"$GPRIDGE_BUILD_DIR" -lgpridge -Wl,-rpath,"$GPRIDGE_BUILD_DIR" -lm printf '%s: ' "$example" ./"$example" | tail -n 1 done :: capi_neb_muller_brown: converged 1 after oracle calls, barrier capi_local_band: images 3 oracle certificate 0 index 0 certified 0 capi_periodic_band: converged 1 oracle certificate 0 index 0 certified 0 barrier The Muller-Brown band crosses the barrier of about 106 energy units between the two lowest minima. The local bands report zeros in the certificate fields because neither program requests an index certificate. Where to go next ---------------- - :doc:`The C API reference <../reference/bindings/c>` lists the conventions, ownership, errors, threads and ABI rules; :doc:`the function reference <../reference/bindings/c_functions>` documents every call. - :doc:`Minimise with a GP surrogate <../howto/minimize>` uses ``gpr_minimize`` on a cluster. - :doc:`OCI-NEB: a climbing image with dimer bursts ` runs GP bands with ``gpr_neb_search_gp`` and ``gpr_ocineb_search``.