Compare the GPRidge binding examples¶
Each example below solves the same problem in the languages shown. The selected language carries across the examples. For the same GP-NEB calculation in Python, C++, C and Fortran, see the Lennard-Jones pentamer.
Build against an installed GPRidge shared library as described in Installation.
The build command for each native program is in its opening comment.
Build examples/band_examples.cpp once for all three settings.
The Python program declares its dependencies for uv run --script.
The C and C++ examples check the library’s ABI with GPR_ABI_CHECK() and GPR_SUCCESS.
The Fortran module exposes the same check as gpr_check_abi.
Band on the Muller–Brown surface¶
A standard nudged elastic band (NEB) finds the path between two minima of the two-dimensional Muller–Brown potential.
uv run --script examples/band_examples.py standard
def standard_band():
config = GPNEBConfig()
config.mode = NEBMode.Standard
config.verbose = False
config.max_outer_iter = 400
config.conv_tol = 0.5
return gp_neb(
potential_muller_brown,
np.array([-0.558224, 1.441726]),
np.array([0.623499, 0.028038]),
7,
config,
)
./band_examples standard
NebResult standardBand()
{
const std::array reactant{-0.558224, 1.441726};
const std::array product{0.623499, 0.028038};
auto config = gpr_neb_config_defaults();
config.mode = GPR_NEB_STANDARD;
config.verbose = 0;
config.max_outer_iter = 400;
config.conv_tol = 0.5;
return neb_search(gpr_oracle_muller_brown, nullptr, reactant.data(),
product.data(), 2, 7, config);
}
/* 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;
}
! SPDX-License-Identifier: MIT
! A nudged elastic band on the Muller-Brown surface through the Fortran
! module.
!
! Build against an installed library (gpridge.mod from the same compiler):
! gfortran fortran/gpridge.f90 fortran_neb_muller_brown.f90 \
! $(pkg-config --libs gpridge) -lstdc++
module mb_surface
use, intrinsic :: iso_c_binding
use gpridge, only: gpr_muller_brown_energy
implicit none
contains
!> The oracle. A failed evaluation would set a non-finite energy; the
!> search then rejects that trial.
subroutine oracle(n_coords, x, energy, gradient, user_data) bind(C)
integer(c_int), value :: n_coords
real(c_double), intent(in) :: x(n_coords)
real(c_double), intent(out) :: energy
real(c_double), intent(out) :: gradient(n_coords)
type(c_ptr), value :: user_data
call gpr_muller_brown_energy(x, energy, gradient)
end subroutine
end module mb_surface
program fortran_neb_muller_brown
use, intrinsic :: iso_c_binding
use gpridge
use mb_surface, only: oracle
implicit none
type(NEBConfig) :: config
type(NEBResult) :: path
real(c_double), allocatable :: energies(:)
character(len=256) :: message
integer :: stat, i
call gpr_check_abi()
print '(4a)', 'gpridge ', gpr_version_string(), ', linalg ', &
gpr_linalg_mode()
config%mode = GPR_NEB_STANDARD
config%verbose = 0
config%max_outer_iter = 400
config%conv_tol = 0.5d0
call gpr_neb_search(oracle, [-0.558224d0, 1.441726d0], &
[0.623499d0, 0.028038d0], 7, config, path, stat, message)
if (stat /= GPR_SUCCESS) then
print '(2a)', 'NEB failed: ', trim(message)
error stop 1
end if
call path%energies(energies)
do i = 1, size(energies)
print '(a, i0, a, f9.3)', 'image ', i - 1, ' E = ', energies(i)
end do
print '(a, l1, a, f7.2)', 'converged ', path%converged(), &
', barrier ', path%barrier()
deallocate(energies)
end program fortran_neb_muller_brown
Local band on a one-atom bowl¶
The local band calls the supplied oracle for the harmonic energy and gradient of a single atom. The result reports the oracle call count and the certificate status. The example limits the search to two outer iterations to show this report without waiting for convergence.
uv run --script examples/band_examples.py local
def local_band():
config = GPNEBConfig()
config.verbose = False
config.max_outer_iter = 2
config.conv_tol = 1.0
local = LocalBandConfig()
local.initial_sweep = False
local.inner_max = 1
local.refit_iters = 0
return neb_search_local(
bowl,
np.array([0.4, 0.0, 0.0]),
np.array([-0.2, 0.0, 0.0]),
1,
config=config,
local_config=local,
)
./band_examples local
NebResult localBand()
{
const std::array reactant{0.4, 0.0, 0.0};
const std::array product{-0.2, 0.0, 0.0};
auto config = gpr_neb_config_defaults();
config.verbose = 0;
config.max_outer_iter = 2;
config.conv_tol = 1.0;
auto local = gpr_local_band_config_defaults();
local.initial_sweep = 0;
local.inner_max = 1;
local.refit_iters = 0;
return neb_search_local(bowl, nullptr, nullptr, nullptr, reactant.data(),
product.data(), 3, 1, &config, &local);
}
/* 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;
}
! SPDX-License-Identifier: MIT
! A local band on a one-atom bowl through the Fortran module.
!
! gfortran fortran/gpridge.f90 fortran_local_band.f90 \
! $(pkg-config --libs gpridge) -lstdc++
module bowl_oracle
use, intrinsic :: iso_c_binding
implicit none
contains
subroutine oracle(n_coords, x, energy, gradient, user_data) bind(C)
integer(c_int), value :: n_coords
real(c_double), intent(in) :: x(n_coords)
real(c_double), intent(out) :: energy
real(c_double), intent(out) :: gradient(n_coords)
type(c_ptr), value :: user_data
integer :: i
energy = 0.0d0
do i = 1, n_coords
energy = energy + 0.5d0 * x(i) * x(i)
gradient(i) = x(i)
end do
end subroutine
end module bowl_oracle
program fortran_local_band
use, intrinsic :: iso_c_binding
use gpridge
use bowl_oracle, only: oracle
implicit none
type(NEBConfig) :: config
type(LocalBandConfig) :: local
type(NEBResult) :: path
type(NEBReport) :: report
real(c_double) :: reactant(3), product(3)
character(len=256) :: message
integer :: stat
call gpr_check_abi(stat, message)
if (stat /= 0) then
write (0, '(a)') trim(message)
error stop 1
end if
print '(3a)', 'gpridge ', gpr_version_string(), ', local band'
reactant = [0.4d0, 0.0d0, 0.0d0]
product = [-0.2d0, 0.0d0, 0.0d0]
config = NEBConfig()
config%verbose = 0
config%max_outer_iter = 2
config%conv_tol = 1.0d0
local = LocalBandConfig()
local%initial_sweep = 0
local%inner_max = 1
local%refit_iters = 0
call gpr_neb_search_local(oracle, reactant, product, 1, path, stat, message, &
config=config, local=local)
if (stat /= 0) then
write (0, '(a)') trim(gpr_last_error_message())
error stop 1
end if
call path%report(report, stat, message)
if (stat /= 0) error stop 1
print '(a,i0,a,i0,a,i0,a,i0)', 'images ', path%n_images(), &
' certificate ', report%n_certificate_calls, ' index ', report%index, &
' certified ', report%certified
if (report%oracle_calls < report%oracle_calls_to_convergence + &
report%n_certificate_calls) error stop 1
end program fortran_local_band
Periodic band with a frozen neighbour¶
The periodic local band takes a cell and an atom descriptor. The frozen atom stays fixed while the moving atom relaxes across the band.
uv run --script examples/band_examples.py periodic
def periodic_band():
reactant = np.array([0.4, 0.0, 0.0, 0.2, 0.0, 0.0])
product = np.array([-0.3, 0.0, 0.0, 0.2, 0.0, 0.0])
cell = 8.0 * np.eye(3)
atoms = Atoms("H2", positions=reactant.reshape(2, 3), cell=cell, pbc=True)
config = PeriodicBandConfig()
config.verbose = 0
config.fmax = 0.05
config.steps = 40
config.convergence_norm = ConvergenceNorm.L2
band = neb_search_periodic(
bowl,
reactant,
product,
3,
box=cell,
atoms_config=atoms_config_from_ase(atoms, frozen_indices=[1]),
periodic_config=config,
)
for i in range(len(band.image_energies())):
if not np.array_equal(band.image_positions(i)[3:], reactant[3:]):
raise SystemExit(f"frozen atom moved on image {i}")
return band
./band_examples periodic
NebResult periodicBand()
{
const std::array reactant{0.4, 0.0, 0.0, 0.2, 0.0, 0.0};
const std::array product{-0.3, 0.0, 0.0, 0.2, 0.0, 0.0};
const std::array cell{8.0, 0.0, 0.0, 0.0, 8.0, 0.0, 0.0, 0.0, 8.0};
const std::array frozen{0, 1};
const std::array numbers{1, 1};
auto descriptor = gpr_atoms_config_defaults();
descriptor.n_atoms_total = 2;
descriptor.is_frozen = frozen.data();
descriptor.atomic_nrs = numbers.data();
const auto atoms = Atoms::create(descriptor);
auto config = gpr_periodic_band_config_defaults();
config.verbose = 0;
config.fmax = 0.05;
config.steps = 40;
config.convergence_norm = GPR_NORM_L2;
auto band =
neb_search_periodic(bowl, nullptr, &atoms, cell.data(), reactant.data(),
product.data(), 6, 3, &config);
for (int i = 0; i < band.n_images(); ++i) {
const auto x = band.image_positions(i, 6);
if (!std::equal(x.begin() + 3, x.end(), reactant.begin() + 3))
throw std::runtime_error("frozen atom moved");
}
return band;
}
/* 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;
}
! SPDX-License-Identifier: MIT
! A periodic local band through the Fortran module: one atom slides across
! a frozen neighbour in an orthorhombic cell.
!
! gfortran fortran/gpridge.f90 fortran_periodic_band.f90 \
! $(pkg-config --libs gpridge) -lstdc++
module periodic_slide
use, intrinsic :: iso_c_binding
implicit none
contains
subroutine oracle(n_coords, x, energy, gradient, user_data) bind(C)
integer(c_int), value :: n_coords
real(c_double), intent(in) :: x(n_coords)
real(c_double), intent(out) :: energy
real(c_double), intent(out) :: gradient(n_coords)
type(c_ptr), value :: user_data
integer :: i
energy = 0.0d0
do i = 1, n_coords
energy = energy + 0.5d0 * x(i) * x(i)
gradient(i) = x(i)
end do
end subroutine
end module periodic_slide
program fortran_periodic_band
use, intrinsic :: iso_c_binding
use gpridge
use periodic_slide, only: oracle
implicit none
integer, parameter :: n_atoms = 2, n_images = 3
real(c_double) :: reactant(3 * n_atoms), product(3 * n_atoms)
real(c_double) :: cell(9), image(3 * n_atoms)
real(c_double), allocatable :: energies(:)
integer :: numbers(n_atoms), stat, i
logical :: frozen(n_atoms)
type(AtomsConfig) :: atoms
type(PeriodicBandConfig) :: band
type(NEBResult) :: path
type(NEBReport) :: report
character(len=256) :: message
call gpr_check_abi(stat, message)
if (stat /= GPR_SUCCESS) error stop message
print *, 'gpridge ', trim(gpr_version_string()), ', periodic band'
reactant = [0.4d0, 0.0d0, 0.0d0, 0.2d0, 0.0d0, 0.0d0]
product = [-0.3d0, 0.0d0, 0.0d0, 0.2d0, 0.0d0, 0.0d0]
cell = 0.0d0
cell(1) = 8.0d0
cell(5) = 8.0d0
cell(9) = 8.0d0
frozen = [.false., .true.]
numbers = 1
atoms = AtomsConfig(n_atoms, is_frozen=frozen, atomic_nrs=numbers, &
stat=stat, errmsg=message)
if (stat /= GPR_SUCCESS) error stop message
band = PeriodicBandConfig()
band%verbose = 0
band%fmax = 0.05d0
band%steps = 40
band%convergence_norm = GPR_NORM_L2
call gpr_neb_search_periodic(oracle, reactant, product, n_images, path, &
stat, message, periodic=band, atoms=atoms, box=cell)
if (stat /= GPR_SUCCESS) error stop message
call path%report(report, stat, message)
if (stat /= GPR_SUCCESS) error stop message
call path%energies(energies, stat, message)
if (stat /= GPR_SUCCESS) error stop message
do i = 0, path%n_images() - 1
print '(a, i0, a, f9.4)', 'image ', i, ' E = ', energies(i + 1)
call path%image_positions(i, image, 3 * n_atoms, stat)
if (stat /= GPR_SUCCESS) error stop message
if (maxval(abs(image(4:6) - product(4:6))) > 0.0d0) &
error stop 'frozen atom moved'
end do
print '(a, i0, a, i0, a, i0, a, f8.4)', 'converged ', &
merge(1, 0, path%converged()), ' certificate ', &
report%n_certificate_calls, ' certified ', report%certified, &
' barrier ', report%barrier
if (report%n_certificate_calls /= 0 .or. report%certified /= 0) error stop 1
if (allocated(energies)) deallocate(energies)
call path%release()
end program fortran_periodic_band
The examples are in the repository’s examples directory.