Algorithm Search⌘K

Algorithmadvanced

Multiscale coarse-graining by force matching

Also called MS-CG, force matching.

Fits coarse-grained forces by least squares to the forces mapped from atomistic simulations onto the coarse sites.

Time
O(T (N^2 + N K^2) + K^3) worst
Space
O(K^2 + N K) extra
Where
K = the number of basis functions; N = the number of coarse sites; T = the number of configurations
Properties
deterministicexactnot iterativenot randomized
Origin
Sergei Izvekov, Gregory A. Voth, 2005

Multiscale coarse-graining by force matching (MS-CG) builds a force field for coarse-grained sites, each of which stands for a group of atoms. It runs an atomistic simulation, maps each saved configuration onto the sites, adds up the atomistic forces on the atoms of each site, and then chooses the coarse-grained force field that reproduces these mapped forces best in the least squares sense. With a force field that is linear in its parameters, for example a pair force tabulated on a grid, this is one linear least squares problem. It differs from iterative Boltzmann inversion, which matches a structural target and needs a new simulation in every iteration: force matching uses the forces and needs no coarse-grained simulation at all. The Mori-Zwanzig formalism explains what both methods leave out: the memory and the noise of the removed atoms.

In plain words

You have a detailed simulation in which every atom is tracked. You want a simpler model in which each small group of atoms is one ball. Take many snapshots of the detailed run. In each snapshot, put a ball at the center of each group, and add up the forces on the atoms of the group to get the force on the ball.

Now choose a rule for the force between two balls, as a table of numbers against distance. For any table, you can compute the forces that the balls would feel in each snapshot. Pick the table that makes these forces as close as possible to the forces from the detailed run, summed over all balls and all snapshots. Because the forces depend on the table in a simple way, this is a standard fitting problem with one answer.

The problem

The input is a set of TT coarse-grained configurations R(t)R^{(t)} of NN sites, with site positions xix_i in a periodic box, and the reference forces Fi(t)F^{(t)}_i on the sites. The configurations come from an equilibrium atomistic run in the canonical ensemble, mapped onto the sites; for the center of mass map, where each atom belongs to one site, the reference force on a site is the sum of the atomistic forces on its atoms. The model is a pair force f(r)f(r) between sites, with f>0f > 0 for repulsion, so the coarse-grained force on site ii is

Fi(R)=∑j≠if(rij) eij,eij=xi−xjrij,F_i(R) = \sum_{j \ne i} f(r_{ij})\, e_{ij}, \qquad e_{ij} = \frac{x_i - x_j}{r_{ij}},

with the minimum image. The pair force is a combination f(r)=∑k=1Kckϕk(r)f(r) = \sum_{k=1}^K c_k \phi_k(r) of KK basis functions; here they are hat functions on a uniform grid r0<⋯<rK−1=rcr_0 < \dots < r_{K-1} = r_c, so ckc_k is the value of ff at the node rkr_k and ff is piecewise linear and zero beyond the cutoff rcr_c. The output is the coefficient vector cc that minimizes

χ2(c)=∑t=1T∑i=1N∥Fi(R(t);c)−Fi(t)∥2.\chi^2(c) = \sum_{t=1}^T \sum_{i=1}^N \lVert F_i(R^{(t)}; c) - F^{(t)}_i \rVert^2 .

The pair potential follows as V(r)=∫rrcf(s) dsV(r) = \int_r^{r_c} f(s)\, ds. Each component of FiF_i is linear in cc, so χ2(c)=∥Ac−F∥2\chi^2(c) = \lVert A c - F \rVert^2 for a design matrix AA with one row per site, component and configuration, and a vector FF of the reference forces. This is a least squares problem.

The algorithm

  1. FORCE-MATCHING(configurations R^(t), reference forces F^(t), basis φ_1..φ_K)
  2. 1G ← 0 (K by K), b ← 0 (length K)
  3. 2for each configuration t
  4. 3build the rows a of A for all sites and components: a_k = Σ_{j≠i} φ_k(r_ij) (e_ij)_α
  5. 4for each row a with its reference force f
  6. 5G ← G + a aᵀ, b ← b + a f
  7. 6set G_pp ← 1 for every p with G_pp = 0 ▷ a basis function that no distance touches gets c_p = 0
  8. 7return c = G⁻¹ b ▷ the normal equations Gc = b

Line L3 visits each pair of sites once and adds ϕk(rij)eij\phi_k(r_{ij}) e_{ij} to the row of site ii and the negative to the row of site jj; a hat function is nonzero at only two nodes, so each pair touches two columns. Lines L4 and L5 form the normal equations ATAc=ATFA^T A c = A^T F without storing AA, so the memory does not grow with TT. Line L7 solves the KK by KK system; the implementation uses Gaussian elimination with partial pivoting from the shared dense helper. A Cholesky decomposition also works, since GG is symmetric positive definite once the unused functions are removed, and a QR factorization of AA is better conditioned when AA is small enough to store.

Example

