========================================== Python API: the functional dimer interface ========================================== This tutorial runs one dimer search through the function-style interface, ``gpridge.run_dimer``, instead of the ``GPDimer`` class. The function takes the inputs of the C++ ``AtomicDimer`` directly (a parameter dictionary, two ``Observation`` objects, an orientation, an ``AtomsConfiguration`` and a potential callback) and returns the bound ``AtomicDimer``, whose getters give the final midpoint, force, curvature and counters. Use it when you need those getters or need to build the ``Observation`` inputs yourself. ``GPDimer`` calls the same ``AtomicDimer`` for you and also handles frozen atoms, the shared ``GaussianProcess`` and logging; :doc:`Python API: a first dimer search ` covers it. The system is the two-atom double well of the first tutorial, defined again here because every page runs on its own. What you need ------------- - The Python bindings of ``gpridge`` and ASE 3.23 or newer. See :doc:`Installation <../getting-started/installation>`. - No input files. Step 1: the oracle and its callback ----------------------------------- .. code:: python import numpy as np from ase import Atoms from ase.calculators.calculator import Calculator, all_changes import gpridge class DoubleWell(Calculator): """V(r) = a (r - r1)^2 (r - r2)^2 in eV, forces in eV/Angstrom.""" implemented_properties = ["energy", "forces"] def __init__(self, a=4.0, r1=1.0, r2=2.0, **kwargs): super().__init__(**kwargs) self.a, self.r1, self.r2 = a, r1, r2 def calculate(self, atoms=None, properties=("energy",), system_changes=all_changes): super().calculate(atoms, properties, system_changes) d = atoms.positions[1] - atoms.positions[0] r = np.linalg.norm(d) u = (self.r1 - r) * (self.r2 - r) dV_dr = 2.0 * self.a * u * (2.0 * r - self.r1 - self.r2) force_on_second = -dV_dr * d / r self.results["energy"] = self.a * u * u self.results["forces"] = np.array([-force_on_second, force_on_second]) atoms = Atoms("H2", positions=[[0.0, 0.0, 0.0], [1.35, 0.0, 0.0]], cell=[10.0, 10.0, 10.0], pbc=False) atoms.calc = DoubleWell() pot_fn = gpridge.ase_potential(atoms) start_energy = atoms.get_potential_energy() ``ase_potential`` wraps ``atoms`` in a callback of the form ``fn(positions, atomic_numbers, forces, box) -> energy``. On each call it overwrites the positions and cell of ``atoms``, runs the calculator, writes the ASE forces into the ``forces`` array unchanged (eV/Å, pointing downhill) and returns the energy (eV). The C++ core converts the forces to gradients itself. After the search ``atoms`` holds the last geometry the callback evaluated, which is not necessarily the saddle. Step 2: parameters ------------------ .. code:: python params = gpridge.default_parameters() params["T_dimer"] = 0.05 params["sigma2"] = 1e-7 params["jitter_sigma2"] = 0.0 ``default_parameters()`` returns a dictionary of every ``InputParameters`` field. Its dimer keys (separation, rotation and translation methods, step settings) carry the values that ``gprd`` runs with, and the remaining keys are neutral placeholders. The three assignments set: - ``T_dimer``, the force convergence criterion in eV/Å. The default is 0.1 and ``GPDimer.run`` uses 0.05. - ``sigma2`` and ``jitter_sigma2``, the two GP noise settings (fields of ``GPRSetup`` in ``structures/Structures.h``). Both default to 1e-4 in ``default_parameters()`` and ``GPDimer``. This functional-interface tutorial explicitly pins the lower-noise settings above to preserve its reference trajectory and call count; they are example settings, not library defaults. ``preset_parameters("fast")`` and ``preset_parameters("accurate")`` return the same dictionary with a different iteration budget and tolerance. The reference lists the keys that each preset changes. Step 3: initial data -------------------- The dimer needs the energy and gradient at the start point, an empty set of earlier observations, an orientation and a description of the atoms. .. code:: python init_middle = gpridge.Observation() init_middle.R = atoms.get_positions().reshape(1, -1) init_middle.E = np.array([[atoms.get_potential_energy()]]) init_middle.G = -atoms.get_forces().reshape(1, -1) init_obs = gpridge.Observation() init_obs.clear() orient = np.array([[-1.0, 0.0, 0.0, 1.0, 0.0, 0.0]]) orient /= np.linalg.norm(orient) atoms_config = gpridge.make_atoms_configuration(atoms) assert init_middle.R.shape == init_middle.G.shape == orient.shape == (1, 6) assert init_middle.E.shape == (1, 1) An ``Observation`` stores one geometry per row: ``R`` and ``G`` have shape ``(n_obs, 3 * n_atoms)`` and ``E`` has shape ``(n_obs, 1)``. ``G`` is the gradient of the energy, which is the negative of the ASE force. This is the one place in the functional interface where the sign differs from ASE, and a missing minus sign gives a search that walks uphill. The orientation has shape ``(1, 3 * n_atoms)`` and unit length. Here it stretches the bond along :math:`x`, the direction of negative curvature at the barrier top. Step 4: run the search ---------------------- .. code:: python dimer = gpridge.run_dimer(params, init_obs, init_middle, orient, atoms_config, pot_fn) midpoint = np.asarray(dimer.get_final_coord_of_mid_point()).reshape(2, 3) separation = np.linalg.norm(midpoint[1] - midpoint[0]) print("converged:", dimer.get_converged(), dimer.get_termination_reason()) print("oracle calls:", dimer.get_total_force_calls()) print("of which index stencil:", dimer.get_force_stop_certificate_calls()) print("surrogate calls:", dimer.get_total_gpr_force_calls()) print(f"bond length at the saddle: {separation:.3f} A") print(f"curvature along the dimer: {dimer.get_final_curvature():.2f} eV/A^2") assert dimer.get_converged() and dimer.get_force_stop_certified() assert dimer.get_termination_reason() == "force_converged" assert abs(separation - 1.5) < 0.01 assert dimer.get_total_force_calls() - dimer.get_force_stop_certificate_calls() < 15 assert abs(dimer.get_final_curvature() + 8.0) < 0.5 The numbers below are from one run. The oracle-call count can differ by a few with another build. :: converged: True force_converged oracle calls: 16 of which index stencil: 12 surrogate calls: 30 bond length at the saddle: 1.499 A curvature along the dimer: -8.00 eV/A^2 ``get_total_force_calls()`` counts evaluations of the true potential and ``get_total_gpr_force_calls()`` counts evaluations of the surrogate, which cost no oracle call. The search stopped after 4 oracle calls with the true force under tolerance. The other 12 are the Cartesian index stencil at that midpoint, one gradient at each side of each coordinate. ``vibrational_stencil``"vibrational"= measures only the bond stretch, 6 oracle calls of which 2 are the stencil, and can call a borderline mode resolved where this full stencil leaves it unresolved. The run converges only because the stencil measured exactly one negative mode. A force stop at a minimum or a flat region ends with ``get_converged()`` false and the reason ``"uncertified_force_stop"``. The curvature is the second derivative of the energy along the unit orientation, so it is negative at a first-order saddle point. For this potential the exact value at :math:`r = 1.5\ \mathrm{\AA}` is :math:`-8\ \mathrm{eV/\AA^2}`: :math:`V''(r) = -4\ \mathrm{eV/\AA^2}`, and a unit step along the orientation changes :math:`r` by :math:`\sqrt{2}\ \mathrm{\AA}`. Step 5: energies and the gradient sign -------------------------------------- The final energy is relative to a zero level, which is the first measured energy (the start geometry). Add ``get_energy_zero_level()`` for the absolute energy. ``get_final_gradient_at_mid_point()`` returns the gradient ``G`` at the midpoint, so it is the negative of the ASE force. (The older name ``get_final_force_at_mid_point()`` returns the same gradient and emits a ``DeprecationWarning``.) The block checks both against the calculator. .. code:: python saddle = Atoms("H2", positions=midpoint, cell=[10.0, 10.0, 10.0], pbc=False) saddle.calc = DoubleWell() absolute_energy = dimer.get_final_energy() + dimer.get_energy_zero_level() print(f"zero level {dimer.get_energy_zero_level():.4f} eV, " f"relative {dimer.get_final_energy():.4f} eV, " f"absolute {absolute_energy:.4f} eV") assert abs(dimer.get_energy_zero_level() - start_energy) < 1e-9 assert abs(absolute_energy - saddle.get_potential_energy()) < 1e-6 final_gradient = np.asarray(dimer.get_final_gradient_at_mid_point()).reshape(2, 3) assert np.allclose(final_gradient, -saddle.get_forces(), atol=1e-6) :: zero level 0.2070 eV, relative 0.0430 eV, absolute 0.2500 eV What to change for your own system ---------------------------------- - Replace ``DoubleWell()`` with the ASE calculator for your system. The calculator must provide ``get_potential_energy()`` and ``get_forces()``. - Build ``init_middle``, ``orient`` and ``atoms_config`` from your own ``atoms``. The orientation has one entry for each coordinate of each atom. For frozen atoms, use ``GPDimer``: it marks them in the ``AtomsConfiguration`` and limits the observations and the orientation to the moving atoms. - For other oracles, ``run_dimer`` also accepts a ``PotentialWrapper``, including one made by ``from_rgpot``. The full list of functions, getters and parameter keys is in :doc:`Python bindings <../reference/bindings/python>`. The next tutorial for the Python API is :doc:`A periodic Pt(111) Morse band `, which runs a periodic band.