Create a Monte Carlo dose calculation QA: commissioning, gamma index, and radiobiology.
- User
Create a Monte Carlo dose calculation QA: commissioning, gamma index, and radiobiology.
Assistant
Create a Monte Carlo dose calculation QA: commissioning, gamma index, and radiobiology.
The user wants a Monte Carlo (MC) dose calculation Quality Assurance (QA) suite. This is a complex topic in medical physics/radiation oncology. The request asks for:
I need to structure the response as a guide or a conceptual framework, perhaps providing code snippets (Python is the standard language for this in the scientific community, using libraries like NumPy, SciPy, and Matplotlib) to illustrate the concepts.
1. Commissioning:
2. Gamma Index:
pymedphys which is great, but writing a custom function is better for educational purposes to show "how it works."3. Radiobiology:
Structure of the Output:
Refining the Code:
scipy.spatial.distance.cdist or just simple broadcasting if possible, to show efficiency. Actually, a naive implementation is easier to read. Let's do a 1D Gamma for clarity, as 2D requires flattening indices and managing coordinates which gets messy.Safety/Disclaimer: I must include a disclaimer that this is for educational purposes and not for clinical use (CLINICAL USE WARNING).
Drafting the Content:
Let's assemble.
Self-Correction during drafting: The user asked for "Monte Carlo dose calculation QA". This implies the result of an MC simulation is being checked. So, the "Reference" data is usually the Treatment Planning System (TPS) or Measurement, and the "Evaluation" data is the MC simulation.
Let's make the Python code modular.
simulate_beam_data(): Creates synthetic PDD.calculate_gamma(): The comparison engine.calculate_radiobiology(): The biological models.This looks like a solid plan. I will provide a complete Python script that covers all three aspects with comments and visualization.
Specific check on Radiobiology models: TCP: . Or the Poisson model . The Poisson model is simpler to code for a demo. NTCP: LKB model. . Where . I will stick to the LKB model for NTCP and the Poisson model for TCP as they are industry standards.
Let's write the response. This is a comprehensive guide and Python framework for performing Monte Carlo (MC) Dose Calculation QA. This covers the three critical pillars you requested:
This code is for educational and research purposes only. It is not FDA-cleared or CE-marked. Do not use it for clinical patient treatment planning without rigorous validation and approval from your institution’s medical physics team.
You will need the standard scientific stack: numpy, matplotlib, and scipy.
Before an MC engine is used for patients, it must match the Linac data.
The "Pass/Fail" metric of Medical Physics.
A 1% dose difference might not matter physically, but biologically it could be critical.
import numpy as np
import matplotlib.pyplot as plt
from scipy.special import erf, ndimage
# ==========================================
# 1. COMMISSIONING: Beam Model Validation
# ==========================================
def commissioning_analysis():
"""
Simulates and compares a Reference PDD (Measurement) vs. MC Simulation.
Calculates depth differences (R50, R80) and output factors.
"""
print("--- 1. Commissioning Analysis ---")
# A. Generate Synthetic Data (Simulating Measurement vs MC)
depth = np.linspace(0, 25, 100) # 0 to 25 cm
# Reference Model (e.g., Water Tank Measurement)
# Simple PDD shape: Build-up + Exponential decay
dose_ref = 1.0 * (1 - np.exp(-0.5 * (depth - 0.5)**2)) * np.exp(-0.035 * depth)
dose_ref[depth < 1.5] = np.linspace(0.5, 1.0, len(depth[depth < 1.5])) # buildup region approximation
# MC Model (Slightly noisy, potentially different tail)
np.random.seed(42)
noise = np.random.normal(0, 0.01, len(depth))
dose_mc = dose_ref * 1.02 + noise # MC usually has statistical noise
# B. Analysis: Calculate D10, R50 (Range)
# Interpolate to find specific depths
def get_depth_at_dose(dose_array, depth_array, target_dose):
# Simple linear interpolation logic
indices = np.where(np.diff(np.sign(dose_array - target_dose)))[0]
if len(indices) > 0:
return depth_array[indices[0]]
return None
r50_ref = get_depth_at_dose(dose_ref, depth, 0.5 * np.max(dose_ref))
r50_mc = get_depth_at_dose(dose_mc, depth, 0.5 * np.max(dose_mc))
print(f"Reference R50: {r50_ref:.2f} cm")
print(f"MC R50: {r50_mc:.2f} cm")
print(f"Difference: {abs(r50_ref - r50_mc):.2f} cm")
# C. Visualization
plt.figure(figsize=(10, 5))
plt.plot(depth, dose_ref, 'k-', label='Reference (Measurement)', linewidth=2)
plt.plot(depth, dose_mc, 'r--', label='Monte Carlo', linewidth=1.5)
plt.xlabel('Depth (cm)')
plt.ylabel('Dose (Normalized)')
plt.title('Commissioning: PDD Comparison')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()
return dose_ref, dose_mc
# ==========================================
# 2. GAMMA INDEX: Spatial Dose Comparison
# ==========================================
def calculate_gamma_1d(reference, evaluation, coords, dta=1.0, dd=0.02):
"""
Simple 1D Gamma Index calculation.
dta: Distance to Agreement (e.g., 1 mm or 1 cm)
dd: Dose Difference criteria (e.g., 2% = 0.02)
"""
print(f"--- 2. Gamma Analysis (DTA={dta}mm, DD={dd*100}%) ---")
gamma = np.zeros(len(reference))
max_dose = np.max(reference)
# Convert coordinates to mm if in cm
coords_mm = coords * 10
for i, (ref_dose, ref_pos) in enumerate(zip(reference, coords_mm)):
min_gamma = float('inf')
# Search through evaluation points
for j, (eval_dose, eval_pos) in enumerate(zip(evaluation, coords_mm)):
# Dose Difference term
dose_diff = abs(ref_dose - eval_dose)
delta_dose = (dose_diff / (dd * max_dose))**2
# Distance term
dist_diff = abs(ref_pos - eval_pos)
delta_dist = (dist_diff / (dta * 10))**2 # Assuming dta passed in cm, convert to mm internally logic?
# Note: In this code, dta is expected in mm, let's normalize dta to 1.0 unit
# Calculation: (r^2/dta^2 + d^2/dd^2)
# Here we assume coords are in mm.
# Let's standardize: coords are in mm. dta is in mm.
term_dist = (dist_diff / dta)**2
term_dose = (dose_diff / (dd * max_dose))**2
current_gamma = np.sqrt(term_dist + term_dose)
if current_gamma < min_gamma:
min_gamma = current_gamma
gamma[i] = min_gamma
pass_rate = np.sum(gamma < 1.0) / len(gamma) * 100
print(f"Gamma Pass Rate (<1.0): {pass_rate:.2f}%")
return gamma
# ==========================================
# 3. RADIOBIOLOGY: TCP/NTCP Modeling
# ==========================================
class RadiobiologyModel:
def __init__(self, alpha_beta=10, d50=50, gamma50=2, tissue_type='tumor'):
"""
alpha_beta: Alpha/Beta ratio (Gy)
d50: Dose for 50% probability (Gy)
gamma50: Slope parameter at 50%
"""
self.ab = alpha_beta
self.d50 = d50
self.gamma = gamma50
self.type = tissue_type
def calculate_bed(self, dose_per_fraction_gy, num_fractions):
"""
Biologically Effective Dose (BED)
BED = nd * [1 + d/(alpha/beta)]
"""
total_dose = dose_per_fraction_gy * num_fractions
bed = total_dose * (1 + dose_per_fraction_gy / self.ab)
return bed
def calculate_tcp_ntcp(self, dose_gy):
"""
Poisson TCP or Lyman NTCP (Simplified Logit model used here)
P = 1 / (1 + exp(4*gamma50*(D50 - D)/D50))
"""
# Using a generalized Logistic formula for simplicity
prob = 1 / (1 + np.exp(4 * self.gamma * (self.d50 - dose_gy) / self.d50))
# If NTCP, we might want to invert logic or use specific LKB parameters,
# but for this QA demo, we calculate probability of response.
return prob
# ==========================================
# MAIN EXECUTION
# ==========================================
if __name__ == "__main__":
# 1. Run Commissioning Check
ref_dose, mc_dose = commissioning_analysis()
# 2. Run Gamma Analysis
# We use the data from commissioning (normalized)
# Let's assume grid spacing is 2.5mm (0.25 cm)
coords = np.linspace(0, 25, 100)
gamma_map = calculate_gamma_1d(ref_dose, mc_dose, coords, dta=2.5, dd=0.02)
# Plot Gamma
plt.figure(figsize=(10, 4))
plt.plot(coords, gamma_map, 'b-', label='Gamma Index')
plt.axhline(1.0, color='r', linestyle='--', label='Pass/Fail Threshold')
plt.fill_between(coords, 0, 1, color='green', alpha=0.1)
plt.title(f"Gamma Analysis (Criteria: 2.5mm / 2%)")
plt.xlabel("Position (cm)")
plt.ylabel("Gamma")
plt.legend()
plt.show()
# 3. Radiobiology Check
print("\n--- 3. Radiobiology QA ---")
# Define a Target (Tumor)
tumor_model = RadiobiologyModel(alpha_beta=10, d50=40, gamma50=3)
# Define an Organ at Risk (Spinal Cord)
oar_model = RadiobiologyModel(alpha_beta=3, d50=55, gamma50=1.5)
# Scenario: Reference says 60Gy, MC says 58Gy (2Gy underdose)
dose_ref = 60
dose_mc = 58
tcp_ref = tumor_model.calculate_tcp_ntcp(dose_ref)
tcp_mc = tumor_model.calculate_tcp_ntcp(dose_mc)
ntcp_ref = oar_model.calculate_tcp_ntcp(dose_ref * 0.2) # Assume OAR gets 20% of dose
ntcp_mc = oar_model.calculate_tcp_ntcp(dose_mc * 0.2)
print(f"Tumor Dose: Ref {dose_ref}Gy vs MC {dose_mc}Gy")
print(f" TCP (Ref): {tcp_ref*100:.2f}%")
print(f" TCP (MC) : {tcp_mc*100:.2f}%")
print(f" Clinical Impact: TCP drop of {(tcp_ref - tcp_mc)*100:.2f}%")
print(f"\nOAR Dose (approx 20%): Ref {dose_ref*0.2}Gy vs MC {dose_mc*0.2}Gy")
print(f" NTCP (Ref): {ntcp_ref*100:.2f}%")
print(f" NTCP (MC) : {ntcp_mc*100:.2f}%")