How to use the searches from Fortran

This page shows how to run the library’s searches (the minimizer, the dimer and the bands) from Fortran with your own energy and force routine. It assumes you can compile and run a program against libgpridge; the Fortran tutorial shows how and also covers the Gaussian process model. Every program on this page is complete and is compiled and run by scripts/run_doc_examples.py.

Choose the procedure

The module gpridge wraps each search of the C API in a procedure that takes a Fortran callback. The callback is an oracle, which returns the energy and the gradient of the coordinates, or a force routine, which returns the energy and the forces of atoms with atomic numbers.

Procedure

Search

Callback

gpr_minimize

GP-accelerated minimization

gpr_oracle_interface

gpr_dimer_search

GP-accelerated dimer saddle search

gpr_force_interface

gpr_neb_search

NEB without a GP (standard, AIE, OIE)

gpr_oracle_interface

gpr_neb_search_potential

the same over a force routine

gpr_force_interface

gpr_neb_search_gp

GP-accelerated NEB (modes GPR_NEB_GP_OIE, GPR_NEB_GP_AIE)

gpr_oracle_interface

gpr_neb_search_gp_potential

the same over a force routine

gpr_force_interface

gpr_ocineb_search

GP-NEB with dimer bursts at the climbing image

gpr_oracle_interface

gpr_neb_search_local

local band

gpr_oracle_interface

gpr_neb_search_local_potential

the same over a force routine

gpr_force_interface

gpr_neb_search_periodic

periodic local band

gpr_oracle_interface

gpr_neb_search_periodic_potential

the same over a force routine

gpr_force_interface

Every argument, type and default is in the generated Fortran API reference. A complete band on the Muller-Brown surface, and the local and periodic bands, are on the Fortran module page. This page covers the minimizer and the dimer, then the error convention that all of them share.

Write the callback

A callback is a module procedure with bind(C) and the argument list of the interface. Pass it by name.

  • An oracle has the interface gpr_oracle_interface: (n_coords, positions, energy, gradient, user_data). It returns the gradient \(\mathrm{d}E/\mathrm{d}R\).

  • A force routine has the interface gpr_force_interface: (n_atoms, positions, atomic_nrs, forces, energy, variance, box, user_data). It returns the forces \(F = -\mathrm{d}E/\mathrm{d}R\). variance and box are C pointers that may be C_NULL_PTR.

  • user_data is a type(c_ptr). The search procedures take an optional user_data and hand it back unchanged.

  • To report that an evaluation failed, set energy to a non-finite value. The searches reject that trial and carry on; the section on errors below gives the limit.

Coordinates are in the units of your routine. The library converts none.

Minimize with your own potential

The program minimizes a Lennard-Jones pair in reduced units (\(\epsilon = \sigma = 1\)). The start has the atoms 1.4 apart and the minimum is at \(2^{1/6}\).

module lj_oracle_mod
  use, intrinsic :: iso_c_binding, only: c_int, c_double, c_ptr
  use gpridge, only: gpr_lj_energy
  implicit none
