Algorithm Search⌘K

Modelresearch

Behler-Parrinello neural network potential

Also called high-dimensional neural network potential.

Writes the energy as a sum of atomic energies, each a neural network of symmetry functions of the atom's neighborhood, trained on quantum calculations.

The Behler-Parrinello potential is a machine-learned interatomic potential. It writes the energy of NN atoms as a sum of atomic energies, U=∑iEiU = \sum_i E_i, and computes each EiE_i with a small neural network from a fixed-length vector of symmetry functions that describe the neighbors of atom ii within a cutoff. The weights of the networks are fitted to energies and forces from quantum calculations, usually density functional theory. The result can be close to the quantum energy surface for configurations like those in the training set, at a cost that grows as O(N)O(N), but its accuracy is a measurement on a test set, not a property of the model.

The machine

Unknowns. The positions r1,…,rNr_1, \ldots, r_N, with Rij=∣ri−rj∣R_{ij} = |r_i - r_j| and the angle θijk\theta_{ijk} at atom ii between the directions to jj and kk.

Cutoff function. With a cutoff radius RcR_c,

fc(R)=12[cos⁡(πR/Rc)+1] for R<Rc,fc(R)=0 otherwise.f_c(R) = \tfrac{1}{2}\left[\cos(\pi R / R_c) + 1\right] \text{ for } R < R_c, \qquad f_c(R) = 0 \text{ otherwise}.

It goes to zero with zero slope at RcR_c, so the energy and the forces are continuous.

Symmetry functions. Each atom ii gets a vector Gi=(Gi1,…,GiM)G_i = (G_i^1, \ldots, G_i^M) of functions of its neighborhood that do not change under translation, rotation or exchange of neighbors of the same element. The radial functions are

Giμ=∑j≠ie−ημ(Rij−Rs,μ)2fc(Rij),G_i^{\mu} = \sum_{j \ne i} e^{-\eta_\mu (R_{ij} - R_{s,\mu})^2} f_c(R_{ij}),

with a width ημ\eta_\mu (in inverse length squared) and a center Rs,μR_{s,\mu} for each μ\mu; with η=0\eta = 0 the function ∑jfc(Rij)\sum_j f_c(R_{ij}) is a smooth count of neighbors. The angular functions are

Giμ=21−ζ∑j,k(1+λcos⁡θijk)ζ e−η(Rij2+Rik2+Rjk2)fc(Rij)fc(Rik)fc(Rjk),G_i^{\mu} = 2^{1-\zeta} \sum_{j, k} (1 + \lambda \cos\theta_{ijk})^{\zeta}\, e^{-\eta (R_{ij}^2 + R_{ik}^2 + R_{jk}^2)} f_c(R_{ij}) f_c(R_{ik}) f_c(R_{jk}),

with λ=±1\lambda = \pm 1 and ζ≥1\zeta \ge 1, summed over pairs of neighbors j,kj, k of atom ii. Papers differ on whether each pair {j,k}\{j, k\} is counted once or twice, which changes these functions by a factor 2; an implementation must state its choice, and the network must be trained with the same one.

Atomic networks. For each element there is one feed-forward network N\mathcal{N}, the same for every atom of that element. With one hidden layer of HH units,

Ei=b(2)+∑h=1Hwh(2)tanh⁡(bh(1)+∑μwhμ(1)Giμ),E_i = b^{(2)} + \sum_{h=1}^{H} w^{(2)}_h \tanh\Big(b^{(1)}_h + \sum_{\mu} w^{(1)}_{h\mu} G_i^{\mu}\Big),

and in practice two hidden layers of 10 to 50 units each are common. The energy is U=∑iEiU = \sum_i E_i.

Forces. By the chain rule, Fk=−∑i∑μ(∂Ei/∂Giμ) ∇kGiμF_k = -\sum_i \sum_\mu (\partial E_i / \partial G_i^\mu)\, \nabla_k G_i^\mu. The derivatives ∂Ei/∂Giμ\partial E_i / \partial G_i^\mu come from backpropagation through each network, and ∇kGiμ\nabla_k G_i^\mu is known in closed form. The forces are the exact gradient of the model energy, so the energy is conserved in molecular dynamics up to the integrator error.

