Algorithm Search⌘K

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
Properties
conservativerandomizednot exactiterativerandomized
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 FNF_N 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 f(x,v,t)f(x, v, t), the number density of molecules in position and velocity, by free streaming and binary collisions:

∂f∂t+v⋅∇xf=∫∫(f(v′)f(v1′)−f(v)f(v1)) g σ(g,Ω) dΩ dv1,\frac{\partial f}{\partial t} + v \cdot \nabla_x f = \int \int \big(f(v') f(v_1') - f(v) f(v_1)\big)\, g\, \sigma(g, \Omega)\, d\Omega\, dv_1,

where g=∣v−v1∣g = |v - v_1| is the relative speed, σ(g,Ω)\sigma(g, \Omega) the differential cross section and v′,v1′v', v_1' the velocities after a collision. For hard spheres of diameter dd the total cross section is σT=πd2\sigma_T = \pi d^2, the scattering is isotropic in the centre of mass frame, and the mean free path at equilibrium is λ=1/(2 nσT)\lambda = 1/(\sqrt{2}\, n \sigma_T) for the number density nn. The flow regime is set by the Knudsen number Kn=λ/ℓ\mathrm{Kn} = \lambda / \ell with ℓ\ell 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 ff over cells and time: density, flow velocity, temperature, stress and heat flux.

The algorithm

  1. DSMC-STEP(particles, Δt) ▷ unit mass, positions x_i, velocities v_i
  2. 1for each particle i do x_i ← x_i + v_i Δt, then apply the boundary conditions
  3. 2sort the particles into cells
  4. 3for each cell c with N_c ≥ 2 particles do
  5. 4M ← ½ N_c (N_c - 1) F_N (σ_T g)_max,c Δt / V_c + carry_c; carry_c ← M - ⌊M⌋, M ← ⌊M⌋
  6. 5repeat M times: pick a pair (i, j) of distinct particles of the cell at random
  7. 6g ← |v_i - v_j|
  8. 7if σ_T g > (σ_T g)_max,c then (σ_T g)_max,c ← σ_T g
  9. 8with probability σ_T g / (σ_T g)_max,c do ▷ else the pair does not collide
  10. 9n ← a unit vector uniform on the sphere ▷ hard spheres scatter isotropically
  11. 10v_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 Δt\Delta t with probability FNσTgΔt/VcF_N \sigma_T g \Delta t / V_c, so the expected number of collisions in the cell is 12Nc(Nc−1)FN⟨σTg⟩Δt/Vc\frac{1}{2} N_c(N_c - 1) F_N \langle \sigma_T g \rangle \Delta t / V_c. NTC draws MM candidate pairs with the upper bound (σTg)max⁡(\sigma_T g)_{\max} and accepts each with the ratio σTg/(σTg)max⁡\sigma_T g/(\sigma_T g)_{\max}, which is rejection sampling of the pairs; it costs O(Nc)O(N_c) per cell instead of O(Nc2)O(N_c^2) for a test of every pair. Bird writes the candidate count with NcNˉcN_c \bar N_c, the product of the number of particles and its time average, in place of Nc(Nc−1)N_c(N_c - 1); the form above gives the exact pair rate when NcN_c is fixed. The fractional part M−⌊M⌋M - \lfloor M \rfloor 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 vi+vjv_i + v_j and the energy 12(∣vi∣2+∣vj∣2)=∣vcm∣2+g2/4\frac{1}{2}(|v_i|^2 + |v_j|^2) = |v_{cm}|^2 + g^2/4 do not change. For other molecular models, such as the variable hard sphere model, σT\sigma_T depends on gg and line L9 samples the deflection angle from the model.

Example

A gas at rest. In one cell of unit volume with N=400N = 400 particles, FN=1F_N = 1, σT=0.002\sigma_T = 0.002 and a Maxwellian of temperature T=1T = 1 (units m=k=1m = k = 1), the mean relative speed is ⟨g⟩=4kT/(πm)\langle g \rangle = 4\sqrt{kT/(\pi m)}. The sample drawn with random.Random(2) has the kinetic temperature 0.94770.9477, so ⟨g⟩=2.1969\langle g \rangle = 2.1969, and the expected number of collisions in 150 steps of Δt=0.1\Delta t = 0.1 is 12⋅400⋅399⋅0.002⋅2.1969⋅15=5259\frac{1}{2} \cdot 400 \cdot 399 \cdot 0.002 \cdot 2.1969 \cdot 15 = 5259. The run with random.Random(2) gave 5241 collisions from 17501 candidates, so about 30 percent of the candidates were accepted. The difference, −18-18, is well inside one standard deviation of a Poisson count, 5259=73\sqrt{5259} = 73.

