Fortran module

Fortran module

fortran/gpridge.f90 is a Fortran 2018 module over the C API. It wraps the handles in derived types with finalizers, mirrors the configuration structs as bind(C) types with the library defaults as initializers, and takes Fortran procedures as oracles.

Tutorial: a Muller-Brown band in Fortran

The oracle is a bind(C) module procedure with the gpr_oracle_interface interface; gpr_neb_search passes it to the C API.

! 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
gfortran fortran/gpridge.f90 examples/fortran_neb_muller_brown.f90 \
    $(pkg-config --libs gpridge) -lstdc++
./a.out
gpridge X.Y.Z, linalg reproducible
image 0  E =  -146.700
image 1  E =   -93.589
image 2  E =   -40.665
...
image 8  E =  -108.167
converged T, barrier  106.03

The first line shows the installed version in place of X.Y.Z; the page does not copy it, so it cannot go stale. The band and its barrier match the C program on the C API page image for image.

The suite builds and runs this program as example_fortran_neb_muller_brown.

Local band

gpr_neb_search_local is the local band. LocalBandConfig() returns gpr_local_band_config_defaults(). gpr_last_error_message() is the thread-local error string. The band report carries certified, index and n_certificate_calls; the certificate count is separate from the search count.

! 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

The suite builds and runs this program as example_fortran_local_band.

Periodic band

gpr_neb_search_periodic is the periodic local band. PeriodicBandConfig() returns gpr_periodic_band_config_defaults(), the same record as GPLocalBand. LocalBandConfig still carries the local knobs. The search does not certify; gpr_neb_request_index_certificate does, and the report’s certified, index and n_certificate_calls record it.

! 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 suite builds and runs this program as example_fortran_periodic_band.

Reference

Errors: stat and errmsg

The search and configuration procedures take stat and errmsg as the allocate statement does. With stat present it receives the C status (GPR_SUCCESS or a negative GPR_ERR_* code) and errmsg, if present, the message; nothing stops. Without stat a failure ends the program with error stop and the message. The older GP model procedures keep their optional ierr and never stop.

call gpr_set_linalg_mode('library', stat, message)
if (stat == GPR_ERR_INVALID_ARG) print *, trim(message)

gpr_error_message() returns the message of the last failing call.

Oracle failures

An oracle reports a failed evaluation by setting a non-finite energy, for example ieee_value(energy, ieee_quiet_nan). The dimer and NEB searches reject that trial and continue; more than eight consecutive failures give stat = GPR_ERR_ORACLE=. gpr_minimize stops at the first failure.

Procedures

Procedure

Purpose

gpr_neb_search(oracle, R_initial, R_final, n_images, config, result, stat, errmsg, user_data)

NEB; result is a NEBResult

gpr_neb_search_potential(force, atomic_nrs, R_initial, R_final, n_images, config, result, stat, errmsg, box, user_data)

NEB over a force callback

gpr_neb_search_gp(oracle, atoms, R_initial, R_final, n_images, config, result, stat, errmsg, model, user_data)

GP-OIE / GP-AIE NEB; frozen atoms of atoms stay put

gpr_neb_search_gp_potential(force, atoms, R_initial, R_final, n_images, config, result, stat, errmsg, model, box, user_data)

The same over a force callback

gpr_neb_search_local(oracle, R_initial, R_final, n_images, result, stat, errmsg, config, local, atoms, box, user_data)

Local band

gpr_neb_search_periodic(oracle, R_initial, R_final, n_images, result, stat, errmsg, periodic, local, atoms, box, user_data)

Periodic local band (PeriodicBandConfig)

gpr_ocineb_search(oracle, atoms, R_initial, R_final, n_images, config, result, stat, errmsg, oci, model, user_data)

GP band with dimer bursts (OCINEBConfig)

gpr_dimer_search(force, atoms, R_init, orient_init, config, R_saddle, E_saddle, report, stat, errmsg, orient_out, user_data)

Dimer; report is a DimerReport

gpr_minimize(oracle, R_init, atoms, config, R_final, E_final, converged, n_oracle_calls, stat, errmsg, G_final, user_data)

GP minimizer

gpr_minimize_request_max_inner_steps(max_inner_steps, stat, errmsg)

Inner surrogate step cap for the next gpr_minimize on this thread (ABI 1.18)

gpr_set_linalg_mode, gpr_linalg_mode

--linalg-mode

gpr_set_linalg_threads

--linalg-threads

gpr_set_training_product, gpr_training_product_configured

--training-product-library

gpr_check_model_package

ISA check of an AOTInductor package

gpr_check_abi, gpr_version_string, gpr_version_components, gpr_abi_version

ABI check and versions

gpr_status_name, gpr_last_status, gpr_error_message

Status of the last failing call

gpr_backend_name, gpr_backend_requires_mpi, gpr_mpi_initialized, gpr_mpi_world_rank, gpr_mpi_world_size, gpr_omp_max_threads

Build and process introspection

GPModel, AtomsConfig

GP model training and prediction (tutorial )