Parameters, fitted and derived.

  • Fitted: all network weights and biases, often thousands per element. They minimize the squared error between the model and the reference energies, often with a weighted squared error of the forces added, on a training set of configurations.
  • Chosen, not fitted: the cutoff RcR_c, the set of symmetry functions and their η\eta, RsR_s, λ\lambda and ζ\zeta, and the size of the networks. They are hyperparameters, set by trial and by validation.
  • Derived: nothing about the energy itself. The structure of the model, a sum of local atomic energies with the right symmetries, is a design choice motivated by the locality of the quantum energy in many materials.

Standing assumptions. The energy is a sum of local contributions, so any interaction beyond RcR_c is missing unless a separate term adds it. The model is only as good as its reference method and its training set.

  1. BP-ENERGY-FORCES(r_1..r_N, network N, radial functions g_1..g_M, R_c)
  2. 1G_i^μ ← 0 for each atom i and each μ
  3. 2for each pair i < j with r = |r_ij| < R_c: for each μ: G_i^μ ← G_i^μ + g_μ(r); G_j^μ ← G_j^μ + g_μ(r)
  4. 3for each atom i: E_i ← N(G_i); a_i ← ∂N/∂G at G_i ▷ by backpropagation
  5. 4U ← Σ_i E_i
  6. 5for each pair i < j with r < R_c:
  7. 6g ← Σ_μ (a_i^μ + a_j^μ) g_μ'(r) ▷ dU/dr for this pair
  8. 7F_i ← F_i - g r_ij / r; F_j ← F_j + g r_ij / r
  9. 8return U, (E_i), F

The pseudocode and the implementation use radial functions only, as a small toy of the model with given weights; a real potential adds the angular functions, whose forces involve triples, and is trained on quantum data. The structure of the force loop is the same as for the embedded atom method, with the vector GiG_i in place of the scalar density.

What it counts

The model gives the energy UU and the forces for any configuration of the elements it was trained on, and through molecular dynamics and Monte Carlo, the properties that follow from them: phase diagrams, melting, defects, diffusion, and reactions that break and form bonds, which a molecular mechanics force field cannot describe. The atomic energies EiE_i themselves are not measurable quantities; only their sum is fitted.

Cost. At fixed density each atom has a bounded number of neighbors, so computing all GiG_i, all networks and all forces costs O(N)O(N) (more precisely O(NK2)O(N K^2) with KK neighbors per atom, because of the angular functions). Per atom this is much more than for a pair potential or EAM, and much less than for density functional theory, whose cost grows about as N3N^3 in standard implementations. This gap is what makes it worth fitting the model.

Relation to other models

  • Born-Oppenheimer molecular dynamics computes the same energy surface from the electrons at each step. The Behler-Parrinello potential is a fit of that surface.
  • Embedded atom method. Also a sum of atomic energies that depend on the neighborhood, with F(∑jf(Rij))F(\sum_j f(R_{ij})) in place of a network of many symmetry functions. EAM has a few fitted functions; the network has thousands of weights and needs many more reference data.
  • Kernel methods. Gaussian approximation potentials and related models use the same decomposition into atomic energies but fit each one by Gaussian process regression or kernel ridge regression on descriptors of the neighborhood.
  • Later generations. Behler's review calls this model the second generation. The third generation adds long-range electrostatics with atomic charges that a second set of networks predicts, and the fourth adds charges that are equilibrated over the whole system, for cases where a charge transfer is not local. Message-passing neural networks learn the descriptors instead of fixing them.

Known results in the model

Hand computation of a radial function. Take Rc=4R_c = 4, η=0.5\eta = 0.5, Rs=0R_s = 0, and an atom with neighbors at distances 1 and 2. Then fc(1)=12(cos⁡(π/4)+1)=0.853553f_c(1) = \tfrac12(\cos(\pi/4) + 1) = 0.853553 and fc(2)=12(cos⁡(π/2)+1)=0.5f_c(2) = \tfrac12(\cos(\pi/2) + 1) = 0.5, so