Relaxation to the Maxwellian. Start 1500 particles with speed 1 in random directions, so ⟨c4⟩/⟨c2⟩2=1\langle c^4 \rangle / \langle c^2 \rangle^2 = 1. The Maxwellian value is 15/9=5/315/9 = 5/3. With FNσT/V=1/1500F_N \sigma_T / V = 1/1500 and Δt=1\Delta t = 1 (random.Random(3)):

steps collisions per particle ⟨c4⟩/⟨c2⟩2\langle c^4 \rangle / \langle c^2 \rangle^2
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 ⟨c4⟩\langle c^4 \rangle 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 NcN_c particles and fixed velocities, NTC gives each unordered pair {i,j}\{i, j\} an expected number of collisions FNσTgijΔt/VcF_N \sigma_T g_{ij} \Delta t / V_c per step, the same as the pair collision rate of the stochastic Kac model of the gas, if (σTg)max⁡(\sigma_T g)_{\max} 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 (Δx/λ)2(\Delta x/\lambda)^2. 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 vi+vjv_i + v_j and ∣vi∣2+∣vj∣2|v_i|^2 + |v_j|^2, and the relative speed ∣vi−vj∣=g|v_i - v_j| = g.

Proof. After line L10, vi+vj=2vcmv_i + v_j = 2 v_{cm}, which is the old sum. The new relative velocity is vi−vj=gnv_i - v_j = g n with ∣n∣=1|n| = 1, so its length is gg. Then ∣vi∣2+∣vj∣2=2∣vcm∣2+12∣vi−vj∣2=2∣vcm∣2+12g2|v_i|^2 + |v_j|^2 = 2|v_{cm}|^2 + \frac{1}{2}|v_i - v_j|^2 = 2|v_{cm}|^2 + \frac{1}{2}g^2, the same before and after, because the identity ∣a∣2+∣b∣2=12∣a+b∣2+12∣a−b∣2|a|^2 + |b|^2 = \frac{1}{2}|a + b|^2 + \frac{1}{2}|a - b|^2 holds for all vectors. □\square

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 dd, the differential cross section in the centre of mass frame is dσ/dΩ=d2/4d\sigma/d\Omega = d^2/4 for every scattering angle, and the total cross section is πd2\pi d^2.

Proof. In the centre of mass frame the relative motion is a point that reflects specularly from a sphere of radius dd. With impact parameter b∈[0,d]b \in [0, d], the angle of incidence β\beta on the sphere satisfies sin⁡β=b/d\sin\beta = b/d, and the deflection is χ=π−2β\chi = \pi - 2\beta, so b=dcos⁡(χ/2)b = d\cos(\chi/2). The classical formula dσ/dΩ=bsin⁡χ∣dbdχ∣d\sigma/d\Omega = \frac{b}{\sin\chi}\big|\frac{db}{d\chi}\big| gives dcos⁡(χ/2)sin⁡χ⋅d2sin⁡(χ/2)=d24\frac{d\cos(\chi/2)}{\sin\chi} \cdot \frac{d}{2}\sin(\chi/2) = \frac{d^2}{4}, using sin⁡χ=2sin⁡(χ/2)cos⁡(χ/2)\sin\chi = 2\sin(\chi/2)\cos(\chi/2). The integral over the sphere is 4πd2/4=πd24\pi d^2/4 = \pi d^2. □\square

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 (Nc2)\binom{N_c}{2} pairs of the cell.

Proof. The first particle is uniform among the NcN_c particles. The second is uniform among the other Nc−1N_c - 1 particles (the implementation draws an index among the first Nc−1N_c - 1 and replaces the first particle by the last one). So each ordered pair of distinct particles has probability 1/(Nc(Nc−1))1/(N_c(N_c - 1)), and each unordered pair has probability 2/(Nc(Nc−1))=1/(Nc2)2/(N_c(N_c - 1)) = 1/\binom{N_c}{2}. □\square