By hand. Take two hat functions on [1,2][1, 2]: ϕ1(r)=2−r\phi_1(r) = 2 - r and ϕ2(r)=r−1\phi_2(r) = r - 1, so f(1)=c1f(1) = c_1 and f(2)=c2f(2) = c_2. Three configurations each have two sites on the xx axis, at distances 1.251.25, 1.751.75 and 1.51.5, and the reference force on the right site is 1.01.0, 0.20.2 and 0.50.5 (repulsive), with the opposite force on the left site. All values are in reduced units. The three rows for the right site are (0.75,0.25)(0.75, 0.25), (0.25,0.75)(0.25, 0.75) and (0.5,0.5)(0.5, 0.5); the left site gives the same rows and forces with the opposite sign, which doubles GG and bb and does not change cc. Without the doubling,

G=(0.8750.6250.6250.875),b=(1.050.65),c=(41/30−7/30)=(1.366667−0.233333).G = \begin{pmatrix} 0.875 & 0.625 \\ 0.625 & 0.875 \end{pmatrix}, \qquad b = \begin{pmatrix} 1.05 \\ 0.65 \end{pmatrix}, \qquad c = \begin{pmatrix} 41/30 \\ -7/30 \end{pmatrix} = \begin{pmatrix} 1.366667 \\ -0.233333 \end{pmatrix}.

The fitted forces at the three distances are 0.9666670.966667, 0.1666670.166667 and 0.5666670.566667, so the residuals are −1/30-1/30, −1/30-1/30 and 2/302/30, and χ2=2⋅6/900=0.013333\chi^2 = 2 \cdot 6 / 900 = 0.013333 with both sites. The three data points do not lie on one line, so no cc fits them exactly; the least squares line passes below the first two points and above the third. The potential at r=1r = 1 is V(1)=(c1+c2)/2=17/30V(1) = (c_1 + c_2) / 2 = 17/30.

Grid refinement. In the tests, the reference forces come from the smooth pair force f∗(r)=3cos⁡(3r)(2.5−r)f^*(r) = 3 \cos(3 r) (2.5 - r) with rc=2.5r_c = 2.5, on 20 configurations of 20 sites in a periodic square of side 6, with no pair closer than 0.850.85. The largest error max⁡k∣ck−f∗(rk)∣\max_k |c_k - f^*(r_k)| at the nodes is 0.4160.416, 0.1150.115, 0.02540.0254 and 0.007660.00766 for K=6K = 6, 1111, 2121 and 4141 hat functions on [0.85,2.5][0.85, 2.5]: each halving of the grid spacing divides the error by 3.33.3 to 4.54.5, which is second order, as for the best piecewise linear fit of a smooth function. These are measurements on one data set.

Noise. If the reference forces are a force of the basis plus independent Gaussian noise of standard deviation 11 on each component, the error ∥c−c∗∥2\lVert c - c^* \rVert_2 with K=11K = 11 is 0.6390.639, 0.2450.245 and 0.1340.134 for T=5T = 5, 2020 and 8080 configurations. It falls about like T−1/2T^{-1/2}. This is the case of real data: the mapped force has a part that the site positions do not determine, and only its mean is fitted.

Correctness

The proof in the proofs file shows that line L3 builds rows with a⋅c=Fiα(R;c)a \cdot c = F_{i \alpha}(R; c), that lines L4 and L5 give G=ATAG = A^T A and b=ATFb = A^T F, and that cc minimizes χ2\chi^2 if and only if Gc=bG c = b, because χ2\chi^2 is a convex quadratic with gradient 2(Gc−b)2 (G c - b). A basis function that no distance touches gives a zero row and column, and line L6 sets its coefficient to zero without changing the other equations. If the used columns of AA are independent, the minimizer is unique; if the reference forces come from a pair force in the basis, it is that force.

The proof also shows what the fit approximates. If the configurations are samples of a random configuration RR and Fˉ(R)\bar F(R) is the conditional mean of the reference force given RR, the expected residual splits as E∥Ac−F∥2=E∥F−Fˉ∥2+E∥Ac−Fˉ∥2\mathbb{E} \lVert A c - F \rVert^2 = \mathbb{E} \lVert F - \bar F \rVert^2 + \mathbb{E} \lVert A c - \bar F \rVert^2. So the fit is the least squares projection of Fˉ\bar F onto the pair forces of the basis. Noid et al. (2008) show that, under their consistency conditions on the map, Fˉ(R)\bar F(R) is the force −∇RW(R)-\nabla_R W(R) of the many-body potential of mean force WW; the proofs file takes this from the paper and does not prove it.

Proof: Force matching returns the least squares fit, and in expectation the projection of the mean forcefull

Setup. The basis has KK hat functions ϕ1,…,ϕK\phi_1, \dots, \phi_K, and the CG pair force is fc(r)=∑kckϕk(r)f_c(r) = \sum_k c_k \phi_k(r). There are TT configurations R(t)R^{(t)} of NN sites, with reference forces F(t)F^{(t)} (one number per site and Cartesian component). The force residual is χ2(c)=∑t∑i,α(Fiα(R(t);c)−Fiα(t))2\chi^2(c) = \sum_t \sum_{i, \alpha} (F_{i \alpha}(R^{(t)}; c) - F^{(t)}_{i \alpha})^2, where Fi(R;c)=∑j≠ifc(rij)eijF_{i}(R; c) = \sum_{j \ne i} f_c(r_{ij}) e_{ij} and eij=(xi−xj)/rije_{ij} = (x_i - x_j) / r_{ij} with the minimum image. We assume exact arithmetic.

