Minimise with a GP surrogate

gpr_minimize (C) and gp_minimize (Python) find a local minimum with fewer oracle calls than a plain optimiser. They fit a Gaussian-process (GP) surrogate to every evaluation so far, take L-BFGS steps on the surrogate, and call the oracle only when a step leaves the region the data cover or when the surrogate proposes to stop. This guide shows how to set the trust radius and the budgets, and how to read the result. Both programs are run by the documentation test.

How the minimiser works

  1. Initial design. The oracle is evaluated at the start and at n_initial_perturb (4) copies of it, each coordinate shifted by a uniform random amount in \(\pm\) perturb_scale / 2 (perturb_scale 0.1, seed 42).

  2. Outer cycle. The GP is refitted (gp_train_iter optimiser steps, 300) and L-BFGS runs on the surrogate for up to 200 inner steps. Each step moves no atom further than max_move (0.1).

  3. Trust region. The surrogate is trusted inside the union of balls of radius trust_radius (0.1) around the training geometries, with distance measured as the largest displacement of any one atom. A step that leaves the union is cut at the exit point, the oracle is called there, and the next outer cycle starts.

  4. Stop. When the surrogate gradient falls under conv_tol, the oracle is called at that point. The run converges only if the norm of the true gradient there is below conv_tol (5e-3); otherwise the evaluation joins the data and the cycles go on.

The run ends when it converges, after max_iter (500) outer cycles, or when max_oracle_calls is reached. The defaults are those of gpr_minimize_config_defaults() and of MinimizationConfig().

Minimise from C

The oracle is the built-in Lennard-Jones potential, gpr_oracle_lj, with \(\epsilon = \sigma = 1\), for three atoms. The minimum is the equilateral triangle with sides \(2^{1/6}\) and \(E = -3\). The program starts from a distorted triangle and runs four settings:

  • the defaults with a tighter conv_tol of 1e-3;

  • a smaller trust radius, 0.03;

  • a budget of three oracle calls, too few to converge;

  • at most 20 inner surrogate steps per cycle, requested with gpr_minimize_request_max_inner_steps(20). The request applies to the next gpr_minimize call on the same thread and is then consumed; the default is 200.

#include <gpr/capi/gpridge_c.h>
#include <math.h>
#include <stdio.h>

#define N_ATOMS 3
#define N_COORDS (3 * N_ATOMS)

typedef struct {
    gpr_lj_params_t lj;
    int calls;
} counted_lj_t;

static void oracle(int n_coords, const double* x, double* e, double* g,
                   void* user_data)
{
    counted_lj_t* c = (counted_lj_t*)user_data;
    ++c->calls;
    gpr_oracle_lj(n_coords, x, e, g, &c->lj);
}

static double norm(const double* v)
{
    double s = 0.0;
    int k;
    for (k = 0; k < N_COORDS; ++k) s += v[k] * v[k];
    return sqrt(s);
}

static int run(const char* label, gpr_atoms_t atoms,
               const gpr_minimize_config_t* config)
{
    /* A distorted triangle; the minimum is the equilateral one, E = -3. */
    const double start[N_COORDS] = {0.0, 0.0, 0.0, 1.3, 0.0, 0.0,
                                    0.5, 1.0, 0.0};
    double x[N_COORDS], e, g[N_COORDS];
    int converged = 0, calls = 0;
    counted_lj_t c = {{N_ATOMS, 1.0, 1.0}, 0};
    int status = gpr_minimize(oracle, &c, start, N_COORDS, atoms, config, x,
                              &e, g, &converged, &calls);
    if (status != GPR_SUCCESS) {
        fprintf(stderr, "%s: %s\n", gpr_status_name(status),
                gpr_last_error_message());
        return -1;
    }
    printf("%-16s converged %d  E %.5f  |g| %.1e  oracle calls %d\n", label,
           converged, e, norm(g), calls);
    if (calls != c.calls) return -1;
    return converged;
}

int main(void)
{
    gpr_minimize_config_t config;
    gpr_atoms_t atoms;
    int converged;

    if (GPR_ABI_CHECK() != GPR_SUCCESS) return 1;
    atoms = gpr_atoms_create_simple(N_ATOMS);
    if (!atoms) return 1;

    config = gpr_minimize_config_defaults();
    config.verbose = 0;
    config.conv_tol = 1e-3;
    printf("defaults: trust_radius %.2f  max_move %.2f  max_iter %d  "
           "max_oracle_calls %d\n",
           config.trust_radius, config.max_move, config.max_iter,
           config.max_oracle_calls);

    /* The default trust radius. */
    converged = run("trust 0.10", atoms, &config);
    if (converged != 1) return 1;

    /* A smaller trust radius: shorter excursions on the surrogate. */
    config.trust_radius = 0.03;
    converged = run("trust 0.03", atoms, &config);
    if (converged != 1) return 1;

    /* A budget too small to converge: the result is the lowest-energy
     * oracle evaluation, and the budget is never exceeded. */
    config.trust_radius = 0.1;
    config.max_oracle_calls = 3;
    converged = run("budget 3 calls", atoms, &config);
    if (converged != 0) return 1;

    /* Cap the inner surrogate steps of the next call on this thread. */
    config.max_oracle_calls = 0;
    if (gpr_minimize_request_max_inner_steps(20) != GPR_SUCCESS) return 1;
    converged = run("20 inner steps", atoms, &config);
    if (converged != 1) return 1;

    gpr_atoms_destroy(atoms);
    return 0;
}
defaults: trust_radius 0.10  max_move 0.10  max_iter 500  max_oracle_calls 0
trust 0.10       converged 1  E -3.00000  |g| <s>  oracle calls <n>
trust 0.03       converged 1  E -3.00000  |g| <s>  oracle calls <n>
budget 3 calls   converged 0  E <s>  |g| <s>  oracle calls 3
20 inner steps   converged 1  E -3.00000  |g| <s>  oracle calls <n>

