Algorithmintro
Analog Monte Carlo particle transport
Also called analog Monte Carlo simulation.
Follows each particle from birth through free flights, collisions and scattering by sampling the physical probabilities, and counts the events of interest.
- Time
- O(N K) average
- Space
- O(1) extra
- Where
- K = the mean number of collisions per history; N = the number of histories
- Model
- Real RAM
- Properties
- randomizedexactiterativerandomized
- Evidence
- Proof sketchCode in 1 languages
- Origin
- John von Neumann, Stanislaw Ulam, Nicholas Metropolis, 1947
Analog Monte Carlo transport solves the linear Boltzmann transport equation by simulating particles one at a time with the physical laws of the problem. A history starts a particle at the source, samples the distance to its next collision with free-flight sampling, samples the type of the collision from the cross sections (absorption or scattering), samples the new direction after a scattering, and goes on until the particle is absorbed or leaves the system. Every particle has weight 1 the whole time, which is what "analog" means: the simulation is a direct copy of the physics. The average of a count over histories is an unbiased estimate of its expected value, with an error that falls like . The collision estimator and the track-length estimator turn the same histories into flux estimates, and implicit capture is the first step away from the analog game.
In plain words
Imagine you could watch one neutron. It flies a random distance, hits a nucleus, and then either disappears into the nucleus or bounces off in a new direction. It does this again and again until it is gone or out of the shield.
Analog Monte Carlo plays this game on a computer with random numbers, and uses the true chances at every step. After many neutrons, you count how many got through the shield, how many came back and how many were absorbed. The fraction that got through is an estimate of the true chance, and the estimate gets better as you play more games. Four times as many games halve the error. Nothing in the method is an approximation of the physics; the only error is the random one.
The problem
The model problem is one-speed transport in a slab with vacuum on both sides. The medium has total cross section and scattering cross section in , absorption , and the scattering ratio . Scattering is isotropic, so the new direction cosine is uniform on . A source emits particles at a point with direction , for example a beam with and .
The questions are the probabilities , and that a source particle is transmitted (leaves at ), reflected (leaves at ) or absorbed, and the mean number of collisions per history. For in both directions (an infinite medium) there is no leakage, , and the number of collisions has a geometric distribution with mean . A general code has a three-dimensional geometry of cells, energy-dependent cross sections, several reactions and angular laws of scattering, but the loop is the same.
The algorithm
ANALOG-HISTORY(x, μ, L, Σ_t, Σ_s) ▷ one particle with weight 1- 1
k ← 0 ▷ collisions so far - 2
loop - 3
s ← -ln(ξ) / Σ_t ▷ free flight, ξ uniform in (0, 1] - 4
x ← x + μ s - 5
if x > L then return (TRANSMITTED, k) - 6
if x < 0 then return (REFLECTED, k) - 7
k ← k + 1 - 8
with probability Σ_a / Σ_t return (ABSORBED, k) - 9
μ ← 2ξ' - 1 ▷ isotropic scattering, ξ' uniform in [0, 1) ANALOG-MONTE-CARLO(N, SOURCE)- 10
for n ← 1 to N do (x, μ) ← SOURCE(), (e, k) ← ANALOG-HISTORY(x, μ, L, Σ_t, Σ_s) - 11
count[e] ← count[e] + 1, add k and k² to the sums - 12
return p_e = count[e] / N with s_e = sqrt(p_e (1 - p_e) / (N - 1)), and the mean of k with its error
Lines L3 to L6 sample the flight and test for leakage. In a slab the faces are planes, so the test is a comparison of with and . Line L8 draws one uniform number and compares it with . Line L9 samples the new direction; in three dimensions it samples a polar cosine and an azimuth and rotates the direction. For anisotropic scattering it samples the cosine from the angular law of the reaction, and in a code with energy dependence line L9 also samples the new energy. Line L12 gives each estimate with its standard error from the sample variance.
Example
One history by hand. Take cm, and , a beam at with , and use for the flights:
| line | random number | result |
|---|---|---|
| L3, L4 | 0.5 | , |
| L8 | 0.7 | : the particle scatters |
| L9 | 0.1 | |
| L3, L4 | 0.4 | , |
| L8 | 0.2 | : absorbed after collisions |
With in the fourth row instead, the flight is cm long, becomes negative, and the particle is reflected after one collision.
A pure absorber. With and cm (two mean free paths), the exact transmission is . A run with random.Random(1) gives:
| standard error | relative error | ||
|---|---|---|---|
| 100 | 0.1000 | 0.0302 | 0.30 |
| 1000 | 0.1310 | 0.0107 | 0.081 |
| 10000 | 0.1375 | 0.0034 | 0.025 |
| 100000 | 0.13625 | 0.0011 | 0.0080 |
The relative error of a binomial count is , which is for , close to the measured value. Each factor of 10 in divides it by about .
Scattering. With in the same slab and (random.Random(2)), the run gives , and , with collisions per history. The three counts add up to exactly. The uncollided part of the transmission is , which agrees with whatever is. In an infinite medium the mean number of collisions is ; the runs give for (exact 2), for (exact 5) and for (exact 100).
Correctness
The claim is a theorem: each history is an exact sample of the random path of one particle in the transport model, so each count of line L12 is an unbiased estimate of the probability of its event, and the mean of is an unbiased estimate of the expected number of collisions. The expected number of collisions in a region, summed over all histories and divided by , is the integral of the collision density over the region, where is the scalar flux that solves the transport equation. The argument writes the collision density as the sum over of the densities of the -th collision, which is the Neumann series of the integral form of the transport equation. The history ends with probability 1 when or when the slab is finite. The full proof is below.
The central limit theorem then gives the error bars: for large the estimate is close to normal with standard deviation , where is the variance of one history. The confidence statement is asymptotic, and it needs a finite variance, which holds for counts.
Proof: Analog Monte Carlo gives unbiased estimates of the transport solutionfull
We assume exact arithmetic and exact independent uniform random numbers. The phase space is , the medium is uniform with , and , and scattering is isotropic. The case is the infinite medium with no faces.
The random path. One history of ANALOG-HISTORY is a sequence of collision points , where is the direction before the collision, ended by absorption or leakage. Given the state after collision (or at the source, ), the next collision is at , where has the density by free-flight sampling, if this point is inside the slab; otherwise the particle leaks. After a collision, line L8 ends the history with probability , and line L9 draws a new with density on . Write for the transition kernel from one collision to the next one in the slab:
the density of the next collision at given a collision at . Here , and the factor turns a path length into a distance in . The density of the first collision is the density of the source flight in the same way.
Lemma 1 (termination). If , or if , the history ends with probability 1, and the number of collisions has finite moments of every order.
Proof. If , each collision ends the history with probability , independently of the past, so . If and , a particle at any point of the slab that scatters into leaves through on the next flight with probability at least , because the path to the face is at most . The direction has probability , so each collision is the last one with probability at least , and . In both cases the tail is geometric, so all moments are finite.
Lemma 2 (the collision density). Let be the density of the -th collision point (zero if the history ended before), so . The expected number of collisions in a set is with , and solves the integral equation
Proof. The number of collisions in is . Its expectation is by monotone convergence, and the sum is finite by Lemma 1. Summing the recursion over gives the equation.
The integral equation of Lemma 2 is the integral form of the linear Boltzmann transport equation for the collision density in slab geometry, and the sum is its Neumann series. Lemma 1 shows that the series converges in the sense of total mass: . So the expected collision density of the analog game is the solution of the transport equation, which is the link between the game and the equation.
Theorem (unbiased counts). For each event , the estimate of line L12 has and variance , the mean of is an unbiased estimate of , and exactly.
Proof. Line L10 runs independent histories with fresh random numbers, so the indicators are independent Bernoulli variables with mean . Their mean has expectation and variance . The same argument holds for , which has a finite variance by Lemma 1. By Lemma 1 every history ends in exactly one of the three events, so the counts add up to .
The infinite medium. With , no history leaks, and each collision is the last one with probability independently. So for , and . With a uniform source of particles per unit volume and time, the collision rate density is , and , which is the check value of the page.
The pure absorber. With the history is one flight, and the beam is transmitted if and only if , which has probability by free-flight sampling. With scattering, the uncollided transmission is the same event and has the same probability.
The error bar. The standard error of line L12 uses the sample variance. By the central limit theorem, tends in law to the standard normal law as , so covers with a probability that tends to about 0.95. This is a statement about the limit ; for a small or a rare event it can be far off.
Complexity
In the real RAM model each collision costs in a slab, so a run of histories costs with the mean number of collisions per history, and extra space for the sums. In an infinite medium , which grows without bound as . In a slab of pure scatterer, a beam history is a random walk that starts near a face, and grows about linearly with the thickness ; a source inside the slab gives of order . These two growth rates are heuristics from the random walk picture, not exact results. In a three-dimensional geometry each flight also costs a search for the distance to the next surface.
The quantity that matters in practice is the cost per unit of accuracy. The figure of merit , with the relative error and the run time, is about constant in for one problem and one code, so it compares methods. It is a measurement and depends on the machine.
Properties
- Unbiased. Every estimate is unbiased for every , with no discretization of space, angle or energy.
- Exact physics. The method can use continuous energy cross sections and exact geometry, which deterministic methods such as the discrete ordinates method cannot.
- Embarrassingly parallel. Histories are independent, so they run in parallel with separate random number streams.
- Slow convergence. The error falls like . A rare event of probability needs about histories for a relative error , so a shield with transmission is out of reach for analog play.
- Exact balance. The counts of transmission, reflection and absorption add up to , so the estimates satisfy exactly.
Variants and improvements
- Non-analog play. The particle carries a weight that the method changes at each event to keep the mean the same. Implicit capture, Russian roulette, particle splitting, weight windows and the exponential transform are the standard tools. Their goal is a lower variance per unit of computer time.
- Better tallies. The collision estimator, the track-length estimator and next-event estimation all score from the same histories, with different variances.
- Criticality. For a multiplying medium the histories run in generations, with fission sites as the next source; see Monte Carlo criticality.
- Light transport. Path tracing in computer graphics is the same random walk for photons with surfaces and materials, written for the rendering equation.
When to use it
Use analog Monte Carlo as a reference for small problems, to test a deterministic code, and when the quantity of interest has a probability that is not small: the absorption in a fuel pin, the leakage of a small assembly. It is also the base that every variance reduction scheme is compared to. Do not use it for deep penetration problems, small detectors far from the source or rare reactions; there a biased game with weights is many orders of magnitude cheaper for the same error.
Pitfalls
- Error bars for one history. The collisions inside a history are correlated. The variance must be computed from the per-history totals, not from the individual scores.
- Small . For a rare event the run may see no event at all, and then the estimate is 0 with a standard error of 0. A zero estimate with a zero error is not a result.
- Infinite loops. With in an infinite medium a history never ends. A code needs a limit on the number of collisions or a time cutoff.
- Random number streams. Two parallel processes with the same seed give the same histories, and the error bar then hides the correlation. Use independent streams.
- Statistical checks. The error bar is only valid if the variance is finite and the run is long enough to sample the tail. Production codes run extra tests on the tally fluctuations; a single error bar can hide a missing rare path.
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/analog-monte-carlo-transport/. The authors are listed in prov/W64KF5.jsonl.
"""Analog Monte Carlo transport of one-speed particles in a slab.
The slab is 0 <= x <= L (L = math.inf gives an infinite medium with no faces), with a
total cross section sigma_t and a scattering cross section sigma_s, both
in cm^-1, and isotropic scattering. Both faces are vacuum: a particle that
leaves does not come back. Each history follows one particle with weight
1 and samples every event from its physical probability:
- the distance to the next collision, s = -ln(xi) / sigma_t;
- at a collision, absorption with probability sigma_a / sigma_t,
else scattering to a new direction cosine mu = 2 xi - 1.
The run counts transmitted, reflected and absorbed particles and the
collisions per history. Each count is an unbiased estimate, with a
standard error from the sample variance.
"""
import math
TRANSMITTED, REFLECTED, ABSORBED = "transmitted", "reflected", "absorbed"
def uniform_open(rng) -> float:
"""A uniform number in (0, 1]."""
return 1.0 - rng.random()
def analog_history(x: float, mu: float, length: float, sigma_t: float, sigma_s: float, rng, max_collisions: int = 10**7):
"""Follow one particle from (x, mu). Returns (event, number of collisions)."""
p_abs = (sigma_t - sigma_s) / sigma_t
has_faces = not math.isinf(length) # L = inf: an infinite medium with no faces
k = 0 # @line L1
while k < max_collisions: # @line L2
s = -math.log(uniform_open(rng)) / sigma_t # @line L3
x += s * mu # @line L4
if x > length: # @line L5
return TRANSMITTED, k
if x < 0.0 and has_faces: # @line L6
return REFLECTED, k
k += 1 # @line L7
if rng.random() < p_abs: # @line L8
return ABSORBED, k
mu = 2.0 * rng.random() - 1.0 # @line L9
raise RuntimeError("history did not end; is sigma_s = sigma_t in an infinite medium?")
def beam_source(length, rng):
"""A normally incident beam on the left face."""
return 0.0, 1.0
def isotropic_volume_source(length, rng):
"""A uniform isotropic source inside a finite slab, or at x = 0 in an infinite medium.
In an infinite medium every point is the same, so one point stands for a uniform source."""
x = 0.0 if math.isinf(length) else length * rng.random()
return x, 2.0 * rng.random() - 1.0
def analog_monte_carlo(n: int, length: float, sigma_t: float, sigma_s: float, rng, source=beam_source):
"""Run n histories. Returns a dict of estimates and standard errors."""
counts = {TRANSMITTED: 0, REFLECTED: 0, ABSORBED: 0}
k_sum = k_sq = 0
k0_transmitted = 0
for _ in range(n): # @line L10
x, mu = source(length, rng)
event, k = analog_history(x, mu, length, sigma_t, sigma_s, rng)
counts[event] += 1 # @line L11
k_sum += k
k_sq += k * k
if event == TRANSMITTED and k == 0:
k0_transmitted += 1
out = {"n": n, "counts": counts}
for ev, c in counts.items(): # @line L12
p = c / n
out[ev] = (p, math.sqrt(p * (1.0 - p) / (n - 1)) if n > 1 else 0.0)
mean_k = k_sum / n
var_k = (k_sq - n * mean_k * mean_k) / (n - 1) if n > 1 else 0.0
out["collisions"] = (mean_k, math.sqrt(max(var_k, 0.0) / n))
p0 = k0_transmitted / n
out["uncollided"] = (p0, math.sqrt(p0 * (1.0 - p0) / (n - 1)) if n > 1 else 0.0)
return out
test_analog_monte_carlo_transport.py 82 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/analog-monte-carlo-transport/. The authors are listed in prov/W64KF5.jsonl.
import math
import random
import pytest
from analog_monte_carlo_transport import (
ABSORBED,
REFLECTED,
TRANSMITTED,
analog_history,
analog_monte_carlo,
isotropic_volume_source,
)
class FixedRng:
"""Returns the given numbers in order, so that a history can be checked by hand."""
def __init__(self, values):
self.values = list(values)
def random(self):
return self.values.pop(0)
def test_hand_trace():
# L = 2 cm, sigma_t = 1, sigma_s = 0.5. The flights use xi = 1 - r.
# r = 0.5: s = ln 2 = 0.693147, collision at x = 0.693147.
# r = 0.7: not below 0.5, so the particle scatters; r = 0.1: mu = -0.8.
# r = 0.4: s = -ln 0.6 = 0.510826, x = 0.693147 - 0.8 * 0.510826 = 0.284487.
# r = 0.2: below 0.5, so the particle is absorbed after 2 collisions.
rng = FixedRng([0.5, 0.7, 0.1, 0.4, 0.2])
assert analog_history(0.0, 1.0, 2.0, 1.0, 0.5, rng) == (ABSORBED, 2)
rng = FixedRng([0.5, 0.7, 0.1, 0.9]) # the second flight is 2.302585 long and leaves on the left
assert analog_history(0.0, 1.0, 2.0, 1.0, 0.5, rng) == (REFLECTED, 1)
def test_pure_absorber_transmission():
n = 20000
out = analog_monte_carlo(n, 2.0, 1.0, 0.0, random.Random(7))
p, se = out[TRANSMITTED]
exact = math.exp(-2.0) # 0.135335
assert abs(p - exact) < 4.0 * math.sqrt(exact * (1 - exact) / n)
assert out[REFLECTED][0] == 0.0
assert se > 0.0
def test_balance_is_exact():
n = 5000
out = analog_monte_carlo(n, 3.0, 1.0, 0.7, random.Random(8))
assert sum(out["counts"].values()) == n
def test_uncollided_part_with_scattering():
# The uncollided transmission is exp(-sigma_t L) whatever the scattering is.
n = 20000
out = analog_monte_carlo(n, 1.5, 2.0, 1.6, random.Random(9))
p0 = out["uncollided"][0]
exact = math.exp(-3.0)
assert abs(p0 - exact) < 4.0 * math.sqrt(exact * (1 - exact) / n)
@pytest.mark.parametrize("c", [0.5, 0.8])
def test_infinite_medium_collisions(c):
# Each collision is the last one with probability 1 - c, so the number of
# collisions is geometric with mean 1 / (1 - c) and variance c / (1 - c)^2.
n = 20000
out = analog_monte_carlo(n, math.inf, 1.0, c, random.Random(10), isotropic_volume_source)
mean, se = out["collisions"]
sd_exact = math.sqrt(c) / (1 - c)
assert abs(mean - 1.0 / (1.0 - c)) < 4.0 * sd_exact / math.sqrt(n)
assert se == pytest.approx(sd_exact / math.sqrt(n), rel=0.1)
assert out["counts"][ABSORBED] == n
def test_pure_scatterer_slab_loses_nothing():
n = 4000
out = analog_monte_carlo(n, 2.0, 1.0, 1.0, random.Random(12))
assert out["counts"][ABSORBED] == 0
assert out["counts"][TRANSMITTED] + out["counts"][REFLECTED] == n
History
In 1947 John von Neumann wrote to Robert Richtmyer with a plan to follow neutrons in a fission device one at a time, with random numbers for the flight distances and the collision types, and Stanislaw Ulam had the same idea while he thought about the odds of solitaire. Nicholas Metropolis gave the method its name. The first such calculations ran on the ENIAC in 1948. Metropolis and Ulam published the method in 1949, with the neutron chain as the main example. Herman Kahn wrote in the early 1950s the first systematic text on the sampling methods for transport, and the books of Spanier and Gelbard (1969) and of Lux and Koblinger (1991) give the theory as it is used today.
References
- Nicholas Metropolis and S. Ulam, The Monte Carlo method, Journal of the American Statistical Association 44(247), 1949, 335-341, the neutron chain reaction as a branching random process sampled one history at a time
- Jerome Spanier and Ely M. Gelbard, Monte Carlo Principles and Neutron Transport Problems, Addison-Wesley, 1969, Dover reprint 2008, Chapter 1 (fundamentals) and Chapter 2 (discrete and continuous random walk processes)
- Ivan Lux and Laszlo Koblinger, Monte Carlo Particle Transport Methods, Neutron and Photon Calculations, CRC Press, 1991, the chapters on the simulation of particle histories and on analog games
- Malvin H. Kalos and Paula A. Whitlock, Monte Carlo Methods, second edition, Wiley-VCH, 2008, Chapter 6 (simulations of stochastic systems, radiation transport)
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 | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag W64KF5 Edit this page History Report an error Markdown