Lemma 1 (the design rows). For each configuration, site ii and component α\alpha, the row aa built by line L3 satisfies a⋅c=Fiα(R;c)a \cdot c = F_{i \alpha}(R; c) for every cc.

Proof. Fiα(R;c)=∑j≠i∑kckϕk(rij)(eij)α=∑kck∑j≠iϕk(rij)(eij)αF_{i \alpha}(R; c) = \sum_{j \ne i} \sum_k c_k \phi_k(r_{ij}) (e_{ij})_\alpha = \sum_k c_k \sum_{j \ne i} \phi_k(r_{ij}) (e_{ij})_\alpha. So the row is ak=∑j≠iϕk(rij)(eij)αa_k = \sum_{j \ne i} \phi_k(r_{ij}) (e_{ij})_\alpha. The code visits each unordered pair {i,j}\{i, j\} once, adds ϕk(rij)(eij)α\phi_k(r_{ij}) (e_{ij})_\alpha to the row of ii and subtracts it from the row of jj. Since eji=−eije_{ji} = -e_{ij} and rji=rijr_{ji} = r_{ij}, the row of jj gets ϕk(rji)(eji)α\phi_k(r_{ji}) (e_{ji})_\alpha, the right term. Distances outside [r0,rc][r_0, r_c] give ϕk=0\phi_k = 0 for all kk and add nothing. □\square

Stack all rows into a matrix AA with TNdTN d rows (d=2d = 2) and the reference forces into a vector FF. By Lemma 1, χ2(c)=∥Ac−F∥2\chi^2(c) = \lVert A c - F \rVert^2.

Lemma 2 (the normal equations). After the loop of lines L2 to L5, G=ATAG = A^T A and b=ATFb = A^T F.

Proof. ATA=∑rows aaaTA^T A = \sum_{\text{rows } a} a a^T and ATF=∑rowsafA^T F = \sum_{\text{rows}} a f, where ff is the reference force of the row. Line L5 adds apaqa_p a_q to GpqG_{pq} and apfa_p f to bpb_p for every row and every pp with ap≠0a_p \ne 0. The skipped terms have ap=0a_p = 0, so they are zero. □\square

Lemma 3 (the minimizer). χ2\chi^2 is a convex quadratic with gradient 2(ATAc−ATF)2 (A^T A c - A^T F). So cc minimizes χ2\chi^2 if and only if Gc=bG c = b. If the columns of AA are linearly independent, GG is positive definite and the minimizer is unique.

Proof. χ2(c+h)=χ2(c)+2hT(ATAc−ATF)+∥Ah∥2\chi^2(c + h) = \chi^2(c) + 2 h^T (A^T A c - A^T F) + \lVert A h \rVert^2. If Gc=bG c = b, the middle term is zero for every hh, and χ2(c+h)≥χ2(c)\chi^2(c + h) \ge \chi^2(c). If Gc≠bG c \ne b, take h=−s(Gc−b)h = -s (G c - b) with a small s>0s > 0; the middle term is −2s∥Gc−b∥2-2 s \lVert G c - b \rVert^2 and the last term is O(s2)O(s^2), so χ2\chi^2 decreases. If the columns are independent, hTGh=∥Ah∥2>0h^T G h = \lVert A h \rVert^2 > 0 for h≠0h \ne 0. □\square

Lemma 4 (unused basis functions). If no distance in the data falls in the support of ϕp\phi_p, then column pp of AA is zero, row and column pp of GG are zero, and bp=0b_p = 0. Lines L6 and L7 then return cp=0c_p = 0, and the other coefficients solve the normal equations of the reduced problem without ϕp\phi_p.

Proof. Column pp of AA is zero, so Gpq=Gqp=0G_{pq} = G_{qp} = 0 for all qq and bp=0b_p = 0. After line L6 sets Gpp=1G_{pp} = 1, equation pp reads cp=0c_p = 0, and cpc_p appears in no other equation. χ2\chi^2 does not depend on cpc_p, so the choice cp=0c_p = 0 keeps the minimum. □\square

Theorem (correctness). If the columns of AA that are not zero are linearly independent, line L7 returns the unique minimizer of χ2\chi^2 with cp=0c_p = 0 for every unused basis function. In particular, if the reference forces are F=Ac∗F = A c^* for some c∗c^* (the true pair force lies in the basis), the result is c∗c^* on the used basis functions. If the used columns are dependent, GG is singular and scimat.solve raises ValueError.

Proof. Lemmas 1 to 4. For F=Ac∗F = A c^*, χ2(c∗)=0\chi^2(c^*) = 0, so c∗c^* is a minimizer, and by uniqueness it is the result. □\square

Lemma 5 (what the fit approximates). Let the configurations be samples of a random coarse configuration RR with reference forces FF, with E∥F∥2<∞\mathbb{E} \lVert F \rVert^2 < \infty, and let Fˉ(R)=E[F∣R]\bar F(R) = \mathbb{E}[F \mid R]. Then for every cc,

E∥A(R)c−F∥2=E∥F−Fˉ(R)∥2+E∥A(R)c−Fˉ(R)∥2.\mathbb{E} \lVert A(R) c - F \rVert^2 = \mathbb{E} \lVert F - \bar F(R) \rVert^2 + \mathbb{E} \lVert A(R) c - \bar F(R) \rVert^2 .

So the minimizer of the expected residual is the least squares projection of the conditional mean force Fˉ\bar F onto the span of the basis forces, and the first term, the part of the force that the coarse configuration does not determine, cannot be fitted by any cc.

