Algorithm Search⌘K

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 g(r)g(r) of a homogeneous and isotropic system of NN particles in a volume VV is the mean density of particles at distance rr from a given particle, divided by the mean density ρ=N/V\rho = N/V. 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 rr, 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 r1,…,rNr_1, \ldots, r_N be the positions, rij=ri−rjr_{ij} = r_i - r_j, and let ⟨⋅⟩\langle \cdot \rangle be the average in the ensemble of the simulation, usually the canonical ensemble or the microcanonical ensemble. The pair distribution function is

g(r)=VN2⟨∑i=1N∑j≠iδ(r−rij)⟩.g(\mathbf{r}) = \frac{V}{N^2}\left\langle \sum_{i=1}^{N} \sum_{j \ne i} \delta(\mathbf{r} - r_{ij}) \right\rangle .

If the system is homogeneous and isotropic, gg depends only on r=∣r∣r = |\mathbf{r}|, and the radial distribution function g(r)g(r) is the average of g(r)g(\mathbf{r}) over the sphere of radius rr. Then ρ g(r) 4πr2 dr\rho\, g(r)\, 4\pi r^2\, dr is the mean number of particles at a distance between rr and r+drr + dr from a given particle.

Normalization. With this definition, ∫Vρ g(r) dr=N−1\int_V \rho\, g(\mathbf{r})\, d\mathbf{r} = N - 1, the number of other particles. So in a finite system at fixed NN, gg goes to 1−O(1/N)1 - O(1/N) at large rr, not to 1 exactly; for an ideal gas it is (N−1)/N(N - 1)/N at every rr.

The histogram estimator. In a cubic periodic box of side LL, take bins of width Δr\Delta r up to L/2L/2 and count each pair through its nearest image, as in periodic boundary conditions. Over τ\tau configurations, bin kk collects hkh_k, the number of ordered pairs with kΔr≤rij<(k+1)Δrk\Delta r \le r_{ij} < (k+1)\Delta r. An ideal gas at the same density has on average

nkid=4πρ3[((k+1)Δr)3−(kΔr)3]n_k^{id} = \frac{4\pi\rho}{3}\left[((k+1)\Delta r)^3 - (k\Delta r)^3\right]

particles in that shell around each particle, and the estimate is g(rk)=hk/(Nτ nkid)g(r_k) = h_k / (N \tau\, n_k^{id}) at the bin center rk=(k+12)Δrr_k = (k + \tfrac{1}{2})\Delta r.

  1. RDF(configurations C_1..C_τ, L, Δr, K)
  2. 1require K Δr ≤ L / 2
  3. 2h_k ← 0 for k = 0..K-1
  4. 3for each configuration:
  5. 4for each pair i < j:
  6. 5d ← |MINIMUM-IMAGE(r_i - r_j)|
  7. 6k ← ⌊d / Δr⌋; if k < K then h_k ← h_k + 2 ▷ the pair counts for i and for j
  8. 7for each bin k: n_k ← (4πρ/3)(((k+1)Δr)^3 - (kΔr)^3)
  9. 8g_k ← h_k / (N τ n_k)
  10. 9return g

The cost is O(τN2)O(\tau N^2) with the double loop, or O(τN)O(\tau N) at fixed density with a linked-cell list whose cells have side at least KΔrK\Delta r. The result is the true gg averaged over each bin, so a small Δr\Delta r 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 ϕ(r)\phi(r), the energy and the pressure are integrals over gg (theorems for a homogeneous system):

UN=2πρ∫0∞ϕ(r) g(r) r2 dr,P=ρkBT−2π3ρ2∫0∞r ϕ′(r) g(r) r2 dr.\frac{U}{N} = 2\pi\rho \int_0^\infty \phi(r)\, g(r)\, r^2\, dr, \qquad P = \rho k_B T - \frac{2\pi}{3}\rho^2 \int_0^\infty r\,\phi'(r)\, g(r)\, r^2\, dr .