G=e−0.5⋅0.853553+e−2⋅0.5=0.517706+0.067668=0.585374.G = e^{-0.5} \cdot 0.853553 + e^{-2} \cdot 0.5 = 0.517706 + 0.067668 = 0.585374 .

With η=0\eta = 0 the same neighbors give the smooth count 0.853553+0.5=1.3535530.853553 + 0.5 = 1.353553, less than 2 because the cutoff function weights far neighbors less. The tests check these numbers.

Exact properties (theorems about the form).

  • Invariance. UU does not change under translations, rotations and exchanges of atoms of the same element, because each GiG_i does not and every atom of an element uses the same network. The total force is zero.
  • Extensivity and locality. Two copies of a system farther apart than RcR_c have twice the energy of one, and EiE_i does not change when an atom moves outside the cutoff sphere of atom ii. The tests check both. The price is that interactions longer than RcR_c, such as Coulomb energies between distant charges, are absent.
  • Radial functions alone are incomplete. An atom with two neighbors at distance 1 has the same radial functions whether the angle between them is 60°60° or 180°180°, so a model with radial functions only gives both the same energy. The angular functions remove this case. Even with angles, a fixed finite set of symmetry functions does not separate every pair of different neighborhoods.
  • Approximation. A network with one hidden layer and enough units can approximate any continuous function of GiG_i on a bounded set to any accuracy (the universal approximation theorem). This says nothing about how many data or units are needed, and nothing about the error of the decomposition into atomic energies itself.

Accuracy (measurements). Behler and Parrinello fitted their 2007 silicon potential to density functional energies and compared its energies and structural properties with those of the reference method. Errors of later potentials are reported as root mean square errors of energy per atom and of force components on test sets held out from training. Such numbers hold only for configurations like the training set. Outside it, at a new pressure, a new phase or an unseen defect, the network extrapolates without warning, which is why training sets are built by repeated sampling of the configurations that the model itself visits.

Code

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

behler_parrinello_potential.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/behler-parrinello-potential/. The authors are listed in prov/JVQRJ5.jsonl.

"""A small Behler-Parrinello potential for one element, with radial symmetry functions only.

This is a toy of the model: a real potential also uses angular symmetry
functions and is trained on quantum energies and forces. Here the weights are
given, and the code computes the energy and the exact forces.
"""

import math
import random

Point = list[float]


def cutoff(r: float, rc: float) -> float:
    return 0.5 * (math.cos(math.pi * r / rc) + 1) if r < rc else 0.0


def dcutoff(r: float, rc: float) -> float:
    return -0.5 * math.pi / rc * math.sin(math.pi * r / rc) if r < rc else 0.0


def g2(r: float, eta: float, rs: float, rc: float) -> float:
    """One term exp(-eta (r - rs)^2) f_c(r) of the radial symmetry function G2."""
    return math.exp(-eta * (r - rs) ** 2) * cutoff(r, rc)


def dg2(r: float, eta: float, rs: float, rc: float) -> float:
    e = math.exp(-eta * (r - rs) ** 2)
    return e * (dcutoff(r, rc) - 2 * eta * (r - rs) * cutoff(r, rc))


class AtomicNetwork:
    """E_i = b2 + sum_h w2[h] tanh(b1[h] + sum_m w1[h][m] G[m]), one hidden layer."""

    def __init__(self, w1: list[list[float]], b1: list[float], w2: list[float], b2: float):
        self.w1, self.b1, self.w2, self.b2 = w1, b1, w2, b2

    @classmethod
    def random(cls, inputs: int, hidden: int, seed: int) -> "AtomicNetwork":
        rng = random.Random(seed)
        w1 = [[rng.gauss(0, 1) for _ in range(inputs)] for _ in range(hidden)]
        b1 = [rng.gauss(0, 0.5) for _ in range(hidden)]
        w2 = [rng.gauss(0, 1) for _ in range(hidden)]
        return cls(w1, b1, w2, rng.gauss(0, 0.5))

    def energy_and_gradient(self, g: list[float]) -> tuple[float, list[float]]:
        """The output and its gradient with respect to the inputs, by backpropagation."""
        t = [math.tanh(b + sum(w * x for w, x in zip(row, g))) for row, b in zip(self.w1, self.b1)]
        e = self.b2 + sum(w * x for w, x in zip(self.w2, t))
        grad = [0.0] * len(g)
        for h, row in enumerate(self.w1):
            c = self.w2[h] * (1 - t[h] * t[h])
            for m, w in enumerate(row):
                grad[m] += c * w
        return e, grad