Proof. Write Ac−F=(Ac−Fˉ)+(Fˉ−F)A c - F = (A c - \bar F) + (\bar F - F) and expand the square. The cross term is 2E[(A(R)c−Fˉ(R))T(Fˉ(R)−F)]2 \mathbb{E}[(A(R) c - \bar F(R))^T (\bar F(R) - F)]. Condition on RR: the first factor is fixed, and E[Fˉ(R)−F∣R]=0\mathbb{E}[\bar F(R) - F \mid R] = 0. So the cross term is zero. □\square

Remark. Noid et al. (2008) show that, when the map from atoms to sites and the site masses satisfy their consistency conditions and the samples come from the canonical ensemble of the atomistic model, Fˉ(R)\bar F(R) is the force of the many-body potential of mean force, −∇RW(R)-\nabla_R W(R). With Lemma 5 this gives the statement that force matching projects the many-body mean force onto the pair basis. The identification of Fˉ\bar F with −∇W-\nabla W is taken from that paper and is not proved here. With finitely many samples, χ2/T\chi^2 / T converges to the expected residual by the law of large numbers, so the fitted cc converges to the minimizer of Lemma 5 when that minimizer is unique. ■\blacksquare

Complexity

In the real RAM model, line L3 costs O(N2)O(N^2) per configuration with a loop over all pairs, or O(N)O(N) at fixed density with a linked cell list. Line L5 costs O(K2)O(K^2) per row in the worst case, because a row has up to KK nonzero entries when a site has neighbors at all distances; there are 2N2N rows per configuration in two dimensions. Line L7 costs O(K3)O(K^3). The total is O(T(N2+NK2)+K3)O(T (N^2 + N K^2) + K^3), with O(K2)O(K^2) memory for GG and O(NK)O(N K) for the rows of one configuration. The atomistic simulation that produces the data is not counted, and it costs much more than the fit.

Properties

  • One linear solve. For a force field linear in its parameters, the fit is a single least squares problem. There is no iteration and no coarse-grained simulation (theorem: the normal equations give the minimizer).
  • Many-body projection. The fit is the projection of the many-body mean force onto the chosen basis (theorem, under the consistency conditions of Noid et al. 2008). With only pair forces in the basis, the many-body part of the mean force is lost, and the fitted pair force is the best pair approximation in the force norm, not the potential of mean force between two sites.
  • Structure is not matched. A force field with the best force residual need not give the right radial distribution function; the error depends on how much of the mean force the basis can represent.
  • State dependence. The mean force is a free energy gradient, so the fitted force depends on the temperature and the density of the atomistic run.
  • No dynamics. Force matching fits the conservative part of the coarse-grained force. The friction and the noise of the removed atoms are not fitted.

Variants and improvements

  • Bonded terms. Bonds, angles and dihedrals between sites get their own basis functions; the problem stays linear in the coefficients.
  • Regularization. When GG is ill conditioned, for example at distances with few samples, add a penalty λ∥c∥2\lambda \lVert c \rVert^2 or a smoothness penalty (Tikhonov regularization), or remove the functions with too few samples. The weight λ\lambda is a choice.
  • Block averaging. Solve the normal equations per block of configurations and average the solutions, which also gives an error bar.
  • Nonlinear models. For an embedded atom model or a neural network potential, χ2\chi^2 is not quadratic and needs an iterative optimizer. This is the form of Ercolessi and Adams (1994), who fitted interatomic potentials to forces from first-principles calculations.
  • Structural and relative entropy methods. Iterative Boltzmann inversion matches g(r)g(r), and relative entropy methods minimize the Kullback-Leibler divergence between the mapped and the coarse-grained distributions. These need coarse-grained simulations but match the structure better when the basis is too small.

When to use it

Use force matching when the atomistic forces are available and the coarse-grained force field is linear in its parameters, because then one solve gives the answer, and the result does not depend on a starting guess or a convergence criterion. Use iterative Boltzmann inversion when the structure must match closely and a small pair basis cannot represent the mean force. For the dynamics of the coarse model, add friction and noise, as in dissipative particle dynamics.

Pitfalls

  • The direction of the pair term. Writing the site force as Fi=∑jf(rij)(xj−xi)/rijF_i = \sum_j f(r_{ij}) (x_j - x_i) / r_{ij} while the reference uses f>0f > 0 for repulsion fits −f-f and gives an attraction where the atoms repel. Use one convention in both: Fi=∑jf(rij)(xi−xj)/rijF_i = \sum_j f(r_{ij}) (x_i - x_j) / r_{ij} with f>0f > 0 for repulsion.
  • Unsampled distances. Hat functions below the closest pair distance have no data, and GG is singular. Line L6 must set their coefficients to zero (or the grid must start at the smallest sampled distance); the potential there must be extrapolated as a repulsion before it is used.
  • The wrong mapped force. The reference force on a site is the sum of the forces on its atoms for the center of mass map with each atom in one site. Using the force on the central atom only, or averaging instead of adding, gives a fit of the wrong quantity.
  • Constrained atoms. With bond constraints in the atomistic run, the constraint forces are part of the force on the atoms. Leaving them out changes the mean force.
  • Reading the pair force as a potential of mean force. With many-body effects, the fitted pair force is a projection, not −dw/dr-dw/dr with w=−kBTln⁡gw = -k_B T \ln g. The two agree only at low density.
  • Too fine a grid. With few samples per hat function, noise dominates and the force oscillates. Refine the grid only while the error bars of the coefficients stay small.

