Algorithm Search⌘K

Algorithmcore

Collision estimator

Also called collision tally.

Estimates the flux in a region by summing weight over total cross section at each collision in that region, divided by the number of histories and the volume.

Time
O(N K) average
Space
O(B) extra
Where
B = the number of tally bins; K = the mean number of collisions per history; N = the number of histories
Properties
randomizedexactiterativerandomized
Origin
Nicholas Metropolis, Stanislaw Ulam, 1949

The collision estimator turns the histories of a Monte Carlo transport run into an estimate of the scalar flux ϕ\phi in a region. Each time a particle of weight ww collides in the region, it scores w/Σtw/\Sigma_t, where Σt\Sigma_t is the total cross section at the collision point; the sum of the scores divided by the number of histories NN and the volume VV is an unbiased estimate of the average flux in the region. The reason is that the collision rate density is F=ΣtϕF = \Sigma_t \phi, so 1/Σt1/\Sigma_t turns a count of collisions into a flux. The track-length estimator estimates the same quantity from the path lengths and is better in thin regions and the only choice in a void, while the collision estimator is better in dense regions with many short flights. Next-event estimation scores the expected contribution to a point detector at each collision, and path tracing in graphics uses the same idea for the light that reaches the eye.

In plain words

You want to know how many particles pass through a box, but you only see where they hit atoms. In a dense material the particles hit atoms often, so a lot of hits does not mean a lot of particles.

The fix is to give each hit a value of one over the density of hits per centimetre. In a dense box each hit counts for little; in a thin box each hit counts for a lot. Add up these values for all particles, divide by the number of particles and the size of the box, and you get the average flux in the box. The answer is right on average. In a box with almost no atoms there are few hits, each with a large value, so the answer is noisy, and in an empty box there are no hits at all.

The problem

A Monte Carlo transport run follows NN independent histories, as in analog Monte Carlo transport. The geometry has tally regions (bins) B1,…,BmB_1, \ldots, B_m with volumes VjV_j. The quantity to estimate is the average scalar flux per source particle,

ϕˉj=1Vj∫Bjϕ(r) dr,\bar\phi_j = \frac{1}{V_j} \int_{B_j} \phi(r)\, dr,

or a reaction rate ∫BjΣrϕ\int_{B_j} \Sigma_r \phi for a reaction rr. Here ϕ(r)=∫ψ(r,Ω) dΩ\phi(r) = \int \psi(r, \Omega)\, d\Omega is the scalar flux of the linear Boltzmann transport equation, in particles per cm2\mathrm{cm}^2 per source particle for a fixed source problem. The code below uses a one-speed slab 0≤x≤L0 \le x \le L with bins of width Δx\Delta x, so the "volume" of a bin is its width, and the flux is in particles per cm per source particle.

The algorithm

  1. COLLISION-ESTIMATOR(N, SOURCE, bins)
  2. 1for n ← 1 to N do
  3. 2(x, μ) ← SOURCE(), w ← 1, h ← 0 ▷ h holds the scores of this history
  4. 3loop: fly to the next collision with free-flight sampling
  5. 4if the particle left the system then break
  6. 5j ← the bin of x
  7. 6h_j ← h_j + w / Σ_t(x) ▷ the collision score
  8. 7with probability Σ_a / Σ_t break ▷ absorbed
  9. 8μ ← a new direction from the scattering law
  10. 9S_j ← S_j + h_j, Q_j ← Q_j + h_j² for every bin j
  11. 10return φ_j = S_j / (N V_j), with s_j = sqrt((Q_j / N - (S_j / N)²) / (N - 1)) / V_j

Line L6 is the only line that differs from an analog history. For a reaction rate it scores wΣr/Σtw \Sigma_r / \Sigma_t instead, which is ww times the probability that the collision is of type rr. Line L9 adds the total of one history, not the single scores, because the collisions of one history are correlated; the variance in line L10 is the variance of these totals. With implicit capture line L7 is replaced by a weight change, and line L6 scores the weight before the collision.

Example