def bp_energy_forces(
    positions: list[Point], net: AtomicNetwork, params: list[tuple[float, float]], rc: float
) -> tuple[float, list[float], list[list[float]]]:
    """The energy U = sum_i E_i(G_i) and the forces, with G_i[m] = sum_j g2(r_ij, eta_m, rs_m, rc).

    params lists the pairs (eta, rs) of the radial symmetry functions. Returns
    (U, atomic energies, forces).
    """
    n, m = len(positions), len(params)
    gs = [[0.0] * m for _ in range(n)]  # @line L1
    close = []
    for i in range(n):  # @line L2
        for j in range(i + 1, n):  # @line L2
            d = [a - b for a, b in zip(positions[i], positions[j])]
            r = math.sqrt(sum(x * x for x in d))
            if r >= rc:  # @line L2
                continue
            close.append((i, j, r, d))
            for k, (eta, rs) in enumerate(params):  # @line L2
                v = g2(r, eta, rs, rc)
                gs[i][k] += v  # @line L2
                gs[j][k] += v  # @line L2
    atomic, grads = [], []
    for i in range(n):  # @line L3
        e, a = net.energy_and_gradient(gs[i])  # @line L3
        atomic.append(e)
        grads.append(a)
    u = sum(atomic)  # @line L4
    forces = [[0.0] * len(positions[0]) for _ in range(n)]
    for i, j, r, d in close:  # @line L5
        g = sum((grads[i][k] + grads[j][k]) * dg2(r, eta, rs, rc) for k, (eta, rs) in enumerate(params))  # @line L6
        for q in range(len(d)):
            c = g * d[q] / r
            forces[i][q] -= c  # @line L7
            forces[j][q] += c  # @line L7
    return u, atomic, forces  # @line L8


def symmetry_functions(positions: list[Point], i: int, params: list[tuple[float, float]], rc: float) -> list[float]:
    """The vector G_i of atom i, computed directly."""
    out = []
    for eta, rs in params:
        out.append(sum(g2(math.dist(positions[i], p), eta, rs, rc) for j, p in enumerate(positions) if j != i))
    return out
test_behler_parrinello_potential.py 113 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/behler-parrinello-potential/. The authors are listed in prov/JVQRJ5.jsonl.

import math
import random

import pytest

from behler_parrinello_potential import AtomicNetwork, bp_energy_forces, cutoff, g2, symmetry_functions

RC = 4.0
PARAMS = [(0.5, 0.0), (1.0, 1.0), (2.0, 1.5), (0.2, 2.5)]
NET = AtomicNetwork.random(len(PARAMS), 5, seed=11)


def cluster(rng, n, side, dmin):
    out = []
    while len(out) < n:
        p = [rng.uniform(0, side) for _ in range(3)]
        if all(math.dist(p, q) >= dmin for q in out):
            out.append(p)
    return out


def energy(pos):
    return bp_energy_forces(pos, NET, PARAMS, RC)[0]


def rotate(p, axis_angle):
    a, b = axis_angle
    ca, sa, cb, sb = math.cos(a), math.sin(a), math.cos(b), math.sin(b)
    x, y, z = p
    x, y = ca * x - sa * y, sa * x + ca * y
    y, z = cb * y - sb * z, sb * y + cb * z
    return [x, y, z]


def test_page_example_g2():
    assert cutoff(1, RC) == pytest.approx(0.853553, abs=1e-6)
    assert cutoff(2, RC) == pytest.approx(0.5)
    assert cutoff(4, RC) == 0.0
    pos = [[0, 0, 0], [1, 0, 0], [0, 2, 0]]
    g = symmetry_functions(pos, 0, [(0.5, 0.0)], RC)[0]
    assert g == pytest.approx(0.585374, abs=1e-6)
    assert g2(1, 0.5, 0, RC) == pytest.approx(0.517706, abs=1e-6)
    assert g2(2, 0.5, 0, RC) == pytest.approx(0.067668, abs=1e-6)
    assert symmetry_functions(pos, 0, [(0.0, 0.0)], RC)[0] == pytest.approx(1.353553, abs=1e-6)