Implementations

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.

force_matching_coarse_graining.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/force-matching-coarse-graining/. The authors are listed in prov/3CW63P.jsonl.
"""Multiscale coarse-graining by force matching (MS-CG).

The coarse-grained (CG) model has one pair force f(r) between sites. The
force is a linear combination f(r) = sum_k c_k phi_k(r) of hat functions
on a uniform grid r_0 < ... < r_(K-1) = r_c. For a configuration of N
sites in a periodic box, the CG force on site i is

    F_i(c) = sum_(j != i) f(r_ij) e_ij,   e_ij = (x_i - x_j) / r_ij,

so a positive f is a repulsion. F_i is linear in c: each Cartesian
component of F_i is a row a of a design matrix A, with a . c = F_i.
Force matching chooses c to minimize

    chi^2(c) = sum over configurations, sites and components of (a . c - F_ref)^2,

where F_ref is the reference force mapped from an atomistic run. This is
a linear least squares problem. The code accumulates the normal equations
G c = b with G = A^T A and b = A^T F_ref, one row at a time, and solves
them with scimat.solve. A basis function that no pair distance touches
gives a zero row in G; its coefficient is set to 0.

Sites live in a 2D periodic square box with the minimum image convention.
"""

import math
from typing import Sequence

import scimat

Point = tuple[float, float]


class HatBasis:
    """Hat functions phi_k on the nodes r_k = r0 + k dr, k = 0..K-1, with r_(K-1) = rc."""

    def __init__(self, r0: float, rc: float, k: int):
        if k < 2 or not 0.0 <= r0 < rc:
            raise ValueError("need k >= 2 and 0 <= r0 < rc")
        self.r0, self.rc, self.k = r0, rc, k
        self.dr = (rc - r0) / (k - 1)
        self.nodes = [r0 + m * self.dr for m in range(k)]

    def values(self, r: float) -> list[tuple[int, float]]:
        """The nonzero values (k, phi_k(r)), at most two, for r0 <= r <= rc; empty outside."""
        if r < self.r0 or r > self.rc:
            return []
        s = (r - self.r0) / self.dr
        m = min(int(s), self.k - 2)
        t = s - m
        return [(m, 1.0 - t), (m + 1, t)]

    def force(self, c: Sequence[float], r: float) -> float:
        """f(r) = sum_k c_k phi_k(r)."""
        return sum(c[m] * v for m, v in self.values(r))

    def potential(self, c: Sequence[float], r: float) -> float:
        """V(r) = integral of f from r to rc, exact for the piecewise linear f; V(rc) = 0."""
        if r >= self.rc:
            return 0.0
        r = max(r, self.r0)
        m = min(int((r - self.r0) / self.dr), self.k - 2)
        fr = self.force(c, r)
        total = 0.5 * (fr + c[m + 1]) * (self.nodes[m + 1] - r)
        for q in range(m + 1, self.k - 1):
            total += 0.5 * (c[q] + c[q + 1]) * self.dr
        return total


def minimum_image(d: float, box: float) -> float:
    return d - box * round(d / box)


def design_rows(x: Sequence[Point], box: float, basis: HatBasis) -> list[list[float]]:
    """The 2N rows of the design matrix of one configuration: row 2i is F_i,x and row 2i+1 is F_i,y."""
    n = len(x)
    rows = [[0.0] * basis.k for _ in range(2 * n)]
    for i in range(n):
        for j in range(i + 1, n):
            dx = minimum_image(x[i][0] - x[j][0], box)
            dy = minimum_image(x[i][1] - x[j][1], box)
            r = math.hypot(dx, dy)
            for m, v in basis.values(r):
                ex, ey = v * dx / r, v * dy / r
                rows[2 * i][m] += ex
                rows[2 * i + 1][m] += ey
                rows[2 * j][m] -= ex
                rows[2 * j + 1][m] -= ey
    return rows


def cg_forces(x: Sequence[Point], box: float, basis: HatBasis, c: Sequence[float]) -> list[float]:
    """The CG forces (F_0x, F_0y, F_1x, ...) of one configuration for the coefficients c."""
    return [scimat.dot(a, c) for a in design_rows(x, box, basis)]


def force_matching(configs: Sequence[Sequence[Point]], forces: Sequence[Sequence[float]],
                   box: float, basis: HatBasis) -> list[float]:
    """Return the coefficients c that minimize chi^2 over all configurations.

    forces[t] is the flat list (F_0x, F_0y, F_1x, ...) of reference forces of configs[t].
    """
    k = basis.k
    g = [[0.0] * k for _ in range(k)]                                   # @line L1
    b = [0.0] * k
    for x, f_ref in zip(configs, forces):                               # @line L2
        rows = design_rows(x, box, basis)                               # @line L3
        for a, f in zip(rows, f_ref):                                   # @line L4
            for p in range(k):                                          # @line L5
                if a[p] != 0.0:
                    b[p] += a[p] * f
                    for q in range(k):
                        g[p][q] += a[p] * a[q]
    unused = [p for p in range(k) if g[p][p] == 0.0]                    # @line L6
    for p in unused:
        g[p][p] = 1.0
    return scimat.solve(g, b)                                           # @line L7