In the run that checked this page, the default trust radius converged in 11 oracle calls and the radius 0.03 in 12. On a smooth surface like this one the trust radius matters little. On a rough or poorly sampled one a smaller radius makes more, shorter excursions on the surrogate and calls the oracle more often, and a larger one risks stepping far on a surrogate that is wrong there.

Set the budgets

max_oracle_calls is a hard cap: the run never calls the oracle more often, and 0 means no cap. The initial design counts against it. With a cap of 3, the start and two perturbed copies use the whole budget, so no surrogate step runs and converged is 0.

max_iter caps the outer cycles, and the inner-step limit caps the surrogate steps in each one; neither counts oracle calls. Use max_oracle_calls to bound the cost and max_iter to bound the wall time of the fits.

Read the result

gpr_minimize returns GPR_SUCCESS whether or not the run converged; a status code means an argument or the oracle failed. Its outputs:

Output

Meaning

R_final

The geometry of the result

E_final

The oracle energy at R_final

G_final

The oracle gradient at R_final

converged

1 when the norm of G_final is below conv_tol

n_oracle_calls

Every oracle call of the run, the initial design included

R_final, E_final and G_final are always one oracle evaluation, never a surrogate prediction. After a converged run it is the evaluation that passed the test. After a run that stopped on a budget it is the lowest-energy evaluation of the run: in the three-call run above, the first perturbed copy, which lies below the start. Check converged before treating R_final as a minimum.

Minimise from Python

gpridge.gp_minimize(oracle, x_init, atoms_config, config, policy=None) runs the same minimiser. The oracle takes the flat coordinate vector and returns (energy, gradient); gpridge.potential_lj(x, n_atoms) is the same Lennard-Jones potential. The atom configuration describes three moving atoms of one type to the kernel. MinimizationConfig has the fields of gpr_minimize_config_t under the same names, plus max_inner_steps in place of the thread-local request and use_hssvd_solver. policy takes a training policy; see Control what goes into the GP.

import numpy as np
import gpridge
from gpridge import (
    MinimizationConfig,
    gp_minimize,
    initialize_atoms_config,
    potential_lj,
)

n_atoms = 3
atoms = gpridge.AtomsConfiguration()
atoms.positions = np.zeros((1, 3 * n_atoms))
atoms.is_frozen = np.zeros((1, n_atoms), dtype=np.uint8)
atoms.id = np.arange(n_atoms, dtype=np.uint32).reshape(1, n_atoms)
atoms.atomic_nrs = np.full((1, n_atoms), 18, dtype=np.int32)
initialize_atoms_config(
    atoms, np.zeros(n_atoms, dtype=np.uint32), atoms.positions.copy(), -1.0, 1
)

calls = 0


def oracle(x):
    global calls
    calls += 1
    return potential_lj(x, n_atoms)


start = np.array([0.0, 0.0, 0.0, 1.3, 0.0, 0.0, 0.5, 1.0, 0.0])
config = MinimizationConfig()
config.verbose = False
config.conv_tol = 1e-3

result = gp_minimize(oracle, start, atoms, config)
assert result.converged and result.oracle_calls == calls
assert abs(result.e_final + 3.0) < 1e-6
assert np.linalg.norm(result.g_final) < config.conv_tol
pairs = [np.linalg.norm(result.x_final[3 * i:3 * i + 3] - result.x_final[3 * j:3 * j + 3])
         for i, j in ((0, 1), (0, 2), (1, 2))]
print(f"converged {result.converged}, E {result.e_final:.5f}, "
      f"{result.oracle_calls} oracle calls, {result.total_iterations} surrogate steps")
print("bond lengths", " ".join(f"{r:.4f}" for r in pairs))
trajectory = result.energy_trajectory
assert len(trajectory) == result.oracle_calls
print(f"{len(trajectory)} oracle energies, first {trajectory[0]:.3f}, "
      f"last {trajectory[-1]:.3f}")
converged True, E -3.00000, <n> oracle calls, <n> surrogate steps
bond lengths 1.1225 1.1225 1.1225
<n> oracle energies, first -2.358, last -3.000

MinimizationResult has x_final, e_final, g_final, converged and oracle_calls as above, plus:

  • total_iterations: the surrogate steps across all outer cycles;

  • energy_trajectory: the oracle energy of each evaluation in order. The first five are the initial design; the rest are the trust-region exits and stop checks, falling to \(-3\).