Tutorial: Fortran interop ========================= This tutorial calls ``libgpridge`` from Fortran through the module ``fortran/gpridge.f90``. It builds three programs. The first checks the library and evaluates analytical potentials. The second trains a Gaussian process on Lennard-Jones data and predicts with it. The third reads the fitted hyperparameters and adds an observation to the trained model. Each program is complete and is compiled and run by the documentation test (``scripts/run_doc_examples.py``) against the build tree. The tutorial needs no knowledge of the C API. The searches (dimer, NEB, minimizer) are in the how-to :doc:`Use the searches from Fortran <../howto/fortran_capi>`. Before you start ---------------- You need three things: - The shared library ``libgpridge``, built from this repository (see the :doc:`installation page <../getting-started/installation>`). The commands below assume the build directory is ``builddir``. - ``gfortran``. The module is a Fortran 2018 module over the C API. - The module source ``fortran/gpridge.f90`` from the same checkout as the library. The module and the library must come from one version: the module records the C ABI version it binds, and ``gpr_check_abi`` (step 1) compares it with the library at run time. Compile the module and your program in one command, and link the library: .. code:: bash gfortran -I fortran -J . fortran/gpridge.f90 program.f90 -o program \ -L builddir -lgpridge -Wl,-rpath,"$PWD/builddir" -lm ./program ``-J .`` writes ``gpridge.mod`` to the current directory. For an installed library use ``$(pkg-config --libs gpridge)`` in place of the ``-L`` and ``-l`` flags. The repository also holds a Fortran Package Manager manifest, ``fpm.toml``, which builds the module and links ``gpridge`` and ``stdc++``; its header comment names the two environment variables it needs. Each program below is the whole content of ``program.f90``. Step 1: Check the library and call a potential ---------------------------------------------- ``use gpridge`` makes the module procedures and derived types visible. It does not re-export the ``iso_c_binding`` names, so import ``c_double`` yourself. The module has three analytical test potentials, which need no external calculator: ``gpr_muller_brown_energy``, ``gpr_lj_energy`` and ``gpr_leps_energy``. Each returns the energy and the gradient. .. code:: fortran program potentials use gpridge use, intrinsic :: iso_c_binding, only: c_double implicit none integer :: abi_major, abi_minor real(c_double) :: xy(2), energy, gradient(2) real(c_double) :: pair(6), pair_gradient(6) call gpr_check_abi() call gpr_abi_version(abi_major, abi_minor) print '(a,i0,a,i0)', "libgpridge " // gpr_version_string() // ", C ABI ", & abi_major, ".", abi_minor ! Muller-Brown at its deepest minimum xy = [-0.558224d0, 1.441726d0] call gpr_muller_brown_energy(xy, energy, gradient) print '(a,f9.3)', "Muller-Brown energy = ", energy print '(a,2es10.2)', "gradient = ", gradient if (abs(energy + 146.7d0) > 0.1d0) error stop "unexpected minimum energy" if (maxval(abs(gradient)) > 1.0d-2) error stop "gradient not small at the minimum" ! Lennard-Jones pair, epsilon = sigma = 1, at its minimum 2**(1/6) pair = [0.0d0, 0.0d0, 0.0d0, 2.0d0**(1.0d0/6.0d0), 0.0d0, 0.0d0] call gpr_lj_energy(pair, 2, 1.0d0, 1.0d0, energy, pair_gradient) print '(a,f9.5)', "LJ pair energy = ", energy if (abs(energy + 1.0d0) > 1.0d-9) error stop "LJ minimum is -epsilon" if (maxval(abs(pair_gradient)) > 1.0d-9) error stop "LJ gradient is zero at the minimum" end program potentials :: libgpridge X.Y.Z, C ABI 1. Muller-Brown energy = -146.700 gradient = -1.11E-03 1.02E-03 LJ pair energy = -1.00000 ``gpr_check_abi`` compares the ABI version the module was written for with the one the loaded library reports. Without a ``stat`` argument it stops the program with the library's message on a mismatch; with ``stat`` it returns the status instead. The version line shows ``X.Y.Z`` and ``1.N`` here because the exact numbers belong to your build. ``gpr_lj_energy(x, n_atoms, epsilon, sigma, energy, gradient)`` takes the :math:`3 n_{\mathrm{atoms}}` coordinates in one array, atom by atom. The library converts no units. With :math:`\epsilon = \sigma = 1` the Lennard-Jones energy is in units of :math:`\epsilon` and the length in units of :math:`\sigma`. The Muller-Brown surface is the standard two-dimensional test surface in arbitrary units. Step 2: Train a model and predict --------------------------------- The Gaussian process kernel works on pair distances. This step trains it on a Lennard-Jones pair at six separations. Each training row holds the energy and the gradient, so one observation gives :math:`1 + n_{\mathrm{coords}}` numbers. Three objects are involved: - ``AtomsConfig(n_atoms)`` describes the atoms. With one argument, all atoms are identical and all move. It is the Fortran form of ``gpr_atoms_create_simple``. - ``ModelConfig()`` holds the model settings and returns the library defaults (``gpr_model_config_defaults``). - ``GPModel(GPR_MODEL_GP)`` is the model. ``GPR_MODEL_TP`` selects a Student-t process. The model procedures return their status in an optional ``ierr``. If you omit ``ierr``, a failure is not reported to the caller, so check it. The message of the failing call is ``gpr_error_message()``. Arrays are flat. The training positions ``R`` hold the observations one after another, :math:`n_{\mathrm{coords}} = 3 n_{\mathrm{moving\ atoms}}` values each; ``E`` holds one energy per observation; ``G`` holds :math:`n_{\mathrm{coords}}` gradient components per observation (the gradient, not the force). .. code:: fortran program train_and_predict use gpridge use, intrinsic :: iso_c_binding, only: c_double implicit none integer, parameter :: n_atoms = 2, n_coords = 3 * n_atoms, n_obs = 6 real(c_double), parameter :: separation(n_obs) = & [0.95d0, 1.05d0, 1.15d0, 1.3d0, 1.5d0, 1.8d0] type(AtomsConfig) :: atoms type(GPModel) :: model type(ModelConfig) :: config real(c_double) :: R(n_obs * n_coords), E(n_obs), G(n_obs * n_coords) real(c_double) :: query(n_coords), e_exact, g_exact(n_coords) real(c_double) :: e_pred, g_pred(n_coords), var_e, var_g(n_coords) real(c_double) :: var_inside, var_far integer :: i, first, last, ierr call gpr_check_abi() do i = 1, n_obs first = n_coords * (i - 1) + 1 last = n_coords * i R(first:last) = [0.0d0, 0.0d0, 0.0d0, separation(i), 0.0d0, 0.0d0] call gpr_lj_energy(R(first:last), n_atoms, 1.0d0, 1.0d0, E(i), & G(first:last)) end do atoms = AtomsConfig(n_atoms) model = GPModel(GPR_MODEL_GP) config = ModelConfig() call model%init(config, atoms, ierr) if (ierr /= GPR_SUCCESS) error stop gpr_error_message() call model%train(R, E, G, n_obs, n_coords, ierr) if (ierr /= GPR_SUCCESS) error stop gpr_error_message() print '(a,i0,a)', "trained on ", model%n_observations(), " observations" ! A separation between two training points query = [0.0d0, 0.0d0, 0.0d0, 1.2d0, 0.0d0, 0.0d0] call gpr_lj_energy(query, n_atoms, 1.0d0, 1.0d0, e_exact, g_exact) call model%predict(query, e_pred, g_pred, n_coords, ierr) if (ierr /= GPR_SUCCESS) error stop gpr_error_message() call model%predict_variance(query, var_e, var_g, n_coords, ierr) if (ierr /= GPR_SUCCESS) error stop gpr_error_message() var_inside = var_e print '(a,f9.5,a,f9.5)', "energy exact", e_exact, " predicted", e_pred print '(a,f9.5,a,f9.5)', "dE/dx(2) exact", g_exact(4), " predicted", g_pred(4) print '(a,es9.2)', "variance at 1.2 = ", var_inside if (abs(e_pred - e_exact) > 1.0d-2) error stop "prediction off" ! Far from the data the variance is larger query(4) = 3.0d0 call model%predict_variance(query, var_far, var_g, n_coords, ierr) if (ierr /= GPR_SUCCESS) error stop gpr_error_message() print '(a,es9.2)', "variance at 3.0 = ", var_far if (var_far <= var_inside) error stop "variance should grow away from the data" call model%release() call atoms%release() end program train_and_predict :: trained on 6 observations energy exact -0.89097 predicted -0.89697 dE/dx(2) exact 2.21169 predicted 2.27691 variance at 1.2 = 1.44E-04 variance at 3.0 = 4.87E+00 The program asserts three things: the predicted energy at separation 1.2 agrees with the potential to 0.01, the variance there is smaller than the variance at separation 3.0, which lies outside the training range, and every library call succeeds. The digits above come from the reference x86-64 build and may differ in your build. The first training call prints one diagnostic line starting with ``[hssvd]`` on standard error. It does not affect the result. ``AtomsConfig``, ``GPModel`` and the search result ``NEBResult`` are reference-counted wrappers with finalizers. Assignment (``a = b``) shares the underlying handle and each wrapper releases its own reference. ``release`` frees a reference at once. The programs call it at the end to show the call; the finalizer does the same when the variable goes out of scope. Step 3: Read the hyperparameters and add an observation ------------------------------------------------------- After ``train``, the optimiser has fitted the kernel hyperparameters. ``n_lengthscales``, ``get_lengthscales``, ``get_magn_sigma2``, ``get_sigma2``, ``get_jitter`` and ``get_alpha`` read them and the posterior weights. The accessors with a buffer take its size from the array you pass. A buffer that is too small is refused with ``GPR_ERR_INVALID_ARG`` and is not written. ``update`` appends observations to a trained model and fits the model again on the whole set. It is not a rank-one update. The arrays have the same layout as for ``train``: with ``n_new = 1``, ``R_new`` and ``G_new`` each hold :math:`n_{\mathrm{coords}}` values and ``E_new`` holds one. The reproduction check below is the rgmin optimizer's posterior. .. code:: fortran program hyperparameters_and_update use gpridge use, intrinsic :: iso_c_binding, only: c_double implicit none integer, parameter :: n_atoms = 2, n_coords = 3 * n_atoms, n_obs = 6 real(c_double), parameter :: separation(n_obs) = & [0.95d0, 1.05d0, 1.15d0, 1.3d0, 1.5d0, 1.8d0] type(AtomsConfig) :: atoms type(GPModel) :: model type(ModelConfig) :: config real(c_double) :: R(n_obs * n_coords), E(n_obs), G(n_obs * n_coords) real(c_double) :: query(n_coords), e_new(1), g_new(n_coords) real(c_double) :: e_pred, g_pred(n_coords), var_before, var_after real(c_double) :: var_g(n_coords), magn_sigma2, sigma2, jitter real(c_double), allocatable :: lengthscale(:), alpha(:), too_short(:) integer :: i, first, last, ierr call gpr_check_abi() do i = 1, n_obs first = n_coords * (i - 1) + 1 last = n_coords * i R(first:last) = [0.0d0, 0.0d0, 0.0d0, separation(i), 0.0d0, 0.0d0] call gpr_lj_energy(R(first:last), n_atoms, 1.0d0, 1.0d0, E(i), & G(first:last)) end do atoms = AtomsConfig(n_atoms) model = GPModel(GPR_MODEL_GP) config = ModelConfig() ! This analytic training set is noiseless. Pin a lower noise model so the ! strict interpolation check below tests update(), not production noise. config%sigma2 = 1.0d-8 config%jitter_sigma2 = 1.0d-5 call model%init(config, atoms) call model%train(R, E, G, n_obs, n_coords) ! The optimiser has fitted the kernel hyperparameters allocate(lengthscale(model%n_lengthscales())) call model%get_lengthscales(lengthscale) call model%get_magn_sigma2(magn_sigma2) call model%get_sigma2(sigma2) jitter = 0.0d0 call model%get_jitter(jitter) print '(a,*(es10.3))', "lengthscales ", lengthscale print '(a,es10.3)', "magn_sigma2 ", magn_sigma2 print '(a,es10.3,a,es10.3)', "sigma2 ", sigma2, " jitter ", jitter if (any(lengthscale <= 0.0d0) .or. magn_sigma2 <= 0.0d0) & error stop "hyperparameters must be positive" ! One posterior weight per energy and per gradient component allocate(alpha(n_obs * (1 + n_coords))) call model%get_alpha(alpha, ierr) print '(a,i0,a,i0)', "get_alpha status ", ierr, " with ", size(alpha) if (ierr /= GPR_SUCCESS) error stop "get_alpha failed" ! A buffer that is too short is refused and left unchanged allocate(too_short(2)) call model%get_alpha(too_short, ierr) print '(a,a)', "short buffer: ", gpr_status_name(ierr) if (ierr /= GPR_ERR_INVALID_ARG) error stop "short buffer must be refused" ! Add one observation: update appends it and fits the model again query = [0.0d0, 0.0d0, 0.0d0, 1.2d0, 0.0d0, 0.0d0] call model%predict_variance(query, var_before, var_g, n_coords) call gpr_lj_energy(query, n_atoms, 1.0d0, 1.0d0, e_new(1), g_new) call model%update(query, e_new, g_new, 1, n_coords, ierr) if (ierr /= GPR_SUCCESS) error stop gpr_error_message() call model%predict(query, e_pred, g_pred, n_coords) call model%predict_variance(query, var_after, var_g, n_coords) print '(a,i0,a)', "now ", model%n_observations(), " observations" print '(a,es9.2,a,es9.2)', "variance at 1.2: ", var_before, " -> ", var_after if (model%n_observations() /= n_obs + 1) error stop "update must append" if (var_after >= var_before) error stop "variance should drop at the new point" if (abs(e_pred - e_new(1)) > 1.0d-3) error stop "model must reproduce the new point" deallocate(lengthscale, alpha, too_short) call model%release() call atoms%release() end program hyperparameters_and_update :: lengthscales 3.538E-01 magn_sigma2 5.870E+02 sigma2 1.000E-08 jitter 1.000E-05 get_alpha status 0 with 42 short buffer: GPR_ERR_INVALID_ARG now 7 observations variance at 1.2: 2.52E-06 -> 1.89E-06 The fitted lengthscale and signal variance come from the optimiser and are the digits of the reference build; the program asserts only that they are positive. ``sigma2`` and ``jitter`` are explicitly set for this noiseless analytic example; the production defaults are documented above. ``sigma2`` is the noise variance of the observations and ``jitter`` is the numerical term added to the diagonal of the covariance matrix. The model's ``magn_sigma2`` and lengthscale setters, ``set_magn_sigma2`` and ``set_lengthscales``, store the new values but do not recompute the posterior of a trained model. ``set_sigma2`` does refresh the noise-dependent posterior state. The variance at the new point drops from the value before the update because the model now holds an observation there. It does not fall to zero: the model keeps the noise and jitter terms. Fortran does not free the allocatable arrays of a main program when it ends, so the program deallocates them. A leak checker such as AddressSanitizer reports them otherwise. Next steps ---------- - :doc:`How to use the searches from Fortran <../howto/fortran_capi>`: minimise with your own potential, run a dimer search, handle errors. - :doc:`Fortran module <../reference/bindings/fortran>`: a band on the Muller-Brown surface and the local and periodic bands. - :doc:`Language tabs ` show those complete programs with their C counterparts. - :doc:`Fortran API reference <../reference/fortran_api>`: every procedure, type and enumerator, generated from ``fortran/gpridge.f90``. - :doc:`C API <../reference/bindings/c>`: the library underneath, including the ownership and error rules the module follows. - :doc:`How to use the T-process <../howto/tprocess>`: the Student-t model, selected with ``GPR_MODEL_TP``.