Algorithmadvanced
Direct simulation Monte Carlo
Also called DSMC, Bird's method.
Simulates a dilute gas by moving particles freely for a time step and then colliding random pairs in each cell with the probabilities of kinetic theory, for the Boltzmann equation.
- Time
- O(S N) average
- Space
- O(N) extra
- Where
- N = the number of simulated particles; S = the number of time steps
- Model
- Real RAM
- Properties
- conservativerandomizednot exactiterativerandomized
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Graeme A. Bird, 1963
Direct simulation Monte Carlo (DSMC) computes flows of a dilute gas, where the mean free path is not small compared with the size of the flow: the upper atmosphere, a spacecraft at re-entry, a vacuum pump, a micro device. It represents the gas by simulated particles, each standing for real molecules, and splits each time step in two parts: all particles move freely, and then, in each cell of a mesh, randomly chosen pairs of particles in the same cell collide with probabilities from kinetic theory. Collisions conserve momentum and energy exactly. The method is a stochastic solver for the Boltzmann equation of a dilute gas, which has no page here; it is not a model of the linear Boltzmann transport equation of neutrons, because the collision partners are other gas particles and the problem is nonlinear. It differs from molecular dynamics, which integrates the exact paths of interacting molecules, and from the lattice Boltzmann method, which evolves velocity distributions on a lattice with a model collision operator such as BGK. The page sits in particle transport because DSMC and neutron Monte Carlo share the idea of free flights and sampled collisions.
In plain words
A gas is a huge number of molecules that fly in straight lines and now and then hit each other. When the gas is thin, each molecule flies a long way between hits, and the usual equations of fluid flow stop being correct.
DSMC keeps a sample of the molecules on the computer, a few million instead of billions of billions. It cuts time into short steps. In each step, every sample molecule flies in a straight line. Then the space is cut into small boxes, and in each box the method picks random pairs and lets some of them collide, more often when they move fast relative to each other. A collision turns the pair to new directions but keeps their total momentum and energy. Averages over many steps give the density, speed and temperature of the flow.
The problem
The Boltzmann equation of a dilute monatomic gas evolves the velocity distribution , the number density of molecules in position and velocity, by free streaming and binary collisions:
where is the relative speed, the differential cross section and the velocities after a collision. For hard spheres of diameter the total cross section is , the scattering is isotropic in the centre of mass frame, and the mean free path at equilibrium is for the number density . The flow regime is set by the Knudsen number with a length of the flow: the Navier-Stokes equations hold for small Kn, with the Chapman-Enskog expansion as the link, and DSMC is used for Kn above about 0.01 or 0.1. The input is the geometry, the boundary conditions (walls, inflow, vacuum), the molecular model and the initial state; the output is averages of over cells and time: density, flow velocity, temperature, stress and heat flux.
The algorithm
DSMC-STEP(particles, Δt) ▷ unit mass, positions x_i, velocities v_i- 1
for each particle i do x_i ← x_i + v_i Δt, then apply the boundary conditions - 2
sort the particles into cells - 3
for each cell c with N_c ≥ 2 particles do - 4
M ← ½ N_c (N_c - 1) F_N (σ_T g)_max,c Δt / V_c + carry_c; carry_c ← M - ⌊M⌋, M ← ⌊M⌋ - 5
repeat M times: pick a pair (i, j) of distinct particles of the cell at random - 6
g ← |v_i - v_j| - 7
if σ_T g > (σ_T g)_max,c then (σ_T g)_max,c ← σ_T g - 8
with probability σ_T g / (σ_T g)_max,c do ▷ else the pair does not collide - 9
n ← a unit vector uniform on the sphere ▷ hard spheres scatter isotropically - 10
v_cm ← (v_i + v_j)/2, v_i ← v_cm + g n/2, v_j ← v_cm - g n/2
Line L4 is Bird's no-time-counter (NTC) scheme. A pair collides in time with probability , so the expected number of collisions in the cell is . NTC draws candidate pairs with the upper bound and accepts each with the ratio , which is rejection sampling of the pairs; it costs per cell instead of for a test of every pair. Bird writes the candidate count with , the product of the number of particles and its time average, in place of ; the form above gives the exact pair rate when is fixed. The fractional part carries over to the next step, so no collisions are lost on average.
Line L10 keeps the centre of mass velocity and the relative speed, so the momentum and the energy do not change. For other molecular models, such as the variable hard sphere model, depends on and line L9 samples the deflection angle from the model.
Example
A gas at rest. In one cell of unit volume with particles, , and a Maxwellian of temperature (units ), the mean relative speed is . The sample drawn with random.Random(2) has the kinetic temperature , so , and the expected number of collisions in 150 steps of is . The run with random.Random(2) gave 5241 collisions from 17501 candidates, so about 30 percent of the candidates were accepted. The difference, , is well inside one standard deviation of a Poisson count, .
Relaxation to the Maxwellian. Start 1500 particles with speed 1 in random directions, so . The Maxwellian value is . With and (random.Random(3)):
| steps | collisions per particle | |
|---|---|---|
| 0 | 0 | 1.000 |
| 1 | 1.14 | 1.215 |
| 2 | 2.46 | 1.414 |
| 3 | 3.75 | 1.511 |
| 5 | 6.10 | 1.643 |
| 10 | 12.67 | 1.675 |
| 25 | 31.93 | 1.740 |
The ratio reaches the Maxwellian value after about 5 collisions per particle, and then fluctuates around it: the sample estimate of from 1500 particles has a standard deviation of about 0.08 in the ratio. The energy and the momentum of the gas are the same at every step to rounding.
Correctness
Two claims are theorems. First, every collision conserves momentum and energy exactly (line L10), so the totals of the gas change only at the boundaries. Second, in a cell with particles and fixed velocities, NTC gives each unordered pair an expected number of collisions per step, the same as the pair collision rate of the stochastic Kac model of the gas, if is a true upper bound. Hard spheres scatter isotropically in the centre of mass frame, so line L9 samples the exact post-collision law. The proofs are below.
The link to the Boltzmann equation is a theorem from the literature, not proved here. Wagner (1992) proved that, as the number of particles goes to infinity with fixed cells and time step, the empirical measure of Bird's particle system converges to the solution of an equation of Boltzmann type in which particles collide with partners anywhere in the same cell, a mollified Boltzmann equation. The Boltzmann equation itself is the further limit of small cells and small time steps. The errors of a finite cell and step are known from analysis and measurement: Alexander, Garcia and Alder (1998) showed that the viscosity and the heat conductivity of hard-sphere DSMC have an error that grows like . The usual practice of cells smaller than about a third of a mean free path, time steps smaller than the mean collision time and about 20 particles per cell is a rule of thumb, not a theorem.
Proof: DSMC conserves momentum and energy and collides pairs at the kinetic ratefull
We assume exact arithmetic and exact independent uniform random numbers. Particles have unit mass. This proof covers what the algorithm does exactly: the conservation laws, the collision law of hard spheres and the rate at which NTC collides pairs. The convergence of DSMC to a kinetic equation is a theorem of Wagner (1992), cited on the page and not proved here.
Lemma 1 (conservation). Line L10 keeps and , and the relative speed .
Proof. After line L10, , which is the old sum. The new relative velocity is with , so its length is . Then , the same before and after, because the identity holds for all vectors.
Line L1 does not change velocities, and the sort of line L2 does not change anything. So the total momentum and the total kinetic energy of the particles change only by boundary conditions, for example at walls or open faces. In a periodic box they are exact invariants.
Lemma 2 (hard spheres scatter isotropically). For two hard spheres of diameter , the differential cross section in the centre of mass frame is for every scattering angle, and the total cross section is .
Proof. In the centre of mass frame the relative motion is a point that reflects specularly from a sphere of radius . With impact parameter , the angle of incidence on the sphere satisfies , and the deflection is , so . The classical formula gives , using . The integral over the sphere is .
So, given that a pair collides, the new direction of the relative velocity is uniform on the sphere, which is line L9, and the relative speed is kept, which is line L10 by Lemma 1.
Lemma 3 (pair choice). Line L5 picks an unordered pair uniformly among the pairs of the cell.
Proof. The first particle is uniform among the particles. The second is uniform among the other particles (the implementation draws an index among the first and replaces the first particle by the last one). So each ordered pair of distinct particles has probability , and each unordered pair has probability .
Theorem (the NTC rate). Consider one candidate in a cell and suppose for all pairs of the cell. The probability that this candidate is the pair and collides is . If the velocities do not change during the step, the expected number of collisions of the pair among the candidates is
which is the collision probability of the pair in time in the stochastic model of a gas in which every pair of molecules in the cell collides at the rate and each simulated particle stands for molecules. The expected total number of collisions in the cell is , where is the mean over the pairs.
Proof. By Lemma 3 the candidate is with probability , and line L8 accepts it with probability using an independent uniform number. The product is the first claim. With candidates the expected count is times this probability, . Summing over the pairs gives the total.
The carry. Line L4 draws candidates and keeps the fractional part. By induction, after steps the number of candidates drawn is the sum of the values minus the current carry, which lies in . So the mean number of candidates per step equals the mean of up to an error below .
What is not exact. The theorem is for fixed velocities. In a step, earlier collisions change the velocities of later candidates, which is a time discretization error of order per step for the collision part. If the bound is too small, a pair with a larger is accepted with probability 1 instead of a larger value, and its rate is too small until line L7 raises the bound. Collision partners anywhere in a cell, instead of at the same point, are the reason why the limit of Wagner's theorem is a mollified Boltzmann equation; the cell size error is studied in the paper of Alexander, Garcia and Alder cited on the page.
The equilibrium rate. For a Maxwellian at temperature , the relative velocity of two independent molecules is Maxwellian with mass , so . With the theorem, the expected number of collisions in a cell per step is , which is the value of the example and of the test.
Complexity
A step costs for the move, for the sort into cells with a counting sort, and per candidate pair. The number of candidates per cell is about , which is when is a fixed fraction of the collision time, because is the real number density. So a step costs and a run of steps costs , with space. In practice the cost is dominated by the number of particles needed for low noise: the statistical error of a cell average falls like , and low-speed flows, where the signal is small compared with the thermal noise, need very many samples.
Properties
- Conservative. Momentum and energy are conserved in each collision exactly; mass is conserved because particles are never created or destroyed inside the gas.
- Physical noise. At equilibrium the fluctuations of DSMC are those of an ideal gas with the simulated number of particles, so they are larger than in the real gas when . With the method can be used to study the fluctuations of the gas itself.
- No closure. Unlike the Navier-Stokes equations, DSMC needs no constitutive law; viscosity and heat conduction come out of the collisions.
- Splitting error. Moving and colliding in separate parts of the step is a form of operator splitting with an error that vanishes as .
- Not exact. For a finite cell size, time step and number of particles, DSMC has errors of all three kinds; only the conservation laws are exact.
Variants and improvements
- Other molecular models. Variable hard sphere and variable soft sphere models fit the temperature dependence of real viscosities; Borgnakke-Larsen exchange handles rotational and vibrational energy of molecules.
- Other pair selection schemes. The time counter of Bird's early work, Nanbu's scheme derived directly from the Boltzmann equation, and the majorant frequency scheme select pairs with the same mean rate and different noise.
- Subcells and nearest neighbours. Pick collision partners from a subcell or the nearest particle in the cell, which lowers the error of a finite cell without more cells.
- Chemistry and radiation. Reactions, ionization and radiation are added as collision outcomes with their own probabilities.
- Hybrid methods. Couple DSMC in rarefied regions to a Navier-Stokes solver where the Knudsen number is small.
When to use it
Use DSMC for rarefied flows, with Knudsen numbers from about 0.01 to the free molecular limit, where the continuum equations fail: hypersonic flow at high altitude, plumes of thrusters in vacuum, flows in micro and nano devices, the gas in a vacuum system. For small Knudsen numbers it is much more expensive than a Navier-Stokes solver, because the cells must resolve the mean free path. For dense gases and liquids use molecular dynamics, because the Boltzmann equation itself assumes binary collisions of uncorrelated particles.
Pitfalls
- Cells too large. Collisions between particles up to a cell apart give too much transport of momentum and energy. The error grows like the square of the cell size over the mean free path.
- Too few particles per cell. With near 1 there are hardly any pairs; with the form instead of , a cell with one particle would even get collision candidates. Keep at about 10 or more.
- A wrong upper bound. If is below the true maximum, pairs with large collide too rarely, and line L7 only fixes this after the fact. Start with a safe bound and let line L7 raise it.
- Repeated collisions. With few particles per cell the same pair can collide twice in one step, which carries no information. Some codes forbid it.
- Noise in slow flows. For a flow speed much smaller than the thermal speed, the signal to noise ratio is very low, and DSMC needs a huge number of samples; low-noise variants exist for this case.
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/direct-simulation-monte-carlo/. The authors are listed in prov/8HF9Q3.jsonl.
"""Direct simulation Monte Carlo (DSMC) for a dilute hard-sphere gas.
The gas lives in a periodic box of length L in x and cross-section area
A, cut into M equal cells along x. Each simulated particle stands for
F_N real molecules and carries a position x and a velocity (vx, vy, vz).
Units have m = k = 1. A time step of size dt has two parts:
1. Move: every particle streams freely, x <- x + vx dt (periodic).
2. Collide: in each cell, Bird's no-time-counter (NTC) scheme draws
n_cand = 1/2 N_c (N_c - 1) F_N (sigma g)_max dt / V_c
candidate pairs (the fractional part is carried to the next step),
picks each pair at random, and accepts it with probability
sigma g / (sigma g)_max. A hard-sphere collision keeps the centre of
mass velocity and turns the relative velocity g to a uniform random
direction, so momentum and energy are conserved exactly.
Bird writes the candidate count with N_c times the time average of N_c
in place of N_c (N_c - 1); for a cell with a fixed number of particles
the form used here gives the exact pair collision rate.
"""
import math
class Gas:
"""The state of a DSMC run."""
def __init__(self, x, v, length, ncells, f_n, sigma, area=1.0):
self.x = list(x)
self.v = [list(u) for u in v]
self.length = length
self.ncells = ncells
self.f_n = f_n
self.sigma = sigma # hard-sphere total cross section pi d^2
self.cell_volume = area * length / ncells
vmax = max(math.sqrt(u[0] ** 2 + u[1] ** 2 + u[2] ** 2) for u in self.v)
self.g_max = [2.0 * vmax] * ncells # an upper bound on |v_i - v_j| at the start
self.carry = [0.0] * ncells
self.collisions = 0
self.candidates = 0
def random_unit_vector(rng):
cos_t = 2.0 * rng.random() - 1.0
sin_t = math.sqrt(max(0.0, 1.0 - cos_t * cos_t))
phi = 2.0 * math.pi * rng.random()
return sin_t * math.cos(phi), sin_t * math.sin(phi), cos_t
def dsmc_step(gas: Gas, dt: float, rng) -> None:
"""Advance the gas by one time step."""
n = len(gas.x)
for i in range(n): # @line L1
gas.x[i] = (gas.x[i] + gas.v[i][0] * dt) % gas.length
cells = [[] for _ in range(gas.ncells)]
width = gas.length / gas.ncells
for i in range(n): # @line L2
cells[min(int(gas.x[i] / width), gas.ncells - 1)].append(i)
for c, members in enumerate(cells): # @line L3
nc = len(members)
if nc < 2:
continue
want = 0.5 * nc * (nc - 1) * gas.f_n * gas.sigma * gas.g_max[c] * dt / gas.cell_volume
want += gas.carry[c] # @line L4
n_cand = int(want)
gas.carry[c] = want - n_cand
for _ in range(n_cand): # @line L5
gas.candidates += 1
a = members[int(rng.random() * nc)]
b = members[int(rng.random() * (nc - 1))]
if b == a:
b = members[nc - 1]
va, vb = gas.v[a], gas.v[b]
g = math.sqrt((va[0] - vb[0]) ** 2 + (va[1] - vb[1]) ** 2 + (va[2] - vb[2]) ** 2) # @line L6
if g > gas.g_max[c]:
gas.g_max[c] = g # @line L7
if rng.random() * gas.g_max[c] >= g: # @line L8
continue
gas.collisions += 1
ux, uy, uz = random_unit_vector(rng) # @line L9
cm = [(va[k] + vb[k]) * 0.5 for k in range(3)]
half = (0.5 * g * ux, 0.5 * g * uy, 0.5 * g * uz)
gas.v[a] = [cm[k] + half[k] for k in range(3)] # @line L10
gas.v[b] = [cm[k] - half[k] for k in range(3)]
def maxwellian(n, temperature, rng):
"""n velocities from the Maxwell-Boltzmann law with m = k = 1."""
s = math.sqrt(temperature)
return [[rng.gauss(0.0, s), rng.gauss(0.0, s), rng.gauss(0.0, s)] for _ in range(n)]
def temperature(v) -> float:
"""Kinetic temperature in the frame of the mean velocity."""
n = len(v)
mean = [sum(u[k] for u in v) / n for k in range(3)]
return sum((u[k] - mean[k]) ** 2 for u in v for k in range(3)) / (3.0 * n)
def momentum_and_energy(v):
p = [sum(u[k] for u in v) for k in range(3)]
e = 0.5 * sum(u[0] ** 2 + u[1] ** 2 + u[2] ** 2 for u in v)
return p, e
test_direct_simulation_monte_carlo.py 78 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/direct-simulation-monte-carlo/. The authors are listed in prov/8HF9Q3.jsonl.
import math
import random
import pytest
from direct_simulation_monte_carlo import Gas, dsmc_step, maxwellian, momentum_and_energy, random_unit_vector, temperature
def test_conservation_is_exact():
rng = random.Random(1)
n = 300
v = maxwellian(n, 1.0, rng)
gas = Gas([rng.random() * 4.0 for _ in range(n)], v, 4.0, 4, 1.0, 0.01)
p0, e0 = momentum_and_energy(gas.v)
for _ in range(30):
dsmc_step(gas, 0.2, rng)
p1, e1 = momentum_and_energy(gas.v)
assert gas.collisions > 100
assert e1 == pytest.approx(e0, rel=1e-12)
for k in range(3):
assert abs(p1[k] - p0[k]) < 1e-10
def test_equilibrium_collision_rate():
# In one cell with N particles the expected number of collisions per step is
# 1/2 N (N - 1) F_N sigma <g> dt / V, with <g> = 4 sqrt(T / pi) for a Maxwellian.
rng = random.Random(2)
n, f_n, sigma, dt, steps = 400, 1.0, 0.002, 0.1, 150
gas = Gas([rng.random() for _ in range(n)], maxwellian(n, 1.0, rng), 1.0, 1, f_n, sigma)
t = temperature(gas.v)
for _ in range(steps):
dsmc_step(gas, dt, rng)
expected = 0.5 * n * (n - 1) * f_n * sigma * 4.0 * math.sqrt(t / math.pi) * dt * steps / gas.cell_volume
# The count is close to Poisson, so its sd is about sqrt(expected).
assert abs(gas.collisions - expected) < 4.0 * math.sqrt(expected)
def test_relaxation_to_maxwellian():
# All speeds equal: <c^4> / <c^2>^2 = 1. The Maxwellian value is 5/3.
rng = random.Random(3)
n = 1500
v = []
for _ in range(n):
ux, uy, uz = random_unit_vector(rng)
v.append([ux, uy, uz])
gas = Gas([rng.random() for _ in range(n)], v, 1.0, 1, 1.0, 1.0 / n)
for _ in range(25):
dsmc_step(gas, 1.0, rng)
assert gas.collisions / n > 5.0 # each particle has collided many times
c2 = sum(u[0] ** 2 + u[1] ** 2 + u[2] ** 2 for u in gas.v) / n
c4 = sum((u[0] ** 2 + u[1] ** 2 + u[2] ** 2) ** 2 for u in gas.v) / n
assert c4 / (c2 * c2) == pytest.approx(5.0 / 3.0, abs=0.12)
def test_anisotropic_temperature_relaxes():
rng = random.Random(4)
n = 1500
v = [[rng.gauss(0.0, math.sqrt(2.0)), rng.gauss(0.0, math.sqrt(0.5)), rng.gauss(0.0, math.sqrt(0.5))] for _ in range(n)]
gas = Gas([rng.random() for _ in range(n)], v, 1.0, 1, 1.0, 1.0 / n)
tx0 = sum(u[0] ** 2 for u in gas.v) / n
ty0 = sum(u[1] ** 2 for u in gas.v) / n
assert tx0 - ty0 > 1.2
for _ in range(20):
dsmc_step(gas, 1.0, rng)
tx = sum(u[0] ** 2 for u in gas.v) / n
ty = sum(u[1] ** 2 for u in gas.v) / n
assert abs(tx - ty) < 0.15
def test_unit_vectors_are_isotropic():
rng = random.Random(5)
n = 20000
s = [random_unit_vector(rng) for _ in range(n)]
for k in range(3):
assert abs(sum(u[k] for u in s) / n) < 4.0 / math.sqrt(3.0 * n)
assert abs(sum(u[k] ** 2 for u in s) / n - 1.0 / 3.0) < 0.01
History
Graeme Bird simulated the relaxation of a hard-sphere gas to equilibrium by random pair collisions in 1963 and developed the method for rarefied flows in the following years, with his first book on molecular gas dynamics in 1976. Nanbu derived a related scheme directly from the Boltzmann equation in 1980. Bird introduced the no-time-counter scheme in 1989, and his 1994 book became the standard reference. Wagner gave a convergence proof in 1992, and Alexander, Garcia and Alder analysed the cell size error in 1998. DSMC is now the standard tool for rarefied gas dynamics.
References
- G. A. Bird, Molecular Gas Dynamics and the Direct Simulation of Gas Flows, Clarendon Press, Oxford, 1994, the chapters on the DSMC procedures, with the no-time-counter selection of collision pairs
- G. A. Bird, Approach to translational equilibrium in a rigid sphere gas, Physics of Fluids 6(10), 1963, 1518-1519, the first simulation of a gas by random collisions of particle pairs
- Wolfgang Wagner, A convergence proof for Bird's direct simulation Monte Carlo method for the Boltzmann equation, Journal of Statistical Physics 66(3-4), 1992, 1011-1044, the limit of the particle system as the number of particles grows
- Francis J. Alexander, Alejandro L. Garcia and Berni J. Alder, Cell size dependence of transport coefficients in stochastic particle algorithms, Physics of Fluids 10(6), 1998, 1540-1542, the error of the viscosity and the heat conductivity as a function of the cell size
- Francis J. Alexander and Alejandro L. Garcia, The direct simulation Monte Carlo method, Computers in Physics 11(6), 1997, 588-593, a short account of the algorithm, with the selection of pairs and the time step and cell size rules
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 8HF9Q3 Edit this page History Report an error Markdown