Techniqueintro
Periodic boundary conditions
Also called minimum image convention.
Surrounds the simulation box by periodic images of itself, with each pair interacting through its closest image, so a small system mimics bulk matter.
Periodic boundary conditions replace the walls of a simulation box by copies of the box: the box of side is repeated in all directions to fill space, each copy holds the same atoms at the same relative positions, and an atom that leaves through one face comes back through the opposite face. A system of a few hundred or a few thousand atoms then has no surface, and it behaves much more like bulk matter than the same atoms in a closed box would. The forces are computed with the minimum image rule: each atom interacts with the nearest copy of each other atom, which needs a cutoff . The linked-cell list and the Verlet neighbor list find the pairs within the cutoff fast; this page is about the boundary itself, and boundary conditions treats the same idea for differential equations.
In plain words
A small box of atoms has walls, and the atoms near the walls feel something no atom in a large sample feels. In a box of a thousand atoms, about half of them touch a wall.
So remove the walls. Imagine the box surrounded by exact copies of itself, like tiles on a floor, in every direction. When an atom moves out through the right side, its copy comes in through the left side at the same moment. Every atom now has neighbors on all sides.
To find the force between two atoms, use the copy of the second atom that is closest to the first one. If the box is large enough compared with the range of the forces, there is only one such copy.
When it applies
Use periodic boundaries to study a homogeneous bulk phase, a liquid, a gas or a crystal, with a small number of atoms. The conditions are:
- The forces are short range, or are treated by a method made for periodic systems. With a cutoff , the minimum image rule gives each pair at most one image within the cutoff. Coulomb and dipole forces decay too slowly for a cutoff; they need Ewald summation or a mesh method such as particle-mesh Ewald, which sum over all images.
- The box is larger than the correlations you want to measure. The periodic copies impose a period on the system, so structure at distances above about , long-wavelength sound and density waves, and the large fluctuations near a critical point are not represented. The radial distribution function can be measured only up to .
- The system is not a surface, a cluster or a single molecule, unless the copies are put far apart. A slab can be studied with periodic boundaries in two directions only, and an isolated molecule in a box large enough that the copies do not interact.
The template
Let the box be , with atoms at number density , so .
WRAP(r) ▷ after each move- 1
for each axis q: x_q ← x_q - L ⌊x_q / L⌋ MINIMUM-IMAGE(r_i, r_j)- 2
Δ ← r_i - r_j - 3
for each axis q: Δ_q ← Δ_q - L round(Δ_q / L) - 4
return Δ, with |Δ| the distance between i and the nearest image of j PAIR-ENERGY(r_1..r_N, r_c)- 5
require r_c ≤ L / 2 - 6
U ← 0; for each pair i < j: - 7
Δ ← MINIMUM-IMAGE(r_i, r_j); if |Δ| < r_c then U ← U + φ(|Δ|) - 8
return U
- Choose and , which fix . Check that (line L5).
- Wrap the positions into the box after each move (line L1). The wrap changes the stored position by a whole number of box lengths, so it changes no distance.
- Use the minimum image for every pair (lines L2 to L4). After line L3, on each axis, and is the shortest of the vectors over all integer vectors .
- Truncate the potential at and say how: truncated, truncated and shifted, or shifted-force, and whether a tail correction is added (see the Lennard-Jones potential).
- Keep unwrapped positions too if you measure diffusion, because wrapped positions jump by .
The minimum image rule is one rule inside the technique; it is not the technique. It is the right rule for short-range forces in a cubic or orthorhombic box. In a triclinic box, the rounding of step 3 is done on the scaled coordinates, and it can miss the nearest image when the box is strongly skewed.
Why . Two images of atom are apart, so they cannot both be closer than to atom . With , each atom sees at most one image of each within the cutoff, and the minimum image finds it. With , some pairs have two images within the cutoff, and the minimum image rule counts only one of them.
Classic examples
One dimension. With , and , the plain difference is , and , so . The nearest image of atom 2 is at , at distance 2 from atom 1, across the boundary. An atom at wraps to , and one at wraps to .
The Lennard-Jones liquid near the triple point. A standard state is in reduced units. With atoms, , so , and the usual cutoff just fits. With , as in Verlet's 1967 runs, . For argon with nm, a box of 256 atoms at is nm on a side.
An fcc crystal in the box. A face-centered cubic lattice of unit cells holds atoms and fills a periodic box exactly, with cell side . At , and the nearest neighbors are at . Under the minimum image rule, each atom has 54 neighbors within : 12 at , 6 at , 24 at and 12 at . With the Lennard-Jones potential truncated at without a shift, the energy is , the same as a direct sum over the infinite lattice with the same cutoff. The test file checks both facts.
How few pairs interact. A cutoff sphere holds the fraction of the box. For at and , this is 6.4 percent; the linked-cell list turns this into a saving.
Variations
- Non-cubic boxes. A truncated octahedron or a rhombic dodecahedron also fills space with copies, and for a given distance between images it holds fewer atoms. Allen and Tildesley give 256 atoms for a cube, 197 for a truncated octahedron and 181 for a rhombic dodecahedron at the same density and the same smallest distance between images (Section 1.6.2). The saving matters for a solute in water, where the solvent is the main cost.
- Triclinic boxes. Write , with the box matrix whose columns are the edge vectors and scaled coordinates . Wrap and round the scaled coordinates. Barostats such as Parrinello-Rahman change during the run.
- Sliding boundaries for shear. In Lees-Edwards boundaries, the copies above and below the box move with opposite velocities, which drives a steady shear flow for measurements of viscosity.
- Slabs and wires. Periodic in two directions for an interface or a membrane, or in one direction for a wire. Long-range sums then need forms of Ewald summation adapted to the geometry.
- Spherical boundary conditions. Put the atoms on the surface of a four-dimensional sphere, which has no boundary and no preferred direction (Allen and Tildesley, Section 1.6.5).
- Long-range forces. With charges, the sum over all images converges only conditionally. Ewald summation splits it into a short-range part, computed with the minimum image, and a smooth part summed in Fourier space.
Pitfalls
- A cutoff above half the box. With , some pairs interact through two images, and the minimum image rule silently drops one. Check , or use a larger box.
- Wrapping with truncation instead of floor. In many languages,
int(x / L)rounds toward zero, so a position is not wrapped. Use the floor, as in line L1. In floating point, can return exactly for a tiny negative ; map it to 0. - Diffusion from wrapped positions. The mean squared displacement must use unwrapped positions, or it stops growing near per axis, the mean squared difference of two independent uniform positions in .
- Molecules cut by the boundary. The atoms of one molecule can be wrapped into different sides of the box. Compute bond vectors with the minimum image, or wrap whole molecules by their centers.
- Angular momentum. Periodic boundaries break rotational symmetry, so the total angular momentum is not conserved; the total linear momentum is. The kinetic temperature then uses degrees of freedom when the total momentum is fixed at zero (see the microcanonical ensemble).
- Finite-size effects. Periodic boundaries remove surfaces, not all effects of size. The period suppresses long waves and limits correlations; results such as the diffusion coefficient or a critical temperature depend on and need a study at several sizes.
Code
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/periodic-boundary-conditions/. The authors are listed in prov/VY641R.jsonl.
import math
from typing import Callable
Point = list[float]
def wrap(r: Point, box: float) -> Point:
"""Put r back into the box [0, box)^d by adding a whole number of box lengths on each axis."""
out = []
for x in r:
y = x - box * math.floor(x / box) # @line L1
out.append(0.0 if y >= box else y)
return out
def minimum_image(ri: Point, rj: Point, box: float) -> Point:
"""The vector from the nearest periodic image of rj to ri, in a cubic box of side box."""
d = [a - b for a, b in zip(ri, rj)] # @line L2
return [x - box * round(x / box) for x in d] # @line L3
def distance(ri: Point, rj: Point, box: float) -> float:
return math.sqrt(sum(x * x for x in minimum_image(ri, rj, box))) # @line L4
def pair_energy(positions: list[Point], box: float, rc: float, phi: Callable[[float], float]) -> float:
"""The sum of phi over all pairs closer than rc, each through its nearest image.
The cutoff must be at most half the box, so that each pair has at most one
image within the cutoff.
"""
if rc > box / 2: # @line L5
raise ValueError("the cutoff must be at most half the box")
u = 0.0 # @line L6
n = len(positions)
for i in range(n): # @line L6
for j in range(i + 1, n): # @line L6
r = distance(positions[i], positions[j], box) # @line L7
if r < rc: # @line L7
u += phi(r) # @line L7
return u # @line L8
def fcc_lattice(cells: int, a: float) -> list[Point]:
"""The 4 cells^3 sites of a face-centered cubic lattice with cubic cell side a, in a box of side cells * a."""
basis = [(0.0, 0.0, 0.0), (0.5, 0.5, 0.0), (0.5, 0.0, 0.5), (0.0, 0.5, 0.5)]
out = []
for i in range(cells):
for j in range(cells):
for k in range(cells):
for b in basis:
out.append([(i + b[0]) * a, (j + b[1]) * a, (k + b[2]) * a])
return out
test_periodic_boundary_conditions.py 112 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/periodic-boundary-conditions/. The authors are listed in prov/VY641R.jsonl.
import itertools
import math
import random
import pytest
from periodic_boundary_conditions import distance, fcc_lattice, minimum_image, pair_energy, wrap
def lj(r):
return 4 * (r ** -12 - r ** -6)
def nearest_image_brute(ri, rj, box):
"""The shortest of the 27 vectors ri - (rj + box m) with m in {-1, 0, 1}^3, for positions in the box."""
best = None
for m in itertools.product((-1, 0, 1), repeat=3):
d = [ri[a] - rj[a] - box * m[a] for a in range(3)]
if best is None or sum(x * x for x in d) < sum(x * x for x in best):
best = d
return best
def test_page_example_one_dimension():
assert minimum_image([1.0], [9.0], 10.0) == [2.0]
assert minimum_image([9.0], [1.0], 10.0) == [-2.0]
assert wrap([10.3], 10.0) == pytest.approx([0.3])
assert wrap([-0.4], 10.0) == pytest.approx([9.6])
def test_wrap_stays_in_box():
rng = random.Random(1)
for _ in range(2000):
r = [rng.uniform(-30.0, 30.0) for _ in range(3)]
w = wrap(r, 7.0)
for x, y in zip(r, w):
assert 0.0 <= y < 7.0
assert (x - y) / 7.0 == pytest.approx(round((x - y) / 7.0), abs=1e-9)
assert wrap([-1e-18], 7.0) == [0.0]
def test_minimum_image_against_27_images():
rng = random.Random(2)
box = 5.0
for _ in range(3000):
ri = [rng.uniform(0, box) for _ in range(3)]
rj = [rng.uniform(0, box) for _ in range(3)]
mi = minimum_image(ri, rj, box)
bf = nearest_image_brute(ri, rj, box)
assert sum(x * x for x in mi) == pytest.approx(sum(x * x for x in bf), rel=1e-12)
assert all(abs(x) <= box / 2 + 1e-12 for x in mi)
def test_distance_does_not_depend_on_which_image_is_stored():
rng = random.Random(3)
box = 6.0
for _ in range(500):
ri = [rng.uniform(0, box) for _ in range(3)]
rj = [rng.uniform(0, box) for _ in range(3)]
shifted = [x + box * rng.randint(-3, 3) for x in rj]
assert distance(ri, shifted, box) == pytest.approx(distance(ri, rj, box), abs=1e-12)
def test_at_most_one_image_within_half_the_box():
rng = random.Random(4)
box = 4.0
for _ in range(500):
ri = [rng.uniform(0, box) for _ in range(3)]
rj = [rng.uniform(0, box) for _ in range(3)]
close = 0
for m in itertools.product((-2, -1, 0, 1, 2), repeat=3):
d = math.sqrt(sum((ri[a] - rj[a] - box * m[a]) ** 2 for a in range(3)))
if d < box / 2:
close += 1
assert close <= 1
def test_fcc_box_has_twelve_nearest_neighbors_each():
a = 1.7
pos = fcc_lattice(3, a)
box = 3 * a
assert len(pos) == 108
rnn = a / math.sqrt(2)
for i in range(0, 108, 7):
near = sum(1 for j in range(108) if j != i and abs(distance(pos[i], pos[j], box) - rnn) < 1e-9)
assert near == 12
def test_fcc_energy_matches_the_infinite_lattice():
# rho* = 0.8442 with 108 atoms gives L = 5.0388, just above 2 rc = 5.
n, rho, rc = 108, 0.8442, 2.5
box = (n / rho) ** (1 / 3)
a = box / 3
pos = fcc_lattice(3, a)
u_box = pair_energy(pos, box, rc, lj) / n
# Per atom energy of the infinite lattice with the same truncation, summed directly.
u_lat = 0.0
for i, j, k in itertools.product(range(-3, 4), repeat=3):
for b in [(0, 0, 0), (0.5, 0.5, 0), (0.5, 0, 0.5), (0, 0.5, 0.5)]:
v = [(i + b[0]) * a, (j + b[1]) * a, (k + b[2]) * a]
r = math.sqrt(sum(x * x for x in v))
if 0 < r < rc:
u_lat += 0.5 * lj(r)
assert u_box == pytest.approx(u_lat, rel=1e-12)
def test_cutoff_above_half_box_is_rejected():
with pytest.raises(ValueError):
pair_energy([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]], 4.0, 2.5, lj)
Exercises
- With , give the minimum image vector from to , and the wrapped positions of and .
- Show that after line L3, , and that is the shortest of the vectors , , in a cubic box.
- Find the smallest number of atoms of a cubic box at that allows .
- In a cubic box of side , place two atoms at and . How many images of the second atom are at the smallest distance from the first? What does the rounding of line L3 return?
- In a two-dimensional box with edge vectors and , find two points for which rounding the scaled coordinates does not give the nearest image.
- Explain why the total angular momentum of an isolated cluster is conserved, but that of a periodic liquid is not.
References
- Michael P. Allen and Dominic J. Tildesley, Computer Simulation of Liquids, second edition, Oxford University Press, 2017, Section 1.6, Studying small systems (1.6.2 Periodic boundary conditions, 1.6.3 Potential truncation, 1.6.4 Computer code for periodic boundaries, 1.6.5 Spherical boundary conditions)
- Daan Frenkel and Berend Smit, Understanding Molecular Simulation, From Algorithms to Applications, second edition, Academic Press, 2002, Chapter 3, the section on technical details (periodic boundary conditions and the truncation of interactions)
- Nicholas Metropolis, Arianna W. Rosenbluth, Marshall N. Rosenbluth, Augusta H. Teller and Edward Teller, Equation of state calculations by fast computing machines, Journal of Chemical Physics 21(6), 1953, 1087-1092, the periodic square of hard disks, with each disk interacting with the nearest image of each other disk
- Loup Verlet, Computer "experiments" on classical fluids. I. Thermodynamical properties of Lennard-Jones molecules, Physical Review 159(1), 1967, 98-103, a periodic cube of 864 Lennard-Jones atoms
Where this leads
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 | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag VY641R Edit this page History Report an error Markdown