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 :doc:`Fortran tutorial <../tutorials/fortran>` 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. .. table:: +---------------------------------------+-------------------------------------------------------------------+--------------------------+ | 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 :doc:`Fortran API reference <../reference/fortran_api>`. A complete band on the Muller-Brown surface, and the local and periodic bands, are on the :doc:`Fortran module <../reference/bindings/fortran>` 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* :math:`\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* :math:`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 (:math:`\epsilon = \sigma = 1`). The start has the atoms 1.4 apart and the minimum is at :math:`2^{1/6}`. .. code:: fortran 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 oracle calls E = -1.00000 separation = 1.12247 potential at the result: E = -1.00000 max |gradient| = 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. Run a dimer search ------------------ The dimer search needs a force routine, a start geometry and a start orientation (3 values per atom). The program below puts two atoms on a bond whose energy has a maximum at a bond length of 3.0, starts 0.3 beyond it and aligns the dimer with the bond. The energy :math:`E(r) = d^4/4 - d^2/2` with :math:`d = r - 3` has its maximum along the bond at :math:`r = 3`, so the search should find a bond length of 3. .. code:: fortran module bond_mod use, intrinsic :: iso_c_binding, only: c_int, c_long, c_double, c_ptr implicit none real(c_double), parameter :: top = 3.0d0 contains subroutine bond_force(n_atoms, positions, atomic_nrs, forces, energy, & variance, 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) real(c_double), intent(out) :: energy type(c_ptr), value :: variance, box, user_data real(c_double) :: delta(3), r, d, scale delta = positions(4:6) - positions(1:3) r = norm2(delta) d = r - top energy = 0.25d0 * d**4 - 0.5d0 * d**2 scale = -(d**3 - d) / r forces(1:3) = -scale * delta forces(4:6) = scale * delta end subroutine end module bond_mod program dimer_on_a_bond use, intrinsic :: iso_c_binding, only: c_double use gpridge use bond_mod, only: top, bond_force implicit none type(AtomsConfig) :: atoms type(DimerConfig) :: config type(DimerReport) :: report real(c_double) :: start(6), orientation(6), saddle(6), e_saddle integer :: stat character(len=256) :: message atoms = AtomsConfig(2) config = DimerConfig() config%T_dimer = 1.0d-3 config%report_level = 0 report%max_oracle_calls = 200 start = [0.0d0, 0.0d0, 0.0d0, 0.0d0, 0.0d0, top + 0.3d0] orientation = [0.0d0, 0.0d0, -sqrt(0.5d0), 0.0d0, 0.0d0, sqrt(0.5d0)] call gpr_dimer_search(bond_force, atoms, start, orientation, config, & saddle, e_saddle, report, stat, message) if (stat /= GPR_SUCCESS) error stop trim(message) print '(a,i0,a,i0)', "converged ", report%converged, ", stop reason ", & report%stop print '(a,i0,a,f8.4)', "force calls ", report%n_force_calls, & ", curvature ", report%curvature print '(a,f8.4,a,f8.4)', "bond length ", norm2(saddle(4:6) - saddle(1:3)), & ", E = ", e_saddle + report%energy_zero_level if (report%converged /= 1) error stop "dimer did not converge" if (report%stop /= GPR_DIMER_STOP_FORCE_CONVERGED) error stop "stop reason" if (abs(norm2(saddle(4:6) - saddle(1:3)) - top) > 0.02d0) & error stop "saddle missed" if (report%curvature >= 0.0d0) error stop "a saddle has negative curvature" end program dimer_on_a_bond :: converged 1, stop reason 1 force calls 7, curvature bond length 2.9998, E = -0.0000 The bond length and the energy are the reference saddle. The curvature depends on the stepper, so the listing does not pin it. The program asserts the bond length to 0.02 and a negative curvature. How to read the report: - ``report%converged`` is 1 when the true force criterion was met and the index stencil measured there found exactly one negative mode. A force stop the stencil does not certify reports 0 with ``report%stop`` equal to ``GPR_DIMER_STOP_UNCERTIFIED_FORCE_STOP``. A search that stops without converging still returns ``GPR_SUCCESS`` with ``converged = 0``, and ``report%stop`` says why. Test ``converged``, not only ``stat``. - ``e_saddle`` is relative to ``report%energy_zero_level``; their sum is the absolute saddle energy. - ``report%max_oracle_calls`` is an input: a budget of force calls, the certificate included, that is never exceeded, with 0 for none. The other fields are outputs. - ``report%certificate_step`` is an input too: the displacement of the stencil that certifies the stopped midpoint. The default 0 selects the library step. The certificate fills ``certified`` and ``n_certificate_calls``, which ``n_force_calls`` does not include. The :doc:`certificate how-to ` explains the measurement. - The dimer writes its progress lines to standard error (``std::clog``). ``config%report_level`` lowers the amount printed; it does not remove the search's own lines. 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: .. code:: fortran 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 -------- - :doc:`Tutorial: Fortran interop <../tutorials/fortran>`: the model, training and prediction. - :doc:`Fortran module <../reference/bindings/fortran>`: bands on the Muller-Brown surface, local and periodic bands. - :doc:`Fortran API reference <../reference/fortran_api>`: every procedure and type. - :doc:`C API <../reference/bindings/c>`: ownership, threads and the error model that the module follows. - :doc:`How to run a GP-NEB band `: the same searches from the command line.