Algorithmcore
Track-length estimator
Also called track-length tally.
Estimates the scalar flux in a region by summing weight times the path length of every track segment inside it, divided by the number of histories and the volume.
- Time
- O(N K B) average
- Space
- O(B) extra
- Where
- B = the number of bins that a flight crosses; K = the mean number of flights per history; N = the number of histories
- Model
- Real RAM
- Properties
- randomizedexactiterativerandomized
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jerome Spanier, Ely M. Gelbard, 1969
The track-length estimator turns the histories of a Monte Carlo transport run into an estimate of the scalar flux in a region. Every straight flight of a particle of weight scores times the length of the part of the flight that lies inside the region; the sum divided by the number of histories and the volume is an unbiased estimate of the average flux. The reason is that the scalar flux is the total path length travelled per unit volume per source particle. The collision estimator estimates the same quantity from collisions only. The track-length estimator scores from every particle that crosses the region, so it has a much lower variance in thin regions, and it is the only one of the two that works in a void; the collision estimator needs no path geometry and can be better in dense regions. Next-event estimation and path tracing score expected contributions at points instead.
In plain words
The flux in a box tells how much travel happens in it. If ten particles each fly one centimetre in a box of one cubic centimetre, the flux is ten. So, to measure the flux, add up the length of every piece of path inside the box, and divide by the size of the box and the number of particles.
A particle that crosses the box without any collision still adds its path. That is why this method works well in a box of thin gas or even an empty box, where almost nobody hits an atom. The cost is geometry: the code must find where each flight enters and leaves each box.
The problem
The problem is the same as for the collision estimator: estimate the average scalar flux per source particle
over tally regions , from histories of analog Monte Carlo transport or of a fair weighted game. A history is a chain of straight flights. A flight starts at in direction and has path length ; its track length in is the length of . The code below uses a slab cut into bins of width . A flight from to with direction cosine has the track length , and it splits among the bins it crosses by the part of in each bin.
The algorithm
TRACK-LENGTH-ESTIMATOR(N, SOURCE, bins)- 1
for n ← 1 to N do - 2
(x, μ) ← SOURCE(), w ← 1, h ← 0 ▷ h holds the scores of this history - 3
loop - 4
s ← -ln(ξ) / Σ_t ▷ free flight - 5
for each bin j that the flight crosses do h_j ← h_j + w · (path length of the flight in bin j) - 6
if the particle left the system then break - 7
with probability Σ_a / Σ_t break ▷ absorbed - 8
μ ← a new direction from the scattering law - 9
S_j ← S_j + h_j, Q_j ← Q_j + h_j² for every bin j - 10
return φ_j = S_j / (N V_j), with s_j = sqrt((Q_j / N - (S_j / N)²) / (N - 1)) / V_j
Line L5 is the difference with the collision estimator. A flight that leaves the system scores only up to the face. With reflecting faces, the flight scores each straight piece between reflections. In a heterogeneous medium, the flight crosses region faces during free-flight sampling, and the code scores each piece as it crosses; with delta tracking there are no face crossings, and the code must find the bin crossings in a separate step. For a reaction rate, line L5 scores instead of .
Example
Two histories by hand. A beam enters a pure absorber of 2 cm with , with two bins of 1 cm. The first history draws a flight cm and is absorbed in bin 0, which scores . The second history draws a flight cm and leaves at , which scores 1 cm in each bin. So and per source particle.
A slanted flight. A flight from with and a path length of 1 cm ends at . With bins of 0.5 cm, it lies for cm in in each of the first two bins, so each bin scores cm of path.
Against the collision estimator. The two estimators were run on the same problems with (random.Random(1) to random.Random(3)). For a beam on a pure absorber of 2 cm with and four bins:
| bin | exact | collision | track length |
|---|---|---|---|
| [0, 0.5] | 0.786939 | 0.7869 ± 0.0069 | 0.7836 ± 0.0023 |
| [0.5, 1] | 0.477302 | 0.4776 ± 0.0060 | 0.4774 ± 0.0032 |
| [1, 1.5] | 0.289499 | 0.2798 ± 0.0049 | 0.2927 ± 0.0030 |
| [1.5, 2] | 0.175590 | 0.1795 ± 0.0040 | 0.1805 ± 0.0026 |
In a slab of 1 cm with and four bins, the first bin gives these values as goes down:
| () | beam, collision | beam, track length | isotropic source, collision | isotropic source, track length |
|---|---|---|---|---|
| 1 | 1.149 ± 0.016 | 1.177 ± 0.006 | 0.795 ± 0.014 | 0.804 ± 0.010 |
| 0.1 | 1.136 ± 0.048 | 1.071 ± 0.007 | 1.638 ± 0.058 | 1.658 ± 0.028 |
| 0.01 | 1.160 ± 0.152 | 1.011 ± 0.004 | 2.780 ± 0.238 | 2.737 ± 0.103 |
The collision estimator gets worse as the slab gets thinner, because fewer particles collide and each score is larger. For a beam the track-length error even goes down, because an uncollided particle scores exactly . For an isotropic source the track-length error also grows, but more slowly: a particle that flies almost parallel to the faces has a long path in one bin. These numbers are measurements, not bounds.
Correctness
The claim is a theorem: for an analog game or a fair weighted game, for every , with no condition on ; it holds in a void too. The proof uses the track-length density: the expected total weighted path length that histories travel in a small volume around , with directions in , is , where is the angular flux. This holds because a flight from a collision or source point carries its weight along the path with survival probability , which is the uncollided part of the transport solution, and the sum over flights is the Neumann series again. Integration over the bin and all directions gives . The full proof is below.
The score of one flight is at most the flight length, so the variance is finite when the flights have finite second moments, which holds when is bounded below by a positive constant or the region is bounded. In an unbounded void a flight can be infinite, but then the particle leaves and the score is the bounded chord of the bin.
Proof: The track-length estimator is unbiased for the average fluxfull
We assume exact arithmetic and exact independent uniform random numbers, and the analog game of analog Monte Carlo transport, in which every history ends with probability 1 and the number of flights has a finite second moment. The argument for a fair weighted game is the same with weights. Write a phase space point as (energy can be added as one more coordinate), for the total cross section, and for the optical depth along a ray.
The flight starts. Let be the density of the starting points of flights: the source points, plus the points just after a scattering. By the same summation over generations as for the collision density, , and in the analog game , where is the source density and the second term is the density of scattered particles leaving collisions. The integral form of the linear Boltzmann transport equation states that the angular flux is the uncollided transport of :
This is the definition of the emission density in the integral equation, and (1) is the integral form of the streaming and absorption part, , solved along each characteristic.
Lemma 1 (one flight). For a flight that starts at , the expected track length in a set of positions is .
Proof. The flight covers the ray up to its path length , which satisfies by free-flight sampling (if the ray leaves the system, the flight stops at the face, and for later the indicator of is 0 because is inside the system). The track length in is . Taking expectations and exchanging the expectation and the integral (the integrand is non-negative) gives the claim.
Lemma 2 (one history). The total track length of one history in satisfies .
Proof. Sum Lemma 1 over the flights of the history. Given its starting point, each flight has the law of Lemma 1, so by the tower rule and the definition of ,
Change variables to the end point for fixed and ; the map is a translation with Jacobian 1. Then
by (1). The exchanges of integrals are valid because everything is non-negative.
Theorem (unbiased). The estimate of line L10 satisfies for every , also where , and .
Proof. is the sum of independent copies of , one per history, so and . Lemma 2 gives the mean. Nothing in Lemmas 1 and 2 needs in .
Finite variance. If is bounded with diameter , each flight contributes at most , so with the number of flights, and . The central limit theorem then gives the asymptotic error bar of line L10.
The slab. In a slab, positions are , the bins are intervals and reduces to . A flight from with path length ends at , and the path length in a bin is the length of divided by , which is what line L5 adds. For a beam on a pure absorber with , the history is one flight, and Lemma 1 gives for the bin , the same exact value as for the collision estimator.
Complexity
Each flight costs plus the work to find its crossings with the bins. With uniform bins in a slab this is per crossed bin, so a run costs with flights per history and bins crossed per flight; with a mesh tally that is not aligned with the geometry, a ray walk through the mesh does the same work. The space is for the sums. In a code where the tally regions are the cells of the geometry, the crossings are found anyway by free-flight sampling, and the tally is almost free.
Properties
- Unbiased everywhere. Including voids and thin regions, where the collision estimator fails or is noisy.
- Scores without collisions. Every particle that crosses the region scores, so the number of scores per history is high in thin regions.
- Bounded scores. The score of one flight is at most its length, or the longest chord of the region. A long chord near a grazing direction is the main source of variance for an isotropic source in a thin region.
- Path geometry. It needs the intersection of each flight with the tally regions, which costs more than the collision estimator when the tally mesh is not the geometry.
Variants and improvements
- Reaction rates. Score for the rate of reaction ; this is the usual estimator of the fission source and of heating in production codes.
- Expected track length. Score at each flight the expected track length in the region along the ray, the integral of over the path lengths at which the ray is inside the region, instead of the sampled one. It has a lower variance, at the cost of an integral per flight.
- Surface current and surface flux. On a surface, count crossings with weight for the current, and with weight for the surface flux, the limit of the track-length estimator for a thin bin. The surface flux estimator has an infinite variance for grazing crossings, so codes cut off small .
- Combined estimators. A weighted combination of the track-length, collision and absorption estimates with weights from the sample covariance has a lower variance than each one; it is used for in criticality codes.
When to use it
Use the track-length estimator for fluxes and reaction rates in cells of the geometry, in thin regions, in gases, in voids and on fine mesh tallies in optically thin parts of the problem. Use the collision estimator in dense regions with many short flights and when path lengths in the tally regions are expensive to find. For a flux at a point, use next-event estimation.
Pitfalls
- The factor . In slab geometry the path length in a bin is the depth in divided by . A code that scores the depth in underestimates the flux.
- Truncated flights. A flight that leaves the system or reaches a reflecting face must score only to the face, and then the rest after the reflection.
- Delta tracking. With delta tracking the tentative flights do not stop at region faces, so the tally must clip each flight to the bins itself. Scoring at the tentative collisions instead gives a collision estimator with the majorant cross section.
- Grazing flights. For an isotropic source in a thin bin, rare flights almost parallel to the faces give large scores. The estimate stays unbiased, but its error falls slowly and the error bar converges slowly.
- Per-flight variance. As for every tally, the variance must come from the history totals.
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/track-length-estimator/. The authors are listed in prov/QW4YNY.jsonl.
"""Track-length estimator of the scalar flux in a one-speed slab.
The slab is 0 <= x <= L with total and scattering cross sections sigma_t
and sigma_s (cm^-1) and isotropic scattering, cut into equal bins of
width dx. Each history follows one particle of weight 1 with analog Monte
Carlo. Every flight is a straight segment; the part of the segment that
lies in bin j has path length |overlap in x| / |mu|, and the history
scores w times that length into bin j. The estimate is
phi_j = (sum of scores in bin j) / (N * dx),
the average flux over the bin per source particle. In one dimension the
bin "volume" is its width dx. The standard error comes from the variance
of the per-history scores.
The faces are "vacuum" or "reflect" (specular reflection). A flight that
reaches a vacuum face scores up to the face and ends the history.
"""
import math
def uniform_open(rng) -> float:
return 1.0 - rng.random()
def beam_source(length, rng):
"""A normally incident beam on the left face."""
return 0.0, 1.0
def uniform_isotropic_source(length, rng):
"""A source uniform in x on [0, L] and isotropic in direction."""
return length * rng.random(), 2.0 * rng.random() - 1.0
def score_segment(a, b, mu, w, dx, nbins, hist):
"""Add w * (path length in bin j) for the x interval between a and b."""
lo, hi = min(a, b), max(a, b)
j = min(int(lo / dx), nbins - 1)
while j < nbins and j * dx < hi:
overlap = min(hi, (j + 1) * dx) - max(lo, j * dx)
if overlap > 0.0:
hist[j] = hist.get(j, 0.0) + w * overlap / abs(mu)
j += 1
def fly(x, mu, s, length, faces, w, dx, nbins, hist):
"""Move a distance s and score every piece of the path. Returns (x, mu, inside)."""
if mu == 0.0: # a flight parallel to the faces stays in its bin
j = min(int(x / dx), nbins - 1)
hist[j] = hist.get(j, 0.0) + w * s
return x, mu, True
while True:
face = length if mu > 0.0 else 0.0
d = (face - x) / mu # path length to the face
if s <= d:
x_new = x + s * mu
score_segment(x, x_new, mu, w, dx, nbins, hist)
return x_new, mu, True
score_segment(x, face, mu, w, dx, nbins, hist)
if faces == "vacuum":
return face, mu, False
s -= d
x, mu = face, -mu
def track_length_estimator(n, length, sigma_t, sigma_s, nbins, rng, source=beam_source, faces="vacuum"):
"""Returns (phi, se): flux per source particle in each bin, and its standard error."""
dx = length / nbins
p_abs = (sigma_t - sigma_s) / sigma_t
total = [0.0] * nbins
total_sq = [0.0] * nbins
for _ in range(n): # @line L1
x, mu = source(length, rng) # @line L2
w = 1.0
hist = {}
while True: # @line L3
s = -math.log(uniform_open(rng)) / sigma_t # @line L4
x, mu, inside = fly(x, mu, s, length, faces, w, dx, nbins, hist) # @line L5
if not inside: # @line L6
break
if rng.random() < p_abs: # @line L7
break
mu = 2.0 * rng.random() - 1.0 # @line L8
for j, v in hist.items(): # @line L9
total[j] += v
total_sq[j] += v * v
phi, se = [], []
for j in range(nbins): # @line L10
mean = total[j] / n
var = (total_sq[j] / n - mean * mean) * n / (n - 1)
phi.append(mean / dx)
se.append(math.sqrt(max(var, 0.0) / n) / dx)
return phi, se
test_track_length_estimator.py 111 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/track-length-estimator/. The authors are listed in prov/QW4YNY.jsonl.
import math
import random
import pytest
from track_length_estimator import fly, track_length_estimator, uniform_isotropic_source
class FixedRng:
def __init__(self, values):
self.values = list(values)
def random(self):
return self.values.pop(0)
def expint(order, z, steps=2000):
"""E_n(z) = integral over u in (0, 1] of exp(-z/u) u^(n-2) du, by Simpson's rule (n >= 2)."""
if z == 0.0:
return 1.0 / (order - 1)
h = 1.0 / steps
total = 0.0
for k in range(steps + 1):
u = k * h
f = 0.0 if u == 0.0 else math.exp(-z / u) * u ** (order - 2)
total += f * (1 if k in (0, steps) else (4 if k % 2 else 2))
return total * h / 3.0
def test_one_history_by_hand():
# Beam on a slab of 2 cm, sigma_t = 1, pure absorber, two bins of 1 cm.
# r = 0.25: xi = 0.75, flight -ln 0.75 = 0.287682, all in bin 0. r = 0.5: absorbed.
phi, _ = track_length_estimator(1 + 1, 2.0, 1.0, 0.0, 2, FixedRng([0.25, 0.5, 0.9, 0.5]))
# The second history: r = 0.9 gives a flight ln 10 = 2.302585, which leaves the slab.
# It scores 1 cm in each bin. Totals: bin 0 = 1.287682, bin 1 = 1.0; N = 2.
assert phi == pytest.approx([1.287682 / 2, 1.0 / 2], abs=1e-6)
def test_slanted_segment_and_reflection():
hist = {}
fly(0.25, 0.5, 1.0, 2.0, "vacuum", 1.0, 0.5, 4, hist) # x goes from 0.25 to 0.75
assert hist == pytest.approx({0: 0.5, 1: 0.5})
hist = {}
x, mu, inside = fly(1.5, 1.0, 1.0, 2.0, "reflect", 1.0, 1.0, 2, hist)
assert inside and x == pytest.approx(1.5) and mu == -1.0
assert hist == pytest.approx({1: 1.0})
def test_pure_absorber_beam_exact():
sig, length, nb, n = 1.0, 2.0, 4, 20000
phi, se = track_length_estimator(n, length, sig, 0.0, nb, random.Random(1))
dx = length / nb
for j in range(nb):
exact = (math.exp(-sig * j * dx) - math.exp(-sig * (j + 1) * dx)) / (sig * dx)
assert abs(phi[j] - exact) < 4.0 * se[j]
def test_reflecting_slab_is_infinite_medium():
length, sig_t, sig_s, n = 2.0, 1.0, 0.5, 6000
phi, se = track_length_estimator(n, length, sig_t, sig_s, 4, random.Random(2), uniform_isotropic_source, "reflect")
exact = (1.0 / length) / (sig_t - sig_s)
for p, e in zip(phi, se):
assert abs(p - exact) < 4.0 * e
def test_pure_absorber_volume_source_against_e3():
length, sig, nb, n = 2.0, 1.0, 4, 20000
phi, se = track_length_estimator(n, length, sig, 0.0, nb, random.Random(3), uniform_isotropic_source)
q, dx = 1.0 / length, length / nb
for j in range(nb):
a, b = j * dx, (j + 1) * dx
left = (expint(3, sig * a) - expint(3, sig * b)) / sig
right = (expint(3, sig * (length - b)) - expint(3, sig * (length - a))) / sig
exact = q / (2.0 * sig * dx) * (2.0 * dx - left - right)
assert abs(phi[j] - exact) < 4.0 * se[j]
def collision_tally(n, length, sig_t, sig_s, nbins, rng):
"""A plain collision estimator on the same problem, for comparison."""
dx, p_abs = length / nbins, (sig_t - sig_s) / sig_t
tot, tot_sq = [0.0] * nbins, [0.0] * nbins
for _ in range(n):
x, mu = 0.0, 1.0 # a normal beam on the left face
hist = [0.0] * nbins
while True:
x += mu * -math.log(1.0 - rng.random()) / sig_t
if not 0.0 <= x <= length:
break
hist[min(int(x / dx), nbins - 1)] += 1.0 / sig_t
if rng.random() < p_abs:
break
mu = 2.0 * rng.random() - 1.0
for j in range(nbins):
tot[j] += hist[j]
tot_sq[j] += hist[j] ** 2
mean = [t / n for t in tot]
se = [math.sqrt((s / n - m * m) / (n - 1)) / dx for s, m in zip(tot_sq, mean)]
return [m / dx for m in mean], se
def test_thin_slab_track_length_beats_collision():
# In an optically thin slab few histories collide, so the collision tally is noisy.
# With a normal beam, every uncollided particle scores exactly dx in each bin.
length, sig_t, sig_s, nb, n = 1.0, 0.1, 0.05, 4, 8000
phi_t, se_t = track_length_estimator(n, length, sig_t, sig_s, nb, random.Random(4))
phi_c, se_c = collision_tally(n, length, sig_t, sig_s, nb, random.Random(5))
for j in range(nb):
assert abs(phi_t[j] - phi_c[j]) < 4.0 * math.hypot(se_t[j], se_c[j])
assert se_t[j] < 0.5 * se_c[j]
History
The interpretation of the scalar flux as the track length per unit volume is old in reactor physics, and early Monte Carlo codes scored track lengths in their cells. Spanier and Gelbard gave the track-length and collision estimators side by side, with their variances, in their 1969 book. Lux and Koblinger gave a general theory of transport estimators, including expected-value variants, in 1991. The track-length estimator is the standard flux tally of production codes today.
References
- Jerome Spanier and Ely M. Gelbard, Monte Carlo Principles and Neutron Transport Problems, Addison-Wesley, 1969, Dover reprint 2008, the estimators of linear functionals of the flux, with the track-length estimator
- Ivan Lux and Laszlo Koblinger, Monte Carlo Particle Transport Methods, Neutron and Photon Calculations, CRC Press, 1991, the chapter on estimators, with the track-length estimator and its comparison with the collision estimator
- E. E. Lewis and W. F. Miller, Jr., Computational Methods of Neutron Transport, Wiley, 1984, the chapter on the Monte Carlo method, with the flux tallies
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 QW4YNY Edit this page History Report an error Markdown