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
- Model
- Real RAM
- Properties
- deterministicexactnot iterativenot randomized
- Evidence
- Proof sketchCode in 1 languages
- 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 coarse-grained configurations of sites, with site positions in a periodic box, and the reference forces 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 between sites, with for repulsion, so the coarse-grained force on site is
with the minimum image. The pair force is a combination of basis functions; here they are hat functions on a uniform grid , so is the value of at the node and is piecewise linear and zero beyond the cutoff . The output is the coefficient vector that minimizes
The pair potential follows as . Each component of is linear in , so for a design matrix with one row per site, component and configuration, and a vector of the reference forces. This is a least squares problem.
The algorithm
FORCE-MATCHING(configurations R^(t), reference forces F^(t), basis φ_1..φ_K)- 1
G ← 0 (K by K), b ← 0 (length K) - 2
for each configuration t - 3
build the rows a of A for all sites and components: a_k = Σ_{j≠i} φ_k(r_ij) (e_ij)_α - 4
for each row a with its reference force f - 5
G ← G + a aᵀ, b ← b + a f - 6
set G_pp ← 1 for every p with G_pp = 0 ▷ a basis function that no distance touches gets c_p = 0 - 7
return c = G⁻¹ b ▷ the normal equations Gc = b
Line L3 visits each pair of sites once and adds to the row of site and the negative to the row of site ; a hat function is nonzero at only two nodes, so each pair touches two columns. Lines L4 and L5 form the normal equations without storing , so the memory does not grow with . Line L7 solves the by system; the implementation uses Gaussian elimination with partial pivoting from the shared dense helper. A Cholesky decomposition also works, since is symmetric positive definite once the unused functions are removed, and a QR factorization of is better conditioned when is small enough to store.
Example
By hand. Take two hat functions on : and , so and . Three configurations each have two sites on the axis, at distances , and , and the reference force on the right site is , and (repulsive), with the opposite force on the left site. All values are in reduced units. The three rows for the right site are , and ; the left site gives the same rows and forces with the opposite sign, which doubles and and does not change . Without the doubling,
The fitted forces at the three distances are , and , so the residuals are , and , and with both sites. The three data points do not lie on one line, so no fits them exactly; the least squares line passes below the first two points and above the third. The potential at is .
Grid refinement. In the tests, the reference forces come from the smooth pair force with , on 20 configurations of 20 sites in a periodic square of side 6, with no pair closer than . The largest error at the nodes is , , and for , , and hat functions on : each halving of the grid spacing divides the error by to , 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 on each component, the error with is , and for , and configurations. It falls about like . 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 , that lines L4 and L5 give and , and that minimizes if and only if , because is a convex quadratic with gradient . 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 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 and is the conditional mean of the reference force given , the expected residual splits as . So the fit is the least squares projection of onto the pair forces of the basis. Noid et al. (2008) show that, under their consistency conditions on the map, is the force of the many-body potential of mean force ; 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 hat functions , and the CG pair force is . There are configurations of sites, with reference forces (one number per site and Cartesian component). The force residual is , where and with the minimum image. We assume exact arithmetic.
Lemma 1 (the design rows). For each configuration, site and component , the row built by line L3 satisfies for every .
Proof. . So the row is . The code visits each unordered pair once, adds to the row of and subtracts it from the row of . Since and , the row of gets , the right term. Distances outside give for all and add nothing.
Stack all rows into a matrix with rows () and the reference forces into a vector . By Lemma 1, .
Lemma 2 (the normal equations). After the loop of lines L2 to L5, and .
Proof. and , where is the reference force of the row. Line L5 adds to and to for every row and every with . The skipped terms have , so they are zero.
Lemma 3 (the minimizer). is a convex quadratic with gradient . So minimizes if and only if . If the columns of are linearly independent, is positive definite and the minimizer is unique.
Proof. . If , the middle term is zero for every , and . If , take with a small ; the middle term is and the last term is , so decreases. If the columns are independent, for .
Lemma 4 (unused basis functions). If no distance in the data falls in the support of , then column of is zero, row and column of are zero, and . Lines L6 and L7 then return , and the other coefficients solve the normal equations of the reduced problem without .
Proof. Column of is zero, so for all and . After line L6 sets , equation reads , and appears in no other equation. does not depend on , so the choice keeps the minimum.
Theorem (correctness). If the columns of that are not zero are linearly independent, line L7 returns the unique minimizer of with for every unused basis function. In particular, if the reference forces are for some (the true pair force lies in the basis), the result is on the used basis functions. If the used columns are dependent, is singular and scimat.solve raises ValueError.
Proof. Lemmas 1 to 4. For , , so is a minimizer, and by uniqueness it is the result.
Lemma 5 (what the fit approximates). Let the configurations be samples of a random coarse configuration with reference forces , with , and let . Then for every ,
So the minimizer of the expected residual is the least squares projection of the conditional mean force 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 .
Proof. Write and expand the square. The cross term is . Condition on : the first factor is fixed, and . So the cross term is zero.
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, is the force of the many-body potential of mean force, . With Lemma 5 this gives the statement that force matching projects the many-body mean force onto the pair basis. The identification of with is taken from that paper and is not proved here. With finitely many samples, converges to the expected residual by the law of large numbers, so the fitted converges to the minimizer of Lemma 5 when that minimizer is unique.
Complexity
In the real RAM model, line L3 costs per configuration with a loop over all pairs, or at fixed density with a linked cell list. Line L5 costs per row in the worst case, because a row has up to nonzero entries when a site has neighbors at all distances; there are rows per configuration in two dimensions. Line L7 costs . The total is , with memory for and 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 is ill conditioned, for example at distances with few samples, add a penalty or a smoothness penalty (Tikhonov regularization), or remove the functions with too few samples. The weight 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, 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 , 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 while the reference uses for repulsion fits and gives an attraction where the atoms repel. Use one convention in both: with for repulsion.
- Unsampled distances. Hat functions below the closest pair distance have no data, and 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 with . 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.
# 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
- 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 3CW63P Edit this page History Report an error Markdown