Build a cosmic ray muon tomography for volcanoes: detector arrays, inversion, and…
- User
Build a cosmic ray muon tomography for volcanoes: detector arrays, inversion, and validation.
Assistant
Build a cosmic ray muon tomography for volcanoes: detector arrays, inversion, and validation.
The user wants me to build a simulation of cosmic ray muon tomography for volcano imaging. This is a fascinating technique that uses muons (high-energy particles created when cosmic rays hit Earth's atmosphere) to see inside dense structures like volcanoes.
Let me think about the physics involved:
Cosmic Ray Muons:
Muon Attenuation:
Tomography Principle:
Inversion:
Key equations:
Let me design the simulation:
Detector Arrays:
Volcano Model:
Forward Modeling:
Inversion:
Validation:
Let me write a comprehensive simulation:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from scipy.ndimage import gaussian_filter
from scipy.optimize import least_squares
import matplotlib.colors as colors
# ... full implementation
I'll create a well-structured program with:
Key Physics Involved:
"""
Cosmic Ray Muon Tomography for Volcano Imaging
==============================================
Simulates muon detection, forward modeling, and density inversion
for imaging internal structures of volcanoes.
Physics:
- Muon flux: Gaisser parameterization
- Energy loss: Bethe-Bloch + radiative processes
- Attenuation: Range-energy relation for rock
"""
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from scipy.ndimage import gaussian_filter
from scipy.interpolate import RegularGridInterpolator
import matplotlib.colors as colors
from matplotlib.patches import Circle, Rectangle
from matplotlib.collections import PatchCollection
import warnings
warnings.filterwarnings('ignore')
# =============================================================================
# PHYSICAL CONSTANTS AND MUON PHYSICS
# =============================================================================
class MuonPhysics:
"""
Muon physics constants and calculations for cosmic ray tomography.
"""
# Fundamental constants
m_mu = 105.7 # Muon mass in MeV/c²
c = 3e8 # Speed of light (m/s)
tau_mu = 2.197e-6 # Muon proper lifetime (s)
# Rock properties (typical andesitic volcano)
rock_density = 2.3 # g/cm³ (can vary 1.8-2.8 for volcanoes)
critical_energy = 850 # GeV (critical energy for rock)
# Energy loss parameters for standard rock
a_loss = 2.0 # MeV/(g/cm²) - ionization loss (minimum ionizing)
b_loss = 4.0e-6 # (g/cm²)⁻¹ - radiative losses (bremsstrahlung, pair production, nuclear)
@staticmethod
def gaisser_flux(zenith_deg, energy_GeV):
"""
Gaisser parameterization of cosmic muon flux.
Flux ~ E^(-γ) * (1/(1 + E*cos(θ)/ε))
Parameters:
-----------
zenith_deg : float or array
Zenith angle in degrees (0 = vertical)
energy_GeV : float or array
Muon energy in GeV
Returns:
--------
flux : differential flux in (m²·sr·s·GeV)⁻¹
"""
gamma = 2.7 # Spectral index
epsilon = 115 # GeV (characteristic energy)
zenith_rad = np.radians(zenith_deg)
cos_zenith = np.cos(zenith_rad)
# Avoid division by zero at horizon
cos_zenith = np.maximum(cos_zenith, 0.01)
flux = 0.14 * energy_GeV**(-gamma) * (1 / (1 + 1.1 * energy_GeV * cos_zenith / epsilon))
flux *= cos_zenith**2
return flux
@staticmethod
def integrated_flux(zenith_deg, threshold_GeV):
"""
Integrated muon flux above energy threshold.
Returns flux in muons/(m²·sr·s)
"""
energies = np.logspace(np.log10(threshold_GeV), 5, 1000)
flux = MuonPhysics.gaisser_flux(zenith_deg, energies)
# Numerical integration
integrated = np.trapz(flux, energies)
return integrated
@staticmethod
def energy_loss_rate(energy_GeV):
"""
Muon energy loss rate in rock (MeV/(g/cm²)).
dE/dx = a + b*E
where a is ionization loss and b*E is radiative losses.
"""
energy_MeV = energy_GeV * 1000
dEdx = MuonPhysics.a_loss + MuonPhysics.b_loss * energy_MeV
return dEdx # MeV/(g/cm²)
@staticmethod
def critical_energy_for_thickness(thickness_gcm2):
"""
Minimum energy needed for muon to traverse given thickness.
Uses continuous slowing down approximation (CSDA) range.
Parameters:
-----------
thickness_gcm2 : float
Rock thickness in g/cm²
Returns:
--------
E_min : Minimum energy in GeV
"""
# For thick absorbers, use approximate formula
# E_min ≈ a*L + b*L² for moderate thicknesses
# More accurate: numerical integration
L = thickness_gcm2
# Iterative solution for E_min
E = L * MuonPhysics.a_loss / 1000 # Initial guess in GeV (ionization only)
for _ in range(10):
# Range formula with radiative losses
if E > 0.1: # GeV
# Approximate range-energy relation
E_new = (np.sqrt(MuonPhysics.a_loss**2 + 2 * MuonPhysics.b_loss * L * 1000) -
MuonPhysics.a_loss) / (MuonPhysics.b_loss * 1000)
E_new = max(E_new, L * MuonPhysics.a_loss / 1000) # Minimum from ionization
if abs(E_new - E) < 0.001:
break
E = 0.5 * (E + E_new)
return max(E, 0.1) # Minimum 100 MeV
@staticmethod
def transmission_probability(thickness_gcm2, zenith_deg):
"""
Probability that muon survives passage through rock.
Parameters:
-----------
thickness_gcm2 : float
Path length through rock in g/cm²
zenith_deg : float
Zenith angle in degrees
Returns:
--------
transmission : survival probability (0-1)
"""
if thickness_gcm2 <= 0:
return 1.0
# Calculate minimum energy needed
E_min = MuonPhysics.critical_energy_for_thickness(thickness_gcm2)
# Calculate flux above threshold (surviving muons)
flux_transmitted = MuonPhysics.integrated_flux(zenith_deg, E_min)
# Calculate total flux (no absorption)
flux_total = MuonPhysics.integrated_flux(zenith_deg, 0.1)
transmission = flux_transmitted / flux_total
return min(transmission, 1.0)
# =============================================================================
# VOLCANO MODEL
# =============================================================================
class VolcanoModel:
"""
3D density model of a volcano with internal structures.
"""
def __init__(self, grid_size=(100, 100, 60), resolution=20):
"""
Initialize volcano model.
Parameters:
-----------
grid_size : tuple
(nx, ny, nz) grid dimensions
resolution : float
Grid resolution in meters
"""
self.nx, self.ny, self.nz = grid_size
self.resolution = resolution # meters per grid cell
# Physical dimensions
self.Lx = self.nx * resolution # meters
self.Ly = self.ny * resolution
self.Lz = self.nz * resolution
# Create coordinate arrays (centered at origin)
self.x = (np.arange(self.nx) - self.nx//2) * resolution
self.y = (np.arange(self.ny) - self.ny//2) * resolution
self.z = np.arange(self.nz) * resolution # z=0 at sea level
# Initialize density array (g/cm³)
self.density = np.ones((self.nx, self.ny, self.nz)) * 2.0 # Background
# Build volcano structure
self._build_volcano()
def _build_volcano(self):
"""
Create realistic volcano density structure.
"""
X, Y, Z = np.meshgrid(self.x, self.y, self.z, indexing='ij')
# Volcano cone shape (symmetric)
base_radius = 3000 # meters
summit_height = 2500 # meters above sea level
crater_depth = 200 # meters
crater_radius = 300 # meters
# Distance from cone axis
R = np.sqrt(X**2 + Y**2)
# Cone surface height
cone_height = summit_height * (1 - R / base_radius)
cone_height = np.maximum(cone_height, 0)
# Air density outside and above volcano
air_density = 0.001 # g/cm³
# Set density based on position
for i in range(self.nx):
for j in range(self.ny):
for k in range(self.nz):
z_k = self.z[k]
r_ij = np.sqrt(self.x[i]**2 + self.y[j]**2)
if z_k > cone_height[i, j, k]:
# Above cone surface - air
self.density[i, j, k] = air_density
elif z_k > summit_height - crater_depth and r_ij < crater_radius:
# Inside crater
crater_bottom = summit_height - crater_depth
if z_k > crater_bottom:
self.density[i, j, k] = air_density
else:
self.density[i, j, k] = 2.2 # Crater floor
else:
# Inside volcano
self.density[i, j, k] = 2.4 # Dense lava
# Add magma chamber (low density anomaly)
chamber_center = np.array([0, 0, 1200]) # meters
chamber_radius = 400 # meters
chamber_density = 2.0 # Partially molten, lower density
dist_from_chamber = np.sqrt((X - chamber_center[0])**2 +
(Y - chamber_center[1])**2 +
(Z - chamber_center[2])**2)
chamber_mask = dist_from_chamber < chamber_radius
self.density[chamber_mask] = chamber_density
# Add dense conduit
conduit_radius = 50 # meters
conduit_density = 2.7 # Dense crystallized magma
conduit_mask = (R < conduit_radius) & (Z > 500) & (Z < summit_height - 100)
self.density[conduit_mask] = conduit_density
# Add flank anomaly (possible future vent)
flank_center = np.array([800, 600, 800])
flank_radius = 200
flank_density = 2.1
dist_from_flank = np.sqrt((X - flank_center[0])**2 +
(Y - flank_center[1])**2 +
(Z - flank_center[2])**2)
flank_mask = dist_from_flank < flank_radius
self.density[flank_mask] = flank_density
# Add a hydrothermal system (very low density)
hydro_center = np.array([-400, 300, 600])
hydro_radius = 250
hydro_density = 1.8
dist_from_hydro = np.sqrt((X - hydro_center[0])**2 +
(Y - hydro_center[1])**2 +
(Z - hydro_center[2])**2)
hydro_mask = dist_from_hydro < hydro_radius
self.density[hydro_mask] = hydro_density
# Smooth transitions
self.density = gaussian_filter(self.density, sigma=1.5)
# Store anomaly locations for validation
self.anomalies = {
'magma_chamber': {'center': chamber_center, 'radius': chamber_radius, 'density': chamber_density},
'conduit': {'center': np.array([0, 0, 1500]), 'radius': conduit_radius, 'density': conduit_density},
'flank_anomaly': {'center': flank_center, 'radius': flank_radius, 'density': flank_density},
'hydrothermal': {'center': hydro_center, 'radius': hydro_radius, 'density': hydro_density}
}
def get_density_at_point(self, x, y, z):
"""
Get density at arbitrary point using interpolation.
"""
# Convert to grid indices
i = (x + self.Lx/2) / self.resolution
j = (y + self.Ly/2) / self.resolution
k = z / self.resolution
# Check bounds
if not (0 <= i < self.nx and 0 <= j < self.ny and 0 <= k < self.nz):
return 0.001 # Air for out of bounds
# Simple trilinear interpolation
i0, j0, k0 = int(i), int(j), int(k)
i1, j1, k1 = min(i0+1, self.nx-1), min(j0+1, self.ny-1), min(k0+1, self.nz-1)
fi, fj, fk = i - i0, j - j0, k - k0
density = (self.density[i0, j0, k0] * (1-fi) * (1-fj) * (1-fk) +
self.density[i1, j0, k0] * fi * (1-fj) * (1-fk) +
self.density[i0, j1, k0] * (1-fi) * fj * (1-fk) +
self.density[i0, j0, k1] * (1-fi) * (1-fj) * fk +
self.density[i1, j1, k0] * fi * fj * (1-fk) +
self.density[i1, j0, k1] * fi * (1-fj) * fk +
self.density[i0, j1, k1] * (1-fi) * fj * fk +
self.density[i1, j1, k1] * fi * fj * fk)
return density
def ray_integrate(self, start_point, direction, max_distance=10000):
"""
Integrate density along a ray.
Parameters:
-----------
start_point : array
(x, y, z) starting position in meters
direction : array
Unit direction vector
max_distance : float
Maximum ray length in meters
Returns:
--------
integrated_density : float
Integrated density in g/cm²
"""
step_size = self.resolution / 2 # Integration step
n_steps = int(max_distance / step_size)
integrated = 0.0
current_pos = np.array(start_point, dtype=float)
for _ in range(n_steps):
# Get density at current position
x, y, z = current_pos
density = self.get_density_at_point(x, y, z)
# Accumulate (density in g/cm³ * step in cm)
# Convert meters to cm: multiply by 100
integrated += density * (step_size * 100) # g/cm³ * cm = g/cm²
# Move along ray
current_pos += direction * step_size
# Check if we've left the model (entered atmosphere above)
if z > self.Lz or density < 0.01:
break
return integrated
def plot_slices(self):
"""
Plot slices through the volcano model.
"""
fig, axes = plt.subplots(2, 2, figsize=(14, 12))
# Convert coordinates to km
x_km = self.x / 1000
y_km = self.y / 1000
z_km = self.z / 1000
# Horizontal slice at mid-height
z_slice = self.nz // 3
ax = axes[0, 0]
im = ax.imshow(self.density[:, :, z_slice].T,
extent=[x_km[0], x_km[-1], y_km[0], y_km[-1]],
origin='lower', cmap='terrain_r', vmin=1.5, vmax=2.8)
ax.set_title(f'Horizontal Slice at z = {self.z[z_slice]:.0f} m', fontsize=12)
ax.set_xlabel('X (km)')
ax.set_ylabel('Y (km)')
plt.colorbar(im, ax=ax, label='Density (g/cm³)')
# Vertical slice through center (Y-Z plane)
ax = axes[0, 1]
im = ax.imshow(self.density[self.nx//2, :, :].T,
extent=[y_km[0], y_km[-1], z_km[0], z_km[-1]],
origin='lower', cmap='terrain_r', vmin=1.5, vmax=2.8,
aspect='auto')
ax.set_title('Vertical Slice at X = 0 (Y-Z plane)', fontsize=12)
ax.set_xlabel('Y (km)')
ax.set_ylabel('Z (km)')
plt.colorbar(im, ax=ax, label='Density (g/cm³)')
# Mark anomalies
for name, anomaly in self.anomalies.items():
c = anomaly['center']
r = anomaly['radius']
if name in ['magma_chamber', 'hydrothermal']:
circle = Circle((c[1]/1000, c[2]/1000), r/1000,
fill=False, color='red', linewidth=2, linestyle='--')
ax.add_patch(circle)
ax.annotate(name.replace('_', ' '), (c[1]/1000, c[2]/1000 + r/1000 + 0.1),
color='red', fontsize=8)
# Vertical slice (X-Z plane)
ax = axes[1, 0]
im = ax.imshow(self.density[:, self.ny//2, :].T,
extent=[x_km[0], x_km[-1], z_km[0], z_km[-1]],
origin='lower', cmap='terrain_r', vmin=1.5, vmax=2.8,
aspect='auto')
ax.set_title('Vertical Slice at Y = 0 (X-Z plane)', fontsize=12)
ax.set_xlabel('X (km)')
ax.set_ylabel('Z (km)')
plt.colorbar(im, ax=ax, label='Density (g/cm³)')
# Mark anomalies
for name, anomaly in self.anomalies.items():
c = anomaly['center']
r = anomaly['radius']
circle = Circle((c[0]/1000, c[2]/1000), r/1000,
fill=False, color='red', linewidth=2, linestyle='--')
ax.add_patch(circle)
# 3D surface plot
ax = fig.add_subplot(2, 2, 4, projection='3d')
# Create volcano surface
theta = np.linspace(0, 2*np.pi, 50)
z_surface = np.linspace(0, 2500, 30)
theta_grid, z_grid = np.meshgrid(theta, z_surface)
# Cone radius at each height
base_r = 3000
summit_h = 2500
r_surface = base_r * (1 - z_grid / summit_h)
x_surf = r_surface * np.cos(theta_grid) / 1000
y_surf = r_surface * np.sin(theta_grid) / 1000
z_surf = z_grid / 1000
ax.plot_surface(x_surf, y_surf, z_surf, alpha=0.5, cmap='terrain')
# Plot anomaly positions
colors_list = ['red', 'orange', 'yellow', 'cyan']
for (name, anomaly), color in zip(self.anomalies.items(), colors_list):
c = anomaly['center']
r = anomaly['radius']
ax.scatter(c[0]/1000, c[1]/1000, c[2]/1000, s=100, c=color,
marker='o', label=name.replace('_', ' '))
ax.set_xlabel('X (km)')
ax.set_ylabel('Y (km)')
ax.set_zlabel('Z (km)')
ax.set_title('3D Volcano Structure', fontsize=12)
ax.legend(loc='upper right', fontsize=8)
plt.tight_layout()
return fig
# =============================================================================
# MUON DETECTOR ARRAY
# =============================================================================
class MuonDetectorArray:
"""
Simulates a muon detector array for tomography.
"""
def __init__(self, position, n_azimuth=12, n_zenith=8,
azimuth_range=(0, 360), zenith_range=(10, 60)):
"""
Initialize detector array.
Parameters:
-----------
position : array
(x, y, z) position in meters
n_azimuth : int
Number of azimuth bins
n_zenith : int
Number of zenith angle bins
azimuth_range : tuple
(min, max) azimuth in degrees
zenith_range : tuple
(min, max) zenith in degrees
"""
self.position = np.array(position)
self.n_azimuth = n_azimuth
self.n_zenith = n_zenith
self.azimuth_bins = np.linspace(azimuth_range[0], azimuth_range[1], n_azimuth + 1)
self.zenith_bins = np.linspace(zenith_range[0], zenith_range[1], n_zenith + 1)
self.azimuth_centers = (self.azimuth_bins[:-1] + self.azimuth_bins[1:]) / 2
self.zenith_centers = (self.zenith_bins[:-1] + self.zenith_bins[1:]) / 2
# Solid angle per bin
self.solid_angles = np.zeros((n_azimuth, n_zenith))
for i in range(n_azimuth):
for j in range(n_zenith):
d_az = np.radians(self.azimuth_bins[i+1] - self.azimuth_bins[i])
cos_z1 = np.cos(np.radians(self.zenith_bins[j]))
cos_z2 = np.cos(np.radians(self.zenith_bins[j+1]))
self.solid_angles[i, j] = d_az * abs(cos_z1 - cos_z2)
# Measured data
self.measured_counts = np.zeros((n_azimuth, n_zenith))
self.expected_counts = np.zeros((n_azimuth, n_zenith))
self.exposure_time = 0 # seconds
def get_direction(self, azimuth_deg, zenith_deg):
"""
Convert viewing angles to direction vector.
"""
az = np.radians(azimuth_deg)
zen = np.radians(zenith_deg)
# Direction pointing upward (toward sky)
dx = np.sin(zen) * np.sin(az)
dy = np.sin(zen) * np.cos(az)
dz = np.cos(zen)
return np.array([dx, dy, dz])
def measure(self, volcano, exposure_time_days=30):
"""
Simulate muon detection for given exposure time.
"""
self.exposure_time = exposure_time_days * 24 * 3600 # Convert to seconds
detector_area = 1.0 # m² (typical detector area)
for i in range(self.n_azimuth):
for j in range(self.n_zenith):
az = self.azimuth_centers[i]
zen = self.zenith_centers[j]
# Get viewing direction
direction = self.get_direction(az, zen)
# Calculate integrated density along ray
# Start from detector, look upward through volcano
integrated_density = volcano.ray_integrate(self.position, direction)
# Calculate transmission probability
transmission = MuonPhysics.transmission_probability(integrated_density, zen)
# Expected muon rate (muons/m²/sr/s)
muon_rate = MuonPhysics.integrated_flux(zen, 0.1)
# Expected counts
expected = muon_rate * detector_area * self.solid_angles[i, j] * self.exposure_time
expected_transmitted = expected * transmission
self.expected_counts[i, j] = expected_transmitted
# Add Poisson noise
if expected_transmitted > 0:
self.measured_counts[i, j] = np.random.poisson(expected_transmitted)
def get_opacity(self):
"""
Calculate opacity (1 - transmission) from measurements.
"""
# Calculate reference flux (open sky)
reference = np.zeros((self.n_azimuth, self.n_zenith))
for i in range(self.n_azimuth):
for j in range(self.n_zenith):
zen = self.zenith_centers[j]
muon_rate = MuonPhysics.integrated_flux(zen, 0.1)
reference[i, j] = muon_rate * self.solid_angles[i, j] * self.exposure_time
# Opacity = 1 - (measured / reference)
with np.errstate(divide='ignore', invalid='ignore'):
opacity = 1 - self.measured_counts / reference
opacity = np.clip(opacity, 0, 1)
opacity[np.isnan(opacity)] = 0
return opacity
def get_density_length(self):
"""
Convert opacity to density-length (g/cm²).
"""
opacity = self.get_opacity()
density_length = np.zeros_like(opacity)
for i in range(self.n_azimuth):
for j in range(self.n_zenith):
zen = self.zenith_centers[j]
if opacity[i, j] > 0.01:
# Invert transmission to get density length
# Simplified: use calibration curve
density_length[i, j] = self._opacity_to_density_length(opacity[i, j], zen)
return density_length
def _opacity_to_density_length(self, opacity, zenith_deg):
"""
Convert opacity to density length using empirical relation.
"""
# Tabulated relationship (from physics)
test_thicknesses = np.linspace(100, 10000, 50) # g/cm²
test_opacities = []
for thick in test_thicknesses:
trans = MuonPhysics.transmission_probability(thick, zenith_deg)
test_opacities.append(1 - trans)
test_opacities = np.array(test_opacities)
# Find thickness corresponding to measured opacity
idx = np.argmin(np.abs(test_opacities - opacity))
return test_thicknesses[idx]
def plot_measurements(self):
"""
Plot detector measurements.
"""
fig, axes = plt.subplots(2, 2, figsize=(14, 12))
# Plot measured counts
ax = axes[0, 0]
im = ax.imshow(self.measured_counts.T, origin='lower',
extent=[self.azimuth_bins[0], self.azimuth_bins[-1],
self.zenith_bins[0], self.zenith_bins[-1]],
aspect='auto', cmap='viridis')
ax.set_xlabel('Azimuth (°)')
ax.set_ylabel('Zenith (°)')
ax.set_title(f'Measured Muon Counts ({self.exposure_time/86400:.0f} days)', fontsize=12)
plt.colorbar(im, ax=ax, label='Counts')
# Plot opacity
ax = axes[0, 1]
opacity = self.get_opacity()
im = ax.imshow(opacity.T, origin='lower',
extent=[self.azimuth_bins[0], self.azimuth_bins[-1],
self.zenith_bins[0], self.zenith_bins[-1]],
aspect='auto', cmap='hot', vmin=0, vmax=1)
ax.set_xlabel('Azimuth (°)')
ax.set_ylabel('Zenith (°)')
ax.set_title('Opacity (1 - Transmission)', fontsize=12)
plt.colorbar(im, ax=ax, label='Opacity')
# Plot density length
ax = axes[1, 0]
density_length = self.get_density_length()
im = ax.imshow(density_length.T/1000, origin='lower',
extent=[self.azimuth_bins[0], self.azimuth_bins[-1],
self.zenith_bins[0], self.zenith_bins[-1]],
aspect='auto', cmap='copper')
ax.set_xlabel('Azimuth (°)')
ax.set_ylabel('Zenith (°)')
ax.set_title('Density-Length (×10³ g/cm²)', fontsize=12)
plt.colorbar(im, ax=ax, label='Density-Length (×10³ g/cm²)')
# Polar plot of measurements
ax = axes[1, 1]
ax.remove()
ax = fig.add_subplot(2, 2, 4, projection='polar')
# Create polar grid
AZ, ZEN = np.meshgrid(np.radians(self.azimuth_centers), self.zenith_centers)
# Plot opacity as polar heat map
im = ax.pcolormesh(AZ, ZEN, opacity.T, cmap='hot', shading='auto')
ax.set_theta_zero_location('N')
ax.set_theta_direction(-1)
ax.set_title('Opacity (Polar View)\n0° = North', fontsize=12, pad=20)
plt.colorbar(im, ax=ax, label='Opacity', shrink=0.8)
plt.tight_layout()
return fig
# =============================================================================
# TOMOGRAPHIC INVERSION
# =============================================================================
class TomographyInversion:
"""
Performs tomographic reconstruction of volcano density structure.
"""
def __init__(self, volcano_model, detectors):
"""
Initialize inversion.
Parameters:
-----------
volcano_model : VolcanoModel
True volcano model (for comparison)
detectors : list
List of MuonDetectorArray objects
"""
self.model = volcano_model
self.detectors = detectors
# Reconstruction grid (coarser than true model)
self.recon_resolution = 100 # meters
self.recon_nx = volcano_model.nx // 5
self.recon_ny = volcano_model.ny // 5
self.recon_nz = volcano_model.nz // 5
# Initialize reconstruction
self.density_recon = np.ones((self.recon_nx, self.recon_ny, self.recon_nz)) * 2.3
# Build ray paths and system matrix
self._build_system_matrix()
def _build_system_matrix(self):
"""
Build system matrix for tomography.
Each row represents a ray path through the volume.
Each column represents a voxel.
"""
print("Building system matrix...")
# Collect all ray paths
self.rays = []
self.measurements = []
self.weights = []
for det_idx, detector in enumerate(self.detectors):
for i in range(detector.n_azimuth):
for j in range(detector.n_zenith):
if detector.measured_counts[i, j] > 10: # Only use significant measurements
az = detector.azimuth_centers[i]
zen = detector.zenith_centers[j]
# Get ray direction
direction = detector.get_direction(az, zen)
# Store ray information
self.rays.append({
'start': detector.position.copy(),
'direction': direction.copy(),
'detector': det_idx,
'azimuth': az,
'zenith': zen
})
# Store measurement
self.measurements.append(detector.get_density_length()[i, j])
self.weights.append(np.sqrt(detector.measured_counts[i, j]))
print(f"Total rays: {len(self.rays)}")
def forward_project(self, density):
"""
Forward project density model to get predicted measurements.
"""
predictions = np.zeros(len(self.rays))
# Create interpolator
x = np.linspace(0, self.model.Lx, self.recon_nx)
y = np.linspace(0, self.model.Ly, self.recon_ny)
z = np.linspace(0, self.model.Lz, self.recon_nz)
for r, ray in enumerate(self.rays):
# Integrate along ray
step_size = self.recon_resolution
n_steps = int(10000 / step_size)
current_pos = ray['start'].copy()
integrated = 0.0
for _ in range(n_steps):
# Get position in grid coordinates
px, py, pz = current_pos
# Convert to grid indices
ix = (px + self.model.Lx/2) / self.recon_resolution
iy = (py + self.model.Ly/2) / self.recon_resolution
iz = pz / self.recon_resolution
# Check bounds and get density
if 0 <= ix < self.recon_nx and 0 <= iy < self.recon_ny and 0 <= iz < self.recon_nz:
i0, j0, k0 = int(ix), int(iy), int(iz)
i0 = min(i0, self.recon_nx - 1)
j0 = min(j0, self.recon_ny - 1)
k0 = min(k0, self.recon_nz - 1)
local_density = density[i0, j0, k0]
integrated += local_density * step_size * 100 # g/cm³ * cm
else:
break
current_pos += ray['direction'] * step_size
predictions[r] = integrated
return predictions
def invert_sirt(self, n_iterations=20, relaxation=0.1):
"""
Perform SIRT (Simultaneous Iterative Reconstruction Technique) inversion.
"""
print(f"Running SIRT inversion ({n_iterations} iterations)...")
# Get measurements
y = np.array(self.measurements)
w = np.array(self.weights)
for iteration in range(n_iterations):
# Forward projection
y_pred = self.forward_project(self.density_recon)
# Compute residual
residual = y - y_pred
# Back-project correction
correction = np.zeros_like(self.density_recon)
for r, ray in enumerate(self.rays):
if w[r] > 0:
step_size = self.recon_resolution
n_steps = int(10000 / step_size)
current_pos = ray['start'].copy()
for _ in range(n_steps):
px, py, pz = current_pos
ix = (px + self.model.Lx/2) / self.recon_resolution
iy = (py + self.model.Ly/2) / self.recon_resolution
iz = pz / self.recon_resolution
if 0 <= ix < self.recon_nx and 0 <= iy < self.recon_ny and 0 <= iz < self.recon_nz:
i0, j0, k0 = int(ix), int(iy), int(iz)
i0 = min(i0, self.recon_nx - 1)
j0 = min(j0, self.recon_ny - 1)
k0 = min(k0, self.recon_nz - 1)
correction[i0, j0, k0] += residual[r] * step_size * 100 / w[r]
else:
break
current_pos += ray['direction'] * step_size
# Apply correction with relaxation
self.density_recon += relaxation * correction / (len(self.rays))
# Enforce physical bounds
self.density_recon = np.clip(self.density_recon, 1.5, 3.0)
# Calculate error
rmse = np.sqrt(np.mean((y - y_pred)**2))
print(f" Iteration {iteration+1}: RMSE = {rmse:.1f} g/cm²")
# Smooth result
self.density_recon = gaussian_filter(self.density_recon, sigma=1.0)
return self.density_recon
def invert_algebraic(self, regularization=0.01):
"""
Algebraic reconstruction with regularization.
"""
print("Running algebraic reconstruction...")
# Simplified 2D slice reconstruction
# Select rays that pass through central slice
slice_rays = []
slice_data = []
for r, ray in enumerate(self.rays):
# Check if ray passes near y=0 plane
start = ray['start']
if abs(start[1]) < 500: # Near center
slice_rays.append(ray)
slice_data.append(self.measurements[r])
if len(slice_rays) < 10:
print("Not enough rays for slice reconstruction")
return self.density_recon
print(f"Reconstructing with {len(slice_rays)} rays")
# Simple backprojection for 2D slice
slice_nx = self.recon_nx
slice_nz = self.recon_nz
backproj = np.zeros((slice_nx, slice_nz))
ray_count = np.zeros((slice_nx, slice_nz))
for r, ray in enumerate(slice_rays):
data = slice_data[r]
step_size = self.recon_resolution
n_steps = int(10000 / step_size)
current_pos = ray['start'].copy()
for _ in range(n_steps):
px, pz = current_pos[0], current_pos[2]
ix = int((px + self.model.Lx/2) / self.recon_resolution)
iz = int(pz / self.recon_resolution)
if 0 <= ix < slice_nx and 0 <= iz < slice_nz:
backproj[ix, iz] += data
ray_count[ix, iz] += 1
else:
break
current_pos += ray['direction'] * step_size
# Normalize by ray count
with np.errstate(divide='ignore', invalid='ignore'):
backproj = backproj / ray_count
backproj[np.isnan(backproj)] = 2.3
# Convert to density (simplified)
# Assume path length of 2000m average
avg_path = 200000 # cm
density_slice = backproj / avg_path
density_slice = np.clip(density_slice, 1.5, 3.0)
# Embed in 3D reconstruction
center_j = self.recon_ny // 2
for i in range(self.recon_nx):
for k in range(self.recon_nz):
self.density_recon[i, center_j, k] = density_slice[i, k]
# Smooth in y direction
for dj in range(-2, 3):
j = center_j + dj
if 0 <= j < self.recon_ny:
self.density_recon[i, j, k] = density_slice[i, k]
return self.density_recon
def validate(self):
"""
Validate reconstruction against true model.
"""
print("Validating reconstruction...")
# Downsample true model to reconstruction resolution
true_downsampled = np.zeros_like(self.density_recon)
scale_x = self.model.nx // self.recon_nx
scale_y = self.model.ny // self.recon_ny
scale_z = self.model.nz // self.recon_nz
for i in range(self.recon_nx):
for j in range(self.recon_ny):
for k in range(self.recon_nz):
i0, i1 = i * scale_x, (i + 1) * scale_x
j0, j1 = j * scale_y, (j + 1) * scale_y
k0, k1 = k * scale_z, (k + 1) * scale_z
i1 = min(i1, self.model.nx)
j1 = min(j1, self.model.ny)
k1 = min(k1, self.model.nz)
true_downsampled[i, j, k] = np.mean(self.model.density[i0:i1, j0:j1, k0:k1])
# Calculate metrics
mask = true_downsampled > 1.0 # Only compare inside volcano
diff = self.density_recon - true_downsampled
mae = np.mean(np.abs(diff[mask]))
rmse = np.sqrt(np.mean(diff[mask]**2))
# Correlation
valid = mask & (true_downsampled > 1.5)
if np.sum(valid) > 10:
corr = np.corrcoef(true_downsampled[valid].flatten(),
self.density_recon[valid].flatten())[0, 1]
else:
corr = 0
print(f" MAE: {mae:.3f} g/cm³")
print(f" RMSE: {rmse:.3f} g/cm³")
print(f" Correlation: {corr:.3f}")
return {
'mae': mae,
'rmse': rmse,
'correlation': corr,
'true_model': true_downsampled,
'reconstruction': self.density_recon
}
def plot_comparison(self, validation_results):
"""
Plot comparison between true model and reconstruction.
"""
fig, axes = plt.subplots(2, 3, figsize=(16, 11))
true_model = validation_results['true_model']
recon = validation_results['reconstruction']
# Coordinates for reconstruction grid
x_recon = np.linspace(-self.model.Lx/2, self.model.Lx/2, self.recon_nx) / 1000
y_recon = np.linspace(-self.model.Ly/2, self.model.Ly/2, self.recon_ny) / 1000
z_recon = np.linspace(0, self.model.Lz, self.recon_nz) / 1000
# True model slice
ax = axes[0, 0]
slice_idx = self.recon_nz // 3
im = ax.imshow(true_model[:, self.recon_ny//2, :].T,
extent=[x_recon[0], x_recon[-1], z_recon[0], z_recon[-1]],
origin='lower', cmap='terrain_r', vmin=1.5, vmax=2.8,
aspect='auto')
ax.set_title('True Density (Y-Z plane)', fontsize=12)
ax.set_xlabel('X (km)')
ax.set_ylabel('Z (km)')
plt.colorbar(im, ax=ax, label='Density (g/cm³)')
# Reconstruction slice
ax = axes[0, 1]
im = ax.imshow(recon[:, self.recon_ny//2, :].T,
extent=[x_recon[0], x_recon[-1], z_recon[0], z_recon[-1]],
origin='lower', cmap='terrain_r', vmin=1.5, vmax=2.8,
aspect='auto')
ax.set_title('Reconstructed Density (Y-Z plane)', fontsize=12)
ax.set_xlabel('X (km)')
ax.set_ylabel('Z (km)')
plt.colorbar(im, ax=ax, label='Density (g/cm³)')
# Difference
ax = axes[0, 2]
diff = recon[:, self.recon_ny//2, :] - true_model[:, self.recon_ny//2, :]
im = ax.imshow(diff.T,
extent=[x_recon[0], x_recon[-1], z_recon[0], z_recon[-1]],
origin='lower', cmap='RdBu_r', vmin=-0.5, vmax=0.5,
aspect='auto')
ax.set_title('Difference (Recon - True)', fontsize=12)
ax.set_xlabel('X (km)')
ax.set_ylabel('Z (km)')
plt.colorbar(im, ax=ax, label='Density diff (g/cm³)')
# Horizontal slices
slice_z = self.recon_nz // 2
ax = axes[1, 0]
im = ax.imshow(true_model[:, :, slice_z].T,
extent=[x_recon[0], x_recon[-1], y_recon[0], y_recon[-1]],
origin='lower', cmap='terrain_r', vmin=1.5, vmax=2.8)
ax.set_title(f'True Density (z = {z_recon[slice_z]:.1f} km)', fontsize=12)
ax.set_xlabel('X (km)')
ax.set_ylabel('Y (km)')
plt.colorbar(im, ax=ax, label='Density (g/cm³)')
# Mark anomalies
for name, anomaly in self.model.anomalies.items():
c = anomaly['center']
circle = Circle((c[0]/1000, c[1]/1000), anomaly['radius']/1000,
fill=False, color='red', linewidth=2, linestyle='--')
ax.add_patch(circle)
ax = axes[1, 1]
im = ax.imshow(recon[:, :, slice_z].T,
extent=[x_recon[0], x_recon[-1], y_recon[0], y_recon[-1]],
origin='lower', cmap='terrain_r', vmin=1.5, vmax=2.8)
ax.set_title(f'Reconstructed (z = {z_recon[slice_z]:.1f} km)', fontsize=12)
ax.set_xlabel('X (km)')
ax.set_ylabel('Y (km)')
plt.colorbar(im, ax=ax, label='Density (g/cm³)')
# Scatter plot of true vs reconstructed
ax = axes[1, 2]
mask = true_model > 1.5
ax.scatter(true_model[mask], recon[mask], alpha=0.3, s=5, c='blue')
ax.plot([1.5, 2.8], [1.5, 2.8], 'r--', label='1:1 line')
ax.set_xlabel('True Density (g/cm³)')
ax.set_ylabel('Reconstructed Density (g/cm³)')
ax.set_title(f'Validation (r = {validation_results["correlation"]:.3f})', fontsize=12)
ax.legend()
ax.set_aspect('equal')
ax.grid(True, alpha=0.3)
# Add metrics text
metrics_text = f"MAE: {validation_results['mae']:.3f} g/cm³\n"
metrics_text += f"RMSE: {validation_results['rmse']:.3f} g/cm³"
ax.text(0.05, 0.95, metrics_text, transform=ax.transAxes,
fontsize=10, verticalalignment='top',
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))
plt.tight_layout()
return fig
# =============================================================================
# MAIN SIMULATION
# =============================================================================
def run_muon_tomography_simulation():
"""
Run complete muon tomography simulation for volcano imaging.
"""
print("="*70)
print("COSMIC RAY MUON TOMOGRAPHY FOR VOLCANO IMAGING")
print("="*70)
# Step 1: Create volcano model
print("\n1. Creating volcano density model...")
volcano = VolcanoModel(grid_size=(100, 100, 60), resolution=20)
# Plot volcano model
fig_volcano = volcano.plot_slices()
fig_volcano.savefig('volcano_model.png', dpi=150, bbox_inches='tight')
print(" Volcano model saved to 'volcano_model.png'")
# Print anomaly information
print("\n Internal structures (anomalies):")
for name, anomaly in volcano.anomalies.items():
print(f" - {name}: center={anomaly['center']/1000} km, "
f"radius={anomaly['radius']}m, density={anomaly['density']} g/cm³")
# Step 2: Set up detector arrays
print("\n2. Setting up detector arrays...")
# Multiple detector positions around the volcano
detector_positions = [
np.array([2000, 0, 500]), # East flank
np.array([-2000, 0, 500]), # West flank
np.array([0, 2000, 500]), # North flank
np.array([0, -2000, 500]), # South flank
np.array([1500, 1500, 300]), # NE flank (lower)
]
detectors = []
exposure_days = 60 # 2 months of data collection
for i, pos in enumerate(detector_positions):
print(f" Detector {i+1} at position {pos/1000} km")
# Different viewing angles for each detector
az_range = (0, 360)
zen_range = (15, 55)
det = MuonDetectorArray(
position=pos,
n_azimuth=16,
n_zenith=10,
azimuth_range=az_range,
zenith_range=zen_range
)
# Take measurements
det.measure(volcano, exposure_time_days=exposure_days)
detectors.append(det)
print(f" Total counts: {np.sum(det.measured_counts):.0f}")
# Plot measurements from first detector
fig_detector = detectors[0].plot_measurements()
fig_detector.savefig('detector_measurements.png', dpi=150, bbox_inches='tight')
print("\n Detector measurements saved to 'detector_measurements.png'")
# Step 3: Tomographic inversion
print("\n3. Running tomographic inversion...")
inversion = TomographyInversion(volcano, detectors)
# Run SIRT inversion
density_recon = inversion.invert_sirt(n_iterations=25, relaxation=0.15)
# Step 4: Validation
print("\n4. Validating reconstruction...")
validation = inversion.validate()
# Plot comparison
fig_comparison = inversion.plot_comparison(validation)
fig_comparison.savefig('tomography_comparison.png', dpi=150, bbox_inches='tight')
print(" Comparison saved to 'tomography_comparison.png'")
# Step 5: Summary and analysis
print("\n" + "="*70)
print("SIMULATION SUMMARY")
print("="*70)
print(f"\nVolcano dimensions: {volcano.Lx/1000:.1f} × {volcano.Ly/1000:.1f} × {volcano.Lz/1000:.1f} km")
print(f"Number of detectors: {len(detectors)}")
print(f"Exposure time per detector: {exposure_days} days")
print(f"Total muon events: {sum(np.sum(d.measured_counts) for d in detectors):.0f}")
print(f"\nReconstruction quality:")
print(f" Mean Absolute Error: {validation['mae']:.3f} g/cm³")
print(f" RMSE: {validation['rmse']:.3f} g/cm³")
print(f" Correlation: {validation['correlation']:.3f}")
# Anomaly detection assessment
print("\nAnomaly detection assessment:")
for name, anomaly in volcano.anomalies.items():
c = anomaly['center']
r = anomaly['radius']
# Find corresponding region in reconstruction
ix = int((c[0] + volcano.Lx/2) / inversion.recon_resolution)
iy = int((c[1] + volcano.Ly/2) / inversion.recon_resolution)
iz = int(c[2] / inversion.recon_resolution)
if 0 <= ix < inversion.recon_nx and 0 <= iy < inversion.recon_ny and 0 <= iz < inversion.recon_nz:
recon_density = density_recon[ix, iy, iz]
true_density = anomaly['density']
detected = "✓" if abs(recon_density - true_density) < 0.3 else "✗"
print(f" {name}: True={true_density:.2f}, Recon={recon_density:.2f} g/cm³ {detected}")
plt.show()
return volcano, detectors, inversion, validation
# =============================================================================
# ADDITIONAL ANALYSIS: MUON PHYSICS DEMONSTRATION
# =============================================================================
def plot_muon_physics():
"""
Plot muon physics relationships for educational purposes.
"""
fig, axes = plt.subplots(2, 2, figsize=(14, 12))
# 1. Angular distribution of cosmic muons
ax = axes[0, 0]
zeniths = np.linspace(0, 80, 100)
fluxes = [MuonPhysics.integrated_flux(z, 0.1) for z in zeniths]
ax.semilogy(zeniths, fluxes, 'b-', linewidth=2)
ax.set_xlabel('Zenith Angle (°)', fontsize=12)
ax.set_ylabel('Integrated Flux (muons/m²/sr/s)', fontsize=12)
ax.set_title('Cosmic Muon Flux vs Zenith Angle', fontsize=12)
ax.grid(True, alpha=0.3)
ax.set_xlim(0, 80)
# 2. Energy spectrum at different angles
ax = axes[0, 1]
energies = np.logspace(-1, 4, 100)
for zenith in [0, 30, 60]:
flux = MuonPhysics.gaisser_flux(zenith, energies)
ax.loglog(energies, flux, linewidth=2, label=f'θ = {zenith}°')
ax.set_xlabel('Muon Energy (GeV)', fontsize=12)
ax.set_ylabel('Differential Flux (m²·sr·s·GeV)⁻¹', fontsize=12)
ax.set_title('Muon Energy Spectrum at Different Angles', fontsize=12)
ax.legend()
ax.grid(True, alpha=0.3)
ax.set_xlim(0.1, 10000)
# 3. Transmission through rock
ax = axes[1, 0]
thicknesses = np.linspace(100, 5000, 50) # g/cm²
for zenith in [0, 30, 45, 60]:
transmissions = [MuonPhysics.transmission_probability(t, zenith) for t in thicknesses]
ax.plot(thicknesses/1000, transmissions, linewidth=2, label=f'θ = {zenith}°')
ax.set_xlabel('Rock Thickness (×10³ g/cm²)', fontsize=12)
ax.set_ylabel('Transmission Probability', fontsize=12)
ax.set_title('Muon Transmission Through Rock', fontsize=12)
ax.legend()
ax.grid(True, alpha=0.3)
ax.set_ylim(0, 1)
# 4. Minimum energy vs rock thickness
ax = axes[1, 1]
thicknesses = np.linspace(100, 10000, 100) # g/cm²
E_min = [MuonPhysics.critical_energy_for_thickness(t) for t in thicknesses]
ax.semilogy(thicknesses/1000, E_min, 'r-', linewidth=2)
ax.set_xlabel('Rock Thickness (×10³ g/cm²)', fontsize=12)
ax.set_ylabel('Minimum Muon Energy (GeV)', fontsize=12)
ax.set_title('Energy Required to Penetrate Rock', fontsize=12)
ax.grid(True, alpha=0.3)
# Add some reference points
ref_points = [
(1000, "Dense lava flow"),
(2500, "Volcano conduit"),
(4000, "Through magma chamber")
]
for thick, label in ref_points:
E = MuonPhysics.critical_energy_for_thickness(thick)
ax.axvline(thick/1000, color='gray', linestyle='--', alpha=0.5)
ax.scatter(thick/1000, E, s=100, c='blue', zorder=5)
ax.annotate(label, (thick/1000, E), xytext=(5, 5),
textcoords='offset points', fontsize=9)
plt.tight_layout()
plt.savefig('muon_physics.png', dpi=150, bbox_inches='tight')
print("Muon physics plots saved to 'muon_physics.png'")
return fig
# =============================================================================
# ENTRY POINT
# =============================================================================
if __name__ == "__main__":
# First show muon physics
print("Generating muon physics demonstration...")
fig_physics = plot_muon_physics()
# Run main simulation
volcano, detectors, inversion, validation = run_muon_tomography_simulation()
print("\n" + "="*70)
print("Simulation complete! Generated files:")
print(" - volcano_model.png")
print(" - detector_measurements.png")
print(" - tomography_comparison.png")
print(" - muon_physics.png")
print("="*70)