def chi2(configs: Sequence[Sequence[Point]], forces: Sequence[Sequence[float]],
         box: float, basis: HatBasis, c: Sequence[float]) -> float:
    """The force residual sum of squares chi^2(c)."""
    total = 0.0
    for x, f_ref in zip(configs, forces):
        for fc, f in zip(cg_forces(x, box, basis, c), f_ref):
            total += (fc - f) ** 2
    return total
scimat.py 227 lines
# SPDX-License-Identifier: MIT
# Shared helper of the scientific-computing pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small dense linear algebra and error norms for the scientific-computing pages.

A matrix is a list of rows and a vector is a list. Entries may be int,
float or fractions.Fraction. The routines that do not take a square root
(solve, inv, det and the arithmetic) keep Fraction entries exact.
cholesky, cholesky_solve and norm2 take square roots and return floats.

API (fixed; other pages copy this file byte for byte):
    zeros(m, n=None)        m by n zero matrix (n = m if not given)
    eye(n)                  n by n identity
    add(A, B), sub(A, B)    entrywise sum and difference (vectors or matrices)
    scale(c, A)             c times A (vector or matrix)
    matmul(A, B)            matrix product
    matvec(A, x)            matrix times vector
    transpose(A)            transpose
    dot(x, y)               inner product of two vectors
    norm2(x)                Euclidean norm of a vector, as a float
    outer(x, y)             outer product x y^T
    solve(A, b)             Gaussian elimination with partial pivoting;
                            b is a vector or a matrix of right sides
    inv(A)                  inverse of A
    det(A)                  determinant of A
    cholesky(A)             lower triangular L with A = L L^T (floats)
    cholesky_solve(L, b)    solve L L^T x = b for a vector b
    err_l1(e, dx=1)         sum |e_j| dx
    err_l2(e, dx=1)         sqrt(sum e_j^2 dx), as a float
    err_linf(e, dx=1)       max |e_j| (dx is not used)
    observed_order(errors)  [log2(E_i / E_(i+1)) for successive errors]
"""

import math


def zeros(m, n=None):
    """Return an m by n matrix of zeros (n = m if n is None)."""
    if n is None:
        n = m
    return [[0] * n for _ in range(m)]


def eye(n):
    """Return the n by n identity matrix."""
    out = zeros(n, n)
    for i in range(n):
        out[i][i] = 1
    return out


def _is_matrix(a):
    return len(a) > 0 and isinstance(a[0], list)


def add(a, b):
    """Return a + b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x + y for x, y in zip(a, b)]


def sub(a, b):
    """Return a - b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x - y for x, y in zip(a, b)]


def scale(c, a):
    """Return c times a, for a vector or a matrix a."""
    if _is_matrix(a):
        return [[c * x for x in row] for row in a]
    return [c * x for x in a]


def transpose(a):
    """Return the transpose of the matrix a."""
    return [list(col) for col in zip(*a)]


def matmul(a, b):
    """Return the matrix product a b."""
    bt = transpose(b)
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """Return the product of the matrix a and the vector x."""
    return [sum(aij * xj for aij, xj in zip(row, x)) for row in a]


def dot(x, y):
    """Return the inner product of the vectors x and y."""
    return sum(a * b for a, b in zip(x, y))


def norm2(x):
    """Return the Euclidean norm of the vector x, as a float."""
    return math.sqrt(float(dot(x, x)))


def outer(x, y):
    """Return the outer product x y^T as a matrix."""
    return [[a * b for b in y] for a in x]


def _eliminate(a, rhs):
    """Reduce a to upper triangular form with partial pivoting.

    a is a copy of the square matrix, rhs a list of right side rows (one
    row per row of a) that receives the same row operations. Return the
    number of row swaps. Raise ValueError if a pivot is zero.
    """
    n = len(a)
    swaps = 0
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(a[i][k]))
        if a[p][k] == 0:
            raise ValueError("matrix is singular")
        if p != k:
            a[k], a[p] = a[p], a[k]
            rhs[k], rhs[p] = rhs[p], rhs[k]
            swaps += 1
        for i in range(k + 1, n):
            f = a[i][k] / a[k][k]
            if f == 0:
                continue
            for j in range(k, n):
                a[i][j] -= f * a[k][j]
            for j in range(len(rhs[i])):
                rhs[i][j] -= f * rhs[k][j]
    return swaps


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    b is a vector (the result is a vector) or a matrix with one column per
    right side (the result is a matrix). Fraction entries stay exact.
    Raise ValueError if a is singular.
    """
    n = len(a)
    work = [list(row) for row in a]
    vector = not _is_matrix(b)
    rhs = [[v] for v in b] if vector else [list(row) for row in b]
    _eliminate(work, rhs)
    m = len(rhs[0]) if n else 0
    x = [[0] * m for _ in range(n)]
    for i in range(n - 1, -1, -1):
        for j in range(m):
            s = rhs[i][j]
            for k in range(i + 1, n):
                s -= work[i][k] * x[k][j]
            x[i][j] = s / work[i][i]
    if vector:
        return [row[0] for row in x]
    return x


def inv(a):
    """Return the inverse of the square matrix a."""
    return solve(a, eye(len(a)))