Two histories by hand. A beam enters a slab of 2 cm with Σt=2 cm−1\Sigma_t = 2\ \mathrm{cm}^{-1} and Σs=1 cm−1\Sigma_s = 1\ \mathrm{cm}^{-1}, with two bins of 1 cm. Each score is 1/Σt=0.51/\Sigma_t = 0.5 cm.

history flight collision at bin score outcome
1 ln⁡2/2=0.3466\ln 2 / 2 = 0.3466 0.3466 0 0.5 scatters to μ=1\mu = 1
1 ln⁡10/2=1.1513\ln 10 / 2 = 1.1513 1.4979 1 0.5 absorbed
2 ln⁡2/2=0.3466\ln 2 / 2 = 0.3466 0.3466 0 0.5 absorbed

The totals are S0=1.0S_0 = 1.0 and S1=0.5S_1 = 0.5, so ϕ0=1.0/(2⋅1)=0.5\phi_0 = 1.0/(2 \cdot 1) = 0.5 and ϕ1=0.5/(2⋅1)=0.25\phi_1 = 0.5/(2 \cdot 1) = 0.25 per source particle.

A pure absorber. A beam on a slab of 2 cm with Σt=1 cm−1\Sigma_t = 1\ \mathrm{cm}^{-1} and Σs=0\Sigma_s = 0 has the flux ϕ(x)=e−x\phi(x) = e^{-x}, so the average over a bin [a,b][a, b] is (e−a−e−b)/(b−a)(e^{-a} - e^{-b})/(b - a). With four bins of 0.5 cm and N=20000N = 20000 (random.Random(1)):

bin exact collision estimate standard error
[0, 0.5] 0.786939 0.7869 0.0069
[0.5, 1] 0.477302 0.4776 0.0060
[1, 1.5] 0.289499 0.2798 0.0049
[1.5, 2] 0.175590 0.1795 0.0040

All four estimates lie within 2 standard errors of the exact value.

An infinite medium. A slab of 2 cm with mirrors on both faces, Σt=1 cm−1\Sigma_t = 1\ \mathrm{cm}^{-1}, c=0.5c = 0.5 and a uniform isotropic source of one particle per history (Q=1/2Q = 1/2 per cm) behaves as an infinite medium, where ϕ=Q/Σa=1\phi = Q/\Sigma_a = 1. With N=20000N = 20000 (random.Random(2)) the four bins give 1.0021.002, 0.9880.988, 0.9910.991 and 1.0221.022, each with a standard error of about 0.0120.012.

Correctness

The claim is a theorem: for an analog game, or for any fair weighted game, E[ϕj]=ϕˉjE[\phi_j] = \bar\phi_j exactly for every NN, provided Σt>0\Sigma_t > 0 everywhere in the bin. The proof uses the collision density FF of the game: the expected number of collisions in a small volume drdr around rr is F(r) drF(r)\, dr, and the analog Monte Carlo proof shows that F=ΣtϕF = \Sigma_t \phi with ϕ\phi the solution of the transport equation. Then the expected score is ∫BjF/Σt=∫Bjϕ\int_{B_j} F/\Sigma_t = \int_{B_j} \phi. In a fair weighted game the expected weight that collides in drdr is again Σtϕ dr\Sigma_t \phi\, dr, and the same argument applies. The full proof is below.

The variance of one history total is finite, because the number of collisions has a geometric tail and each score is bounded by w/min⁡Σtw/\min \Sigma_t. So the error bar of line L10 is valid in the limit of large NN by the central limit theorem.

Proof: The collision estimator is unbiased for the average fluxfull

We assume exact arithmetic and exact independent uniform random numbers, and a transport game in which every history ends with probability 1 and the number of collisions has a finite second moment (for the analog game this is Lemma 1 of the analog Monte Carlo proof). Write PP for the phase space of position, direction and energy, Σt(p)>0\Sigma_t(p) > 0 for the total cross section at p∈Pp \in P, and B⊂PB \subset P for a tally bin, whose spatial part has volume VV.

