Algorithmintro
Free-flight distance sampling
Also called distance to collision sampling.
Samples the distance to the next collision as -ln(xi)/Sigma_t in a uniform medium, and by spending one sampled optical depth region by region in a heterogeneous one.
- Time
- O(M) worst
- Space
- O(1) extra
- Where
- M = the number of regions that the flight crosses
- Model
- Real RAM
- Properties
- randomizedexactiterativerandomized
- Evidence
- Proof sketchCode in 1 languages
- Origin
- John von Neumann, Stanislaw Ulam, Nicholas Metropolis, 1947
Free-flight sampling draws the distance that a neutral particle (a neutron or a photon) travels before its next collision. In a uniform medium with total cross section the distance has the exponential law with mean , and inverse transform sampling gives with uniform on . In a medium made of regions with different cross sections, the method draws one optical depth and spends it along the path, region by region, until the depth is used up. Delta tracking (also called Woodcock tracking) samples the same law in a different way: it takes flights at a constant majorant cross section and rejects some collisions, so it needs no distances to region faces. Free-flight sampling is the first step of every history in analog Monte Carlo transport.
In plain words
A particle that moves through matter has a fixed chance per centimetre to hit an atom. That chance does not depend on how far the particle already went. So the distance to the next hit is random, short distances are the most likely, and the mean distance is the mean free path.
To sample it, draw a random number and turn it into a distance with a logarithm. A small number gives a long flight. If the path crosses layers of different materials, think of the random number as a budget of "hitting chance". Each layer uses some of the budget, more for dense layers. The particle collides in the layer where the budget runs out. If the budget is still left at the outer face, the particle escapes.
The problem
A particle is at position in a slab made of regions . Region is the interval and has a constant total cross section in . The particle moves with direction cosine , so a path length moves it to . The optical depth along the path is
The probability of no collision on the first centimetres of path is . This follows from the definition of the cross section: the probability of a collision in , given none before, is . The task is to draw the collision point with this law, or to report that the particle leaves the slab first, which has probability , with the optical depth to the outer face. In three dimensions the regions are cells of a geometry and the faces are surfaces, but the method is the same.
The algorithm
FREE-FLIGHT-UNIFORM(Σ_t) ▷ a uniform medium, Σ_t > 0- 1
draw ξ uniform in (0, 1] - 2
return s = -ln(ξ) / Σ_t FREE-FLIGHT(x, μ, i, b, Σ, ξ) ▷ particle at x in region i, ξ uniform in (0, 1]- 3
τ ← -ln ξ ▷ optical depth to spend - 4
loop - 5
d ← path length from x to the face of region i in direction μ - 6
if Σ_i d > τ then - 7
return collision at x + μ τ / Σ_i, in region i - 8
τ ← τ - Σ_i d ▷ the particle crosses region i - 9
x ← the face, i ← the next region along μ - 10
if i is outside the slab then return escape at x
Line L5 is for and for . In a void region , so line L6 is false and the particle always crosses it. The comparison uses a strict inequality, so a depth that ends exactly on a face counts as a crossing, which has probability 0. The method needs one random number per flight however many regions the flight crosses. In a uniform medium FREE-FLIGHT reduces to FREE-FLIGHT-UNIFORM.
Example
A uniform medium. With the mean free path is cm. The number gives cm, the median of the law. The number gives cm, a flight of 4.6 mean free paths, which happens with probability 0.01.
Two regions. Region 0 is with and region 1 is with . A particle starts at with and :
| line | region | (cm) | before | action | |
|---|---|---|---|---|---|
| L3 | 2.302585 | draw the depth | |||
| L6, L8 | 0 | 1 | 0.5 | 2.302585 | cross, |
| L6, L7 | 1 | 2 | 4.0 | 1.802585 | collide at |
The total optical depth of the slab is , so the particle escapes with probability . It collides in region 0 with probability and in region 1 with probability . With every path length doubles for the same depth in , and the same gives the collision at .
Correctness
The claim is a theorem: for exact arithmetic and an exact uniform , FREE-FLIGHT returns a collision point whose path length satisfies for every before the face, and it returns escape with probability . The reason is that has the exponential law with mean 1, , and that the loop stops at the first path length with . Because is continuous and does not decrease, holds exactly when , which has probability . The full proof is below.
Proof: Free-flight sampling gives the exact law of the distance to collisionfull
We assume exact arithmetic and an exact uniform random number on . The particle starts at in region with direction cosine , and is the piecewise constant total cross section at the point . Write for the optical depth after a path length , and let be the path length to the outer face of the slab and .
Lemma 1 (the physical law). If the probability of a collision in , given no collision before , is , then the probability of no collision on is .
Proof. The hypothesis gives , so at every point where is continuous, and is continuous everywhere. With , the unique solution is .
Lemma 2 (the depth). satisfies for .
Proof. holds if and only if . Because is uniform on and , this has probability .
Lemma 3 (the loop). Let and . If , FREE-FLIGHT returns a collision at path length ; otherwise it returns escape.
Proof. Let be the path lengths at which the particle reaches the faces of the regions it crosses, so the region crossed on has the constant cross section and the path length . We show by induction on that when the loop starts its pass , the particle is at path length and the variable holds , and unless and . For this is line L3. In pass , line L6 compares with . If , line L7 returns the point at path length , where is linear with slope and equals . This is , because on by the induction hypothesis and increases strictly on . If , lines L8 and L9 set and move to , which is the hypothesis for , and line L10 returns escape if . In that case on the whole path, so up to the event exactly.
The event for some face has probability 0, because has a density and there are finitely many faces. Up to this event, if and only if , because is continuous and does not decrease.
Theorem. For , the path length of the returned collision satisfies , and the escape probability is . So the sample has the physical law of Lemma 1.
Proof. By Lemma 3, (a collision after or an escape) is the event , which is the event up to a null event. By Lemma 2 it has probability . Escape is the event , with probability .
The uniform medium. If everywhere, and the collision is at , which is FREE-FLIGHT-UNIFORM. Its density is with mean and standard deviation .
Why one depth is enough. The memoryless property shows that the depth left after a face, given , has again the exponential law with mean 1 and is independent of the path so far. So drawing a new depth at each face gives the same law, which is the reason why codes may do either.
Complexity
In the real RAM model, FREE-FLIGHT-UNIFORM costs : one random number and one logarithm. FREE-FLIGHT costs per region crossed, so for a flight that crosses regions, with extra space. In three dimensions each crossing needs a distance to the surfaces of the current cell, which is usually the most expensive part of a transport code. Delta tracking removes these distance computations, but it takes about tentative flights per real collision.
Properties
- Exact. The sample has the exact law of the physical flight, with no discretization of the path.
- Memoryless. The exponential law has no memory: given that the particle has gone without collision, the rest of the flight has the same law. This is why the method can stop at a face and go on with the depth that is left.
- One random number per flight. The number of regions crossed does not change the number of random numbers.
- Monotone in . A smaller always gives a longer flight. This is useful for correlated sampling, where two problems use the same random numbers.
Variants and improvements
- Delta tracking. Fly with a majorant everywhere and accept a tentative collision with probability . It suits geometries with many small cells, and it is the method of choice in volume rendering (volumetric path tracing).
- Continuously varying media. If varies inside a region, solve by integration and root finding, or use delta tracking.
- Exponential transform. Sample the flight with a modified cross section and correct the weight. This is a variance reduction method, not an analog flight.
- Forced collision. Sample the flight from the law conditioned on a collision inside a region, and multiply the weight by the collision probability. It gives collisions in thin regions.
When to use it
Use free-flight sampling with optical depth accumulation in any Monte Carlo transport code with a geometry of cells with piecewise constant cross sections, which is the usual case in reactor physics and shielding. Use delta tracking when the geometry has many cells per mean free path, or when the cross section varies continuously. In a void, the flight goes straight to the next face.
Pitfalls
- The logarithm of zero. Draw in , for example as with from a generator in . A value gives an infinite flight.
- A new random number at each face. Some codes draw a new at each face. By the memoryless property this is also correct, but it uses more random numbers and breaks correlated sampling. Mixing both methods in one flight, for example by keeping the old depth after a direction change, is wrong.
- Path length and depth in . In slab geometry the path length is the change in divided by . A code that forgets the factor gives flights that are too short for slanted particles.
- A particle parallel to the faces. With , line L5 gives an infinite distance. The flight ends with a collision in the current region if , and never ends in a void. The code must test this case.
- Rounding on faces. After line L9 the particle sits exactly on a face. A geometry code must place it in the next region and not in the region it left, or it can loop on the face.
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/free-flight-sampling/. The authors are listed in prov/21RHN1.jsonl.
"""Free-flight distance sampling for neutral particle transport.
In a uniform medium with total cross section sigma_t (in cm^-1), the
distance s to the next collision has the density sigma_t exp(-sigma_t s).
Inverse transform sampling gives s = -ln(xi) / sigma_t for xi uniform on
(0, 1].
In a slab made of regions with constant cross sections, the particle
draws one optical depth tau = -ln(xi) and spends it region by region: in
each region it either reaches the collision, or crosses the region and
subtracts the optical thickness of the part it crossed. This samples the
exact law P(S > s) = exp(-tau(s)), where tau(s) is the optical depth
along the path.
"""
import math
def uniform_open(rng) -> float:
"""A uniform number in (0, 1], so that its logarithm is finite."""
return 1.0 - rng.random()
def sample_free_flight(sigma_t: float, rng) -> float:
"""Distance to the next collision in a uniform medium."""
if sigma_t <= 0.0:
return math.inf # a void: the particle never collides
xi = uniform_open(rng) # @line L1
return -math.log(xi) / sigma_t # @line L2
def free_flight(x: float, mu: float, i: int, bounds: list[float], sigmas: list[float], xi: float):
"""Move a particle through a slab of regions to its next collision.
The slab has regions 0, ..., M-1, region k is [bounds[k], bounds[k+1]]
with total cross section sigmas[k]. The particle is at x in region i
and moves with direction cosine mu. The number xi is uniform in (0, 1].
Returns (x_new, i_new, event), where event is "collide" or "escape".
On escape, i_new is -1 (left face) or M (right face) and x_new is
the face.
"""
m = len(sigmas)
tau = -math.log(xi) # @line L3
while True: # @line L4
if mu > 0.0: # @line L5
d = (bounds[i + 1] - x) / mu
elif mu < 0.0:
d = (bounds[i] - x) / mu
else:
d = math.inf # moves parallel to the faces
if sigmas[i] <= 0.0:
raise ValueError("a particle parallel to the faces of a void never collides")
if sigmas[i] * d > tau: # @line L6
return x + mu * tau / sigmas[i], i, "collide" # @line L7
tau -= sigmas[i] * d # @line L8
if mu > 0.0: # @line L9
x, i = bounds[i + 1], i + 1
else:
x, i = bounds[i], i - 1
if i < 0 or i >= m: # @line L10
return x, i, "escape"
def optical_depth(x0: float, x1: float, mu: float, bounds: list[float], sigmas: list[float]) -> float:
"""Optical depth along a straight path from x0 to x1 with direction cosine mu."""
lo, hi = min(x0, x1), max(x0, x1)
tau = 0.0
for k, sig in enumerate(sigmas):
a, b = max(lo, bounds[k]), min(hi, bounds[k + 1])
if b > a:
tau += sig * (b - a)
return tau / abs(mu)
def region_of(x: float, bounds: list[float]) -> int:
"""Index k with bounds[k] <= x < bounds[k+1], for x inside the slab."""
for k in range(len(bounds) - 1):
if bounds[k] <= x < bounds[k + 1]:
return k
raise ValueError("x is outside the slab")
test_free_flight_sampling.py 103 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/free-flight-sampling/. The authors are listed in prov/21RHN1.jsonl.
import math
import random
import pytest
from free_flight_sampling import free_flight, optical_depth, region_of, sample_free_flight
def test_hand_values():
# xi = 0.5 and sigma_t = 2 cm^-1 give s = ln 2 / 2.
x, i, ev = free_flight(0.0, 1.0, 0, [0.0, 10.0], [2.0], 0.5)
assert ev == "collide" and i == 0
assert x == pytest.approx(0.346574, abs=1e-6)
# Two regions: [0, 1) with 0.5 cm^-1 and [1, 3) with 2 cm^-1, xi = 0.1.
# tau = 2.302585; region 0 uses 0.5, so 1.802585 is left for region 1.
x, i, ev = free_flight(0.0, 1.0, 0, [0.0, 1.0, 3.0], [0.5, 2.0], 0.1)
assert ev == "collide" and i == 1
assert x == pytest.approx(1.901293, abs=1e-6)
# A slanted path with mu = 0.5 doubles the path per unit of depth.
x, i, ev = free_flight(0.0, 0.5, 0, [0.0, 1.0, 3.0], [0.5, 2.0], 0.1)
assert ev == "collide" and i == 1
assert x == pytest.approx(1.0 + 0.5 * (2.302585093 - 1.0) / 2.0, abs=1e-6)
def test_escape_and_void():
# xi = 0.01 gives tau = 4.6, more than the 3 units of the slab.
x, i, ev = free_flight(0.0, 1.0, 0, [0.0, 1.0, 2.0, 3.0], [1.0, 0.0, 2.0], 0.01)
assert ev == "escape" and i == 3 and x == 3.0
# A void region never holds a collision.
rng = random.Random(5)
for _ in range(2000):
x, i, ev = free_flight(0.0, 1.0, 0, [0.0, 1.0, 2.0, 3.0], [1.0, 0.0, 2.0], 1.0 - rng.random())
assert not (ev == "collide" and i == 1)
# Moving to the left from the middle region.
x, i, ev = free_flight(1.5, -1.0, 1, [0.0, 1.0, 2.0], [1.0, 1.0], math.exp(-0.25))
assert ev == "collide" and i == 1 and x == pytest.approx(1.25)
x, i, ev = free_flight(1.5, -1.0, 1, [0.0, 1.0, 2.0], [1.0, 1.0], math.exp(-2.0))
assert ev == "escape" and i == -1 and x == 0.0
def test_uniform_mean_and_tail():
rng = random.Random(11)
sig, n = 2.0, 40000
s = [sample_free_flight(sig, rng) for _ in range(n)]
mean = sum(s) / n
# The exponential law has mean 1/sigma and standard deviation 1/sigma.
assert abs(mean - 1.0 / sig) < 4.0 * (1.0 / sig) / math.sqrt(n)
for length in (0.5, 1.0, 2.0):
p = math.exp(-sig * length)
frac = sum(1 for v in s if v > length) / n
assert abs(frac - p) < 4.0 * math.sqrt(p * (1 - p) / n)
assert sample_free_flight(0.0, rng) == math.inf
def test_region_collision_probabilities_exact_law():
# P(collision in region k) = exp(-tau before k) - exp(-tau up to the end of k).
bounds, sigmas = [0.0, 0.5, 1.5, 2.0, 3.0], [1.0, 0.2, 3.0, 0.0]
rng = random.Random(3)
n = 40000
counts = [0] * (len(sigmas) + 1) # the last entry counts escapes
for _ in range(n):
x, i, ev = free_flight(0.0, 1.0, 0, bounds, sigmas, 1.0 - rng.random())
counts[i if ev == "collide" else len(sigmas)] += 1
cum = [0.0]
for k, sig in enumerate(sigmas):
cum.append(cum[-1] + sig * (bounds[k + 1] - bounds[k]))
for k in range(len(sigmas)):
p = math.exp(-cum[k]) - math.exp(-cum[k + 1])
assert abs(counts[k] / n - p) <= 4.0 * math.sqrt(p * (1 - p) / n) + 1e-12
p_esc = math.exp(-cum[-1])
assert abs(counts[-1] / n - p_esc) < 4.0 * math.sqrt(p_esc * (1 - p_esc) / n)
def delta_tracking(x, mu, bounds, sigmas, sig_max, rng):
"""An independent method: tentative flights at a majorant, accepted with sigma / sig_max."""
while True:
x += mu * sample_free_flight(sig_max, rng)
if x < bounds[0] or x >= bounds[-1]:
return x, "escape"
if rng.random() < sigmas[region_of(x, bounds)] / sig_max:
return x, "collide"
def test_agrees_with_delta_tracking():
bounds, sigmas = [0.0, 1.0, 1.7, 3.0], [0.4, 2.5, 1.0]
rng = random.Random(21)
n = 30000
a = [free_flight(0.1, 0.6, 0, bounds, sigmas, 1.0 - rng.random()) for _ in range(n)]
b = [delta_tracking(0.1, 0.6, bounds, sigmas, 2.5, rng) for _ in range(n)]
xa = [x for x, _, ev in a if ev == "collide"]
xb = [x for x, ev in b if ev == "collide"]
pa, pb = len(xa) / n, len(xb) / n
assert abs(pa - pb) < 4.0 * math.sqrt(2 * pa * (1 - pa) / n)
ma, mb = sum(xa) / len(xa), sum(xb) / len(xb)
va = sum((v - ma) ** 2 for v in xa) / (len(xa) - 1)
assert abs(ma - mb) < 4.0 * math.sqrt(2 * va / min(len(xa), len(xb)))
def test_optical_depth():
assert optical_depth(0.0, 3.0, 1.0, [0.0, 1.0, 3.0], [0.5, 2.0]) == pytest.approx(4.5)
assert optical_depth(3.0, 0.5, -0.5, [0.0, 1.0, 3.0], [0.5, 2.0]) == pytest.approx(2 * 4.25)
History
Free-flight sampling is as old as the Monte Carlo method. In 1947 von Neumann proposed to follow neutrons in a fission device one by one, with flight distances from the exponential law and collisions sampled from the cross sections, and the first such calculations ran at Los Alamos in the following years. Metropolis and Ulam described the method in 1949 with the neutron chain as their example. Woodcock and coworkers gave delta tracking in 1965 for reactor geometries with many regions.
References
- Ivan Lux and Laszlo Koblinger, Monte Carlo Particle Transport Methods, Neutron and Photon Calculations, CRC Press, 1991, the chapter on the simulation of the free flight, with the sampling of the path length in heterogeneous media
- Malvin H. Kalos and Paula A. Whitlock, Monte Carlo Methods, second edition, Wiley-VCH, 2008, Chapter 3 (sampling random variables) and Chapter 6 (radiation transport)
- Jerome Spanier and Ely M. Gelbard, Monte Carlo Principles and Neutron Transport Problems, Addison-Wesley, 1969, Dover reprint 2008, Chapter 2 (discrete and continuous random walk processes)
- Nicholas Metropolis and S. Ulam, The Monte Carlo method, Journal of the American Statistical Association 44(247), 1949, 335-341, the neutron chain as the first example of the method
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 21RHN1 Edit this page History Report an error Markdown