def det(a):
    """Return the determinant of the square matrix a (0 if singular)."""
    work = [list(row) for row in a]
    rhs = [[] for _ in a]
    try:
        swaps = _eliminate(work, rhs)
    except ValueError:
        return 0
    d = -1 if swaps % 2 else 1
    for i in range(len(a)):
        d *= work[i][i]
    return d


def cholesky(a):
    """Return the lower triangular L with a = L L^T, in floats.

    Raise ValueError if a is not symmetric positive definite.
    """
    n = len(a)
    low = [[0.0] * n for _ in range(n)]
    for j in range(n):
        s = float(a[j][j]) - sum(low[j][k] ** 2 for k in range(j))
        if s <= 0.0:
            raise ValueError("matrix is not positive definite")
        low[j][j] = math.sqrt(s)
        for i in range(j + 1, n):
            t = float(a[i][j]) - sum(low[i][k] * low[j][k] for k in range(j))
            low[i][j] = t / low[j][j]
    return low


def cholesky_solve(low, b):
    """Solve L L^T x = b, with L from cholesky, for a vector b."""
    n = len(low)
    y = [0.0] * n
    for i in range(n):
        y[i] = (float(b[i]) - sum(low[i][k] * y[k] for k in range(i))) / low[i][i]
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        x[i] = (y[i] - sum(low[k][i] * x[k] for k in range(i + 1, n))) / low[i][i]
    return x


def err_l1(e, dx=1):
    """Return the discrete L1 norm sum |e_j| dx."""
    return sum(abs(v) for v in e) * dx


def err_l2(e, dx=1):
    """Return the discrete L2 norm sqrt(sum e_j^2 dx), as a float."""
    return math.sqrt(float(sum(v * v for v in e) * dx))


def err_linf(e, dx=1):
    """Return the max norm max |e_j|. dx is accepted for a uniform call and not used."""
    return max(abs(v) for v in e)


def observed_order(errors):
    """Return [log2(E_i / E_(i+1))] for a list of errors on meshes h, h/2, h/4, ..."""
    return [math.log2(float(errors[i]) / float(errors[i + 1])) for i in range(len(errors) - 1)]
test_force_matching_coarse_graining.py 148 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/force-matching-coarse-graining/. The authors are listed in prov/3CW63P.jsonl.
import math
import random

import pytest

from force_matching_coarse_graining import (HatBasis, cg_forces, chi2, design_rows, force_matching,
                                            minimum_image)

BOX = 6.0
RC = 2.5
R0 = 0.85


def configs(seed, count, n=20, box=BOX, dmin=R0):
    """Random configurations of n sites with no pair closer than dmin."""
    rng = random.Random(seed)
    out = []
    for _ in range(count):
        x = []
        while len(x) < n:
            p = (rng.uniform(0.0, box), rng.uniform(0.0, box))
            if all(math.hypot(minimum_image(p[0] - q[0], box), minimum_image(p[1] - q[1], box)) >= dmin for q in x):
                x.append(p)
        out.append(x)
    return out


def smooth_force(r):
    return 3.0 * math.cos(3.0 * r) * (RC - r)


def pair_forces(x, f, box=BOX, rc=RC):
    """Brute force: the forces of the pair force f(r) for r <= rc."""
    n = len(x)
    out = [0.0] * (2 * n)
    for i in range(n):
        for j in range(n):
            if i != j:
                dx = minimum_image(x[i][0] - x[j][0], box)
                dy = minimum_image(x[i][1] - x[j][1], box)
                r = math.hypot(dx, dy)
                if r <= rc:
                    out[2 * i] += f(r) * dx / r
                    out[2 * i + 1] += f(r) * dy / r
    return out


def test_hat_basis_is_a_partition_of_unity_and_integrates_exactly():
    b = HatBasis(1.0, 2.0, 5)
    for k in range(101):
        r = 1.0 + k / 100
        assert sum(v for _, v in b.values(r)) == pytest.approx(1.0, abs=1e-14)
    assert b.values(0.99) == [] and b.values(2.01) == []
    c = [2.0 * r - 1.0 for r in b.nodes]  # f(r) = 2 r - 1, V(r) = (rc^2 - r^2) - (rc - r)
    for r in (1.0, 1.1, 1.5, 1.99, 2.0):
        assert b.force(c, r) == pytest.approx(2.0 * r - 1.0, abs=1e-14)
        assert b.potential(c, r) == pytest.approx((4.0 - r * r) - (2.0 - r), abs=1e-14)


def test_small_example_by_hand():
    b = HatBasis(1.0, 2.0, 2)
    data = [(1.25, 1.0), (1.75, 0.2), (1.5, 0.5)]
    xs = [[(r, 0.0), (0.0, 0.0)] for r, _ in data]
    fs = [[f, 0.0, -f, 0.0] for _, f in data]
    c = force_matching(xs, fs, 10.0, b)
    assert c[0] == pytest.approx(41 / 30, abs=1e-12)
    assert c[1] == pytest.approx(-7 / 30, abs=1e-12)
    assert chi2(xs, fs, 10.0, b, c) == pytest.approx(2 * 6 / 900, abs=1e-12)
    assert b.potential(c, 1.0) == pytest.approx(17 / 30, abs=1e-12)


