Skip to content

A program from functions

qccompute.program.FunctionProgram(name, energy_gradient, hessian=None) makes a program of Python functions of the positions (bohr): a model surface, an ML potential in a script, a teaching example. It runs in this process and is thread-safe, so lists run side by side and sessions work as for any other program. It takes the shared keywords threads (its thread count, which the runner holds its BLAS pools at) and accuracy (recorded as met: nothing converges). An exception from a function is a failed calculation of kind internal, with the function's traceback in the failed output; a ProgramError it raises is the calculation's own failure.

With takes_input=True the functions get the input after the positions, so one program stands in for a chemistry engine on any molecule and setting: the function reads the symbols, charge, multiplicity, model and keywords. settings= declares the JSON Schema of the keywords it reads; the program refuses any other key (unknown_key), and the function checks their values:

def engine(x, inp):  # positions (bohr), the input
    calc = Calculator(inp.structure.symbols, inp.structure.charge,
                      method=inp.model.method, accuracy=inp.keywords.get("acc", 1.0))
    return calc.energy_gradient(x)

settings = {"type": "object", "properties": {
    "acc": {"type": "number", "exclusiveMinimum": 0, "x-concern": "convergence"}}}
qccompute.register_program(
    FunctionProgram("engine", engine, takes_input=True, settings=settings)
)

Its version and numerics identity is a digest of the functions (fn-...): their code, constants, defaults, closures and the module globals they read (D, A and R0 below), recursing into the Python functions they call. Edit the function or one of those values and a store no longer serves the old results. Give version="..." to name the numbers yourself, for example a model's checksum when the functions call an ML model.

"""Make a program of two Python functions and run it like any other program.

A Morse potential between two atoms: the smallest complete program. The runner gives
it lists, sessions and the store, exactly as any other program.
"""

import numpy as np
from qcdata import CalcType, ProgramInput, Structure

import qccompute
from qccompute.program import FunctionProgram

D, A, R0 = 0.17, 1.03, 1.40  # well depth (Eh), width (1/bohr), bond length (bohr)


def morse(x: np.ndarray) -> tuple[float, np.ndarray]:
    """Energy (Eh) and gradient (Eh/bohr) of a Morse bond at positions x (bohr)."""
    d = x[1] - x[0]
    r = float(np.linalg.norm(d))
    e = np.exp(-A * (r - R0))
    de_dr = 2 * D * A * e * (1 - e)
    return D * (1 - e) ** 2, np.array([-de_dr * d / r, de_dr * d / r])


qccompute.register_program(FunctionProgram("morse", morse))

h2 = Structure(
    symbols=["H", "H"], geometry=np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 1.6]])
)
inp = ProgramInput(program="morse", calctype=CalcType.gradient, structure=h2)

out = qccompute.compute(inp)
print(out.results.energy, out.results.gradient[1])

# A scan along the bond, side by side: the input at each new geometry
scan = [
    ProgramInput.from_spec(inp, h2.with_geometry([[0, 0, 0], [0, 0, r]]))
    for r in np.linspace(1.0, 3.0, 9)
]
energies = [o.results.energy for o in qccompute.compute(scan)]
print(np.round(energies, 4))