Algorithmadvanced
Kahn's method for Compton scattering
Also called Klein-Nishina sampling.
Samples the energy and angle of a Compton scattered photon from the Klein-Nishina law by mixing two simple densities and rejecting, with no square roots or tables.
- Time
- O(N) average
- Space
- O(1) extra
- Where
- N = the number of samples
- Model
- Real RAM
- Properties
- randomizedexactiterativerandomized
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Herman Kahn, 1954
Kahn's method samples the scattering of a photon by a free electron at rest (Compton scattering) from the Klein-Nishina cross section. The photon energy before and after, in units of the electron rest energy keV, are and , and the method samples the ratio , which lies in ; the scattering angle then follows from the Compton formula. It writes the target density as a mixture of two densities that are easy to sample by inverse transform sampling and uses rejection sampling in each branch, with acceptance factors that are at most 1. The accepted samples have exactly the Klein-Nishina law. Each try needs three uniform numbers and a few arithmetic operations, with no square roots, logarithms or tables, and about 60 percent of the tries are accepted at the energies of nuclear medicine and reactor shielding. Other algorithms sample the same law (Koblinger's direct method, table methods with the alias method); this page is about Kahn's scheme.
In plain words
When an X-ray or gamma ray hits an electron, it bounces off in a new direction and loses some energy. A small angle means a small loss, and a back bounce means the largest loss. A physics formula from 1929 gives how likely each angle is.
A simulation must pick a random angle that follows this formula. There is no simple trick that turns one random number into such an angle. Kahn's method makes a guess from one of two simple shapes, chosen at random, and then keeps or throws away the guess with a test. Guesses that are kept follow the formula exactly. More than half of the guesses are kept at the usual energies, and every step uses only additions, multiplications and divisions.
The problem
A photon of energy scatters off a free electron at rest. Write and for the cosine of the scattering angle. The Compton formula gives the energy after the scattering, , so runs from (forward, ) to (backward, ). The Klein-Nishina cross section per unit solid angle is
with the classical electron radius. With and , the density of on is proportional to
The task is to draw (and so and ) with this density, for any . The azimuth of the new direction is uniform on and is sampled separately. In the limit the law becomes the Thomson law with density proportional to in .
The algorithm
KAHN(α) ▷ α = E / (m c²) > 0- 1
loop - 2
draw ξ_1, ξ_2, ξ_3 uniform in [0, 1) - 3
if ξ_1 ≤ (1 + 2α) / (9 + 2α) then ▷ branch 1 - 4
q ← 1 + 2α ξ_2 ▷ uniform on [1, 1 + 2α] - 5
if ξ_3 ≤ 4 (1/q - 1/q²) then accept - 6
else ▷ branch 2 - 7
q ← (1 + 2α) / (1 + 2α ξ_2) ▷ density proportional to 1/q² on [1, 1 + 2α] - 8
μ ← 1 - (q - 1)/α; if ξ_3 ≤ (μ² + 1/q) / 2 then accept - 9
return α' = α / q and μ = 1 - (q - 1)/α
Branch 1 proposes uniformly; the factor has its maximum 1 at , so it is a valid acceptance probability. Branch 2 proposes with density proportional to , by inverse transform sampling: the distribution function of that density on inverts to line L7. Its factor is at most 1. The branch weights and make the sum of the two accepted densities proportional to , as the proof shows.
Example
Hand trace with (a 511 keV photon). The weight of branch 1 is .
| try | branch | test | result | ||||
|---|---|---|---|---|---|---|---|
| 1 | 0.5 | 2 | 0.25 | 0 | ? | reject | |
| 2 | 0.2 | 1 | 0.5 | 0 | ? | accept |
The photon scatters at 90 degrees with : it leaves with keV, and the electron takes the other half. A back scattering of the same photon () gives and keV.
The acceptance rate. The probability that one try is accepted is . Numerical integration gives:
| accepted fraction | ||
|---|---|---|
| 0.01 | 5.1 keV | 0.591 |
| 0.1 | 51 keV | 0.585 |
| 1 | 511 keV | 0.627 |
| 2 | 1.02 MeV | 0.644 |
| 5 | 2.55 MeV | 0.589 |
| 10 | 5.11 MeV | 0.474 |
| 100 | 51.1 MeV | 0.110 |
As the fraction tends to . At high energy the law is strongly forward and the two proposal shapes fit it badly, so the method gets slow; codes switch to another sampler there.
Moments. Numerical integration of gives the exact mean of : for , for and for , so the scattering gets more forward as the energy grows. With samples of Kahn's method at (random.Random(1)) the sample mean is , within the statistical error of about . At the exact mean of is the Thomson value .
Correctness
The claim is a theorem: the accepted has the density on for every , so the method is exact. The reason is a short computation. Branch 1 has the proposal density and the acceptance . Branch 2 has the proposal density and the acceptance . With the branch weights, the density of an accepted in one try is
which is a constant times . A rejected try starts afresh, so the accepted value has the normalised density. The full proof is below.
Proof: Kahn's method samples the Klein-Nishina law exactlyfull
We assume exact arithmetic and exact independent uniform numbers on in each try, independent between tries. Fix , write , , and
the Klein-Nishina density in up to a constant. As runs over , runs over .
Lemma 1 (the target). The Klein-Nishina law for is the law of when has density proportional to on .
Proof. The Klein-Nishina density in is proportional to with and . The map is affine with , a constant, so the density in is the same expression divided by , which is .
Lemma 2 (the acceptance factors are probabilities). For , and .
Proof. for . And , .
Lemma 3 (the proposals). In branch 1, line L4 gives with density on . In branch 2, line L7 gives with density on .
Proof. The first is clear. For the second, is a decreasing function of from (at ) to (at ). Its inverse is with , which is the density of because is uniform. As a check, .
Lemma 4 (one try). For every measurable , the probability that one try accepts a value is with
Proof. Branch 1 is taken with probability and branch 2 with , by . Given the branch and , the try accepts with the factor of Lemma 2, because is uniform and independent. So the density of an accepted is, by Lemma 3,
The first term is and the second is . Their sum is .
Theorem (exactness). KAHN() ends with probability 1, the number of tries has the geometric law with success probability , and the returned has the density on . So the returned has the Klein-Nishina law and is the Compton energy.
Proof. By Lemma 4 with , each try accepts with probability ( on ), independently of the other tries. So the number of tries is geometric and finite with probability 1. The returned value is the value of the first accepted try. Because tries are independent and identical, its law is the law of in one try given acceptance: . Lemma 1 turns this into the Klein-Nishina law of .
The efficiency. . As , put ; then , , and , while . So . The same limit shows that the accepted law tends to the Thomson law , which has .
Complexity
Each try costs three uniform numbers and arithmetic, with no transcendental functions. The number of tries is geometric with success probability from the table, so the expected cost of one sample is tries: about 1.6 tries for and about 9 at . A run of samples costs in expectation for a fixed , with space.
Properties
- Exact. No table, fit or truncation; the law is exact up to rounding.
- Cheap per try. Only additions, multiplications and divisions. This mattered in 1954 and still matters on hardware where logarithms are slow.
- Valid for all energies. The acceptance factors are at most 1 for every , but the efficiency falls at high energy.
- Free electrons only. It samples the Klein-Nishina law for an electron at rest. Binding effects need a correction.
Variants and improvements
- Koblinger's method. Koblinger wrote as a mixture of four terms that can each be sampled exactly by inversion, with no rejection. Codes use it at higher energies, where Kahn's method is slow.
- Bound electrons. Multiply the Klein-Nishina law by an incoherent scattering function of the momentum transfer, and reject with after Kahn's step. This lowers forward scattering at low energy.
- Doppler broadening. For bound electrons with a momentum distribution, sample the electron momentum from the Compton profile and correct the scattered energy.
- Tables. Tabulate the inverse distribution function in for a grid of and interpolate, or use the alias method on a fine grid. This is fast but approximate.
- Other rejection schemes. Butcher and Messel wrote another mixture with rejection for their shower calculations, and the EGS codes use a scheme of that type.
When to use it
Use Kahn's method to sample free-electron Compton scattering in photon transport at energies up to a few MeV, for example in shielding, medical physics and gamma-ray detector codes. At higher energies use Koblinger's direct method or a table. Where binding matters (low energies, high atomic number), add the incoherent scattering function correction.
Pitfalls
- The wrong density. The density in and the density in differ by the factor , which is constant, so they have the same shape; but a density in needs the factor . Mixing these up gives the wrong angles.
- The direction update. The sampled is the cosine relative to the old direction. The new direction must be built by rotating the old one by and a uniform azimuth, not set to along a fixed axis.
- Units. is the energy in units of MeV. Using MeV directly gives a wrong law.
- Small . Line L8 divides by . For near the smallest positive float the rounding of is poor; use the Thomson limit there.
- The weights of the branches. The weight of branch 1 is , not . With wrong weights the method is still a valid sampler of some law, so tests on ranges do not catch the error; compare moments with the exact law.
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/kahn-compton-sampling/. The authors are listed in prov/7W42N2.jsonl.
"""Kahn's rejection method for the Klein-Nishina distribution.
A photon of energy E scatters off a free electron at rest. Write
alpha = E / (m c^2) and q = alpha / alpha' = E / E', so that the
Compton formula reads q = 1 + alpha (1 - mu), with mu the cosine of the
scattering angle, and q runs over [1, 1 + 2 alpha]. The Klein-Nishina
cross section, as a density in q, is proportional to
(1 / q^2) (q + 1/q - 1 + mu^2), mu = 1 - (q - 1) / alpha.
Kahn's method mixes two easy densities in q (uniform, and the density of
(1 + 2 alpha) / (1 + 2 alpha xi)) with weights (1 + 2 alpha) / (9 + 2 alpha)
and 8 / (9 + 2 alpha), and accepts with a factor at most 1 in each branch.
The accepted q has exactly the Klein-Nishina law. The method uses no
square roots, logarithms or tables.
"""
import math
def kahn_sample(alpha: float, rng):
"""Sample one Compton scattering. Returns (alpha_out, mu, tries)."""
tries = 0
p1 = (1.0 + 2.0 * alpha) / (9.0 + 2.0 * alpha)
while True: # @line L1
tries += 1
r1, r2, r3 = rng.random(), rng.random(), rng.random() # @line L2
if r1 <= p1: # @line L3
q = 1.0 + 2.0 * alpha * r2 # @line L4
if r3 <= 4.0 * (1.0 / q - 1.0 / (q * q)): # @line L5
break
else: # @line L6
q = (1.0 + 2.0 * alpha) / (1.0 + 2.0 * alpha * r2) # @line L7
mu = 1.0 - (q - 1.0) / alpha
if r3 <= 0.5 * (mu * mu + 1.0 / q): # @line L8
break
mu = 1.0 - (q - 1.0) / alpha
return alpha / q, mu, tries # @line L9
def klein_nishina_mu_density(alpha: float, mu: float) -> float:
"""Unnormalized Klein-Nishina density in mu: P^2 (P + 1/P - 1 + mu^2), P = E'/E."""
p = 1.0 / (1.0 + alpha * (1.0 - mu))
return p * p * (p + 1.0 / p - 1.0 + mu * mu)
def kahn_efficiency(alpha: float, steps: int = 2000) -> float:
"""Exact probability that one try of Kahn's method is accepted (Simpson's rule in q)."""
k = 4.0 * (1.0 + 2.0 * alpha) / ((9.0 + 2.0 * alpha) * 2.0 * alpha)
a, b = 1.0, 1.0 + 2.0 * alpha
h = (b - a) / steps
total = 0.0
for i in range(steps + 1):
q = a + i * h
mu = 1.0 - (q - 1.0) / alpha
f = (q + 1.0 / q - 1.0 + mu * mu) / (q * q)
total += f * (1 if i in (0, steps) else (4 if i % 2 else 2))
return k * total * h / 3.0
def scattered_energy(energy_kev: float, mu: float, mc2_kev: float = 510.99895) -> float:
"""Compton formula E' = E / (1 + (E / m c^2)(1 - mu))."""
return energy_kev / (1.0 + energy_kev / mc2_kev * (1.0 - mu))
test_kahn_compton_sampling.py 85 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kahn-compton-sampling/. The authors are listed in prov/7W42N2.jsonl.
import math
import random
import pytest
from kahn_compton_sampling import kahn_efficiency, kahn_sample, klein_nishina_mu_density, scattered_energy
def kn_moments(alpha, steps=4000):
"""Exact mean of mu and mu^2 under Klein-Nishina, by Simpson's rule in mu."""
h = 2.0 / steps
z = m1 = m2 = 0.0
for i in range(steps + 1):
mu = -1.0 + i * h
f = klein_nishina_mu_density(alpha, mu) * (1 if i in (0, steps) else (4 if i % 2 else 2))
z += f
m1 += f * mu
m2 += f * mu * mu
return m1 / z, m2 / z
def reference_sample(alpha, rng):
"""Brute force: uniform mu, accepted with density / max (the max is at mu = 1, where it is 2)."""
while True:
mu = 2.0 * rng.random() - 1.0
if 2.0 * rng.random() <= klein_nishina_mu_density(alpha, mu):
return mu
@pytest.mark.parametrize("alpha", [0.1, 1.0, 5.0])
def test_moments_match_klein_nishina(alpha):
rng = random.Random(int(alpha * 10) + 1)
n = 20000
mus = [kahn_sample(alpha, rng)[1] for _ in range(n)]
e1, e2 = kn_moments(alpha)
m1 = sum(mus) / n
m2 = sum(m * m for m in mus) / n
sd1 = math.sqrt(max(e2 - e1 * e1, 1e-12))
assert abs(m1 - e1) < 4.0 * sd1 / math.sqrt(n)
assert abs(m2 - e2) < 4.0 / math.sqrt(n) # mu^2 lies in [0, 1], so its sd is below 1
def test_histogram_matches_brute_force():
alpha, n, nb = 1.0, 20000, 8
rng = random.Random(42)
a = [kahn_sample(alpha, rng)[1] for _ in range(n)]
b = [reference_sample(alpha, rng) for _ in range(n)]
for j in range(nb):
lo, hi = -1.0 + 2.0 * j / nb, -1.0 + 2.0 * (j + 1) / nb
pa = sum(1 for m in a if lo <= m < hi) / n
pb = sum(1 for m in b if lo <= m < hi) / n
assert abs(pa - pb) < 4.0 * math.sqrt(2.0 * max(pa, 1e-3) / n)
@pytest.mark.parametrize("alpha", [0.1, 1.0, 5.0])
def test_acceptance_rate(alpha):
rng = random.Random(7)
n = 20000
tries = sum(kahn_sample(alpha, rng)[2] for _ in range(n))
eff = kahn_efficiency(alpha)
assert 0.0 < eff <= 1.0
assert n / tries == pytest.approx(eff, abs=4.0 * math.sqrt(eff * (1 - eff) / tries))
def test_thomson_limit_and_ranges():
rng = random.Random(3)
n = 20000
out = [kahn_sample(1e-4, rng) for _ in range(n)]
m2 = sum(mu * mu for _, mu, _ in out) / n
assert abs(m2 - 0.4) < 4.0 * 0.3 / math.sqrt(n) # (1 + mu^2) law: <mu^2> = 2/5
rng = random.Random(4)
for _ in range(2000):
a_out, mu, _ = kahn_sample(2.0, rng)
assert -1.0 - 1e-12 <= mu <= 1.0 + 1e-12
assert 2.0 / 5.0 - 1e-12 <= a_out <= 2.0 + 1e-12
assert a_out == pytest.approx(2.0 / (1.0 + 2.0 * (1.0 - mu)))
def test_hand_values():
# A 511 keV photon has alpha = 1; at 90 degrees, q = 2 and E' is half of E.
assert scattered_energy(510.99895, 0.0) == pytest.approx(255.499475)
# Back scattering of a 1 MeV photon: E' = E / (1 + 2 alpha).
assert scattered_energy(1000.0, -1.0) == pytest.approx(1000.0 / (1.0 + 2000.0 / 510.99895))
History
Oskar Klein and Yoshio Nishina derived the cross section in 1929 from Dirac's equation. Herman Kahn, then at RAND, collected the sampling methods for Monte Carlo transport in his 1954 report Applications of Monte Carlo, and Section 23 of the report gives the rejection scheme for the Klein-Nishina formula. The method went into the photon codes of the following decades. Koblinger gave a direct sampling method for photon energies above 1.4 MeV in 1975, and some codes use both, with Kahn's method at the lower energies.
References
- Herman Kahn, Applications of Monte Carlo, RAND Corporation report AECU-3259, 1954 (revised 1956 as RM-1237-AEC), Section 23, the Klein-Nishina scattering formula
- O. Klein and Y. Nishina, Über die Streuung von Strahlung durch freie Elektronen nach der neuen relativistischen Quantendynamik von Dirac, Zeitschrift für Physik 52, 1929, 853-868, the cross section for the scattering of a photon by a free electron
- Ivan Lux and Laszlo Koblinger, Monte Carlo Particle Transport Methods, Neutron and Photon Calculations, CRC Press, 1991, the chapter on photon transport, with the sampling of Compton scattering
- Malvin H. Kalos and Paula A. Whitlock, Monte Carlo Methods, second edition, Wiley-VCH, 2008, Chapter 3 (sampling random variables), composition and rejection
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 7W42N2 Edit this page History Report an error Markdown