contains
  subroutine lj_pair(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_lj_energy(x, 2, 1.0d0, 1.0d0, energy, gradient)
  end subroutine
end module lj_oracle_mod

program minimize_pair
  use, intrinsic :: iso_c_binding, only: c_double
  use gpridge
  use lj_oracle_mod, only: lj_pair
  implicit none

  type(AtomsConfig) :: atoms
  type(MinimizeConfig) :: config
  real(c_double) :: start(6), x(6), g(6), energy, separation
  real(c_double) :: e_true, g_true(6)
  logical :: converged
  integer :: calls, stat
  character(len=256) :: message

  atoms = AtomsConfig(2)
  config = MinimizeConfig()
  config%conv_tol = 1.0d-3
  config%verbose = 0

  start = [0.0d0, 0.0d0, 0.0d0, 1.4d0, 0.0d0, 0.0d0]
  call gpr_minimize(lj_pair, start, atoms, config, x, energy, converged, &
                    calls, stat, message, G_final=g)
  if (stat /= GPR_SUCCESS) error stop trim(message)

  separation = norm2(x(4:6) - x(1:3))
  print '(a,l1,a,i0,a)', "converged ", converged, " after ", calls, &
      " oracle calls"
  print '(a,f9.5,a,f9.5)', "E = ", energy, "  separation = ", separation
  if (.not. converged) error stop "not converged"

  ! E_final and G_final are oracle values; the potential agrees
  call gpr_lj_energy(x, 2, 1.0d0, 1.0d0, e_true, g_true)
  print '(a,f9.5,a,es9.2)', "potential at the result: E = ", e_true, &
      "  max |gradient| = ", maxval(abs(g_true))
  if (maxval(abs(g_true)) > 5.0d-2) error stop "result is not a minimum"
end program minimize_pair
converged T after <n> oracle calls
E =  -1.00000  separation =   1.12247
potential at the result: E =  -1.00000  max |gradient| =  <s>

The energy and the separation are the Lennard-Jones minimum. The oracle call count and the residual gradient depend on the stepper, so the listing does not pin them. The program asserts that the search converged and that the true gradient at the result is below 0.05.

About the result:

  • E_final and G_final are an exact evaluation of your routine at R_final, never a model prediction or a merged near-coincident row. converged is true only when that gradient’s norm is below conv_tol; a small model gradient only proposes the stop. Without convergence the result is the lowest point the oracle measured.

  • The GP kernel is a function of pair distances. A potential that depends on absolute positions, such as a harmonic well at the origin, gives the model no features to fit. The minimizer then spends its oracle budget without converging. Use a potential of an atomic system.

  • config%max_iter bounds outer surrogate-relaxation cycles of up to 200 inner surrogate steps each. Call gpr_minimize_request_max_inner_steps (C ABI 1.18) before gpr_minimize to change that cap for the next search on the thread; the C entry point of the same name does the same. config%max_oracle_calls is never exceeded; 0 leaves the calls unbounded.

  • The first failed oracle evaluation ends gpr_minimize with GPR_ERR_ORACLE.

The first training inside the search prints one diagnostic line starting with [hssvd] on standard error. It does not affect the result.

Handle errors

The search and configuration procedures take stat and errmsg the way the allocate statement does. With stat present, it receives the status and errmsg receives the message of a failure. With stat absent, a failure stops the program with the message. The GP model procedures keep their optional ierr (see the tutorial); they do not stop the program.

The status codes are the GPR_* constants of the module. gpr_status_name(stat) gives the name of a code and gpr_error_message() the message of the last failing call on the calling thread. The next status-returning call resets it, so read it right after the failure.

A potential reports a failed evaluation with a non-finite energy. The dimer and the bands reject that trial. After more than eight consecutive failures the search returns GPR_ERR_ORACLE; gpr_minimize returns it at the first failure. The program shows a configuration error and an oracle error:

module failing_oracle_mod
  use, intrinsic :: iso_c_binding, only: c_int, c_double, c_ptr
  use, intrinsic :: ieee_arithmetic, only: ieee_value, ieee_quiet_nan
  implicit none
contains
  ! An oracle that cannot evaluate: it reports the failure with a NaN energy.
  subroutine always_fails(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
    energy = ieee_value(energy, ieee_quiet_nan)
    gradient = 0.0d0
  end subroutine
end module failing_oracle_mod

program errors
  use, intrinsic :: iso_c_binding, only: c_double
  use gpridge
  use failing_oracle_mod, only: always_fails
  implicit none

  type(AtomsConfig) :: atoms
  type(MinimizeConfig) :: config
  real(c_double) :: x(6), energy
  logical :: converged
  integer :: calls, stat
  character(len=256) :: message

  ! A configuration call that is refused
  message = ""
  call gpr_set_linalg_mode("fastest", stat, message)
  print '(a,a)', gpr_status_name(stat), ": " // trim(message)
  if (stat /= GPR_ERR_INVALID_ARG) error stop "an unknown mode must be refused"

  ! A search whose oracle fails on every call
  atoms = AtomsConfig(2)
  config = MinimizeConfig()
  config%verbose = 0
  message = ""
  call gpr_minimize(always_fails, [0.0d0, 0.0d0, 0.0d0, 1.4d0, 0.0d0, 0.0d0], &
                    atoms, config, x, energy, converged, calls, stat, message)
  print '(a,a)', gpr_status_name(stat), ": " // trim(message)
  if (stat /= GPR_ERR_ORACLE) error stop "a failing oracle gives GPR_ERR_ORACLE"
  if (converged) error stop "a failed search is not converged"
end program errors
GPR_ERR_INVALID_ARG: linalg mode must be reproducible or library, got fastest
GPR_ERR_ORACLE: oracle callback failed: non-finite energy or gradient

A search that fails does not hand back a result: gpr_minimize sets converged to false, and the band searches leave the NEBResult invalid (path%is_valid() is false).

See also