NEBResult%report(report, stat, errmsg), NEBResult%max_energy_image()

NEBReport of any NEB run

GPModel%predict_full, GPModel%predict_batch, GPModel%model_type

Mean and variance in one call, many points

GPModel%train_marginal_likelihood, GPModel%append_fixed, GPModel%calibrate_forces, GPModel%calibrate_loo

ABI 1.13 prior-free fit, fixed-factor append, held-out force and closed-form LOO calibration

AtomsConfig(n_atoms) gives identical moving atoms; AtomsConfig(n_atoms, is_frozen…, atom_types=…, atomic_nrs=…, positions=…, actdist_fro=…, stat=…, errmsg=…)= builds the C descriptor of gpr_atoms_create, with frozen atoms as a logical array and type indices from 0.

Arrays are assumed-shape: the procedures take sizes from the arguments and refuse mismatched lengths with GPR_ERR_INVALID_ARG before calling the library. That includes the GPModel procedures train, update, predict, predict_variance, predict_full, predict_batch, get_lengthscales and set_lengthscales, train_marginal_likelihood, append_fixed, calibrate_forces, calibrate_loo, the NEBResult%image_positions procedure and gpr_lj_energy: a buffer shorter than the call needs returns the status and is left unwritten, where an assumed-size dummy argument used to let the C layer read or write past it. The GPModel calls go through the extent-checked C functions of ABI 1.11 through 1.13, and set_hssvd_backend / get_hssvd_backend are the ABI 1.19 solver selector, so the check lives in the C layer. A section such as query(7:12) is accepted, and a non-contiguous section is copied by the compiler. NEBResult%energies returns an allocatable array.

BQFitReport is the interoperable copy of gpr_bq_fit_report_t, the MarginalLikelihoodReport fields plus failed_trials; pass it to c_gpr_bq_fit_hyperparameters_checked, whose report argument is untyped, and never a MarginalLikelihoodReport, which is smaller.

MarginalLikelihoodReport and CalibrationReport are interoperable copies of the C reports. The former returns the prior-free Gaussian negative log marginal likelihood and its components in physical output coordinates, physical signal and noise variances, optimizer iterations (rgmin’s SCG steps plus the L-BFGS fallback steps that finish a stalled rgmin SCG fit), and length-scale count. The latter is shared by held-out force and LOO calibration and returns standardized-residual moments, physical mean log predictive density, and central-normal coverage before and after the RMS calibration scale is applied. Held-out exactly deterministic zero-residual components are omitted without applying a variance floor.

Callback interfaces

subroutine gpr_oracle_interface(n_coords, positions, energy, gradient, user_data) bind(C)
  integer(c_int), value :: n_coords
  real(c_double), intent(in) :: positions(n_coords)
  real(c_double), intent(out) :: energy, gradient(n_coords)
  type(c_ptr), value :: user_data

subroutine gpr_force_interface(n_atoms, positions, atomic_nrs, forces, energy, &
    energy_noise_rms, box, user_data) bind(C)
  integer(c_long), value :: n_atoms
  real(c_double), intent(in) :: positions(3 * n_atoms)
  integer(c_int), intent(in) :: atomic_nrs(n_atoms)
  real(c_double), intent(out) :: forces(3 * n_atoms), energy
  type(c_ptr), value :: energy_noise_rms, box, user_data   ! may be C_NULL_PTR

The force callback returns forces, not gradients. energy_noise_rms is the root-mean-square noise on the energy (a standard deviation in eV, not a variance; the slot was called variance before). user_data passes any c_loc target through unchanged.

Configuration types

NEBConfig, DimerConfig, MinimizeConfig, ModelConfig and OCINEBConfig are bind(C) copies of the C structs in field order. A default-initialized variable equals the C \*_config_defaults(), and NEBConfig(), ModelConfig(), MinimizeConfig(), OCINEBConfig() and gpr_*_config_defaults() return the loaded library’s own defaults. test_fortran_layout compares the initializers with the library field by field, so a changed C default fails the suite instead of drifting, and compares c_sizeof and the offset of the last member of every bind(C) type, AtomsDescriptor included, with sizeof and offsetof from a C translation unit. DimerReport carries the outcome of a dimer search; its max_oracle_calls is read as a budget. NEBReport is gpr_neb_report_t. When NEBConfig%use_idpp is nonzero, SIDPP is the library default. Call gpr_neb_request_sidpp(.false.) before a search to select classic IDPP, or pass .true. to select SIDPP explicitly. The request is thread-local and is consumed by the next search even when its arguments fail validation. It has no effect on gpr_neb_search_periodic or gpr_neb_search_periodic_potential: periodic bands take their initializer from PeriodicBandConfig%initial alone, and both searches still consume the request. On both periodic entry points a nonzero step of gpr_neb_request_index_certificate takes precedence over LocalBandConfig%certificate_step.

Module files

A .mod file is specific to the compiler and its version. Compile gpridge.f90 with the compiler that builds the program; the library itself has no Fortran dependency. The suite builds it with gfortran 15 and 16 and -std=f2018.