Introduction
In our previous lessons, we've systematically constructed the essential building blocks for a Monte Carlo simulation. You've learned how to sample the distance to a particle's next collision, how to determine the type of interaction that occurs, and how to handle the kinematics of Compton scattering. Most recently, we developed the logic for tracking a particle through a slab geometry, focusing on the crucial decision of whether a particle interacts within a material or crosses a boundary first.
Now, we will assemble all these individual components into a cohesive whole. The goal of this lesson is to write a single Python function that simulates the complete life cycle—or "history"—of a single photon. This function will represent the core engine of our Monte Carlo code, tracing a particle's random walk from its creation at the source to its eventual termination by absorption, escape, or falling below an energy cutoff.
The Anatomy of a Particle History
The life of a simulated particle is governed by a main loop that continues as long as the particle is considered "alive." At each step of this loop, the particle moves, and an event occurs. This process repeats until a terminal event happens. The flowchart below, which we've seen before, perfectly encapsulates the logic we are about to implement in code.

To manage the particle's state as it evolves, it's convenient to use a simple data structure, like a Python dictionary or a class. This structure will hold all the relevant information:
pos: A 3D vector for the particle's current position .dir: A 3D unit vector for the particle's direction .energy: The particle's energy , which changes after scattering.weight: The statistical weight of the particle, initially 1.0 for an analog simulation.is_alive: A boolean flag that controls the main simulation loop.
Our primary task is to write a function, let's call it simulate_photon_history, that takes an initial particle state and simulation parameters (like geometry and material data) and executes this loop until particle['is_alive'] becomes False.
The general algorithm for this function is summarized concisely in the "Introduction to the Monte Carlo simulation of radiation transport" slides from CERN.
[PDF] Introduction to the Monte Carlo simulation of radiation transport
This presentation provides a clear, high-level overview of the Monte Carlo algorithm. Focus on the list that outlines the basic simulation steps.
Find the slide titled "Basic Monte Carlo simulation algorithm". Please read the ten steps listed there. We will be implementing steps 3 through 10 for a single event inside our function. Note that for our photon simulation, "secondary particles" (step 8) would be electrons, which we are not tracking in this model (we assume their energy is deposited locally).
Implementing the Simulation Loop in Python
Let's translate that algorithmic flow into a Python function. We will build it piece by piece, assuming we have access to helper functions for sampling and cross-section lookups, which were conceptually developed in previous lessons.
1. Initialization and the Main Loop
First, we define the function signature and set up the initial state and the main while loop. Our slab will be defined from to .
import numpy as np
# --- Placeholder Helper Functions (developed in previous lessons) ---
def get_cross_sections(energy_mev):
# In a real code, this would look up data from a library.
# For now, let's use constant values for water-like material.
# sigma_t and sigma_s for Compton scattering.
if 0.1 <= energy_mev <= 1.0:
sigma_t = 0.167 # cm^-1
sigma_s = 0.1 # cm^-1
return sigma_t, sigma_s
return 0, 0 # Terminate if outside energy range
def sample_compton(energy_in):
# This function would implement Klein-Nishina sampling.
# For this lesson, we'll use a simplified model.
energy_out = energy_in * (0.5 + 0.4 * np.random.random())
# New direction is sampled isotropically for simplicity here
# In a real implementation, you'd use the sampled scattering angle
cos_theta = 2 * np.random.random() - 1
phi = 2 * np.pi * np.random.random()
sin_theta = np.sqrt(1 - cos_theta**2)
# This simplified direction sampling is not physically rigorous
# but serves to illustrate the update step.
new_dir = np.array([
sin_theta * np.cos(phi),
sin_theta * np.sin(phi),
cos_theta
])
return energy_out, new_dir
# ----------------------------------------------------------------
def simulate_photon_history(initial_particle, slab_thickness, energy_cutoff):
"""
Simulates the entire history of a single photon.
Returns a string indicating the reason for termination.
"""
particle = initial_particle.copy()
while particle['is_alive']:
# The core simulation logic will go here.
# For now, let's add a safeguard against infinite loops.
if particle.get('steps', 0) > 1000:
print("Warning: Max steps exceeded.")
break
particle['steps'] = particle.get('steps', 0) + 1
# --- Steps from the algorithm will be inserted here ---
return "Max steps exceeded" # Placeholder return
2. Transport and Boundary Checks
Inside the loop, the first action is to determine the particle's next step. This logic comes directly from our last lesson.
# (Inside the while loop)
# 1. Get material properties at current energy
sigma_t, sigma_s = get_cross_sections(particle['energy'])
if sigma_t <= 0:
particle['is_alive'] = False
return "Energy out of range"
# 2. Sample distance to next collision
s_coll = -np.log(np.random.random()) / sigma_t
# 3. Calculate distance to nearest boundary
pos_z = particle['pos'][2]
dir_z = particle['dir'][2]
s_bound = np.inf
if dir_z > 0: # Moving towards z=d
s_bound = (slab_thickness - pos_z) / dir_z
elif dir_z < 0: # Moving towards z=0
s_bound = (0 - pos_z) / dir_z
# 4. Compare distances and move the particle
if s_coll < s_bound:
# Event is a collision
particle['pos'] += s_coll * particle['dir']
# --> Next, we'll handle the collision event itself
else:
# Event is a boundary crossing
particle['pos'] += s_bound * particle['dir']
# Check for escape
if dir_z > 0: # Exited through the bottom (transmitted)
particle['is_alive'] = False
return "Transmitted"
else: # Exited through the top (reflected)
particle['is_alive'] = False
return "Reflected"
The video "Computational Physics Video 31" provides a clear, practical demonstration of this core loop, showing how to sample the step, determine the event, and update the particle state.
Computational Physics Video 31 - Writing a Monte Carlo Radiation Transport Code
This video walks through the creation of a simple Monte Carlo neutron transport code. The logic for photon transport is identical in structure. Pay attention to how the main while loop is constructed and how decisions are made at each step.
Watch from the start of the history loop, where the particle is initialized and the while loop begins. The author samples an exponentially distributed step length s and a new random direction. This corresponds to our s_coll sampling and the post-scattering direction update. Next, see how the code decides between scattering and absorption from this segment. The key is the comparison of a random number to the ratio of the absorption cross-section to the total cross-section (Sigma_a / Sigma_t). This is the exact logic we will add next.
3. Interaction and Termination
If the particle has a collision (s_coll < s_bound), we must determine what happened. Was it absorbed, or did it scatter?
# (Inside the `if s_coll < s_bound:` block, after updating position)
# 5. Handle the collision event
# Decide between scattering and absorption
prob_scatter = sigma_s / sigma_t
if np.random.random() < prob_scatter:
# Event is scattering
new_energy, new_dir = sample_compton(particle['energy'])
# Update particle state
particle['energy'] = new_energy
particle['dir'] = new_dir.copy() # Use copy to avoid reference issues
# Check for termination by energy cutoff
if particle['energy'] < energy_cutoff:
particle['is_alive'] = False
return "Absorbed (E-cutoff)"
else:
# Event is absorption
particle['is_alive'] = False
return "Absorbed (interaction)"
This simple if statement based on a random number and the cross-section ratio is the heart of analog Monte Carlo event selection. It ensures that, on average, the correct fraction of particles will scatter versus be absorbed.
The excellent guide on Scratchapixel illustrates this entire procedure with clear explanations and diagrams.
Monte Carlo Methods in Practice - Scratchapixel
This article provides a complete walkthrough of building a simple photon transport simulation. The logic it describes is exactly what we are implementing.
Please read the section titled "Principle of the Experiment: Let's Simulate!". Focus on the implementation logic described starting from this paragraph. It covers: Sampling the distance x (our s_coll). Checking for a boundary crossing by calculating s (our s_bound). Updating the position. Checking for absorption using a random number and the ratio sigma_a / sigma_t. This text provides the complete logic for one iteration of our while loop.
The Complete Function
Now, let's assemble all the pieces into our final function and test it.
import numpy as np
# --- Placeholder Helper Functions ---
def get_cross_sections(energy_mev):
if 0.01 <= energy_mev <= 10.0:
# Simplified cross-sections for water at ~1 MeV
sigma_t = 0.167 # cm^-1
sigma_s = 0.08 # cm^-1
return sigma_t, sigma_s
return 0, 0
def sample_compton(energy_in):
# Simplified mock-up of Compton sampling
energy_out = energy_in * (0.5 + 0.4 * np.random.random())
cos_theta = 2 * np.random.random() - 1
phi = 2 * np.pi * np.random.random()
sin_theta = np.sqrt(1 - cos_theta**2)
new_dir = np.array([
sin_theta * np.cos(phi),
sin_theta * np.sin(phi),
cos_theta
])
return energy_out, new_dir
# --- The Main Simulation Function ---
def simulate_photon_history(initial_particle, slab_thickness, energy_cutoff):
"""
Simulates the entire history of a single photon in a slab.
Returns a string indicating the reason for termination.
"""
particle = initial_particle.copy()
while particle['is_alive']:
if particle.get('steps', 0) > 500: # Safety break
return "Max steps exceeded"
particle['steps'] = particle.get('steps', 0) + 1
sigma_t, sigma_s = get_cross_sections(particle['energy'])
if sigma_t <= 0:
particle['is_alive'] = False
return "Energy out of range"
s_coll = -np.log(max(1e-9, np.random.random())) / sigma_t
pos_z, dir_z = particle['pos'][2], particle['dir'][2]
s_bound = np.inf
if dir_z > 1e-9:
s_bound = (slab_thickness - pos_z) / dir_z
elif dir_z < -1e-9:
s_bound = -pos_z / dir_z
if s_coll < s_bound:
# Collision
particle['pos'] += s_coll * particle['dir']
prob_scatter = sigma_s / sigma_t
if np.random.random() < prob_scatter:
# Scatter
new_energy, new_dir = sample_compton(particle['energy'])
particle['energy'] = new_energy
particle['dir'] = new_dir.copy()
if particle['energy'] < energy_cutoff:
particle['is_alive'] = False
return "Absorbed (E-cutoff)"
else:
# Absorb
particle['is_alive'] = False
return "Absorbed (interaction)"
else:
# Boundary crossing
particle['pos'] += s_bound * particle['dir']
if dir_z > 0:
particle['is_alive'] = False
return "Transmitted"
else:
particle['is_alive'] = False
return "Reflected"
return "Unknown" # Should not be reached
# --- Example Usage ---
if __name__ == '__main__':
# Define simulation parameters
SLAB_D = 10.0 # cm
E_CUTOFF = 0.01 # MeV
# Define the initial source particle
source_particle = {
'pos': np.array([0.0, 0.0, 0.0]),
'dir': np.array([0.0, 0.0, 1.0]),
'energy': 1.0, # MeV
'is_alive': True
}
# Run one history
termination_reason = simulate_photon_history(source_particle, SLAB_D, E_CUTOFF)
print(f"Photon history terminated. Reason: {termination_reason}")
This Python code provides a complete, working model for a single particle history. It integrates every concept from this module into a single, functional unit.
Conclusion
In this lesson, you have assembled the fundamental building blocks of Monte Carlo particle transport into a single, powerful function. By combining transport logic with interaction sampling inside a loop, you can now simulate the complete random walk of a photon through a simple geometry. This function is the heart of any Monte Carlo simulation code.
Key Takeaways:
- A particle history is simulated using a
whileloop that runs as long as the particle'sis_aliveflag is true. - Each iteration of the loop involves a transport step followed by a decision: either the particle crosses a boundary (and potentially escapes) or it undergoes a collision.
- A collision leads to another probabilistic decision: the particle either scatters, changing its energy and direction, or it is absorbed, terminating its history.
- A particle's history also ends if it escapes the defined geometry or its energy falls below a specified cutoff threshold.
Preview of the Next Lesson:
Simulating a single photon is illustrative, but to get statistically meaningful results, we need to simulate thousands or millions of them. In the next lesson, "Run a Monte Carlo simulation for a batch of source photons in a slab geometry," we will wrap our simulate_photon_history function in an outer loop. This will allow us to run a "batch" of particles and begin to compute average quantities, which is the ultimate purpose of the Monte Carlo method.