The collision density. For a history, let p1,p2,…p_1, p_2, \ldots be the phase space points just before its collisions, with weights w1,w2,…w_1, w_2, \ldots (wk=1w_k = 1 in an analog game). The weighted collision density FF is defined by

E[∑kwk g(pk)]=∫Pg(p) F(p) dpE\Big[\sum_k w_k\, g(p_k)\Big] = \int_P g(p)\, F(p)\, dp

for every bounded measurable g≥0g \ge 0 with support where Σt>0\Sigma_t > 0. For an analog game, Lemma 2 of the analog proof shows that FF is the sum of the densities of the kk-th collisions and solves the integral transport equation F=F1+KFF = F_1 + K F. Its solution is F=ΣtψF = \Sigma_t \psi, where ψ\psi is the angular flux of the linear Boltzmann transport equation with the same source: the collision rate density is the cross section times the flux, by the definition of the cross section. A weighted game is called fair if its weighted collision density is the same FF; implicit capture and Russian roulette are fair, which is shown on their pages.

Lemma (one history). The total score of one history in the bin, h=∑kwk1[pk∈B]/Σt(pk)h = \sum_k w_k \mathbf{1}[p_k \in B] / \Sigma_t(p_k), satisfies E[h]=∫Bψ dp=∫Brϕ drE[h] = \int_B \psi\, dp = \int_{B_r} \phi\, dr, where BrB_r is the spatial part of the bin and ϕ\phi the scalar flux, if BB contains all directions and energies at its points (otherwise the angular and energy parts of the bin are integrated over).

Proof. Take g(p)=1[p∈B]/Σt(p)g(p) = \mathbf{1}[p \in B]/\Sigma_t(p), which is bounded because Σt\Sigma_t has a positive lower bound on BB. Then E[h]=∫BF/Σt=∫BψE[h] = \int_B F/\Sigma_t = \int_B \psi. □\square

Theorem (unbiased). The estimate ϕB=SB/(NV)\phi_B = S_B/(N V) of line L10 satisfies E[ϕB]=1V∫Brϕ drE[\phi_B] = \frac{1}{V}\int_{B_r} \phi\, dr for every N≥1N \ge 1, and Var[ϕB]=Var[h]/(NV2)\mathrm{Var}[\phi_B] = \mathrm{Var}[h]/(N V^2).

Proof. SBS_B is the sum of the history totals h1,…,hNh_1, \ldots, h_N of line L9. They are independent and have the law of hh, because each history uses fresh random numbers. So E[SB]=NE[h]E[S_B] = N E[h] and Var[SB]=NVar[h]\mathrm{Var}[S_B] = N \mathrm{Var}[h], and division by NVN V gives both statements with the lemma. ■\blacksquare

Finite variance. h≤(max⁡kwk) k/min⁡BΣth \le (\max_k w_k)\, k / \min_B \Sigma_t, where kk is the number of collisions. In the analog game the weights are 1 and kk has a finite second moment, so Var[h]<∞\mathrm{Var}[h] < \infty. Then (ϕB−EϕB)/sB(\phi_B - E\phi_B)/s_B tends in law to the standard normal law by the central limit theorem, and line L10 gives a valid asymptotic error bar. The variance of hh must be taken over the history totals: two collisions of one history in BB are not independent, so the sum of the squares of single scores does not give Var[h]\mathrm{Var}[h].

Reaction rates. With the score wΣr/Σtw \Sigma_r / \Sigma_t in place of w/Σtw/\Sigma_t, the same argument gives E[h]=∫BΣrψE[h] = \int_B \Sigma_r \psi, the rate of reaction rr in the bin.

The void. If Σt=0\Sigma_t = 0 on a part of the bin, no collision happens there, and the estimate misses ∫ϕ\int \phi over that part. The lemma needs Σt>0\Sigma_t > 0 on the bin.