def test_design_rows_match_brute_force_forces():
    b = HatBasis(R0, RC, 11)
    rng = random.Random(4)
    c = [rng.uniform(-2.0, 2.0) for _ in range(b.k)]
    for x in configs(5, 3):
        assert cg_forces(x, BOX, b, c) == pytest.approx(pair_forces(x, lambda r: b.force(c, r)), abs=1e-12)
        rows = design_rows(x, BOX, b)
        for p in range(b.k):  # the pair forces cancel, so every column sums to zero over sites
            assert abs(sum(rows[2 * i][p] for i in range(len(x)))) < 1e-12
            assert abs(sum(rows[2 * i + 1][p] for i in range(len(x)))) < 1e-12


def test_force_in_the_basis_is_recovered_exactly():
    b = HatBasis(R0, RC, 11)
    c_star = [smooth_force(r) for r in b.nodes]
    xs = configs(3, 5)
    fs = [cg_forces(x, BOX, b, c_star) for x in xs]
    c = force_matching(xs, fs, BOX, b)
    assert max(abs(p - q) for p, q in zip(c, c_star)) < 1e-10


def test_solution_is_the_least_squares_minimizer():
    b = HatBasis(R0, RC, 8)
    xs = configs(6, 4)
    fs = [pair_forces(x, smooth_force) for x in xs]
    c = force_matching(xs, fs, BOX, b)
    grad = [0.0] * b.k
    for x, f_ref in zip(xs, fs):
        for a, f in zip(design_rows(x, BOX, b), f_ref):
            res = sum(ap * cp for ap, cp in zip(a, c)) - f
            for p in range(b.k):
                grad[p] += 2.0 * a[p] * res
    assert max(abs(g) for g in grad) < 1e-8
    best = chi2(xs, fs, BOX, b, c)
    rng = random.Random(8)
    for _ in range(10):
        d = [rng.uniform(-0.01, 0.01) for _ in range(b.k)]
        assert chi2(xs, fs, BOX, b, [p + q for p, q in zip(c, d)]) > best


def test_second_order_convergence_on_a_smooth_force():
    xs = configs(1, 20)
    fs = [pair_forces(x, smooth_force) for x in xs]
    errors = []
    for k in (6, 11, 21, 41):
        b = HatBasis(R0, RC, k)
        c = force_matching(xs, fs, BOX, b)
        errors.append(max(abs(c[m] - smooth_force(b.nodes[m])) for m in range(k)))
    ratios = [errors[i] / errors[i + 1] for i in range(3)]
    assert all(q > 3.0 for q in ratios)
    assert errors[-1] < 0.01


def test_zero_mean_noise_averages_out():
    b = HatBasis(R0, RC, 11)
    c_star = [smooth_force(r) for r in b.nodes]
    rng = random.Random(7)
    err = []
    for count in (5, 80):
        xs = configs(2, count)
        fs = [[f + rng.gauss(0.0, 1.0) for f in cg_forces(x, BOX, b, c_star)] for x in xs]
        c = force_matching(xs, fs, BOX, b)
        err.append(math.sqrt(sum((p - q) ** 2 for p, q in zip(c, c_star))))
    assert err[1] < 0.5 * err[0]
    assert err[1] < 0.3


def test_unused_basis_function_gets_zero():
    b = HatBasis(0.1, RC, 25)  # no pair is closer than 0.85, so the first hats are never touched
    xs = configs(9, 3)
    fs = [pair_forces(x, smooth_force) for x in xs]
    c = force_matching(xs, fs, BOX, b)
    assert c[0] == 0.0 and c[1] == 0.0
    with pytest.raises(ValueError):
        HatBasis(2.0, 1.0, 5)

History

Ercolessi and Adams introduced force matching in 1994 to fit interatomic potentials to forces from first-principles calculations of many configurations. Izvekov and Voth turned it into a coarse-graining method in 2005: map an atomistic run onto sites and fit the site forces, first for biomolecular systems and then for liquids, with the pair force expanded in a basis. In 2008 Noid and coworkers gave the method a basis in statistical mechanics, with the consistency conditions on the map and the result that the fit approximates the gradient of the many-body potential of mean force. The method is known as multiscale coarse-graining (MS-CG).

References

  1. Furio Ercolessi and James B. Adams, Interatomic potentials from first-principles calculations: the force-matching method, Europhysics Letters 26(8), 1994, 583-588, the fit of a potential to forces from first-principles calculations by least squares
  2. Sergei Izvekov and Gregory A. Voth, A multiscale coarse-graining method for biomolecular systems, The Journal of Physical Chemistry B 109(7), 2005, 2469-2473, the force matching of coarse-grained sites to mapped atomistic forces
  3. Sergei Izvekov and Gregory A. Voth, Multiscale coarse graining of liquid-state systems, The Journal of Chemical Physics 123(13), 2005, 134105, the method for liquids, with the pair force expanded in a basis and fitted by least squares
  4. W. G. Noid, Jhih-Wei Chu, Gary S. Ayton, Vinod Krishna, Sergei Izvekov, Gregory A. Voth, Avisek Das and Hans C. Andersen, The multiscale coarse-graining method. I. A rigorous bridge between atomistic and coarse-grained models, The Journal of Chemical Physics 128(24), 2008, 244114, the consistency conditions on the map, and the result that force matching approximates the gradient of the many-body potential of mean force

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 proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
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)
WritingW2 basic
  • a scene preset for the example