Data structurecore
Verlet neighbor list
Also called Verlet list.
Stores for each atom the atoms within the cutoff plus a skin, and is rebuilt only when some atom has moved more than half the skin.
- Time
- O(N^2) build_directO(N) build_with_cells_fixed_densityO(N + P) step
- Space
- O(N + P) total
- Where
- N = the number of atoms; P = the number of pairs in the list
- Model
- Word RAM
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Loup Verlet, 1967
A Verlet neighbor list stores, once, all pairs of atoms closer than a list radius , where is the cutoff of the forces and the skin is a margin, and then reuses this list for many time steps. At each step the force loop tests only the stored pairs, and the list is built again only when the atoms have moved far enough that a pair outside the list could have come within . It differs from the linked-cell list, which stores the atoms by position and is rebuilt at every step; a cell list is the usual way to build a Verlet list. Both are parts of the force loop of molecular dynamics under periodic boundary conditions.
In plain words
Suppose you must check, many times a minute, which people in a crowd stand within two meters of each other. People walk slowly, so the answer changes little from one check to the next.
So once in a while, write down every pair of people within two and a half meters, a little more than you need. At each check, look only at the pairs on your paper. A pair that was more than two and a half meters apart cannot come within two meters until the two people have walked half a meter between them.
Keep track of how far people walked since you made the paper. When the two who walked farthest have together walked more than half a meter, make a new paper.
The abstract type
The list answers, at each time step , the query "all unordered pairs with " for the current positions in a periodic cubic box of side , with the distance taken under the minimum image rule. The positions change a little between queries. The list is a cache of candidate pairs with a test that says when the cache can no longer be trusted. The answer is the same as that of the direct loop or a linked-cell list at every step; only the cost differs.
Representation
- The list radius is , with , so that the minimum image of each pair in the list is unique.
- The list is the set of pairs with and at the last build. Codes store it in compressed form: an array
pointof start positions and an arraylistof neighbors, so that the neighbors of atom with arelist[point[i]]tolist[point[i+1] - 1]. The implementation keeps a plain list of pairs. - The reference positions , the positions at the last build.
- The displacement of atom since the build, , taken under the minimum image rule so that an atom that crosses the boundary and is wrapped back into the box does not seem to have jumped by .
Invariant (V). Let be the two largest displacements since the last build. If , then every pair with now is in the list.
The reason is the triangle inequality on the torus. If the pair was not in the list, then at the build, and now . So the pair is not within the cutoff.
Operations
BUILD(r_1..r_N)- 1
r_ℓ ← r_c + s - 2
for each pair i < j: - 3
if |r_ij| < r_ℓ under the minimum image rule then add (i, j) to the list - 4
r_i^0 ← r_i for each atom i PAIRS(r_1..r_N) ▷ called once per time step- 5
d_i ← |r_i - r_i^0| under the minimum image rule, for each atom i - 6
if d_(1) + d_(2) > s, where d_(1) ≥ d_(2) are the two largest d_i then - 7
BUILD(r_1..r_N) - 8
for each pair (i, j) in the list: - 9
if |r_ij| < r_c then report (i, j)
Lines L2 and L3 are the direct loop here; with a linked-cell list of cell side at least , the build looks only at neighboring cells. Line L6 is the automatic update test that Allen and Tildesley give, after Fincham (1981) and Thompson (1983). The simpler and more common test is the half-skin rule: rebuild when . It is also safe, because gives , but it rebuilds at least as often. Many codes skip the test and rebuild every 10 to 20 steps; that interval is a choice, and it is safe only if no two atoms can close the skin between rebuilds.
Example
Take a box of side (in units of ) with and , so . Three atoms lie at , and .
| pair | distance at the build | in the list () | within () |
|---|---|---|---|
| (0, 1) | 2.950 | yes | no |
| (0, 2) | 3.050 | no | no |
| (1, 2) | 4.243 | no | no |
The list is , and the step reports no pair.
Two atoms move toward each other. Atom 0 moves to and atom 2 to , so . Now , but the pair is not in the list. Each atom alone moved less than the skin, so a test of the form "rebuild when one atom has moved more than " does not rebuild, and the force loop misses the pair. The test of line L6 gives and rebuilds. The new list is , with and , and the step reports . The half-skin rule also rebuilds, since .
One atom moves more than the other. Start again from the build. Atom 1 moves to and atom 2 to , so . The test of line L6 gives , so the list is kept. The half-skin rule rebuilds, since . Both report no pair, which is right: and are both above . The test of line L6 saved one build.
Correctness
PAIRS reports exactly the pairs within . Each reported pair passes the test of line L9, so it is within the cutoff. Conversely, after lines L5 to L7, either the list was just built, so that , or the test of line L6 found ; in both cases invariant (V) holds, and every pair within is in the list, so line L9 reports it. Each pair is stored once with , so it is reported once. The proof uses only the triangle inequality for the minimum image distance, which is the distance on the torus, so it holds even when atoms cross the boundary between builds. The full proof is in the proofs folder.
Proof: The Verlet list with the two-displacement test reports exactly the pairs within the cutofffull
We use the names of the pseudocode. The box is with periodic boundaries. For two points and , let be the minimum image distance, the distance from to the nearest periodic image of :
In a cubic box this minimum splits into one term per axis, and the rounding attains it on each axis, so the code computes exactly . The cutoff is , the skin is and the list radius is . A build at the positions stores the set and the reference positions .
Lemma 1 (triangle inequality on the torus). For all points , and , . Proof. Choose and with and . Then by the triangle inequality in , and the left side is at least .
Lemma 2 (invariant V). Let be the current positions, , and let be the two largest values. If , then every pair with is in . Proof. Take a pair that is not in , so . By Lemma 1 applied twice,
Since , . So , and the pair is not within the cutoff.
Lemma 3 (the half-skin rule). If , then . So the half-skin rule rebuilds whenever the test of line L6 does, and Lemma 2 holds after it too. Proof. .
Theorem. Each call of PAIRS reports each unordered pair with exactly once, and no other pair. Proof. After lines L5 to L7 there are two cases. If line L6 found , line L7 rebuilt the list at the current positions, so now , all , and the hypothesis of Lemma 2 holds. Otherwise line L6 found . In both cases, by Lemma 2, every pair within is in . Line L8 visits each element of once, and holds each unordered pair at most once, as with . Line L9 reports exactly the visited pairs with . So the reported set is the set of pairs within the cutoff, each once.
The theorem does not need . That condition, which the implementation checks, makes the nearest image of each pair within unique, so that one stored pair stands for one interaction, as the force loop assumes. The theorem also does not assume that the atoms move by small steps: the displacement is the torus distance from the reference position, and Lemma 1 holds for any motion.
Termination. BUILD runs over the pairs and the atoms. PAIRS computes displacements, finds the two largest in , calls BUILD at most once, and runs over the finite list. So each call stops.
Remark (the wrong test). The test "rebuild when " is not safe. Two atoms at distance that each move toward each other have , and they end at distance , a pair not in the list. Lemma 2 needs the sum of the two displacements, because the gap closes from both ends.
Complexity
The model is the word RAM, with one distance test counted as one operation. Let be the number of pairs in the list.
- Build. tests with the direct loop. With a linked-cell list whose cells have side at least , at fixed density.
- Step without a rebuild. for the displacements of line L5 and the two largest values, and for the pair tests.
- Size of the list. At number density , an atom has on average about atoms within , so , which is at fixed density. For the Lennard-Jones liquid at with and , this is about 73.6 neighbors per atom within , of which about 52.4 lie within : about 71 percent of the tested pairs are hits, against at most 15.5 percent for the 27 cells of a cell list. These are geometric averages for a uniform density, not measurements.
- Space. .
| operation | time | case |
|---|---|---|
| build | direct loop | |
| build | with a cell list, at fixed density | |
| step | without a rebuild | |
| space | total |
The number of steps between rebuilds depends on the skin, the temperature and the time step , so the gain is a measurement. A larger skin makes rebuilds rarer and the list longer; the best skin is found by trying a few values. Allen and Tildesley show the speedup for the Lennard-Jones fluid at , , and as a function of the skin (Section 5.3.1).
Variants
- Half-skin rule. Rebuild when one atom has moved more than . It needs only the largest displacement, and it rebuilds at least as often as the test of line L6.
- Fixed interval. Rebuild every steps, with often 10 to 20. It needs no displacement tracking, but it has no guarantee: a fast atom can cross the skin, and a missed pair gives a wrong force with no warning. It is a rule of thumb.
- Verlet list built with cells. Build the list with a linked-cell list of cell side , so that both the build and the step are at fixed density (Frenkel and Smit, Appendix F.3).
- Full list. Store each pair twice, once for each atom. It doubles the memory and the tests, but each atom then sums its own force with no writes to other atoms, which suits parallel and GPU code.
- Lists for Monte Carlo. In Monte Carlo, one atom moves at a time, and the same displacement test decides when to rebuild.
- Multiple time steps. In RESPA, the short-range force uses the Verlet list and the slow force is evaluated less often.
When to use it
Use a Verlet list when atoms move a small distance per step compared with the cutoff, as in liquids, solids and biomolecules, so that one build serves many steps. It is worth more when the force per pair is costly, because the list wastes fewer tests than the 27 cells of a cell list. For a small system, a few hundred atoms or fewer, build it with the direct loop. For a large system, build it with a linked-cell list. Do not use it when the atoms move fast relative to the skin, as in a hot gas or a shock, because the list is then rebuilt at almost every step and the extra memory buys nothing; a plain linked-cell list is then better.
Pitfalls
- Testing one displacement against the full skin. Two atoms that each move toward each other close a gap of , so the test misses pairs, as the example shows. Use the half-skin rule or the two largest displacements.
- Displacements per step instead of since the build. The test needs the displacement from the reference positions of the last build. Small steps add up.
- Displacements across the boundary. If positions are wrapped into the box, an atom that crosses the boundary seems to jump by . Use the minimum image of , or keep unwrapped positions for the displacements.
- A list radius above half the box. With , a pair can have two images within , and one stored pair cannot stand for both. Check , as the implementation does.
- A box that changes size. Under a barostat, the box and all distances scale. A list built in the old box can miss pairs in the new one unless the test accounts for the change.
- Calling it a speedup in all cases. The gain depends on the skin, the density and the temperature. It is a measured result for a given system.
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/verlet-neighbor-list/. The authors are listed in prov/NKWXRA.jsonl.
import math
Point = list[float]
def minimum_image_dist2(a: Point, b: Point, box: float) -> float:
"""Squared distance from a to the nearest periodic image of b in a cubic box of side box."""
s = 0.0
for x, y in zip(a, b):
d = x - y
d -= box * round(d / box)
s += d * d
return s
class VerletList:
"""A Verlet neighbor list with cutoff rc and skin in a periodic cubic box.
The list holds the pairs i < j closer than rc + skin at the last build.
rule is "two" (rebuild when the two largest displacements since the build
add up to more than the skin) or "half" (rebuild when one displacement is
more than half the skin). Both are safe; "half" rebuilds at least as often.
"""
def __init__(self, positions: list[Point], box: float, rc: float, skin: float, rule: str = "two") -> None:
if rc + skin > box / 2:
raise ValueError("rc + skin must be at most half the box")
if rule not in ("two", "half"):
raise ValueError("rule must be 'two' or 'half'")
self.box, self.rc, self.skin, self.rule = box, rc, skin, rule
self.builds = 0
self.build(positions)
def build(self, positions: list[Point]) -> None:
"""Store every pair i < j closer than rc + skin, and the positions at this build. O(N^2)."""
rl2 = (self.rc + self.skin) ** 2 # @line L1
n = len(positions)
self.neighbors: list[tuple[int, int]] = []
for i in range(n): # @line L2
for j in range(i + 1, n): # @line L2
if minimum_image_dist2(positions[i], positions[j], self.box) < rl2: # @line L3
self.neighbors.append((i, j)) # @line L3
self.reference = [list(r) for r in positions] # @line L4
self.builds += 1
def displacements(self, positions: list[Point]) -> list[float]:
"""The minimum image distance of each atom from its position at the last build."""
return [math.sqrt(minimum_image_dist2(r, r0, self.box)) for r, r0 in zip(positions, self.reference)]
def needs_rebuild(self, positions: list[Point]) -> bool:
d = self.displacements(positions) # @line L5
if self.rule == "half":
return max(d, default=0.0) > self.skin / 2
top = sorted(d, reverse=True)[:2] + [0.0, 0.0] # @line L6
return top[0] + top[1] > self.skin # @line L6
def pairs(self, positions: list[Point]) -> list[tuple[int, int]]:
"""The pairs i < j closer than rc at these positions, rebuilding the list first if needed."""
if self.needs_rebuild(positions): # @line L7
self.build(positions) # @line L7
rc2 = self.rc * self.rc
out = []
for i, j in self.neighbors: # @line L8
if minimum_image_dist2(positions[i], positions[j], self.box) < rc2: # @line L9
out.append((i, j)) # @line L9
return out
test_verlet_neighbor_list.py 111 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/verlet-neighbor-list/. The authors are listed in prov/NKWXRA.jsonl.
import itertools
import random
import pytest
from verlet_neighbor_list import VerletList, minimum_image_dist2
def brute_force_pairs(positions, box, rc):
"""Every pair i < j whose nearest periodic image is closer than rc.
In a cubic box the 27 images split by coordinate, so the nearest image
takes the smallest of the shifts -box, 0 and box on each axis.
"""
out = []
for i, j in itertools.combinations(range(len(positions)), 2):
best = 0.0
for a in range(3):
d = positions[i][a] - positions[j][a]
best += min(d * d, (d - box) ** 2, (d + box) ** 2)
if best < rc * rc:
out.append((i, j))
return out
def page_atoms():
return [[1.0, 0.0, 0.0], [3.95, 0.0, 0.0], [1.0, 3.05, 0.0]]
def test_page_example_build():
v = VerletList(page_atoms(), 10.0, 2.5, 0.5)
assert v.neighbors == [(0, 1)]
assert v.pairs(page_atoms()) == []
def test_page_example_two_atoms_approach():
v = VerletList(page_atoms(), 10.0, 2.5, 0.5)
moved = [[1.0, 0.3, 0.0], [3.95, 0.0, 0.0], [1.0, 2.75, 0.0]]
assert v.displacements(moved) == pytest.approx([0.3, 0.0, 0.3])
# One atom alone moved less than the skin, but the pair (0, 2) is now at 2.45.
assert max(v.displacements(moved)) < v.skin
assert v.needs_rebuild(moved)
assert v.pairs(moved) == [(0, 2)]
assert v.builds == 2
def test_page_example_stale_list_would_miss_the_pair():
v = VerletList(page_atoms(), 10.0, 2.5, 0.5)
moved = [[1.0, 0.3, 0.0], [3.95, 0.0, 0.0], [1.0, 2.75, 0.0]]
stale = [p for p in v.neighbors if minimum_image_dist2(moved[p[0]], moved[p[1]], 10.0) < 2.5 ** 2]
assert stale == []
assert brute_force_pairs(moved, 10.0, 2.5) == [(0, 2)]
def test_page_example_two_rule_saves_a_rebuild():
moved = [[1.0, 0.0, 0.0], [3.65, 0.0, 0.0], [1.0, 2.95, 0.0]]
two = VerletList(page_atoms(), 10.0, 2.5, 0.5, rule="two")
half = VerletList(page_atoms(), 10.0, 2.5, 0.5, rule="half")
assert not two.needs_rebuild(moved)
assert half.needs_rebuild(moved)
assert two.pairs(moved) == half.pairs(moved) == brute_force_pairs(moved, 10.0, 2.5)
@pytest.mark.parametrize("rule", ["two", "half"])
def test_random_walk_against_brute_force(rule):
rng = random.Random(11)
box, rc, skin, n = 7.0, 1.5, 0.4, 60
pos = [[rng.uniform(0, box) for _ in range(3)] for _ in range(n)]
v = VerletList(pos, box, rc, skin, rule=rule)
for _ in range(60):
for r in pos:
for a in range(3):
r[a] = (r[a] + rng.gauss(0.0, 0.02)) % box
assert v.pairs(pos) == brute_force_pairs(pos, box, rc)
assert 1 < v.builds < 60
def test_two_rule_rebuilds_no_more_than_half_rule():
rng = random.Random(12)
box, rc, skin, n = 7.0, 1.5, 0.4, 80
start = [[rng.uniform(0, box) for _ in range(3)] for _ in range(n)]
steps = [[[rng.gauss(0.0, 0.02) for _ in range(3)] for _ in range(n)] for _ in range(150)]
counts = {}
for rule in ("two", "half"):
pos = [list(r) for r in start]
v = VerletList(pos, box, rc, skin, rule=rule)
for step in steps:
for r, dr in zip(pos, step):
for a in range(3):
r[a] = (r[a] + dr[a]) % box
v.pairs(pos)
counts[rule] = v.builds
assert counts["two"] <= counts["half"]
def test_atom_crossing_the_boundary():
pos = [[9.9, 5.0, 5.0], [2.3, 5.0, 5.0]]
v = VerletList(pos, 10.0, 2.5, 0.5)
assert v.neighbors == [(0, 1)]
pos[0][0] = (9.9 + 0.2) % 10.0
assert v.displacements(pos)[0] == pytest.approx(0.2)
assert v.pairs(pos) == [(0, 1)]
assert v.builds == 1
def test_list_radius_must_fit_the_box():
with pytest.raises(ValueError):
VerletList([[0.0, 0.0, 0.0]], 5.0, 2.3, 0.4)
History
Loup Verlet introduced the list in his 1967 paper on the Lennard-Jones fluid, the same paper that made the Verlet integrator popular. He kept for each atom a table of the atoms within a radius somewhat larger than the cutoff and refreshed it only from time to time, so most steps did not search the whole box. Automatic tests based on the displacements since the last build came later; Allen and Tildesley credit the test on the two largest displacements to Fincham (1981) and Thompson (1983). Combining the list with cells, so that the build too is linear in , became the standard method in molecular dynamics codes.
References
- Loup Verlet, Computer "experiments" on classical fluids. I. Thermodynamical properties of Lennard-Jones molecules, Physical Review 159(1), 1967, 98-103, the table of neighbors within a radius larger than the cutoff, refreshed at intervals
- Michael P. Allen and Dominic J. Tildesley, Computer Simulation of Liquids, second edition, Oxford University Press, 2017, Section 5.3.1, The Verlet neighbour list (the automatic update test on the two largest displacements, and the measured speedup for the Lennard-Jones fluid)
- Daan Frenkel and Berend Smit, Understanding Molecular Simulation, From Algorithms to Applications, second edition, Academic Press, 2002, Appendix F, Saving CPU time (F.1 Verlet list, F.3 Combining the Verlet and cell lists, F.4 Efficiency)
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 | W4 complete |
|
Tag NKWXRA Edit this page History Report an error Markdown