The slab example. For a beam on a pure absorber with Σt\Sigma_t constant, the only collision is at the end of the first flight, with density F(x)=Σte−ΣtxF(x) = \Sigma_t e^{-\Sigma_t x}. A bin [a,b][a, b] then has E[h]=∫abe−Σtx dx=(e−Σta−e−Σtb)/ΣtE[h] = \int_a^b e^{-\Sigma_t x}\, dx = (e^{-\Sigma_t a} - e^{-\Sigma_t b})/\Sigma_t, and the flux average is this value divided by b−ab - a, which is the exact value used on the page.

Complexity

The tally adds O(1)O(1) work per collision with uniform bins, or O(log⁡B)O(\log B) with a search over BB bins of any size, to the O(NK)O(N K) cost of the histories, where KK is the mean number of collisions per history. It needs O(B)O(B) space for the sums and the scores of the current history. The cost that matters is the variance per history, which depends on the problem:

  • Dense regions. Many collisions per history in the bin give a low variance, often lower than the track-length estimator, because each score is small.
  • Thin regions. With ΣtΔx≪1\Sigma_t \Delta x \ll 1, only a fraction of about ΣtΔx\Sigma_t \Delta x of the particles that cross the bin collide in it, and each score 1/Σt1/\Sigma_t is large. The relative variance then grows like 1/(ΣtΔx)1/(\Sigma_t \Delta x). The track-length page has a table of this effect.

Properties

  • Unbiased. Exactly, for every NN, where Σt>0\Sigma_t > 0.
  • No geometry work. The score needs only the collision point, not the path, so it is cheap in complex geometry and needs no distances to the bin faces.
  • Same histories. It uses the histories of the run as they are, so several estimators can score from one run, and their difference is a check on the code.
  • Point quantities. It cannot estimate the flux at a point or on a surface, because no collision happens exactly there. Next-event estimation does this.

Variants and improvements

  • Reaction rates. Score wΣr(E)/Σt(E)w \Sigma_r(E)/\Sigma_t(E) for reaction rr, for example wνΣf/Σtw \nu \Sigma_f / \Sigma_t for the fission source in a criticality run.
  • Absorption estimator. Score w/Σaw/\Sigma_a at each absorption only. It is also unbiased, but it has fewer scores and a higher variance in a scatterer.
  • Next-event estimator. At each collision, score the probability that the next flight reaches a point detector. It is unbiased but has an infinite variance for collisions close to the detector.
  • Combined estimators. A linear combination of the collision and track-length estimates with weights that minimise the sample variance has a lower variance than either one. This is a measured gain that depends on the problem.

When to use it

Use the collision estimator in thick regions with many collisions, for reaction rates in fuel and absorbers, and in geometries where computing path lengths in tally cells is expensive. Use the track-length estimator in thin regions, in gases and in voids. In a k-eigenvalue run it is common to compute both and their combination.

Pitfalls

  • Voids. In a region with Σt=0\Sigma_t = 0 there are no collisions, and the estimator gives 0 for a flux that is not 0. It is unbiased only where Σt>0\Sigma_t > 0.
  • Energy dependence. The score uses Σt\Sigma_t at the energy of the particle before the collision. Using the energy after the collision gives a biased result.
  • The score of the weight. With implicit capture or roulette, the score uses the weight before the collision changes it.
  • Per-collision variance. A variance computed from the individual scores instead of the history totals is too small when a history collides many times in the bin.
  • Bin volumes. The volume in line L10 must be the true volume of the tally region. In complex geometry, a wrong or estimated volume biases the result, even if the scores are right.

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.

collision_estimator.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/collision-estimator/. The authors are listed in prov/NDP0HX.jsonl.
"""Collision 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. It is cut into equal bins of
width dx. Each history starts one particle of weight 1 from a source and
follows it with analog Monte Carlo. At each collision in bin j the history
scores w / sigma_t into bin j. The flux estimate in bin j is

    phi_j = (sum of scores in bin j) / (N * dx),

which is the average flux over the bin per source particle. The standard
error comes from the variance of the per-history scores, because the
collisions inside one history are not independent.

The faces are "vacuum" (a particle that leaves is lost) or "reflect"
(specular reflection). A reflecting slab with a uniform source behaves
as an infinite medium.
"""

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 move(x, mu, s, length, faces):
    """Move a distance s from x along mu. Returns (x, mu, inside)."""
    x += s * mu
    if faces == "vacuum":
        return x, mu, 0.0 <= x <= length
    while x < 0.0 or x > length:  # unfold the path by mirror reflection
        if x < 0.0:
            x = -x
        else:
            x = 2.0 * length - x
        mu = -mu
    return x, mu, True


