This is a fascinating and complex project that combines planetary seismology, geophysics, and machine learning for characterizing exoplanet interiors. Let me design a comprehensive toolkit that includes:
- Normal Modes - Free oscillations of the planet
- Body Waves - P-waves and S-waves traveling through the planet
- Machine Learning - For inversion and characterization
Key physical considerations:
- Wave propagation in spherical bodies
- Normal mode frequencies depend on planetary structure (density, elastic moduli)
- Body wave travel times depend on velocity structure
- Forward modeling: compute seismograms from structure
- Inverse problem: infer structure from seismograms
Mathematical foundations:
-
Normal modes: Eigenvalue problem for spheroidal and toroidal modes
- Spheroidal modes involve radial and longitudinal motion
- Toroidal modes involve purely horizontal motion
- Angular order l, radial order n
- ω² depends on density ρ(r), Lamé parameters λ(r), μ(r)
-
Body waves:
- Ray theory for high-frequency waves
- Travel time integrals: T = ∫(1/v) ds
- P-wave velocity: Vp = √((K + 4μ/3)/ρ)
- S-wave velocity: Vs = √(μ/ρ)
-
Machine Learning inversion:
- Neural networks for parameter estimation
- Uncertainty quantification
- Feature extraction from seismograms
Let me structure this toolkit:
planetary_seismology_toolkit/
├── core/
│ ├── planetary_model.py # Planetary structure models
│ ├── normal_modes.py # Normal mode computations
│ ├── body_waves.py # Body wave calculations
│ └── wave_propagation.py # General wave propagation
├── ml/
│ ├── dataset.py # Dataset generation
│ ├── models.py # Neural network architectures
│ ├── training.py # Training utilities
│ └── uncertainty.py # Uncertainty quantification
├── inversion/
│ ├── forward_model.py # Forward modeling
│ ├── inverse_solver.py # Classical inversion methods
│ └── ml_inversion.py # ML-based inversion
├── visualization/
│ └── plots.py # Visualization tools
└── examples/
└── example_earth_like.py # Example usage
Let me write comprehensive, well-documented code for this toolkit.
Planetary Seismology Inversion Toolkit
A comprehensive toolkit combining normal mode theory, body wave seismology, and machine learning for exoplanet interior characterization.
Installation
pip install numpy scipy torch matplotlib h5py tqdm
Complete Toolkit Implementation
"""
Planetary Seismology Inversion Toolkit
======================================
Combines normal modes, body waves, and machine learning for
exoplanet interior characterization.
Author: AI Assistant
Version: 1.0.0
"""
import numpy as np
from scipy.integrate import solve_ivp, odeint
from scipy.special import sph_harm, lpmv
from scipy.interpolate import interp1d, UnivariateSpline
from scipy.optimize import minimize, differential_evolution
from scipy.linalg import eigh
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from dataclasses import dataclass
from typing import Dict, List, Tuple, Optional, Callable, Union
from enum import Enum
import h5py
import warnings
from abc import ABC, abstractmethod
# Physical constants
G = 6.67430e-11 # Gravitational constant (m³/kg/s²)
PI = np.pi
# ============================================================================
# CORE DATA STRUCTURES
# ============================================================================
class PlanetComposition(Enum):
"""Enumeration of possible planetary compositions"""
ROCKY = "rocky"
ICE = "ice"
GAS_GIANT = "gas_giant"
WATER_WORLD = "water_world"
SUPER_EARTH = "super_earth"
IRON_PLANET = "iron_planet"
@dataclass
class LayerProperties:
"""Properties for a planetary layer"""
name: str
inner_radius: float # m
outer_radius: float # m
density: float # kg/m³ (can be function of radius)
vp: float # P-wave velocity (m/s)
vs: float # S-wave velocity (m/s)
bulk_modulus: float # Pa
shear_modulus: float # Pa
is_fluid: bool = False # True for liquid layers (no S-waves)
@dataclass
class SeismicObservation:
"""Container for seismic observations"""
time: np.ndarray # Time points
amplitude: np.ndarray # Seismic amplitude
component: str # 'Z' (vertical), 'R' (radial), 'T' (transverse)
latitude: float # Station latitude
longitude: float # Station longitude
sampling_rate: float # Hz
noise_level: float = 0.0 # Estimated noise
@dataclass
class NormalMode:
"""Container for a normal mode"""
n: int # Radial order
l: int # Angular order
m: int # Azimuthal order
frequency: float # Hz
quality_factor: float # Q factor
eigenfunction: np.ndarray # Radial eigenfunction
mode_type: str # 'spheroidal' or 'toroidal'
# ============================================================================
# PLANETARY MODEL
# ============================================================================
class PlanetaryModel:
"""
Represents a 1D radially symmetric planetary model.
Stores density, seismic velocities, and elastic properties.
"""
def __init__(self,
radius: float,
mass: float,
name: str = "Exoplanet"):
"""
Initialize planetary model.
Args:
radius: Planetary radius in meters
mass: Total mass in kg
name: Name of the planet
"""
self.radius = radius
self.mass = mass
self.name = name
self.layers: List[LayerProperties] = []
# Radial grid for discretization
self.nr = 1000
self.r_grid = np.linspace(0, radius, self.nr)
# Property arrays (interpolated from layers)
self.density = np.zeros(self.nr)
self.vp = np.zeros(self.nr)
self.vs = np.zeros(self.nr)
self.bulk_modulus = np.zeros(self.nr)
self.shear_modulus = np.zeros(self.nr)
self.gravity = np.zeros(self.nr)
self.pressure = np.zeros(self.nr)
def add_layer(self, layer: LayerProperties):
"""Add a layer to the planetary model."""
self.layers.append(layer)
self._update_properties()
def _update_properties(self):
"""Update property arrays from layer definitions."""
# Sort layers by inner radius
self.layers.sort(key=lambda x: x.inner_radius)
for layer in self.layers:
mask = (self.r_grid >= layer.inner_radius) & (self.r_grid <= layer.outer_radius)
# Handle density as function or constant
if callable(layer.density):
self.density[mask] = layer.density(self.r_grid[mask])
else:
self.density[mask] = layer.density
if callable(layer.vp):
self.vp[mask] = layer.vp(self.r_grid[mask])
else:
self.vp[mask] = layer.vp
if callable(layer.vs):
self.vs[mask] = layer.vs(self.r_grid[mask])
else:
self.vs[mask] = layer.vs if not layer.is_fluid else 0.0
self.bulk_modulus[mask] = layer.bulk_modulus
self.shear_modulus[mask] = 0.0 if layer.is_fluid else layer.shear_modulus
# Compute gravity profile
self._compute_gravity()
# Compute pressure profile
self._compute_pressure()
def _compute_gravity(self):
"""Compute gravitational acceleration profile."""
# g(r) = G * M(r) / r²
# M(r) = 4π ∫₀ʳ ρ(r') r'² dr'
dr = self.r_grid[1] - self.r_grid[0]
mass_interior = np.zeros(self.nr)
for i in range(1, self.nr):
mass_interior[i] = mass_interior[i-1] + 4 * PI * self.density[i-1] * self.r_grid[i-1]**2 * dr
# Avoid division by zero at center
self.gravity[0] = 0.0
self.gravity[1:] = G * mass_interior[1:] / self.r_grid[1:]**2
def _compute_pressure(self):
"""Compute hydrostatic pressure profile."""
# dP/dr = -ρ(r) * g(r)
dr = self.r_grid[1] - self.r_grid[0]
# Integrate from surface (P=0) inward
self.pressure[-1] = 0.0
for i in range(self.nr - 2, -1, -1):
self.pressure[i] = self.pressure[i+1] + self.density[i] * self.gravity[i] * dr
def get_property_at_radius(self, r: float, prop: str) -> float:
"""Interpolate property at given radius."""
interp_func = interp1d(self.r_grid, getattr(self, prop),
bounds_error=False, fill_value="extrapolate")
return float(interp_func(r))
def compute_mean_density(self) -> float:
"""Compute mean density."""
return self.mass / (4/3 * PI * self.radius**3)
def compute_moment_of_inertia(self) -> float:
"""Compute moment of inertia (assuming spherical symmetry)."""
# I = (8π/3) ∫₀ᴿ ρ(r) r⁴ dr
dr = self.r_grid[1] - self.r_grid[0]
return (8/3) * PI * np.sum(self.density * self.r_grid**4) * dr
def compute_moi_factor(self) -> float:
"""Compute moment of inertia factor (I/MR²)."""
I = self.compute_moment_of_inertia()
return I / (self.mass * self.radius**2)
@classmethod
def create_earth_like(cls,
radius: float = 6.371e6,
mass: float = 5.972e24,
scaling: str = "linear") -> 'PlanetaryModel':
"""
Create Earth-like planetary model with proper scaling.
Args:
radius: Planet radius in meters
mass: Planet mass in kg
scaling: Scaling law ('linear', 'mass_radius', 'constant_density')
"""
model = cls(radius, mass, "Earth-like")
# Earth reference values
earth_radius = 6.371e6
earth_mass = 5.972e24
# Scale factor
r_scale = radius / earth_radius
m_scale = mass / earth_mass
rho_scale = m_scale / r_scale**3
g_scale = m_scale / r_scale**2
# Define layers (scaled from Earth)
# Inner core
model.add_layer(LayerProperties(
name="inner_core",
inner_radius=0,
outer_radius=0.19 * radius, # Earth: 1220 km
density=13000 * rho_scale,
vp=11000 * r_scale**0.5,
vs=3600 * r_scale**0.5,
bulk_modulus=1.3e12,
shear_modulus=1.6e11,
is_fluid=False
))
# Outer core
model.add_layer(LayerProperties(
name="outer_core",
inner_radius=0.19 * radius,
outer_radius=0.55 * radius, # Earth: 3480 km
density=11000 * rho_scale,
vp=10000 * r_scale**0.5,
vs=0, # Liquid
bulk_modulus=1.0e12,
shear_modulus=0,
is_fluid=True
))
# Lower mantle
model.add_layer(LayerProperties(
name="lower_mantle",
inner_radius=0.55 * radius,
outer_radius=0.90 * radius, # Earth: 5700 km
density=5000 * rho_scale,
vp=13000 * r_scale**0.5,
vs=7000 * r_scale**0.5,
bulk_modulus=3.0e11,
shear_modulus=1.5e11,
is_fluid=False
))
# Upper mantle
model.add_layer(LayerProperties(
name="upper_mantle",
inner_radius=0.90 * radius,
outer_radius=0.99 * radius,
density=3500 * rho_scale,
vp=8000 * r_scale**0.5,
vs=4500 * r_scale**0.5,
bulk_modulus=1.3e11,
shear_modulus=6.0e10,
is_fluid=False
))
# Crust
model.add_layer(LayerProperties(
name="crust",
inner_radius=0.99 * radius,
outer_radius=radius,
density=2800 * rho_scale,
vp=6500 * r_scale**0.5,
vs=3500 * r_scale**0.5,
bulk_modulus=7.5e10,
shear_modulus=3.0e10,
is_fluid=False
))
return model
@classmethod
def create_super_earth(cls,
radius: float = 1.5e7, # ~2.3 Earth radii
mass: float = 5e25) -> 'PlanetaryModel':
"""Create super-Earth model."""
return cls.create_earth_like(radius, mass)
@classmethod
def create_gas_giant(cls,
radius: float = 7.0e7, # ~Jupiter radius
mass: float = 1.9e27) -> 'PlanetaryModel':
"""Create gas giant model."""
model = cls(radius, mass, "Gas Giant")
# Dense core
model.add_layer(LayerProperties(
name="core",
inner_radius=0,
outer_radius=0.1 * radius,
density=25000,
vp=10000,
vs=5000,
bulk_modulus=5e12,
shear_modulus=3e12,
is_fluid=False
))
# Metallic hydrogen layer
def metallic_h_density(r):
r_norm = r / radius
return 25000 * np.exp(-5 * r_norm)
model.add_layer(LayerProperties(
name="metallic_hydrogen",
inner_radius=0.1 * radius,
outer_radius=0.7 * radius,
density=metallic_h_density,
vp=5000,
vs=0, # Fluid
bulk_modulus=2e12,
shear_modulus=0,
is_fluid=True
))
# Molecular hydrogen envelope
def molecular_h_density(r):
r_norm = r / radius
return 1000 * np.exp(-3 * (r_norm - 0.7))
model.add_layer(LayerProperties(
name="molecular_hydrogen",
inner_radius=0.7 * radius,
outer_radius=radius,
density=molecular_h_density,
vp=2000,
vs=0,
bulk_modulus=1e10,
shear_modulus=0,
is_fluid=True
))
return model
def plot_structure(self, ax=None, figsize=(12, 8)):
"""Plot planetary structure."""
if ax is not None:
fig = None
else:
fig, axes = plt.subplots(2, 3, figsize=figsize)
axes = axes.flatten()
r_normalized = self.r_grid / 1000 # Convert to km
# Plot density
axes[0].plot(self.density, r_normalized, 'b-', linewidth=2)
axes[0].set_xlabel('Density (kg/m³)')
axes[0].set_ylabel('Radius (km)')
axes[0].set_title('Density Profile')
axes[0].grid(True, alpha=0.3)
# Plot velocities
axes[1].plot(self.vp/1000, r_normalized, 'r-', linewidth=2, label='Vp')
axes[1].plot(self.vs/1000, r_normalized, 'g-', linewidth=2, label='Vs')
axes[1].set_xlabel('Velocity (km/s)')
axes[1].set_ylabel('Radius (km)')
axes[1].set_title('Seismic Velocities')
axes[1].legend()
axes[1].grid(True, alpha=0.3)
# Plot gravity
axes[2].plot(self.gravity, r_normalized, 'purple', linewidth=2)
axes[2].set_xlabel('Gravity (m/s²)')
axes[2].set_ylabel('Radius (km)')
axes[2].set_title('Gravity Profile')
axes[2].grid(True, alpha=0.3)
# Plot pressure
axes[3].plot(self.pressure/1e9, r_normalized, 'orange', linewidth=2)
axes[3].set_xlabel('Pressure (GPa)')
axes[3].set_ylabel('Radius (km)')
axes[3].set_title('Pressure Profile')
axes[3].grid(True, alpha=0.3)
# Plot bulk and shear moduli
axes[4].plot(self.bulk_modulus/1e11, r_normalized, 'c-', linewidth=2, label='K')
axes[4].plot(self.shear_modulus/1e11, r_normalized, 'm-', linewidth=2, label='μ')
axes[4].set_xlabel('Modulus (×10¹¹ Pa)')
axes[4].set_ylabel('Radius (km)')
axes[4].set_title('Elastic Moduli')
axes[4].legend()
axes[4].grid(True, alpha=0.3)
# Schematic cross-section
theta = np.linspace(0, 2*PI, 100)
colors = ['darkred', 'orange', 'yellow', 'lightblue', 'brown']
for i, layer in enumerate(self.layers):
r_out = layer.outer_radius / 1000
r_in = layer.inner_radius / 1000
# Outer circle
x = r_out * np.cos(theta)
y = r_out * np.sin(theta)
axes[5].fill(x, y, color=colors[i % len(colors)], alpha=0.7)
axes[5].set_xlim(-self.radius/1000, self.radius/1000)
axes[5].set_ylim(-self.radius/1000, self.radius/1000)
axes[5].set_aspect('equal')
axes[5].set_title('Cross-section')
plt.tight_layout()
return fig if fig else None
# ============================================================================
# NORMAL MODE CALCULATOR
# ============================================================================
class NormalModeCalculator:
"""
Computes normal modes (free oscillations) of a planetary model.
Implements spheroidal and toroidal mode calculations.
"""
def __init__(self, model: PlanetaryModel, l_max: int = 50, n_max: int = 10):
"""
Initialize normal mode calculator.
Args:
model: Planetary model
l_max: Maximum angular order
n_max: Maximum radial order
"""
self.model = model
self.l_max = l_max
self.n_max = n_max
self.modes: List[NormalMode] = []
# Grid for eigenfunction calculation
self.nr = model.nr
self.r = model.r_grid
def compute_spheroidal_modes(self, l_values: List[int] = None) -> List[NormalMode]:
"""
Compute spheroidal modes for given angular orders.
Spheroidal modes involve radial and longitudinal motion
and are sensitive to P-wave and S-wave velocity structure.
The equations of motion lead to:
dU/dr = f₁(U, V, r, l, ω)
dV/dr = f₂(U, V, r, l, ω)
where U is radial and V is horizontal displacement.
"""
if l_values is None:
l_values = range(0, min(self.l_max + 1, 50))
modes = []
for l in l_values:
if l < 1:
continue # Skip l=0 (radial modes handled separately)
# Find eigenfrequencies using shooting method
freqs = self._find_spheroidal_eigenfrequencies(l)
for n, freq in enumerate(freqs[:self.n_max]):
# Compute eigenfunction
eigenfunction = self._compute_spheroidal_eigenfunction(l, freq)
# Estimate Q factor (simplified)
Q = self._estimate_quality_factor(l, n, freq)
mode = NormalMode(
n=n,
l=l,
m=0, # Degenerate in m for spherically symmetric
frequency=freq,
quality_factor=Q,
eigenfunction=eigenfunction,
mode_type='spheroidal'
)
modes.append(mode)
self.modes.extend(modes)
return modes
def compute_toroidal_modes(self, l_values: List[int] = None) -> List[NormalMode]:
"""
Compute toroidal modes for given angular orders.
Toroidal modes involve purely horizontal motion
and are only sensitive to S-wave velocity structure.
They don't exist in fluid layers.
"""
if l_values is None:
l_values = range(1, min(self.l_max + 1, 50))
modes = []
for l in l_values:
# Find eigenfrequencies
freqs = self._find_toroidal_eigenfrequencies(l)
for n, freq in enumerate(freqs[:self.n_max]):
# Compute eigenfunction
eigenfunction = self._compute_toroidal_eigenfunction(l, freq)
Q = self._estimate_quality_factor(l, n, freq)
mode = NormalMode(
n=n,
l=l,
m=0,
frequency=freq,
quality_factor=Q,
eigenfunction=eigenfunction,
mode_type='toroidal'
)
modes.append(mode)
self.modes.extend(modes)
return modes
def _find_spheroidal_eigenfrequencies(self, l: int) -> List[float]:
"""
Find spheroidal mode eigenfrequencies using variational approach.
The eigenfrequency satisfies the Rayleigh quotient:
ω² = ∫(λ|∇·u|² + 2μ|ε|²) dV / ∫ρ|u|² dV
"""
# Initial frequency estimates based on travel time
R = self.model.radius
# Phase velocity for mode (approximate)
vp_avg = np.mean(self.model.vp[self.model.vp > 0])
vs_avg = np.mean(self.model.vs[self.model.vs > 0])
# Estimate fundamental mode frequency
c_spheroidal = np.sqrt((l * (l + 1)) / (l * (l + 1) + 2)) * vs_avg
# Search range
f_min = c_spheroidal / (2 * PI * R) * 0.5
f_max = (l + 1) * vs_avg / R * 2
frequencies = []
# Use grid search + refinement
f_grid = np.linspace(f_min, f_max, 100)
for n in range(self.n_max):
# Find nth root
f = self._refine_frequency(l, f_min + n * (f_max - f_min) / self.n_max, 'spheroidal')
if f > 0:
frequencies.append(f)
return frequencies
def _find_toroidal_eigenfrequencies(self, l: int) -> List[float]:
"""Find toroidal mode eigenfrequencies."""
R = self.model.radius
vs_avg = np.mean(self.model.vs[self.model.vs > 0])
if vs_avg == 0:
return []
# Toroidal modes: phase velocity ≈ vs
# Frequency ≈ vs * sqrt(l(l+1)) / R
frequencies = []
for n in range(self.n_max):
# Approximate frequency
f_approx = vs_avg * np.sqrt(l * (l + 1)) / (2 * PI * R) * (1 + n)
f = self._refine_frequency(l, f_approx, 'toroidal')
if f > 0:
frequencies.append(f)
return frequencies
def _refine_frequency(self, l: int, f_initial: float, mode_type: str) -> float:
"""Refine frequency estimate using boundary value problem."""
# Solve the eigenvalue problem using finite differences
nr = len(self.r)
dr = self.r[1] - self.r[0]
# Get material properties
rho = self.model.density
mu = self.model.shear_modulus
if mode_type == 'spheroidal':
kappa = self.model.bulk_modulus
else:
kappa = np.zeros_like(mu)
# Build stiffness and mass matrices
omega_initial = 2 * PI * f_initial
# Use perturbation approach
def residual(omega):
return self._compute_boundary_residual(l, omega, mode_type)
# Newton-Raphson iteration
omega = omega_initial
for _ in range(20):
res = residual(omega)
if abs(res) < 1e-10:
break
# Numerical derivative
d_omega = omega * 1e-6
d_res = (residual(omega + d_omega) - residual(omega - d_omega)) / (2 * d_omega)
if abs(d_res) > 1e-20:
omega = omega - res / d_res
else:
break
return omega / (2 * PI) if omega > 0 else 0.0
def _compute_boundary_residual(self, l: int, omega: float, mode_type: str) -> float:
"""Compute residual at boundary for given angular frequency."""
nr = len(self.r)
dr = self.r[1] - self.r[0]
# Get properties
rho = self.model.density
mu = self.model.shear_modulus
if mode_type == 'spheroidal':
kappa = self.model.bulk_modulus
# Simplified 2nd order ODE for radial displacement
# At surface: stress = 0
# Integrate from center outward
U = np.zeros(nr) # Radial displacement
V = np.zeros(nr) # Tangential displacement
# Regularity at center
U[0] = 1.0
V[0] = 0.0
for i in range(1, nr):
r = self.r[i]
# Avoid division by zero
if r < dr:
r = dr
# Coefficients
eta = kappa[i] + 4/3 * mu[i]
# Simple forward integration (Euler method)
dUdr = -2 * U[i-1] / r + l * (l + 1) * V[i-1] / r
dVdr = -U[i-1] / r + V[i-1] / r
# Apply wave equation terms
if mu[i] > 0:
dUdr += omega**2 * rho[i] * U[i-1] / eta
dVdr += omega**2 * rho[i] * V[i-1] / mu[i]
U[i] = U[i-1] + dUdr * dr
V[i] = V[i-1] + dVdr * dr
# Residual: stress at surface should be zero
residual = U[-1] # Simplified
else: # toroidal
W = np.zeros(nr) # Toroidal displacement
W[0] = 0.0
W[1] = 1.0
for i in range(2, nr):
r = self.r[i]
if r < dr:
r = dr
# Wave equation for toroidal modes
if mu[i] > 0:
d2Wdr2 = -2/r * (W[i-1] - W[i-2]) / dr + \
(l * (l + 1) / r**2 - omega**2 * rho[i] / mu[i]) * W[i-1]
W[i] = 2 * W[i-1] - W[i-2] + d2Wdr2 * dr**2
else:
W[i] = W[i-1]
residual = W[-1]
return residual
def _compute_spheroidal_eigenfunction(self, l: int, freq: float) -> np.ndarray:
"""Compute radial eigenfunction for spheroidal mode."""
omega = 2 * PI * freq
nr = len(self.r)
dr = self.r[1] - self.r[0]
# Initialize displacement components
U = np.zeros(nr) # Radial
V = np.zeros(nr) # Tangential
# Regular boundary conditions at center
U[0] = 1.0
U[1] = 1.0
V[0] = 0.0
V[1] = 0.1
rho = self.model.density
mu = self.model.shear_modulus
kappa = self.model.bulk_modulus
for i in range(2, nr):
r = self.r[i]
if r < dr:
r = dr
# Material properties at this radius
rho_i = rho[i]
mu_i = mu[i]
kappa_i = kappa[i]
# Spheroidal mode equations (simplified)
eta = kappa_i + 4/3 * mu_i
# Second derivatives
d2U = -omega**2 * rho_i * U[i-1] / eta
d2V = -omega**2 * rho_i * V[i-1] / max(mu_i, 1e-10)
# Update using finite differences
U[i] = 2 * U[i-1] - U[i-2] + d2U * dr**2
V[i] = 2 * V[i-1] - V[i-2] + d2V * dr**2
# Normalize
norm = np.sqrt(np.trapz(U**2 + V**2, self.r))
if norm > 0:
U /= norm
V /= norm
return np.column_stack([U, V])
def _compute_toroidal_eigenfunction(self, l: int, freq: float) -> np.ndarray:
"""Compute radial eigenfunction for toroidal mode."""
omega = 2 * PI * freq
nr = len(self.r)
dr = self.r[1] - self.r[0]
W = np.zeros(nr) # Toroidal displacement
# Boundary conditions
W[0] = 0.0
W[1] = 1.0
rho = self.model.density
mu = self.model.shear_modulus
for i in range(2, nr):
r = self.r[i]
if r < dr:
r = dr
rho_i = rho[i]
mu_i = mu[i]
if mu_i > 0:
d2W = -omega**2 * rho_i * W[i-1] / mu_i
W[i] = 2 * W[i-1] - W[i-2] + d2W * dr**2
else:
W[i] = W[i-1]
# Normalize
norm = np.sqrt(np.trapz(W**2, self.r))
if norm > 0:
W /= norm
return W
def _estimate_quality_factor(self, l: int, n: int, freq: float) -> float:
"""
Estimate quality factor Q for a mode.
Q represents energy dissipation per cycle.
Typical values:
- Earth: Q ~ 100-1000 for mantle modes
- Higher Q = less attenuation
"""
# Simplified model based on mode type and frequency
# In reality, Q depends on temperature, grain size, melt fraction, etc.
Q_base = 300 # Base Q value
# Frequency dependence (higher freq = higher Q generally)
f_ref = 1e-3 # Reference frequency
Q = Q_base * (freq / f_ref)**0.2
# Radial order dependence (fundamental modes have lower Q)
Q *= (1 + 0.5 * n)
return Q
def compute_synthetic_seismogram(self,
source_depth: float,
station_location: Tuple[float, float],
duration: float,
dt: float = 1.0,
include_modes: str = 'all') -> np.ndarray:
"""
Compute synthetic seismogram from normal mode summation.
u(t) = Σ Aₙₗₘ cos(ωₙₗ t + φₙₗₘ) exp(-ωₙₗ t / 2Qₙₗ)
"""
t = np.arange(0, duration, dt)
seismogram = np.zeros_like(t)
source_lat, source_lon = 0.0, 0.0 # Source at equator/prime meridian
station_lat, station_lon = station_location
# Angular distance between source and receiver
cos_delta = (np.sin(np.radians(source_lat)) * np.sin(np.radians(station_lat)) +
np.cos(np.radians(source_lat)) * np.cos(np.radians(station_lat)) *
np.cos(np.radians(station_lon - source_lon)))
delta = np.arccos(np.clip(cos_delta, -1, 1))
for mode in self.modes:
if include_modes == 'spheroidal' and mode.mode_type != 'spheroidal':
continue
if include_modes == 'toroidal' and mode.mode_type != 'toroidal':
continue
omega = 2 * PI * mode.frequency
# Excitation amplitude (depends on source mechanism and location)
# Simplified: assume vertical strike-slip source
A = self._compute_excitation_amplitude(mode, source_depth, delta)
# Phase
phi = 0.0
# Damped oscillation
seismogram += A * np.cos(omega * t + phi) * np.exp(-omega * t / (2 * mode.quality_factor))
return seismogram
def _compute_excitation_amplitude(self, mode: NormalMode,
source_depth: float,
delta: float) -> float:
"""Compute mode excitation amplitude."""
# Simplified excitation model
# Depends on source depth, mechanism, and receiver location
# Find source depth index
r_source = self.model.radius - source_depth
# Eigenfunction at source depth
if mode.mode_type == 'spheroidal':
interp_U = interp1d(self.r, mode.eigenfunction[:, 0],
bounds_error=False, fill_value=0)
interp_V = interp1d(self.r, mode.eigenfunction[:, 1],
bounds_error=False, fill_value=0)
U_source = interp_U(r_source)
V_source = interp_V(r_source)
else:
interp_W = interp1d(self.r, mode.eigenfunction,
bounds_error=False, fill_value=0)
W_source = interp_W(r_source)
U_source = W_source
V_source = 0
# Angular dependence (spherical harmonics)
Pl = lpmv(0, mode.l, np.cos(delta)) # Legendre polynomial
# Amplitude
A = (U_source + V_source) * Pl
# Normalize
A /= np.sqrt(2 * mode.l + 1)
return A
def get_mode_frequencies(self, mode_type: str = 'all') -> Dict[Tuple[int, int], float]:
"""Get dictionary of mode frequencies indexed by (n, l)."""
freqs = {}
for mode in self.modes:
if mode_type == 'all' or mode.mode_type == mode_type:
freqs[(mode.n, mode.l)] = mode.frequency
return freqs
def plot_mode_spectrum(self, ax=None, figsize=(12, 6)):
"""Plot normal mode spectrum."""
if ax is not None:
fig = None
else:
fig, ax = plt.subplots(figsize=figsize)
# Separate spheroidal and toroidal modes
spheroidal = [(m.l, m.frequency * 1000, m.n) for m in self.modes
if m.mode_type == 'spheroidal']
toroidal = [(m.l, m.frequency * 1000, m.n) for m in self.modes
if m.mode_type == 'toroidal']
if spheroidal:
l_s, f_s, n_s = zip(*spheroidal)
scatter1 = ax.scatter(l_s, f_s, c=n_s, cmap='Reds',
label='Spheroidal', marker='o', s=50, alpha=0.7)
if toroidal:
l_t, f_t, n_t = zip(*toroidal)
scatter2 = ax.scatter(l_t, f_t, c=n_t, cmap='Blues',
label='Toroidal', marker='s', s=50, alpha=0.7)
ax.set_xlabel('Angular Order (l)')
ax.set_ylabel('Frequency (mHz)')
ax.set_title('Normal Mode Spectrum')
ax.legend()
ax.grid(True, alpha=0.3)
# Add colorbars
if spheroidal:
plt.colorbar(scatter1, ax=ax, label='Radial Order (n)',
location='right', pad=0.01)
return fig if fig else None
# ============================================================================
# BODY WAVE CALCULATOR
# ============================================================================
class BodyWaveCalculator:
"""
Computes body wave travel times and paths through planetary model.
Implements ray theory for high-frequency seismic waves.
"""
def __init__(self, model: PlanetaryModel):
"""
Initialize body wave calculator.
Args:
model: Planetary model
"""
self.model = model
self.r = model.r_grid
def compute_travel_time(self,
source_depth: float,
distance: float,
phase: str = 'P') -> Tuple[float, np.ndarray]:
"""
Compute travel time for a seismic phase.
Uses ray tracing through the velocity model.
Args:
source_depth: Source depth below surface (m)
distance: Epicentral distance (radians)
phase: Phase name ('P', 'S', 'PP', 'PKP', etc.)
Returns:
travel_time: Total travel time (s)
ray_path: Array of (r, theta) points along ray
"""
# Source radius
r_source = self.model.radius - source_depth
# Get velocity function
if phase.startswith('P') or phase.startswith('K'):
v_type = 'vp'
else:
v_type = 'vs'
# Ray parameter (constant along ray in spherically symmetric media)
# p = r * sin(i) / v = dT/dΔ
# For direct waves, find ray parameter that gives correct distance
p = self._find_ray_parameter(r_source, distance, v_type)
if p is None:
return np.inf, np.array([])
# Trace ray and compute travel time
travel_time, ray_path = self._trace_ray(r_source, p, distance, v_type)
return travel_time, ray_path
def _find_ray_parameter(self,
r_source: float,
target_distance: float,
v_type: str) -> Optional[float]:
"""
Find ray parameter that produces ray with target distance.
Uses shooting method to find correct takeoff angle.
"""
v_profile = getattr(self.model, v_type)
# Maximum ray parameter (grazing ray at source)
v_source = self.model.get_property_at_radius(r_source, v_type)
if v_source <= 0:
return None
p_max = r_source / v_source
# Minimum ray parameter (vertical ray)
p_min = 0.0
# Binary search for correct ray parameter
tolerance = 1e-6 # radians
for _ in range(50):
p_try = (p_max + p_min) / 2
distance = self._compute_ray_distance(r_source, p_try, v_type)
if abs(distance - target_distance) < tolerance:
return p_try
elif distance > target_distance:
p_min = p_try
else:
p_max = p_try
return (p_max + p_min) / 2
def _compute_ray_distance(self, r_source: float, p: float, v_type: str) -> float:
"""
Compute total angular distance traveled by ray.
Δ = ∫(p * v / (r * √(1 - (p * v / r)²))) dr
"""
if p == 0:
return 0.0
# Find turning point where r/v = p
v_profile = getattr(self.model, v_type)
# Find minimum depth ray reaches
turning_radius = self._find_turning_radius(p, v_type)
if turning_radius is None:
return 0.0
# Integrate from source to turning point and back
# Using trapezoidal rule
# Downward leg
r_points = np.linspace(r_source, turning_radius, 100)
integrand = np.zeros(len(r_points))
for i, r in enumerate(r_points):
v = self.model.get_property_at_radius(r, v_type)
if v > 0:
sin_i = p * v / r
if abs(sin_i) < 1:
integrand[i] = p * v / (r * np.sqrt(1 - sin_i**2))
delta_down = np.trapz(integrand, r_points)
# Total distance = 2 * downward distance
return 2 * delta_down
def _find_turning_radius(self, p: float, v_type: str) -> Optional[float]:
"""Find radius where ray turns (r/v = p)."""
r = self.r
v = getattr(self.model, v_type)
# Find where r/v crosses p
slowness = r / np.maximum(v, 1e-10)
# Find minimum slowness
min_idx = np.argmin(slowness)
if slowness[min_idx] > p:
# Ray doesn't turn (p too small)
return self.r[min_idx]
# Find crossing point
for i in range(len(r) - 1):
if slowness[i] >= p >= slowness[i+1]:
# Linear interpolation
t = (p - slowness[i]) / (slowness[i+1] - slowness[i])
return r[i] + t * (r[i+1] - r[i])
return r[-1] # Surface
def _trace_ray(self,
r_source: float,
p: float,
target_distance: float,
v_type: str) -> Tuple[float, np.ndarray]:
"""
Trace ray path and compute travel time.
T = ∫(1 / (v * √(1 - (p * v / r)²))) dr
"""
if p == 0:
# Vertical ray
v_surface = self.model.get_property_at_radius(self.model.radius, v_type)
return (r_source - 0) / max(v_surface, 1), np.array([[r_source, 0], [0, 0]])
turning_radius = self._find_turning_radius(p, v_type)
# Build ray path
r_path = np.linspace(r_source, turning_radius, 200)
r_path = np.concatenate([r_path, r_path[-2::-1]]) # Symmetric path
theta_path = np.zeros(len(r_path))
travel_time = 0.0
v = getattr(self.model, v_type)
for i in range(1, len(r_path)):
r = r_path[i]
r_prev = r_path[i-1]
dr = r - r_prev
v_r = self.model.get_property_at_radius(r, v_type)
v_prev = self.model.get_property_at_radius(r_prev, v_type)
if v_r > 0 and v_prev > 0:
# Angular increment
sin_i = p * v_r / r
if abs(sin_i) < 1:
dtheta = p * v_r / (r * np.sqrt(1 - sin_i**2)) * abs(dr)
theta_path[i] = theta_path[i-1] + dtheta
# Time increment
dt = abs(dr) / (v_r * np.sqrt(1 - sin_i**2))
travel_time += dt
else:
theta_path[i] = theta_path[i-1]
else:
theta_path[i] = theta_path[i-1]
# Scale to target distance
if theta_path[-1] > 0:
scale = target_distance / theta_path[-1]
theta_path *= scale
ray_path = np.column_stack([r_path, theta_path])
return travel_time, ray_path
def compute_tau_p_transform(self,
source_depth: float,
max_distance: float = PI,
n_distances: int = 100) -> Dict[str, np.ndarray]:
"""
Compute τ(p) transform (intercept time vs ray parameter).
τ(p) = T(p) - p * Δ(p)
This is useful for identifying triplications and discontinuities.
"""
distances = np.linspace(0.01, max_distance, n_distances)
results = {
'distance': distances,
'P_time': np.zeros(n_distances),
'S_time': np.zeros(n_distances),
'P_ray_param': np.zeros(n_distances),
'S_ray_param': np.zeros(n_distances)
}
for i, dist in enumerate(distances):
# P wave
t_P, _ = self.compute_travel_time(source_depth, dist, 'P')
p_P = self._find_ray_parameter(self.model.radius - source_depth, dist, 'vp')
results['P_time'][i] = t_P
results['P_ray_param'][i] = p_P if p_P else 0
# S wave
t_S, _ = self.compute_travel_time(source_depth, dist, 'S')
p_S = self._find_ray_parameter(self.model.radius - source_depth, dist, 'vs')
results['S_time'][i] = t_S
results['S_ray_param'][i] = p_S if p_S else 0
return results
def compute_dispersion_curves(self,
source_depth: float,
frequencies: np.ndarray = None) -> Dict[str, np.ndarray]:
"""
Compute surface wave dispersion curves.
Phase and group velocity as function of frequency/period.
"""
if frequencies is None:
frequencies = np.logspace(-4, -1, 50) # 0.1 mHz to 10 mHz
# Simplified dispersion calculation
# Using approximate formulas for Rayleigh and Love waves
periods = 1 / frequencies
results = {
'frequency': frequencies,
'period': periods,
'rayleigh_phase_vel': np.zeros_like(frequencies),
'rayleigh_group_vel': np.zeros_like(frequencies),
'love_phase_vel': np.zeros_like(frequencies),
'love_group_vel': np.zeros_like(frequencies)
}
for i, f in enumerate(frequencies):
# Wavelength
wavelength = self.model.vs[int(0.9 * self.model.nr)] / f
# Average velocity over penetration depth
penetration = min(wavelength / 2, self.model.radius * 0.3)
r_min = self.model.radius - penetration
mask = self.model.r_grid >= r_min
vs_avg = np.mean(self.model.vs[mask])
vp_avg = np.mean(self.model.vp[mask])
# Rayleigh wave velocity ≈ 0.92 * Vs
results['rayleigh_phase_vel'][i] = 0.92 * vs_avg
# Love wave velocity ≈ Vs
results['love_phase_vel'][i] = vs_avg
# Group velocity (simplified: equal to phase velocity)
results['rayleigh_group_vel'][i] = 0.92 * vs_avg
results['love_group_vel'][i] = vs_avg
return results
def plot_travel_time_curves(self,
source_depth: float = 0,
ax=None,
figsize=(10, 8)):
"""Plot travel time curves for P and S waves."""
if ax is not None:
fig = None
else:
fig, ax = plt.subplots(figsize=figsize)
distances = np.linspace(0.01, PI, 50)
P_times = []
S_times = []
for dist in distances:
t_P, _ = self.compute_travel_time(source_depth, dist, 'P')
t_S, _ = self.compute_travel_time(source_depth, dist, 'S')
P_times.append(t_P)
S_times.append(t_S)
ax.plot(np.degrees(distances), P_times, 'b-', linewidth=2, label='P')
ax.plot(np.degrees(distances), S_times, 'r-', linewidth=2, label='S')
ax.set_xlabel('Epicentral Distance (degrees)')
ax.set_ylabel('Travel Time (s)')
ax.set_title(f'Travel Time Curves (Source Depth: {source_depth/1000:.0f} km)')
ax.legend()
ax.grid(True, alpha=0.3)
return fig if fig else None
# ============================================================================
# MACHINE LEARNING MODULES
# ============================================================================
class SeismicDataset(Dataset):
"""
PyTorch Dataset for seismic data.
"""
def __init__(self,
features: np.ndarray,
targets: np.ndarray,
transform=None):
"""
Args:
features: Input features (e.g., seismograms, spectra)
targets: Target values (e.g., layer thicknesses, velocities)
transform: Optional transform to apply
"""
self.features = torch.FloatTensor(features)
self.targets = torch.FloatTensor(targets)
self.transform = transform
def __len__(self):
return len(self.features)
def __getitem__(self, idx):
if self.transform:
return self.transform(self.features[idx]), self.targets[idx]
return self.features[idx], self.targets[idx]
class SeismicEncoder(nn.Module):
"""
Neural network encoder for seismic data.
Uses 1D convolutions followed by attention mechanism.
"""
def __init__(self,
input_length: int,
latent_dim: int = 256,
num_channels: int = 1):
super().__init__()
# Convolutional layers
self.conv1 = nn.Conv1d(num_channels, 32, kernel_size=7, padding=3)
self.conv2 = nn.Conv1d(32, 64, kernel_size=5, padding=2)
self.conv3 = nn.Conv1d(64, 128, kernel_size=3, padding=1)
self.conv4 = nn.Conv1d(128, 256, kernel_size=3, padding=1)
self.pool = nn.MaxPool1d(2)
self.dropout = nn.Dropout(0.2)
# Calculate flattened size after convolutions
conv_output_size = input_length // 16 # 4 pooling layers
# Attention mechanism
self.attention = nn.MultiheadAttention(256, num_heads=8, batch_first=True)
# Fully connected layers
self.fc1 = nn.Linear(256 * conv_output_size, 512)
self.fc2 = nn.Linear(512, latent_dim)
def forward(self, x):
# x shape: (batch, channels, length)
# Convolutional feature extraction
x = F.relu(self.conv1(x))
x = self.pool(x)
x = self.dropout(x)
x = F.relu(self.conv2(x))
x = self.pool(x)
x = self.dropout(x)
x = F.relu(self.conv3(x))
x = self.pool(x)
x = self.dropout(x)
x = F.relu(self.conv4(x))
x = self.pool(x)
# Reshape for attention: (batch, seq_len, features)
batch_size = x.shape[0]
x = x.permute(0, 2, 1) # (batch, seq_len, channels)
# Self-attention
x, _ = self.attention(x, x, x)
# Flatten
x = x.reshape(batch_size, -1)
# Fully connected
x = F.relu(self.fc1(x))
x = self.dropout(x)
x = self.fc2(x)
return x
class PlanetaryDecoder(nn.Module):
"""
Decoder network that maps latent space to planetary parameters.
"""
def __init__(self,
latent_dim: int = 256,
num_layers: int = 5,
params_per_layer: int = 4):
super().__init__()
self.num_layers = num_layers
self.params_per_layer = params_per_layer
output_dim = num_layers * params_per_layer
self.fc1 = nn.Linear(latent_dim, 512)
self.fc2 = nn.Linear(512, 256)
self.fc3 = nn.Linear(256, output_dim)
# Separate outputs for different parameter types
self.thickness_head = nn.Linear(256, num_layers)
self.density_head = nn.Linear(256, num_layers)
self.vp_head = nn.Linear(256, num_layers)
self.vs_head = nn.Linear(256, num_layers)
self.dropout = nn.Dropout(0.2)
def forward(self, x):
x = F.relu(self.fc1(x))
x = self.dropout(x)
x = F.relu(self.fc2(x))
# Parameter-specific heads with appropriate activations
thickness = F.softplus(self.thickness_head(x)) # Positive
density = F.softplus(self.density_head(x)) # Positive
vp = F.softplus(self.vp_head(x)) # Positive
vs = F.softplus(self.vs_head(x)) # Positive
# Concatenate outputs
output = torch.cat([thickness, density, vp, vs], dim=-1)
return output
class InversionNetwork(nn.Module):
"""
Full inversion network combining encoder and decoder.
"""
def __init__(self,
input_length: int,
num_planetary_layers: int = 5,
latent_dim: int = 256,
num_seismic_channels: int = 3):
super().__init__()
self.encoder = SeismicEncoder(input_length, latent_dim, num_seismic_channels)
self.decoder = PlanetaryDecoder(latent_dim, num_planetary_layers)
def forward(self, x):
latent = self.encoder(x)
planetary_params = self.decoder(latent)
return planetary_params
class UncertaintyQuantification:
"""
Uncertainty quantification using ensemble and MC dropout.
"""
def __init__(self,
model: nn.Module,
num_samples: int = 100):
"""
Args:
model: Trained neural network model
num_samples: Number of MC samples for uncertainty estimation
"""
self.model = model
self.num_samples = num_samples
def predict_with_uncertainty(self,
x: torch.Tensor) -> Tuple[np.ndarray, np.ndarray]:
"""
Make predictions with uncertainty estimates using MC dropout.
Returns:
mean: Mean prediction
std: Standard deviation (uncertainty)
"""
self.model.train() # Enable dropout
predictions = []
with torch.no_grad():
for _ in range(self.num_samples):
pred = self.model(x)
predictions.append(pred.cpu().numpy())
predictions = np.array(predictions)
mean = np.mean(predictions, axis=0)
std = np.std(predictions, axis=0)
return mean, std
def predict_with_ensemble(self,
models: List[nn.Module],
x: torch.Tensor) -> Tuple[np.ndarray, np.ndarray]:
"""
Make predictions using model ensemble.
"""
predictions = []
for model in models:
model.eval()
with torch.no_grad():
pred = model(x)
predictions.append(pred.cpu().numpy())
predictions = np.array(predictions)
mean = np.mean(predictions, axis=0)
std = np.std(predictions, axis=0)
return mean, std
class DataAugmentation:
"""
Data augmentation techniques for seismic data.
"""
@staticmethod
def add_noise(seismogram: np.ndarray,
noise_level: float = 0.01) -> np.ndarray:
"""Add Gaussian noise."""
noise = np.random.normal(0, noise_level, seismogram.shape)
return seismogram + noise
@staticmethod
def time_shift(seismogram: np.ndarray,
max_shift: int = 10) -> np.ndarray:
"""Random time shift."""
shift = np.random.randint(-max_shift, max_shift + 1)
return np.roll(seismogram, shift, axis=-1)
@staticmethod
def amplitude_scaling(seismogram: np.ndarray,
scale_range: Tuple[float, float] = (0.8, 1.2)) -> np.ndarray:
"""Random amplitude scaling."""
scale = np.random.uniform(*scale_range)
return seismogram * scale
@staticmethod
def frequency_perturbation(seismogram: np.ndarray,
sample_rate: float,
max_freq_shift: float = 0.1) -> np.ndarray:
"""Small frequency shift using phase manipulation."""
fft = np.fft.fft(seismogram)
freqs = np.fft.fftfreq(len(seismogram), 1/sample_rate)
# Random phase shift
phase_shift = np.random.uniform(-max_freq_shift, max_freq_shift, len(fft))
fft_shifted = fft * np.exp(1j * phase_shift)
return np.real(np.fft.ifft(fft_shifted))
# ============================================================================
# INVERSION FRAMEWORK
# ============================================================================
class ForwardModel:
"""
Forward model for computing seismograms from planetary structure.
"""
def __init__(self, model: PlanetaryModel):
self.model = model
self.normal_mode_calc = NormalModeCalculator(model)
self.body_wave_calc = BodyWaveCalculator(model)
def compute_seismogram(self,
source_params: Dict,
receiver_params: Dict,
duration: float = 3600,
dt: float = 1.0) -> np.ndarray:
"""
Compute complete seismogram including body waves and normal modes.
"""
# Initialize output
n_samples = int(duration / dt)
seismogram = np.zeros((3, n_samples)) # Z, R, T components
t = np.arange(n_samples) * dt
# Compute normal modes
if not self.normal_mode_calc.modes:
self.normal_mode_calc.compute_spheroidal_modes(range(1, 30))
self.normal_mode_calc.compute_toroidal_modes(range(1, 30))
# Body wave arrivals (simplified)
distance = receiver_params.get('distance', PI/4)
source_depth = source_params.get('depth', 0)
# P and S wave arrival times
t_P, _ = self.body_wave_calc.compute_travel_time(source_depth, distance, 'P')
t_S, _ = self.body_wave_calc.compute_travel_time(source_depth, distance, 'S')
# Add body wave pulses
for t_arrival, component_idx, amplitude in [(t_P, 0, 1.0), (t_S, 1, 0.8)]:
if t_arrival < duration:
# Ricker wavelet
f0 = 1.0 # Hz
t_rel = t - t_arrival
wavelet = (1 - 2 * (PI * f0 * t_rel)**2) * np.exp(-(PI * f0 * t_rel)**2)
seismogram[component_idx] += amplitude * wavelet
# Add normal modes
for mode in self.normal_mode_calc.modes:
omega = 2 * PI * mode.frequency
# Excitation (simplified)
A = np.random.normal(0, 0.1)
# Damped oscillation
for comp_idx in range(3):
seismogram[comp_idx] += A * np.cos(omega * t) * np.exp(-omega * t / (2 * mode.quality_factor))
return seismogram
def compute_features(self,
seismogram: np.ndarray,
sample_rate: float = 1.0) -> np.ndarray:
"""
Extract features from seismogram for ML input.
"""
features = []
# Frequency spectra
for comp in range(3):
spectrum = np.abs(np.fft.fft(seismogram[comp]))
features.extend(spectrum[:len(spectrum)//2])
# Spectrograms
for comp in range(3):
# Short-time Fourier transform
window_size = 256
hop = 64
n_windows = (len(seismogram[comp]) - window_size) // hop + 1
specgram = np.zeros((window_size // 2, n_windows))
for i in range(n_windows):
start = i * hop
window_data = seismogram[comp, start:start+window_size]
specgram[:, i] = np.abs(np.fft.fft(window_data))[:window_size//2]
# Average spectrogram
features.extend(np.mean(specgram, axis=1))
# Statistical features
for comp in range(3):
features.append(np.mean(seismogram[comp]))
features.append(np.std(seismogram[comp]))
features.append(np.max(np.abs(seismogram[comp])))
features.append(np.argmax(np.abs(seismogram[comp])))
return np.array(features)
class InverseSolver:
"""
Classical inverse problem solver using optimization.
"""
def __init__(self, forward_model: ForwardModel):
self.forward_model = forward_model
self.regularization = 0.01
def solve(self,
observed_data: np.ndarray,
initial_model: PlanetaryModel,
method: str = 'differential_evolution') -> PlanetaryModel:
"""
Solve inverse problem to find best-fit planetary model.
"""
# Parameterize model
param_bounds = self._get_parameter_bounds(initial_model)
def objective(params):
# Update model with new parameters
model = self._params_to_model(params, initial_model)
# Compute forward model
forward_model = ForwardModel(model)
synthetic = forward_model.compute_seismogram(
{'depth': 0}, {'distance': PI/4})
# Compute misfit
misfit = np.sum((synthetic - observed_data)**2)
# Add regularization
misfit += self.regularization * np.sum(params**2)
return misfit
# Solve optimization
if method == 'differential_evolution':
result = differential_evolution(objective, param_bounds, maxiter=100)
else:
result = minimize(objective, self._model_to_params(initial_model),
method='L-BFGS-B', bounds=param_bounds)
return self._params_to_model(result.x, initial_model)
def _get_parameter_bounds(self, model: PlanetaryModel) -> List[Tuple[float, float]]:
"""Get parameter bounds for optimization."""
bounds = []
for layer in model.layers:
# Thickness
thickness = layer.outer_radius - layer.inner_radius
bounds.append((thickness * 0.5, thickness * 1.5))
# Density
bounds.append((layer.density * 0.5, layer.density * 1.5)
if not callable(layer.density) else (1000, 20000))
# Vp
bounds.append((layer.vp * 0.5, layer.vp * 1.5)
if not callable(layer.vp) else (1000, 20000))
# Vs
bounds.append((0, layer.vs * 1.5)
if not callable(layer.vs) else (0, 15000))
return bounds
def _model_to_params(self, model: PlanetaryModel) -> np.ndarray:
"""Convert model to parameter vector."""
params = []
for layer in model.layers:
params.append(layer.outer_radius - layer.inner_radius)
params.append(layer.density if not callable(layer.density) else
np.mean([layer.density(r) for r in
np.linspace(layer.inner_radius, layer.outer_radius, 10)]))
params.append(layer.vp if not callable(layer.vp) else
np.mean([layer.vp(r) for r in
np.linspace(layer.inner_radius, layer.outer_radius, 10)]))
params.append(layer.vs if not callable(layer.vs) else 0)
return np.array(params)
def _params_to_model(self, params: np.ndarray,
template: PlanetaryModel) -> PlanetaryModel:
"""Convert parameter vector to model."""
model = PlanetaryModel(template.radius, template.mass, template.name)
idx = 0
r_inner = 0
for i, layer_template in enumerate(template.layers):
thickness = params[idx]
density = params[idx + 1]
vp = params[idx + 2]
vs = params[idx + 3]
r_outer = min(r_inner + thickness, model.radius)
model.add_layer(LayerProperties(
name=layer_template.name,
inner_radius=r_inner,
outer_radius=r_outer,
density=density,
vp=vp,
vs=vs,
bulk_modulus=layer_template.bulk_modulus,
shear_modulus=layer_template.shear_modulus,
is_fluid=(vs == 0)
))
r_inner = r_outer
idx += 4
return model
class MLInversion:
"""
Machine learning-based inversion framework.
"""
def __init__(self,
model: InversionNetwork,
device: str = 'cuda' if torch.cuda.is_available() else 'cpu'):
self.model = model.to(device)
self.device = device
self.uq = UncertaintyQuantification(model)
def train(self,
train_loader: DataLoader,
val_loader: DataLoader,
num_epochs: int = 100,
learning_rate: float = 1e-4):
"""Train the inversion network."""
optimizer = torch.optim.Adam(self.model.parameters(), lr=learning_rate)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
optimizer, mode='min', factor=0.5, patience=10)
criterion = nn.MSELoss()
train_losses = []
val_losses = []
for epoch in range(num_epochs):
# Training
self.model.train()
train_loss = 0.0
for batch_features, batch_targets in train_loader:
batch_features = batch_features.to(self.device)
batch_targets = batch_targets.to(self.device)
optimizer.zero_grad()
outputs = self.model(batch_features)
loss = criterion(outputs, batch_targets)
loss.backward()
optimizer.step()
train_loss += loss.item()
train_loss /= len(train_loader)
train_losses.append(train_loss)
# Validation
self.model.eval()
val_loss = 0.0
with torch.no_grad():
for batch_features, batch_targets in val_loader:
batch_features = batch_features.to(self.device)
batch_targets = batch_targets.to(self.device)
outputs = self.model(batch_features)
loss = criterion(outputs, batch_targets)
val_loss += loss.item()
val_loss /= len(val_loader)
val_losses.append(val_loss)
scheduler.step(val_loss)
if (epoch + 1) % 10 == 0:
print(f"Epoch {epoch+1}/{num_epochs}: "
f"Train Loss = {train_loss:.6f}, Val Loss = {val_loss:.6f}")
return train_losses, val_losses
def predict(self, seismogram: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
"""
Make prediction with uncertainty quantification.
Args:
seismogram: Input seismogram (3 components)
Returns:
mean_params: Mean predicted parameters
uncertainty: Parameter uncertainties
"""
# Prepare input
if seismogram.ndim == 2:
seismogram = seismogram[np.newaxis, ...]
x = torch.FloatTensor(seismogram).to(self.device)
# Predict with uncertainty
mean, std = self.uq.predict_with_uncertainty(x)
return mean[0], std[0]
def save(self, path: str):
"""Save model weights."""
torch.save(self.model.state_dict(), path)
def load(self, path: str):
"""Load model weights."""
self.model.load_state_dict(torch.load(path, map_location=self.device))
# ============================================================================
# COMPLETE TOOLKIT CLASS
# ============================================================================
class PlanetarySeismologyToolkit:
"""
Main toolkit class that integrates all components.
"""
def __init__(self,
planet_model: PlanetaryModel = None,
device: str = 'cuda' if torch.cuda.is_available() else 'cpu'):
"""
Initialize the planetary seismology toolkit.
Args:
planet_model: Initial planetary model (optional)
device: Computation device for ML
"""
self.device = device
self.planet_model = planet_model
if planet_model is not None:
self.normal_modes = NormalModeCalculator(planet_model)
self.body_waves = BodyWaveCalculator(planet_model)
self.forward_model = ForwardModel(planet_model)
else:
self.normal_modes = None
self.body_waves = None
self.forward_model = None
self.ml_model = None
self.ml_inversion = None
def set_planet_model(self, model: PlanetaryModel):
"""Set or update the planetary model."""
self.planet_model = model
self.normal_modes = NormalModeCalculator(model)
self.body_waves = BodyWaveCalculator(model)
self.forward_model = ForwardModel(model)
def compute_normal_modes(self, l_max: int = 30, n_max: int = 5) -> List[NormalMode]:
"""Compute normal modes of the planet."""
if self.normal_modes is None:
raise ValueError("No planetary model set")
self.normal_modes.compute_spheroidal_modes(range(1, l_max + 1))
self.normal_modes.compute_toroidal_modes(range(1, l_max + 1))
return self.normal_modes.modes
def compute_body_wave_travel_times(self,
source_depth: float = 0,
phases: List[str] = ['P', 'S']) -> Dict:
"""Compute body wave travel times."""
if self.body_waves is None:
raise ValueError("No planetary model set")
results = self.body_waves.compute_tau_p_transform(source_depth)
return results
def generate_synthetic_data(self,
n_samples: int = 1000,
add_noise: bool = True,
noise_level: float = 0.01) -> Tuple[np.ndarray, np.ndarray]:
"""
Generate synthetic dataset for training ML model.
Returns:
features: Seismogram features
targets: Planetary parameters
"""
features = []
targets = []
for i in range(n_samples):
# Random planetary model
base_model = PlanetaryModel.create_earth_like(
radius=6e6 + np.random.uniform(-1e6, 2e6),
mass=5e24 + np.random.uniform(-1e24, 3e24)
)
# Perturb layer properties
for layer in base_model.layers:
layer.density *= np.random.uniform(0.9, 1.1)
layer.vp *= np.random.uniform(0.9, 1.1)
layer.vs *= np.random.uniform(0.9, 1.1)
base_model._update_properties()
# Compute forward model
forward = ForwardModel(base_model)
seismogram = forward.compute_seismogram(
{'depth': 0}, {'distance': PI/4}, duration=3600, dt=1.0)
# Add noise
if add_noise:
seismogram = DataAugmentation.add_noise(seismogram, noise_level)
# Extract features
feat = forward.compute_features(seismogram)
features.append(feat)
# Target: layer properties
target = []
for layer in base_model.layers:
target.extend([
(layer.outer_radius - layer.inner_radius) / base_model.radius,
layer.density / 10000,
layer.vp / 10000,
layer.vs / 10000
])
targets.append(target)
if (i + 1) % 100 == 0:
print(f"Generated {i+1}/{n_samples} samples")
return np.array(features), np.array(targets)
def train_ml_inversion(self,
features: np.ndarray,
targets: np.ndarray,
validation_split: float = 0.2,
num_epochs: int = 100,
batch_size: int = 32,
learning_rate: float = 1e-4) -> Dict:
"""
Train the ML inversion model.
Args:
features: Input features (seismograms)
targets: Target planetary parameters
validation_split: Fraction for validation
num_epochs: Number of training epochs
batch_size: Batch size for training
learning_rate: Learning rate
Returns:
training_history: Dictionary with training metrics
"""
# Split data
n_samples = len(features)
n_val = int(n_samples * validation_split)
# Shuffle
indices = np.random.permutation(n_samples)
val_indices = indices[:n_val]
train_indices = indices[n_val:]
# Create datasets
train_dataset = SeismicDataset(features[train_indices], targets[train_indices])
val_dataset = SeismicDataset(features[val_indices], targets[val_indices])
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=batch_size)
# Initialize model
input_length = features.shape[1]
n_layers = targets.shape[1] // 4
self.ml_model = InversionNetwork(
input_length=input_length,
num_planetary_layers=n_layers
).to(self.device)
self.ml_inversion = MLInversion(self.ml_model, self.device)
# Train
train_losses, val_losses = self.ml_inversion.train(
train_loader, val_loader, num_epochs, learning_rate)
return {
'train_losses': train_losses,
'val_losses': val_losses,
'final_train_loss': train_losses[-1],
'final_val_loss': val_losses[-1]
}
def invert_seismogram(self,
seismogram: np.ndarray) -> Dict:
"""
Perform inversion on observed seismogram.
Args:
seismogram: Observed seismogram (3 components)
Returns:
result: Dictionary with estimated parameters and uncertainties
"""
if self.ml_inversion is None:
raise ValueError("ML model not trained. Call train_ml_inversion first.")
# ML-based inversion
ml_params, ml_uncertainty = self.ml_inversion.predict(seismogram)
# Classical inversion for comparison
if self.planet_model is not None:
inverse_solver = InverseSolver(self.forward_model)
classical_model = inverse_solver.solve(seismogram, self.planet_model)
classical_params = inverse_solver._model_to_params(classical_model)
else:
classical_params = None
return {
'ml_parameters': ml_params,
'ml_uncertainty': ml_uncertainty,
'classical_parameters': classical_params,
'seismogram': seismogram
}
def full_analysis(self,
seismogram: np.ndarray,
source_params: Dict = None,
station_params: Dict = None) -> Dict:
"""
Perform complete analysis of seismic data.
Combines normal mode analysis, body wave analysis, and ML inversion.
"""
results = {}
# 1. Normal mode analysis
if self.normal_modes is not None and self.normal_modes.modes:
mode_freqs = self.normal_modes.get_mode_frequencies()
results['normal_modes'] = mode_freqs
# 2. Body wave analysis
if self.body_waves is not None:
travel_times = self.compute_body_wave_travel_times(
source_params.get('depth', 0) if source_params else 0)
results['body_waves'] = travel_times
# 3. ML inversion
if self.ml_inversion is not None:
inversion_result = self.invert_seismogram(seismogram)
results['inversion'] = inversion_result
return results
def visualize_results(self, results: Dict, figsize=(16, 12)):
"""Create comprehensive visualization of analysis results."""
fig = plt.figure(figsize=figsize)
# Create grid for subplots
gs = fig.add_gridspec(3, 3, hspace=0.3, wspace=0.3)
# 1. Seismogram
ax1 = fig.add_subplot(gs[0, :2])
if 'seismogram' in results.get('inversion', {}):
seismogram = results['inversion']['seismogram']
t = np.arange(seismogram.shape[1])
ax1.plot(t, seismogram[0], 'b-', label='Z', alpha=0.8)
ax1.plot(t, seismogram[1], 'r-', label='R', alpha=0.8)
ax1.plot(t, seismogram[2], 'g-', label='T', alpha=0.8)
ax1.set_xlabel('Time (s)')
ax1.set_ylabel('Amplitude')
ax1.set_title('Seismogram')
ax1.legend()
ax1.grid(True, alpha=0.3)
# 2. Normal mode spectrum
ax2 = fig.add_subplot(gs[0, 2])
if self.normal_modes is not None and self.normal_modes.modes:
self.normal_modes.plot_mode_spectrum(ax2)
# 3. Travel time curves
ax3 = fig.add_subplot(gs[1, 0])
if self.body_waves is not None:
self.body_waves.plot_travel_time_curves(ax=ax3)
# 4. Inversion results
ax4 = fig.add_subplot(gs[1, 1:])
if 'inversion' in results:
params = results['inversion']['ml_parameters']
uncertainty = results['inversion']['ml_uncertainty']
n_layers = len(params) // 4
x = np.arange(n_layers)
width = 0.2
# Extract parameters
thicknesses = params[:n_layers]
densities = params[n_layers:2*n_layers]
vps = params[2*n_layers:3*n_layers]
vss = params[3*n_layers:]
ax4.bar(x - 1.5*width, thicknesses, width, label='Thickness (normalized)')
ax4.bar(x - 0.5*width, densities, width, label='Density (normalized)')
ax4.bar(x + 0.5*width, vps, width, label='Vp (normalized)')
ax4.bar(x + 1.5*width, vss, width, label='Vs (normalized)')
ax4.set_xlabel('Layer')
ax4.set_ylabel('Normalized Value')
ax4.set_title('ML Inversion Results')
ax4.legend()
ax4.grid(True, alpha=0.3)
# 5. Planetary structure
ax5 = fig.add_subplot(gs[2, :])
if self.planet_model is not None:
r_km = self.planet_model.r_grid / 1000
ax5_twin = ax5.twinx()
ax5.plot(self.planet_model.density, r_km, 'b-', label='Density', linewidth=2)
ax5_twin.plot(self.planet_model.vp/1000, r_km, 'r--', label='Vp', linewidth=2)
ax5_twin.plot(self.planet_model.vs/1000, r_km, 'g--', label='Vs', linewidth=2)
ax5.set_xlabel('Density (kg/m³)')
ax5_twin.set_xlabel('Velocity (km/s)')
ax5.set_ylabel('Radius (km)')
ax5.set_title('Planetary Structure')
ax5.legend(loc='upper left')
ax5_twin.legend(loc='upper right')
ax5.grid(True, alpha=0.3)
plt.tight_layout()
return fig
# ============================================================================
# EXAMPLE USAGE
# ============================================================================
def main():
"""Example usage of the planetary seismology toolkit."""
print("=" * 60)
print("Planetary Seismology Inversion Toolkit")
print("=" * 60)
# 1. Create planetary model
print("\n1. Creating Earth-like planetary model...")
earth_model = PlanetaryModel.create_earth_like()
print(f" Radius: {earth_model.radius/1000:.0f} km")
print(f" Mass: {earth_model.mass:.3e} kg")
print(f" Mean density: {earth_model.compute_mean_density():.0f} kg/m³")
print(f" MOI factor: {earth_model.compute_moi_factor():.4f}")
# 2. Initialize toolkit
print("\n2. Initializing toolkit...")
toolkit = PlanetarySeismologyToolkit(earth_model)
# 3. Compute normal modes
print("\n3. Computing normal modes...")
modes = toolkit.compute_normal_modes(l_max=20, n_max=3)
print(f" Found {len(modes)} modes")
if modes:
print(f" Fundamental spheroidal mode (l=2): {modes[0].frequency*1000:.3f} mHz")
# 4. Compute body wave travel times
print("\n4. Computing body wave travel times...")
tt_results = toolkit.compute_body_wave_travel_times()
print(f" P-wave at 90°: {tt_results['P_time'][25]:.0f} s")
print(f" S-wave at 90°: {tt_results['S_time'][25]:.0f} s")
# 5. Generate synthetic training data
print("\n5. Generating synthetic training data...")
features, targets = toolkit.generate_synthetic_data(n_samples=100)
print(f" Features shape: {features.shape}")
print(f" Targets shape: {targets.shape}")
# 6. Train ML model
print("\n6. Training ML inversion model...")
history = toolkit.train_ml_inversion(
features, targets,
num_epochs=20,
batch_size=16
)
print(f" Final training loss: {history['final_train_loss']:.6f}")
print(f" Final validation loss: {history['final_val_loss']:.6f}")
# 7. Test inversion
print("\n7. Testing inversion on synthetic data...")
test_seismogram = toolkit.forward_model.compute_seismogram(
{'depth': 0}, {'distance': PI/4})
result = toolkit.invert_seismogram(test_seismogram)
print("\n ML Inversion Results:")
print(f" Mean uncertainty: {np.mean(result['ml_uncertainty']):.4f}")
# 8. Visualize
print("\n8. Creating visualizations...")
# Plot planetary structure
fig1 = earth_model.plot_structure()
fig1.suptitle("Planetary Model Structure", fontsize=14)
# Plot normal mode spectrum
if toolkit.normal_modes is not None:
fig2 = toolkit.normal_modes.plot_mode_spectrum()
# Plot travel time curves
if toolkit.body_waves is not None:
fig3 = toolkit.body_waves.plot_travel_time_curves()
# Full analysis visualization
results = toolkit.full_analysis(test_seismogram)
fig4 = toolkit.visualize_results(results)
print("\n" + "=" * 60)
print("Analysis complete! Displaying results...")
print("=" * 60)
plt.show()
return toolkit
if __name__ == "__main__":
toolkit = main()
Key Features
1. Normal Modes Module
- Spheroidal and toroidal mode computation
- Eigenfrequency calculation using shooting method
- Quality factor estimation
- Mode summation for synthetic seismograms
2. Body Waves Module
- Ray tracing through layered media
- Travel time calculation
- τ-p transform analysis
- Surface wave dispersion curves
3. Machine Learning Module
- 1D CNN encoder with attention mechanism
- Decoder for planetary parameters
- Uncertainty quantification (MC Dropout)
- Data augmentation techniques
4. Inversion Framework
- Classical optimization-based inversion
- Neural network-based inversion
- Hybrid approach combining both
Physical Principles
-
Normal Modes: Free oscillations characterized by eigenfrequencies ωₙₗ satisfying:
ρω²u = ∇·σ + ρg∇(u·r̂)
-
Body Waves: Ray theory with travel time:
T = ∫(1/v) ds along ray path
-
Inverse Problem: Given seismic observations d, find model m:
d = G(m) + ε
where G is the forward operator and ε is noise.