Theorem (the NTC rate). Consider one candidate in a cell and suppose (σTg)max⁡≥σTgij(\sigma_T g)_{\max} \ge \sigma_T g_{ij} for all pairs of the cell. The probability that this candidate is the pair {i,j}\{i, j\} and collides is σTgij/((Nc2)(σTg)max⁡)\sigma_T g_{ij} / \big(\binom{N_c}{2} (\sigma_T g)_{\max}\big). If the velocities do not change during the step, the expected number of collisions of the pair {i,j}\{i, j\} among the M0=12Nc(Nc−1)FN(σTg)max⁡Δt/VcM_0 = \frac{1}{2}N_c(N_c - 1) F_N (\sigma_T g)_{\max} \Delta t / V_c candidates is

FNσTgijΔtVc,F_N \sigma_T g_{ij} \frac{\Delta t}{V_c},

which is the collision probability of the pair in time Δt\Delta t in the stochastic model of a gas in which every pair of molecules in the cell collides at the rate σTgij/Vc\sigma_T g_{ij} / V_c and each simulated particle stands for FNF_N molecules. The expected total number of collisions in the cell is 12Nc(Nc−1)FNσTg‾ Δt/Vc\frac{1}{2} N_c (N_c - 1) F_N \overline{\sigma_T g}\, \Delta t / V_c, where σTg‾\overline{\sigma_T g} is the mean over the pairs.

Proof. By Lemma 3 the candidate is {i,j}\{i, j\} with probability 1/(Nc2)1/\binom{N_c}{2}, and line L8 accepts it with probability σTgij/(σTg)max⁡≤1\sigma_T g_{ij}/(\sigma_T g)_{\max} \le 1 using an independent uniform number. The product is the first claim. With M0M_0 candidates the expected count is M0M_0 times this probability, 12Nc(Nc−1)FN(σTg)max⁡ΔtVc⋅2Nc(Nc−1)⋅σTgij(σTg)max⁡=FNσTgijΔtVc\frac{1}{2}N_c(N_c - 1) F_N (\sigma_T g)_{\max} \frac{\Delta t}{V_c} \cdot \frac{2}{N_c(N_c - 1)} \cdot \frac{\sigma_T g_{ij}}{(\sigma_T g)_{\max}} = F_N \sigma_T g_{ij} \frac{\Delta t}{V_c}. Summing over the pairs gives the total. ■\blacksquare

The carry. Line L4 draws ⌊M0+carry⌋\lfloor M_0 + \text{carry} \rfloor candidates and keeps the fractional part. By induction, after ss steps the number of candidates drawn is the sum of the ss values M0M_0 minus the current carry, which lies in [0,1)[0, 1). So the mean number of candidates per step equals the mean of M0M_0 up to an error below 1/s1/s.

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 Δt\Delta t per step for the collision part. If the bound (σTg)max⁡(\sigma_T g)_{\max} is too small, a pair with a larger σTg\sigma_T g 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 TT, the relative velocity of two independent molecules is Maxwellian with mass m/2m/2, so ⟨g⟩=8kT/(πm/2)=4kT/(πm)\langle g \rangle = \sqrt{8kT/(\pi m/2)} = 4\sqrt{kT/(\pi m)}. With the theorem, the expected number of collisions in a cell per step is 12Nc(Nc−1)FNσT⟨g⟩Δt/Vc\frac{1}{2}N_c(N_c - 1) F_N \sigma_T \langle g \rangle \Delta t / V_c, which is the value of the example and of the test.

Complexity

A step costs O(N)O(N) for the move, O(N)O(N) for the sort into cells with a counting sort, and O(1)O(1) per candidate pair. The number of candidates per cell is about 12Nc2FN(σTg)max⁡Δt/Vc\frac{1}{2} N_c^2 F_N (\sigma_T g)_{\max} \Delta t / V_c, which is O(Nc)O(N_c) when Δt\Delta t is a fixed fraction of the collision time, because FNNc/VcF_N N_c / V_c is the real number density. So a step costs O(N)O(N) and a run of SS steps costs O(SN)O(S N), with O(N)O(N) 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 1/Nc⋅(number of samples)1/\sqrt{N_c \cdot (\text{number of samples})}, 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 FN>1F_N > 1. With FN=1F_N = 1 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 Δt→0\Delta t \to 0.
  • 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 NcN_c near 1 there are hardly any pairs; with the form Nc2N_c^2 instead of Nc(Nc−1)N_c(N_c - 1), a cell with one particle would even get collision candidates. Keep NcN_c at about 10 or more.
  • A wrong upper bound. If (σTg)max⁡(\sigma_T g)_{\max} is below the true maximum, pairs with large gg 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.

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

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of space.extra
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)
WritingW2 basic
  • a scene preset for the example