The tail corrections of the Lennard-Jones potential are these integrals from rcr_c to infinity with g=1g = 1. The running coordination number n(R)=4πρ∫0Rg(r) r2 drn(R) = 4\pi\rho \int_0^R g(r)\, r^2\, dr is the mean number of neighbors closer than RR; taken to the first minimum of gg, it counts the first shell.

Examples and non-examples

Two atoms in a box. Put N=2N = 2 atoms independently and uniformly in a periodic box of volume VV. Given one atom, the other one has density 1/V1/V everywhere, and ρ=2/V\rho = 2/V, so g(r)=(1/V)/(2/V)=1/2g(r) = (1/V)/(2/V) = 1/2 at every r≤L/2r \le L/2. This is the (N−1)/N(N-1)/N rule; the tests of the code confirm it with random positions.

A simple cubic crystal. Put N=27N = 27 atoms on a simple cubic lattice with spacing 1 in a periodic box with L=3L = 3, so ρ=1\rho = 1, and use Δr=0.125\Delta r = 0.125 up to L/2=1.5L/2 = 1.5. Each atom has 6 neighbors at distance 1 and 12 at 2≈1.414\sqrt 2 \approx 1.414. So h8=27⋅6=162h_8 = 27 \cdot 6 = 162 in the bin [1,1.125)[1, 1.125) and h11=27⋅12=324h_{11} = 27 \cdot 12 = 324 in the bin [1.375,1.5)[1.375, 1.5), and all other bins are empty. For bin 8, n8id=4π3(1.1253−1)=1.7753n_8^{id} = \tfrac{4\pi}{3}(1.125^3 - 1) = 1.7753, so g=162/(27⋅1.7753)=6/1.7753=3.3797g = 162 / (27 \cdot 1.7753) = 6 / 1.7753 = 3.3797. For bin 11, g=12/3.2479=3.6946g = 12 / 3.2479 = 3.6946. 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 3\sqrt 3. 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, g(r)g(r) is close to 0 below about 0.9σ0.9\sigma, has a high first peak near 1.1σ1.1\sigma, then a few smaller peaks about σ\sigma apart, and is close to 1 beyond about 3σ3\sigma. 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, g(r)→exp⁡(−ϕ(r)/kBT)g(r) \to \exp(-\phi(r)/k_B T), the Boltzmann factor of one pair. For hard spheres of diameter dd, g=0g = 0 for r<dr < d 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 rr 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, g(r)g(\mathbf{r}) depends on the direction. The spherical average g(r)g(r) 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 r>L/2r > L/2 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 gg. The estimator stops at L/2L/2.

  • Structure factor. S(k)=1+ρ∫(g(r)−1) e−ik⋅r drS(k) = 1 + \rho \int (g(\mathbf{r}) - 1)\, e^{-i \mathbf{k} \cdot \mathbf{r}}\, d\mathbf{r}, the quantity that scattering experiments measure.
  • Potential of mean force. w(r)=−kBTln⁡g(r)w(r) = -k_B T \ln g(r), the free energy of a pair at distance rr, averaged over all other particles. Iterative Boltzmann inversion starts from it to fit a coarse-grained pair potential that reproduces a target gg.
  • Compressibility equation. In the grand canonical ensemble, ρkBTκT=1+ρ∫(g(r)−1) dr\rho k_B T \kappa_T = 1 + \rho \int (g(\mathbf{r}) - 1)\, d\mathbf{r}, with κT\kappa_T the isothermal compressibility. In a box at fixed NN the O(1/N)O(1/N) term of gg matters in this integral.
  • Pair distribution of two positions. ρ(2)(r1,r2)\rho^{(2)}(\mathbf{r}_1, \mathbf{r}_2), the density of pairs with one particle at each position. In a homogeneous system ρ(2)=ρ2g(r1−r2)\rho^{(2)} = \rho^2 g(\mathbf{r}_1 - \mathbf{r}_2).
  • Coordination number. The integral of 4πρ g(r) r24\pi\rho\, g(r)\, r^2 up to the first minimum of gg.

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.

radial_distribution_function.pyI0RawGitHub
# 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

  1. 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)
  2. 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)
  3. 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
  4. 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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
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)
WritingW4 complete
  • a review of the text: no review record reviews/WE4PJK/text.yaml