Load Cap'n Proto parameters and wrap potentials =============================================== This page covers two tasks. The first is to give ``gprd`` its dimer parameters as a binary Cap'n Proto file instead of the text file ``input.dat``. The second is to hand your own energy and force routine to the C++ library or to the Python package through ``PotentialWrapper``. It does not cover the configuration of ``gprn``. That is a TOML file or a binary message of the unified schema ``schema/params.capnp``; see the :doc:`Cap'n Proto configuration schema <../reference/bindings/capnp>` page. The dimer file below uses the older schema ``schema/gprd_params.capnp``. gpridge has no client that evaluates potentials on a remote server. The potential protocol and its server, ``potserv``, belong to the rgpot project. The last section says what the header declares. Write a dimer parameter file ---------------------------- ``schema/gen_capnp_params.py`` converts a TOML file to the binary message of ``gprd_params.capnp``. Its dependencies (``pycapnp``, ``tomli``, ``rich``) are declared in the script header for ``uv``. Run it from ``schema/``, where the schema file sits, and start from ``schema/config.toml``: .. code:: bash cd schema uv run gen_capnp_params.py config.toml dimer_params.bin The script logs ``Successfully created 'dimer_params.bin'.`` and writes the file. The TOML tables it reads are ``cellDimensions``, ``[runSelector]``, ``[problem]`` (with ``[problem.paramTrans]``, ``[problem.initialRotations]`` and ``[problem.relaxation]``), ``[gpr]``, ``[early_stopping]``, ``[pruning]``, ``[debug]``, ``[linearAlgebra]`` and ``[optimizer]``. A table that is absent leaves its fields at the Cap'n Proto defaults. The key names follow the schema field names (camel case), except in ``[early_stopping]``, which uses snake case (``dist_metric``, ``use_adaptive_threshold``, ``half_life``). ``schema/config.toml`` shows the key names and, in comments, the name of the internal parameter that several of them set. The schema's top-level struct is ``InputParameters``. Its sub-structs are: .. table:: +--------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Struct | Holds | +================================+========================================================================================================================================================================================================+ | ``problem`` (a group) | Dimer separation, the rotation and translation optimizers, the final force criterion, the initial-rotation and relaxation controls (``RelaxationControl``: outer, inner and rotation iteration limits) | +--------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | ``GprModel`` | ``gpSigma2``, ``jitterSigma2``, ``noiseSigma2``, the prior (``mu``, ``nu``, ``s2``) and the profiling switches | +--------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | ``HyperparameterOptimization`` | The hyperparameter optimizer: ``scg`` or ``adam``, with ``checkDerivative``, ``maxIter``, ``tolFunc``, ``tolSol`` and a union of the options of the chosen one | +--------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | ``EarlyStopping`` | The distance metric (``max1DLog``, ``rmsd``, ``emd``) and the trust-threshold settings | +--------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | ``Pruning`` | ``usePrune``, ``pruneBegin``, ``pruneNVals``, ``pruneThreshold`` | +--------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | ``Debug`` | Report and debug levels, debug output paths | +--------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | ``LinearAlgebra`` | ScaLAPACK block size and process rows, CUTLASS plugin path | +--------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | ``RunSelector`` | ``iDist``, ``iRun`` and the separation list ``sepDists`` | +--------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ Load the file ------------- Build with Cap'n Proto support, then pass the file to ``gprd`` with ``--config``: .. code:: bash meson setup builddir -Duse_capnp=true meson compile -C builddir gprd --pos pos.con --config dimer_params.bin ``-Duse_capnp=true`` needs the ``capnproto`` package; ``pixi.toml`` lists it as a dependency. A ``gprd`` built without it refuses a ``.bin`` configuration with ``is a binary Cap'n Proto config and requires building with -Duse_capnp=true``. The other ``gprd`` options are in the :doc:`gprd command-line reference <../reference/cli_reference_gprd>`. In C++, ``gpr::io::loadParametersFromCapnp`` from ``managers/io/CapnProtoManager.h`` is the loader. It maps the file read-only with ``mmap``, reads the message with ``capnp::FlatArrayMessageReader``, and copies the fields into a ``gpr::InputParameters``. It throws ``std::runtime_error`` when the file cannot be opened, is empty, or cannot be mapped. .. code:: cpp #include "managers/io/CapnProtoManager.h" gpr::InputParameters params; gpr::io::loadParametersFromCapnp("dimer_params.bin", params); Wrap a potential in C++ ----------------------- ``pot::PotentialWrapper`` (``gpr/potentials/PotentialWrapper.h``) is a type-erased wrapper that the searches call to evaluate energy and forces. Its basic callable is ``ForceFn``: .. code:: cpp void(long N, const double* R, const int* atomicNrs, double* F, double* U, double* energy_noise_rms, const double* box) ``R`` and ``F`` hold 3N values atom by atom, ``atomicNrs`` holds N atomic numbers, ``U`` receives the energy, and ``box`` is a 3x3 cell, row-major. ``energy_noise_rms`` receives the root-mean-square noise on the energy, a standard deviation in eV and not a variance, and may be left untouched when the potential is noise-free. The slot was called ``variance`` before; the type is unchanged, so existing callbacks keep working. The header defines more callable types. A batch setter adds a batch form to a wrapper that already has the single-system form: .. table:: +---------------------------------+-------------------------------------------------------+---------------------------------------------------+ | Callable | Differs from ``ForceFn`` by | Built with | +=================================+=======================================================+===================================================+ | ``ForceFn`` | the basic form | ``PotentialWrapper(fn)`` | +---------------------------------+-------------------------------------------------------+---------------------------------------------------+ | ``ForceWithUncertaintyFn`` | separate ``energy_noise_rms`` and ``force_noise_rms`` | ``PotentialWrapper::from_force_with_uncertainty`` | +---------------------------------+-------------------------------------------------------+---------------------------------------------------+ | ``ForceBatchFn`` | B same-composition systems per call, one shared box | ``setForceBatch(fn)`` | +---------------------------------+-------------------------------------------------------+---------------------------------------------------+ | ``ForceBatchWithForceNoiseFn`` | a batch with force noise and zero energy noise | ``setForceBatch(fn)`` | +---------------------------------+-------------------------------------------------------+---------------------------------------------------+ | ``ForceBatchWithUncertaintyFn`` | a batch with both noise arrays | ``setForceBatchWithUncertainty(fn)`` | +---------------------------------+-------------------------------------------------------+---------------------------------------------------+ The C API has the same two single-system forms: ``gpr_potential_from_force`` (a ``gpr_force_fn``) and ``gpr_potential_from_force_with_uncertainty`` (a ``gpr_force_with_uncertainty_fn``). Destroy the handle with ``gpr_potential_destroy``. The :doc:`C API <../reference/bindings/c>` page covers the handle rules. From an rgpot potential ~~~~~~~~~~~~~~~~~~~~~~~ ``PotentialWrapper::from_rgpot`` adapts an rgpot potential, which takes an ``AtomMatrix`` of positions, the atom types and a cell, and returns ``(energy, forces)``, ``(energy, forces, energy_variance)``, or ``(energy, forces, energy_variance, force_noise_rms)``. The factory converts between that layout and the flat arrays above. It has three forms: one that takes a reference to the potential, one that takes a ``std::shared_ptr`` (use it when the wrapper outlives the potential's scope), and a C++-only overload for a ``std::shared_ptr``. .. code:: cpp #include "gpr/potentials/PotentialWrapper.h" // pot is any rgpot potential object auto wrapper = pot::PotentialWrapper::from_rgpot(pot); rgpot does not publish nanobind types, so a C caller cannot name an rgpot class. A C caller implements the same contract with ``gpr_potential_from_force_with_uncertainty``. Wrap a potential in Python -------------------------- The Python package has the same wrapper. A *write-in-place* callable takes ``positions`` (shape ``(N, 3)``), ``atomic_numbers``, ``forces`` (shape ``(N, 3)``, writable) and ``box`` (shape ``(3, 3)``), writes the forces into ``forces`` and returns the energy. ``PotentialWrapper.force`` then returns ``(energy, forces)``: .. code:: python import numpy as np from gpridge import PotentialWrapper def my_potential(positions, atomic_numbers, forces, box): forces[:] = -0.1 * positions return float(0.05 * np.sum(positions**2)) pot = PotentialWrapper(my_potential) positions = np.arange(6, dtype=np.float64).reshape(2, 3) atomic_numbers = np.ones(2, dtype=np.int32) box = 10.0 * np.eye(3) energy, forces = pot.force(positions, atomic_numbers, box) assert np.isclose(energy, 0.05 * np.sum(positions**2)) assert np.allclose(forces, -0.1 * positions) An rgpot-style callable takes ``positions``, ``atomic_numbers`` and ``cell`` and returns ``(energy, forces)``, ``(energy, forces, energy_variance)`` or ``(energy, forces, energy_variance, force_noise_rms)``. Wrap it with ``PotentialWrapper.from_rgpot``, or the module-level ``from_rgpot``, which does the same. ``force_with_uncertainty`` returns the four values, with 0.0 for a noise channel the callable did not give. It converts the energy variance to energy RMS: .. code:: python import numpy as np from gpridge import PotentialWrapper, from_rgpot def rgpot_style(positions, atomic_numbers, cell): forces = -0.1 * np.asarray(positions) return float(0.05 * np.sum(np.asarray(positions) ** 2)), forces, 0.125 pot = PotentialWrapper.from_rgpot(rgpot_style) # or from_rgpot(rgpot_style) positions = np.arange(6, dtype=np.float64).reshape(2, 3) atomic_numbers = np.ones(2, dtype=np.int32) box = 10.0 * np.eye(3) energy, forces, energy_rms, force_rms = pot.force_with_uncertainty( positions, atomic_numbers, box) assert energy_rms == np.sqrt(0.125) and force_rms == 0.0 ``gpridge.ase_potential(atoms)`` turns an ASE ``Atoms`` object that has a calculator into a write-in-place callable. On every call it overwrites the positions of ``atoms``, and the cell when the box passed in is not all zeros. It raises ``ImportError`` without ASE and ``ValueError`` for an ``Atoms`` object without a calculator. .. code:: python import numpy as np from ase.build import bulk from ase.calculators.emt import EMT from gpridge import PotentialWrapper, ase_potential atoms = bulk("Cu", "fcc", a=3.6, cubic=True) atoms.calc = EMT() pot = PotentialWrapper(ase_potential(atoms)) energy, forces = pot.force(atoms.get_positions(), atoms.get_atomic_numbers().astype(np.int32), np.array(atoms.cell)) assert forces.shape == (len(atoms), 3) Remote potentials ----------------- ``PotentialWrapper`` has no factory for a potential server: a ``from_rpc_client(PotClient*)`` that was declared in ``gpr/potentials/PotentialWrapper.h`` was never defined, so a call failed at link time, and the declaration has been removed. Neither driver has an option that connects to a potential server. To use a potential that runs elsewhere today, write a callback that talks to it and pass that callback to one of the wrappers above.