def test_forces_match_finite_differences():
    rng = random.Random(1)
    pos = cluster(rng, 8, 3.5, 0.9)
    _, _, f = bp_energy_forces(pos, NET, PARAMS, RC)
    eps = 1e-6
    for i in range(len(pos)):
        for q in range(3):
            plus = [p[:] for p in pos]
            minus = [p[:] for p in pos]
            plus[i][q] += eps
            minus[i][q] -= eps
            num = -(energy(plus) - energy(minus)) / (2 * eps)
            assert f[i][q] == pytest.approx(num, abs=1e-6)


def test_invariance_translation_rotation_permutation():
    rng = random.Random(2)
    pos = cluster(rng, 9, 3.5, 0.9)
    u0 = energy(pos)
    shifted = [[x + 0.37, y - 1.2, z + 2.5] for x, y, z in pos]
    assert energy(shifted) == pytest.approx(u0, abs=1e-12)
    turned = [rotate(p, (0.7, -1.1)) for p in pos]
    assert energy(turned) == pytest.approx(u0, abs=1e-12)
    perm = pos[:]
    rng.shuffle(perm)
    assert energy(perm) == pytest.approx(u0, abs=1e-12)


def test_total_force_is_zero():
    rng = random.Random(3)
    pos = cluster(rng, 10, 3.5, 0.9)
    _, _, f = bp_energy_forces(pos, NET, PARAMS, RC)
    for q in range(3):
        assert abs(sum(row[q] for row in f)) < 1e-10


def test_atomic_energy_is_local():
    rng = random.Random(4)
    pos = cluster(rng, 6, 3.0, 0.9)
    _, e0, _ = bp_energy_forces(pos, NET, PARAMS, RC)
    i = 0
    c = [sum(p[q] for p in pos) / len(pos) for q in range(3)]
    u = [c[q] - pos[i][q] for q in range(3)]
    norm = math.sqrt(sum(x * x for x in u))
    # a new atom just beyond the cutoff of atom i, past the center of the cluster
    extra = [pos[i][q] + (RC + 0.01) * u[q] / norm for q in range(3)]
    _, e1, _ = bp_energy_forces(pos + [extra], NET, PARAMS, RC)
    assert e1[i] == pytest.approx(e0[i], abs=1e-12)
    close = [k for k, p in enumerate(pos) if math.dist(p, extra) < RC]
    assert close  # some other atom does see it, so the check is not empty
    assert any(abs(e1[k] - e0[k]) > 1e-9 for k in close)


def test_energy_is_extensive():
    rng = random.Random(5)
    pos = cluster(rng, 6, 3.0, 0.9)
    u = energy(pos)
    copy = [[x + 50, y, z] for x, y, z in pos]
    assert energy(pos + copy) == pytest.approx(2 * u, abs=1e-12)


def test_isolated_atom_energy_is_network_at_zero():
    e, _ = NET.energy_and_gradient([0.0] * len(PARAMS))
    assert energy([[0.0, 0.0, 0.0]]) == pytest.approx(e)

References

  1. Jörg Behler and Michele Parrinello, Generalized neural-network representation of high-dimensional potential-energy surfaces, Physical Review Letters 98(14), 2007, 146401, the energy as a sum of atomic networks of symmetry functions, and the application to silicon
  2. Jörg Behler, Atom-centered symmetry functions for constructing high-dimensional neural network potentials, Journal of Chemical Physics 134(7), 2011, 074106, the cutoff function and the radial and angular symmetry functions
  3. Jörg Behler, Four generations of high-dimensional neural network potentials, Chemical Reviews 121(16), 2021, 10037-10072, the four generations, the training procedure and the treatment of long-range electrostatics

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/JVQRJ5/text.yaml