def collision_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
            x, mu, inside = move(x, mu, s, length, faces)
            if not inside:  # @line L4
                break
            j = min(int(x / dx), nbins - 1)  # @line L5
            hist[j] = hist.get(j, 0.0) + w / sigma_t  # @line L6
            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_collision_estimator.py 82 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/collision-estimator/. The authors are listed in prov/NDP0HX.jsonl.
import math
import random

import pytest

from collision_estimator import collision_estimator, move, 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 = 2, sigma_s = 1, two bins of 1 cm.
    # r = 0.5: flight ln 2 / 2 = 0.3466, collision in bin 0, score 1/2.
    # r = 0.7: scatter; r = 1.0: mu = 1. r = 0.9: flight ln 10 / 2 = 1.1513, x = 1.4979.
    # Bin 1 scores 1/2. r = 0.1: absorbed.
    # The second history collides in bin 0 (score 1/2) and is absorbed there.
    # With N = 2 and dx = 1 cm: phi_0 = 1.0 / 2 and phi_1 = 0.5 / 2.
    rng = FixedRng([0.5, 0.7, 1.0, 0.9, 0.1, 0.5, 0.1])
    phi, se = collision_estimator(2, 2.0, 2.0, 1.0, 2, rng)
    assert phi == pytest.approx([(0.5 + 0.5) / 2, 0.5 / 2])


def test_pure_absorber_beam_exact():
    sig, length, nb, n = 1.0, 2.0, 4, 20000
    phi, se = collision_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():
    # Source 1 per history spread over L, so Q = 1 / L; then phi = Q / sigma_a everywhere.
    length, sig_t, sig_s, n = 2.0, 1.0, 0.5, 6000
    phi, se = collision_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():
    # phi(x) = (Q / (2 sigma)) (2 - E2(sigma x) - E2(sigma (L - x))) with Q = 1 / L.
    length, sig, nb, n = 2.0, 1.0, 4, 30000
    phi, se = collision_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 test_mirror_move():
    x, mu, inside = move(0.5, 1.0, 1.0, 1.0, "reflect")  # one reflection at x = 1
    assert inside and x == pytest.approx(0.5) and mu == -1.0
    x, mu, inside = move(0.5, 1.0, 2.0, 1.0, "reflect")  # reflections at x = 1 and x = 0
    assert inside and x == pytest.approx(0.5) and mu == 1.0
    x, mu, inside = move(0.5, -1.0, 0.75, 1.0, "reflect")
    assert x == pytest.approx(0.25) and mu == 1.0
    assert move(0.5, 1.0, 0.75, 1.0, "vacuum")[2] is False

History

Collision scores are as old as Monte Carlo transport: the first neutron calculations at Los Alamos in the late 1940s counted collisions and absorptions in regions. The theory of estimators as unbiased functionals of the random walk was worked out in the 1950s and 1960s. Spanier and Gelbard gave the collision and track-length estimators side by side with their variances in their 1969 book, and Lux and Koblinger gave a general theory of estimators for transport in 1991.

References

  1. 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 collision density as the basic quantity
  2. Ivan Lux and Laszlo Koblinger, Monte Carlo Particle Transport Methods, Neutron and Photon Calculations, CRC Press, 1991, the chapter on estimators, with the collision, track-length and next-event estimators
  3. Malvin H. Kalos and Paula A. Whitlock, Monte Carlo Methods, second edition, Wiley-VCH, 2008, Chapter 6 (radiation transport), the estimators of the flux

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