Definitionintro
Radial distribution function
Also called pair correlation function.
The density of particles at distance r from a given particle divided by the bulk density, estimated from a histogram of pair distances.
The radial distribution function of a homogeneous and isotropic system of particles in a volume is the mean density of particles at distance from a given particle, divided by the mean density . It is 0 where particles cannot be, it has peaks at the distances of the neighbor shells, and in a liquid it goes to 1 at large , where the position of one particle says nothing about the others. In a simulation it is measured with a histogram of pair distances, and it is the main description of the structure of a liquid. Through Fourier transform it gives the structure factor that X-ray and neutron scattering measure.
Definition
Let be the positions, , and let be the average in the ensemble of the simulation, usually the canonical ensemble or the microcanonical ensemble. The pair distribution function is
If the system is homogeneous and isotropic, depends only on , and the radial distribution function is the average of over the sphere of radius . Then is the mean number of particles at a distance between and from a given particle.
Normalization. With this definition, , the number of other particles. So in a finite system at fixed , goes to at large , not to 1 exactly; for an ideal gas it is at every .
The histogram estimator. In a cubic periodic box of side , take bins of width up to and count each pair through its nearest image, as in periodic boundary conditions. Over configurations, bin collects , the number of ordered pairs with . An ideal gas at the same density has on average
particles in that shell around each particle, and the estimate is at the bin center .
RDF(configurations C_1..C_τ, L, Δr, K)- 1
require K Δr ≤ L / 2 - 2
h_k ← 0 for k = 0..K-1 - 3
for each configuration: - 4
for each pair i < j: - 5
d ← |MINIMUM-IMAGE(r_i - r_j)| - 6
k ← ⌊d / Δr⌋; if k < K then h_k ← h_k + 2 ▷ the pair counts for i and for j - 7
for each bin k: n_k ← (4πρ/3)(((k+1)Δr)^3 - (kΔr)^3) - 8
g_k ← h_k / (N τ n_k) - 9
return g
The cost is with the double loop, or at fixed density with a linked-cell list whose cells have side at least . The result is the true averaged over each bin, so a small gives more detail and more noise; a kernel density estimate is a smooth alternative to the histogram.
What it gives. For a potential that is a sum of pair terms , the energy and the pressure are integrals over (theorems for a homogeneous system):
The tail corrections of the Lennard-Jones potential are these integrals from to infinity with . The running coordination number is the mean number of neighbors closer than ; taken to the first minimum of , it counts the first shell.
Examples and non-examples
Two atoms in a box. Put atoms independently and uniformly in a periodic box of volume . Given one atom, the other one has density everywhere, and , so at every . This is the rule; the tests of the code confirm it with random positions.
A simple cubic crystal. Put atoms on a simple cubic lattice with spacing 1 in a periodic box with , so , and use up to . Each atom has 6 neighbors at distance 1 and 12 at . So in the bin and in the bin , and all other bins are empty. For bin 8, , so . For bin 11, . The running coordination number is 6 after the first shell and 18 after the second; with a larger box it is 26 after the third shell of 8 atoms at . In a body-centered cubic crystal the first shells hold 8 and 6 atoms, and in a face-centered cubic crystal the first shell holds 12.
A simple liquid. In the Lennard-Jones liquid near its triple point, is close to 0 below about , has a high first peak near , then a few smaller peaks about apart, and is close to 1 beyond about . The first peak and the minimum after it hold about 12 neighbors. These values are measurements from simulation, and they agree with scattering data for argon.
A dilute gas. At low density, , the Boltzmann factor of one pair. For hard spheres of diameter , for at every density.
Non-example: a system that is not homogeneous. Near a wall, at an interface or in a pore, the density depends on the position. A single function of normalized by one bulk density mixes regions with different densities and is not the radial distribution function; one uses the full pair density of two positions instead.
Non-example: a system that is not isotropic. In a crystal or a liquid crystal, depends on the direction. The spherical average still exists, as in the crystal example above, but it loses the angular information.
Non-example: beyond half the box. In a cubic periodic box, a sphere of radius around an atom leaves the region in which each pair has one nearest image. The histogram then misses pairs, and its estimate falls below the true . The estimator stops at .
Related definitions
- Structure factor. , the quantity that scattering experiments measure.
- Potential of mean force. , the free energy of a pair at distance , averaged over all other particles. Iterative Boltzmann inversion starts from it to fit a coarse-grained pair potential that reproduces a target .
- Compressibility equation. In the grand canonical ensemble, , with the isothermal compressibility. In a box at fixed the term of matters in this integral.
- Pair distribution of two positions. , the density of pairs with one particle at each position. In a homogeneous system .
- Coordination number. The integral of up to the first minimum of .
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/radial-distribution-function/. The authors are listed in prov/WE4PJK.jsonl.
import math
Point = list[float]
def minimum_image_distance(ri: Point, rj: Point, box: float) -> float:
s = 0.0
for a, b in zip(ri, rj):
d = a - b
d -= box * round(d / box)
s += d * d
return math.sqrt(s)
def rdf_histogram(configurations: list[list[Point]], box: float, dr: float, nbins: int) -> tuple[list[float], list[float], list[int]]:
"""The histogram estimate of g(r) in a cubic periodic box of side box.
Every configuration has the same number N of atoms. Bin k holds the
distances in [k dr, (k + 1) dr). The result is (r, g, h): the bin
centers, the estimate of g at each center and the raw counts, where h
adds 2 for each pair, once for each atom of the pair.
"""
if nbins * dr > box / 2 + 1e-12: # @line L1
raise ValueError("the histogram must stop at half the box")
h = [0] * nbins # @line L2
n = len(configurations[0])
for positions in configurations: # @line L3
if len(positions) != n:
raise ValueError("every configuration must have the same number of atoms")
for i in range(n): # @line L4
for j in range(i + 1, n): # @line L4
d = minimum_image_distance(positions[i], positions[j], box) # @line L5
k = int(d / dr) # @line L6
if k < nbins: # @line L6
h[k] += 2 # @line L6
rho = n / box ** 3
tau = len(configurations)
r_mid = []
g = []
for k in range(nbins): # @line L7
lo = k * dr
n_id = 4 * math.pi * rho / 3 * ((lo + dr) ** 3 - lo ** 3) # @line L7
g.append(h[k] / (n * tau * n_id)) # @line L8
r_mid.append(lo + dr / 2)
return r_mid, g, h # @line L9
def coordination_number(g: list[float], dr: float, rho: float, nbins: int) -> float:
"""4 pi rho times the integral of g(r) r^2 from 0 to nbins dr, with g constant on each bin.
With the histogram estimate this is exactly the mean number of neighbors
closer than nbins dr.
"""
total = 0.0
for k in range(nbins):
lo = k * dr
total += g[k] * 4 * math.pi * rho / 3 * ((lo + dr) ** 3 - lo ** 3)
return total
def simple_cubic(cells: int, a: float) -> list[Point]:
return [[a * x, a * y, a * z] for x in range(cells) for y in range(cells) for z in range(cells)]
test_radial_distribution_function.py 117 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/radial-distribution-function/. The authors are listed in prov/WE4PJK.jsonl.
import itertools
import math
import random
import pytest
from radial_distribution_function import coordination_number, minimum_image_distance, rdf_histogram, simple_cubic
def uniform_gas(rng, n, box):
return [[rng.uniform(0, box) for _ in range(3)] for _ in range(n)]
def random_hard_spheres(rng, n, box, d):
"""Random sequential addition: insert uniform points, rejecting any closer than d to one already placed."""
out = []
while len(out) < n:
p = [rng.uniform(0, box) for _ in range(3)]
if all(minimum_image_distance(p, q, box) >= d for q in out):
out.append(p)
return out
def test_minimum_image_distance_against_images():
rng = random.Random(1)
box = 4.0
for _ in range(50):
a = [rng.uniform(0, box) for _ in range(3)]
b = [rng.uniform(0, box) for _ in range(3)]
best = min(
math.dist(a, [b[q] + box * m[q] for q in range(3)])
for m in itertools.product((-1, 0, 1), repeat=3)
)
assert minimum_image_distance(a, b, box) == pytest.approx(best, abs=1e-12)
def test_page_example_simple_cubic():
# 27 atoms on a simple cubic lattice with a = 1 in a box of side 3, so rho = 1.
pos = simple_cubic(3, 1.0)
r, g, h = rdf_histogram([pos], 3.0, 0.125, 12)
assert h[8] == 27 * 6
assert h[11] == 27 * 12
assert sum(h) == 27 * 18
assert g[8] == pytest.approx(3.3797, abs=1e-4)
assert g[11] == pytest.approx(3.6946, abs=1e-4)
assert all(g[k] == 0 for k in range(12) if k not in (8, 11))
assert r[8] == pytest.approx(1.0625)
def test_coordination_numbers_simple_cubic():
pos = simple_cubic(4, 1.0)
dr = 0.05
nb = 38 # up to 1.9, below the shell at 2 = box / 2
_, g, _ = rdf_histogram([pos], 4.0, dr, nb)
assert coordination_number(g, dr, 1.0, 21) == pytest.approx(6) # up to 1.05
assert coordination_number(g, dr, 1.0, 30) == pytest.approx(18) # up to 1.5
assert coordination_number(g, dr, 1.0, 36) == pytest.approx(26) # up to 1.8
def test_ideal_gas_is_one_at_large_n():
rng = random.Random(2)
box, n = 5.0, 100
confs = [uniform_gas(rng, n, box) for _ in range(20)]
r, g, _ = rdf_histogram(confs, box, 0.1, 25)
tail = [g[k] for k in range(10, 25)]
for x in tail:
assert abs(x - 1) < 0.1
assert abs(sum(tail) / len(tail) - (n - 1) / n) < 0.02
def test_ideal_gas_finite_n_gives_n_minus_one_over_n():
rng = random.Random(3)
box, n = 5.0, 5
confs = [uniform_gas(rng, n, box) for _ in range(4000)]
_, g, _ = rdf_histogram(confs, box, 0.25, 10)
mean = sum(g[2:]) / len(g[2:])
assert abs(mean - 0.8) < 0.03
assert abs(mean - 1.0) > 0.1
def test_two_atoms_give_one_half():
rng = random.Random(4)
box = 2.0
confs = [uniform_gas(rng, 2, box) for _ in range(20000)]
_, g, _ = rdf_histogram(confs, box, 0.25, 4)
mean = sum(g[1:]) / 3
assert abs(mean - 0.5) < 0.03
def test_hard_spheres_zero_inside_and_one_far_away():
rng = random.Random(5)
box, n, d = 6.0, 150, 0.8
confs = [random_hard_spheres(rng, n, box, d) for _ in range(6)]
dr = 0.1
_, g, _ = rdf_histogram(confs, box, dr, 30)
assert all(g[k] == 0 for k in range(8)) # r < 0.8
assert max(g[8:12]) > 1.1 # contact peak
for k in range(22, 30): # 2.2 <= r < 3.0
assert abs(g[k] - 1) < 0.1
def test_translation_does_not_change_the_estimate():
rng = random.Random(6)
box = 4.0
pos = uniform_gas(rng, 30, box)
moved = [[(x + 1.7) % box for x in p] for p in pos]
_, g1, h1 = rdf_histogram([pos], box, 0.1, 20)
_, g2, h2 = rdf_histogram([moved], box, 0.1, 20)
assert h1 == h2
def test_rejects_range_beyond_half_box():
with pytest.raises(ValueError):
rdf_histogram([simple_cubic(2, 1.0)], 2.0, 0.25, 5)
References
- Michael P. Allen and Dominic J. Tildesley, Computer Simulation of Liquids, second edition, Oxford University Press, 2017, Section 2.6 (structural quantities, the definition of g(r) and its use for the energy and the pressure) and Section 8.2 (liquid structure, the histogram method and its normalization)
- Jean-Pierre Hansen and Ian R. McDonald, Theory of Simple Liquids, with Applications to Soft Matter, fourth edition, Academic Press, 2013, the chapters on statistical mechanics and on the static structure of liquids (particle densities, distribution functions and the structure factor)
- Daan Frenkel and Berend Smit, Understanding Molecular Simulation, From Algorithms to Applications, second edition, Academic Press, 2002, Chapter 4, the measurement of the radial distribution function in molecular dynamics
- Aneesur Rahman, Correlations in the motion of atoms in liquid argon, Physical Review 136(2A), 1964, A405-A411, the pair distribution function of simulated liquid argon
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 | W4 complete |
|
Tag WE4PJK Edit this page History Report an error Markdown