Create a volcano deformation and gas monitoring joint inversion.
- User
Create a volcano deformation and gas monitoring joint inversion.
Assistant
Create a volcano deformation and gas monitoring joint inversion.
The user wants a joint inversion program for volcano deformation and gas monitoring. This is a geophysical inverse problem where we try to find the source parameters that explain both deformation (like ground displacement) and gas emission observations simultaneously.
Let me think about the physics involved:
Deformation Modeling: Volcanic deformation is often modeled using a Mogi point source or other analytical models. The Mogi model assumes a spherical pressure source in an elastic half-space. The surface displacement is related to the pressure change, source depth, and position.
Gas Monitoring: Volcanic gas emissions (like SO2, CO2) are related to magma degassing. The gas flux can be related to the volume of magma degassing and the pressure conditions.
Physical Laws to Consider:
Mogi Model for Deformation:
Where:
Gas Emission Model:
Simplified model: gas emission rate proportional to pressure change and source volume
Joint Inversion:
Let me create a comprehensive program that:
I'll create a well-structured Python program with:
Let me write this code:
Wait, I have a syntax error in the params_display. Let me fix that.
Also, I should make the code more robust and add more features. Let me revise: Looking at this problem, I need to consider several physical principles:
Here's a comprehensive program that implements this:
This program implements a complete joint inversion system for volcano monitoring with the following features:
Physical Models:
Inversion Methods:
Key Features:
Visualizations:
"""
Volcano Deformation and Gas Monitoring Joint Inversion
=======================================================
This program performs joint inversion of deformation (GPS/InSAR) and
gas emission (SO2/CO2) data to estimate volcanic source parameters.
Physical Models:
1. Mogi point source for deformation (elastic half-space)
2. Pressure-dependent gas emission model
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib.collections import PatchCollection
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.gridspec as gridspec
from scipy.optimize import minimize, differential_evolution
from scipy.stats import norm, uniform
import warnings
warnings.filterwarnings('ignore')
# Physical constants
G_SHEAR = 30e9 # Shear modulus (Pa) - typical for crustal rocks
NU = 0.25 # Poisson's ratio
class MogiSource:
"""
Mogi point source model for volcanic deformation.
Assumes a spherical pressure source in an elastic half-space.
"""
def __init__(self, x0=0, y0=0, depth=5000, radius=500, dP=10e6):
"""
Initialize Mogi source parameters.
Parameters:
-----------
x0, y0 : float
Horizontal position of source (m)
depth : float
Depth to center of source (m)
radius : float
Radius of spherical source (m)
dP : float
Pressure change (Pa)
"""
self.x0 = x0
self.y0 = y0
self.depth = depth
self.radius = radius
self.dP = dP
def compute_displacement(self, x, y):
"""
Compute surface displacement at given points.
Uses the Mogi (1958) analytical solution for a spherical
pressure source in an elastic half-space.
Parameters:
-----------
x, y : arrays
Observation point coordinates (m)
Returns:
--------
ux, uy, uz : arrays
Displacement components (m)
"""
# Relative position
dx = x - self.x0
dy = y - self.y0
# Radial distance from source
r = np.sqrt(dx**2 + dy**2)
R = np.sqrt(r**2 + self.depth**2)
# Mogi source strength (volume change equivalent)
# C = (3 * a³ * ΔP) / (4 * G) for incompressible material
# For compressible: multiply by (1-ν)
C = (3 * self.radius**3 * self.dP * (1 - NU)) / (4 * G_SHEAR)
# Displacement components
ux = C * dx / R**3
uy = C * dy / R**3
uz = C * self.depth / R**3
return ux, uy, uz
def compute_volume_change(self):
"""
Compute the volume change at the source.
Returns:
--------
dV : float
Volume change (m³)
"""
# For Mogi source: dV = π * a³ * ΔP / G * (1-ν)
dV = np.pi * self.radius**3 * self.dP / G_SHEAR * (1 - NU)
return dV
class GasEmissionModel:
"""
Model for volcanic gas emissions based on source parameters.
Gas flux is related to:
1. Magma volume and gas content
2. Pressure-dependent exsolution
3. Degassing efficiency
"""
def __init__(self, base_flux=100, pressure_coeff=1e-7,
solubility_exponent=0.5):
"""
Initialize gas emission model.
Parameters:
-----------
base_flux : float
Background gas flux (t/day)
pressure_coeff : float
Coefficient relating pressure to flux enhancement
solubility_exponent : float
Power law exponent for pressure-solubility relation
"""
self.base_flux = base_flux
self.pressure_coeff = pressure_coeff
self.solubility_exponent = solubility_exponent
def compute_flux(self, pressure_change, source_volume):
"""
Compute gas flux based on pressure and volume.
Physical basis:
- Higher pressure increase → more gas exsolution
- Larger source volume → more magma available for degassing
Parameters:
-----------
pressure_change : float
Pressure change (Pa)
source_volume : float
Source volume (m³)
Returns:
--------
flux : float
Gas flux (t/day)
"""
# Pressure-dependent enhancement factor
# Uses solubility law: C ∝ P^(1/n) for CO2-H2O systems
p_effect = np.abs(pressure_change) ** self.solubility_exponent
# Volume-normalized flux
volume_factor = (source_volume / 1e9) ** 0.5 # Scaled by 1 km³
# Total flux
flux = self.base_flux + self.pressure_coeff * p_effect * volume_factor
# Sign indicates if flux increases or decreases with pressure
if pressure_change < 0:
flux *= 0.7 # Decompression can cause more efficient degassing
return max(flux, 0) # Ensure non-negative
class JointInversion:
"""
Joint inversion of deformation and gas data to estimate
volcanic source parameters.
"""
def __init__(self, n_stations=20, noise_deform=0.005, noise_gas=10):
"""
Initialize the joint inversion problem.
Parameters:
-----------
n_stations : int
Number of GPS stations
noise_deform : float
Noise level for deformation data (m)
noise_gas : float
Noise level for gas data (t/day)
"""
self.n_stations = n_stations
self.noise_deform = noise_deform
self.noise_gas = noise_gas
# True source parameters (for synthetic test)
self.true_params = {
'x0': 500,
'y0': -300,
'depth': 4000,
'radius': 800,
'dP': 15e6,
'base_flux': 150,
'pressure_coeff': 2e-7
}
# Parameter bounds for inversion
self.bounds = {
'x0': (-5000, 5000),
'y0': (-5000, 5000),
'depth': (1000, 10000),
'radius': (100, 2000),
'dP': (1e6, 50e6),
'base_flux': (50, 300),
'pressure_coeff': (1e-8, 1e-6)
}
# Generate synthetic data
self.generate_synthetic_data()
def generate_synthetic_data(self):
"""Generate synthetic observations for testing."""
np.random.seed(42)
# Station positions (distributed around the volcano)
r = np.random.uniform(500, 8000, self.n_stations)
theta = np.random.uniform(0, 2*np.pi, self.n_stations)
self.station_x = r * np.cos(theta)
self.station_y = r * np.sin(theta)
# Create true Mogi source
mogi = MogiSource(
x0=self.true_params['x0'],
y0=self.true_params['y0'],
depth=self.true_params['depth'],
radius=self.true_params['radius'],
dP=self.true_params['dP']
)
# Compute true displacements
ux, uy, uz = mogi.compute_displacement(self.station_x, self.station_y)
# Add noise to deformation data
self.obs_ux = ux + np.random.normal(0, self.noise_deform, self.n_stations)
self.obs_uy = uy + np.random.normal(0, self.noise_deform, self.n_stations)
self.obs_uz = uz + np.random.normal(0, self.noise_deform, self.n_stations)
# Compute true gas flux
gas_model = GasEmissionModel(
base_flux=self.true_params['base_flux'],
pressure_coeff=self.true_params['pressure_coeff']
)
source_volume = (4/3) * np.pi * mogi.radius**3
true_flux = gas_model.compute_flux(mogi.dP, source_volume)
# Gas observations at multiple locations (with spatial variation)
self.gas_station_r = r / 1000 # km
self.obs_gas = np.random.normal(true_flux, self.noise_gas, self.n_stations)
self.obs_gas = np.maximum(self.obs_gas, 10) # Ensure positive
# Store true values for comparison
self.true_ux = ux
self.true_uy = uy
self.true_uz = uz
self.true_flux = true_flux
def forward_model(self, params):
"""
Run forward model with given parameters.
Parameters:
-----------
params : dict or array
Model parameters
Returns:
--------
pred_ux, pred_uy, pred_uz, pred_gas : arrays
Predicted observations
"""
if isinstance(params, np.ndarray):
params = self.array_to_params(params)
# Mogi source
mogi = MogiSource(
x0=params['x0'],
y0=params['y0'],
depth=params['depth'],
radius=params['radius'],
dP=params['dP']
)
# Compute predicted deformation
pred_ux, pred_uy, pred_uz = mogi.compute_displacement(
self.station_x, self.station_y
)
# Compute predicted gas flux
gas_model = GasEmissionModel(
base_flux=params['base_flux'],
pressure_coeff=params['pressure_coeff']
)
source_volume = (4/3) * np.pi * mogi.radius**3
pred_flux = gas_model.compute_flux(mogi.dP, source_volume)
pred_gas = np.full(self.n_stations, pred_flux)
return pred_ux, pred_uy, pred_uz, pred_gas
def misfit(self, params, weight_deform=1.0, weight_gas=1.0):
"""
Compute weighted misfit between observed and predicted data.
Parameters:
-----------
params : array
Model parameters
weight_deform : float
Weight for deformation misfit
weight_gas : float
Weight for gas misfit
Returns:
--------
total_misfit : float
Total weighted misfit
"""
params_dict = self.array_to_params(params)
# Forward model
pred_ux, pred_uy, pred_uz, pred_gas = self.forward_model(params_dict)
# Deformation misfit (normalized)
misfit_ux = np.sum((self.obs_ux - pred_ux)**2) / self.noise_deform**2
misfit_uy = np.sum((self.obs_uy - pred_uy)**2) / self.noise_deform**2
misfit_uz = np.sum((self.obs_uz - pred_uz)**2) / self.noise_deform**2
deform_misfit = (misfit_ux + misfit_uy + misfit_uz) / (3 * self.n_stations)
# Gas misfit (normalized)
gas_misfit = np.sum((self.obs_gas - pred_gas)**2) / (self.noise_gas**2 * self.n_stations)
# Total weighted misfit
total_misfit = weight_deform * deform_misfit + weight_gas * gas_misfit
return total_misfit
def array_to_params(self, array):
"""Convert parameter array to dictionary."""
return {
'x0': array[0],
'y0': array[1],
'depth': array[2],
'radius': array[3],
'dP': array[4],
'base_flux': array[5],
'pressure_coeff': array[6]
}
def params_to_array(self, params):
"""Convert parameter dictionary to array."""
return np.array([
params['x0'],
params['y0'],
params['depth'],
params['radius'],
params['dP'],
params['base_flux'],
params['pressure_coeff']
])
def run_optimization(self, method='differential_evolution'):
"""
Run optimization to find best-fit parameters.
Parameters:
-----------
method : str
Optimization method ('differential_evolution', 'minimize')
Returns:
--------
best_params : dict
Best-fit parameters
result : optimization result object
"""
bounds_list = [
self.bounds['x0'],
self.bounds['y0'],
self.bounds['depth'],
self.bounds['radius'],
self.bounds['dP'],
self.bounds['base_flux'],
self.bounds['pressure_coeff']
]
if method == 'differential_evolution':
result = differential_evolution(
self.misfit,
bounds_list,
seed=42,
maxiter=500,
tol=1e-7,
polish=True,
workers=-1
)
else:
x0 = [500, 0, 5000, 500, 10e6, 100, 1e-7]
result = minimize(
self.misfit,
x0,
method='L-BFGS-B',
bounds=bounds_list
)
best_params = self.array_to_params(result.x)
self.best_params = best_params
return best_params, result
def run_mcmc(self, n_samples=10000, n_burnin=2000):
"""
Run MCMC sampling for uncertainty quantification.
Uses the Metropolis-Hastings algorithm with adaptive step size.
Parameters:
-----------
n_samples : int
Number of MCMC samples
n_burnin : int
Number of burn-in samples to discard
Returns:
--------
chain : array
MCMC chain of shape (n_samples - n_burnin, n_params)
acceptance_rate : float
MCMC acceptance rate
"""
# Initialize
n_params = 7
bounds_list = [
self.bounds['x0'],
self.bounds['y0'],
self.bounds['depth'],
self.bounds['radius'],
self.bounds['dP'],
self.bounds['base_flux'],
self.bounds['pressure_coeff']
]
# Initial state
current = self.params_to_array(self.true_params) * 0.9
current = np.clip(current,
[b[0] for b in bounds_list],
[b[1] for b in bounds_list])
current_misfit = self.misfit(current)
# Step sizes (will be adapted)
step_sizes = np.array([
500, 500, 1000, 200, 5e6, 50, 5e-8
])
# Storage
chain = np.zeros((n_samples, n_params))
accepted = 0
for i in range(n_samples):
# Propose new state
proposal = current + np.random.normal(0, step_sizes)
# Check bounds
in_bounds = all(
bounds_list[j][0] <= proposal[j] <= bounds_list[j][1]
for j in range(n_params)
)
if in_bounds:
proposal_misfit = self.misfit(proposal)
# Metropolis criterion
log_alpha = current_misfit - proposal_misfit
if np.log(np.random.random()) < log_alpha:
current = proposal
current_misfit = proposal_misfit
accepted += 1
chain[i] = current
# Adapt step size
if (i + 1) % 500 == 0 and i < n_burnin:
rate = accepted / (i + 1)
if rate < 0.2:
step_sizes *= 0.8
elif rate > 0.5:
step_sizes *= 1.2
# Remove burn-in
chain = chain[n_burnin:]
acceptance_rate = accepted / n_samples
self.chain = chain
self.acceptance_rate = acceptance_rate
return chain, acceptance_rate
class VolcanoVisualization:
"""
Visualization class for volcano monitoring results.
"""
def __init__(self, inversion):
"""
Initialize visualization.
Parameters:
-----------
inversion : JointInversion
Inversion results to visualize
"""
self.inv = inversion
def plot_deformation_map(self, ax=None, show_stations=True):
"""Plot deformation vectors and contours."""
if ax is None:
fig, ax = plt.subplots(figsize=(10, 8))
# Grid for contours
x = np.linspace(-10000, 10000, 100)
y = np.linspace(-10000, 10000, 100)
X, Y = np.meshgrid(x, y)
# Compute deformation field
mogi = MogiSource(**{k: self.inv.best_params[k]
for k in ['x0', 'y0', 'depth', 'radius', 'dP']})
ux, uy, uz = mogi.compute_displacement(X, Y)
# Vertical displacement contours
levels = np.linspace(uz.min(), uz.max(), 20)
contour = ax.contourf(X, Y, uz, levels=levels, cmap='RdBu_r', alpha=0.7)
plt.colorbar(contour, ax=ax, label='Vertical displacement (m)')
# Horizontal displacement vectors
skip = 8
scale = np.max(np.sqrt(ux**2 + uy**2)) * 20
ax.quiver(X[::skip, ::skip], Y[::skip, ::skip],
ux[::skip, ::skip], uy[::skip, ::skip],
scale=scale, color='black', alpha=0.5)
# Source location
ax.scatter(self.inv.best_params['x0'],
self.inv.best_params['y0'],
marker='*', s=200, c='red',
edgecolors='black', linewidths=1,
label='Source location', zorder=5)
# True source location
ax.scatter(self.inv.true_params['x0'],
self.inv.true_params['y0'],
marker='*', s=200, c='yellow',
edgecolors='black', linewidths=1,
label='True source', zorder=5)
if show_stations:
# Observation stations
ax.scatter(self.inv.station_x, self.inv.station_y,
c='white', edgecolors='black', s=50,
marker='^', label='GPS stations', zorder=4)
ax.set_xlabel('Easting (m)')
ax.set_ylabel('Northing (m)')
ax.set_title('Deformation Field')
ax.legend(loc='upper right')
ax.set_aspect('equal')
ax.grid(True, alpha=0.3)
return ax
def plot_gas_emissions(self, ax=None):
"""Plot gas emission observations and predictions."""
if ax is None:
fig, ax = plt.subplots(figsize=(10, 6))
# Observed gas
ax.scatter(self.inv.gas_station_r, self.inv.obs_gas,
c='blue', s=50, alpha=0.7, label='Observed')
# Predicted gas
pred_ux, pred_uy, pred_uz, pred_gas = self.inv.forward_model(
self.inv.best_params
)
pred_flux = pred_gas[0]
ax.axhline(y=pred_flux, color='red', linestyle='--',
linewidth=2, label=f'Predicted: {pred_flux:.1f} t/day')
ax.axhline(y=self.inv.true_flux, color='green', linestyle=':',
linewidth=2, label=f'True: {self.inv.true_flux:.1f} t/day')
ax.set_xlabel('Distance from vent (km)')
ax.set_ylabel('SO₂ flux (t/day)')
ax.set_title('Gas Emission Observations')
ax.legend()
ax.grid(True, alpha=0.3)
return ax
def plot_mcmc_results(self, chain):
"""Plot MCMC parameter distributions and correlations."""
param_names = ['x₀ (m)', 'y₀ (m)', 'Depth (m)',
'Radius (m)', 'ΔP (MPa)',
'Base flux (t/d)', 'P coeff (×10⁻⁷)']
true_values = [
self.inv.true_params['x0'],
self.inv.true_params['y0'],
self.inv.true_params['depth'],
self.inv.true_params['radius'],
self.inv.true_params['dP'] / 1e6,
self.inv.true_params['base_flux'],
self.inv.true_params['pressure_coeff'] * 1e7
]
# Scale parameters for display
chain_scaled = chain.copy()
chain_scaled[:, 4] /= 1e6 # MPa
chain_scaled[:, 6] *= 1e7 # Scale coefficient
fig, axes = plt.subplots(3, 3, figsize=(12, 12))
# Parameter histograms
for i in range(7):
ax = axes.flat[i]
ax.hist(chain_scaled[:, i], bins=30, density=True,
alpha=0.7, color='steelblue', edgecolor='black')
ax.axvline(true_values[i], color='red', linestyle='--',
linewidth=2, label='True')
ax.axvline(np.median(chain_scaled[:, i]), color='green',
linestyle='-', linewidth=2, label='Median')
ax.set_xlabel(param_names[i])
ax.set_ylabel('Probability density')
ax.legend(fontsize=8)
# Correlation plot (depth vs dP)
ax = axes[2, 1]
ax.scatter(chain_scaled[:, 2], chain_scaled[:, 4],
alpha=0.3, s=5, c='steelblue')
ax.scatter(true_values[2], true_values[4],
c='red', s=100, marker='*', label='True')
ax.set_xlabel(param_names[2])
ax.set_ylabel(param_names[4])
ax.legend()
# Misfit evolution
ax = axes[2, 2]
misfits = [self.inv.misfit(chain[i]) for i in range(0, len(chain), 100)]
ax.plot(misfits, color='steelblue')
ax.set_xlabel('Sample (×100)')
ax.set_ylabel('Misfit')
ax.set_title('Misfit Evolution')
plt.tight_layout()
return fig
def plot_cross_section(self, ax=None):
"""Plot cross-section through the volcano."""
if ax is None:
fig, ax = plt.subplots(figsize=(12, 6))
# Cross-section profile
x = np.linspace(-10000, 10000, 200)
y = np.zeros_like(x)
# True model
mogi_true = MogiSource(**{k: self.inv.true_params[k]
for k in ['x0', 'y0', 'depth', 'radius', 'dP']})
_, _, uz_true = mogi_true.compute_displacement(x, y)
# Best-fit model
mogi_best = MogiSource(**{k: self.inv.best_params[k]
for k in ['x0', 'y0', 'depth', 'radius', 'dP']})
_, _, uz_best = mogi_best.compute_displacement(x, y)
# Plot
ax.fill_between(x, -3000, 0, color='saddlebrown', alpha=0.3, label='Ground')
ax.axhline(y=0, color='black', linewidth=2)
# Source locations
ax.scatter(self.inv.true_params['x0'], -self.inv.true_params['depth'],
s=300, c='red', marker='o', label='True source', zorder=5)
ax.scatter(self.inv.best_params['x0'], -self.inv.best_params['depth'],
s=300, c='yellow', marker='o', edgecolors='black',
label='Best-fit source', zorder=5)
# Displacement profiles
ax2 = ax.twinx()
ax2.plot(x, uz_true * 100, 'r-', linewidth=2, label='True disp. (×100)')
ax2.plot(x, uz_best * 100, 'g--', linewidth=2, label='Best-fit disp. (×100)')
ax2.set_ylabel('Vertical displacement ×100 (m)', color='blue')
ax2.tick_params(axis='y', labelcolor='blue')
ax.set_xlabel('Distance (m)')
ax.set_ylabel('Elevation (m)')
ax.set_title('Cross-Section Profile')
ax.set_ylim(-8000, 1000)
ax.legend(loc='upper left')
ax2.legend(loc='upper right')
ax.grid(True, alpha=0.3)
return ax
def plot_joint_inversion_comparison(self):
"""Plot comparison of joint vs separate inversions."""
fig = plt.figure(figsize=(16, 12))
gs = gridspec.GridSpec(2, 3, figure=fig, hspace=0.3, wspace=0.3)
# 1. Deformation map
ax1 = fig.add_subplot(gs[0, 0])
self.plot_deformation_map(ax=ax1)
# 2. Gas emissions
ax2 = fig.add_subplot(gs[0, 1])
self.plot_gas_emissions(ax=ax2)
# 3. Cross-section
ax3 = fig.add_subplot(gs[0, 2])
self.plot_cross_section(ax=ax3)
# 4. Parameter comparison
ax4 = fig.add_subplot(gs[1, :2])
param_names = ['x₀', 'y₀', 'Depth', 'Radius', 'ΔP', 'Base flux', 'P coeff']
true_vals = [
self.inv.true_params['x0'],
self.inv.true_params['y0'],
self.inv.true_params['depth'],
self.inv.true_params['radius'],
self.inv.true_params['dP'] / 1e6,
self.inv.true_params['base_flux'],
self.inv.true_params['pressure_coeff'] * 1e7
]
best_vals = [
self.inv.best_params['x0'],
self.inv.best_params['y0'],
self.inv.best_params['depth'],
self.inv.best_params['radius'],
self.inv.best_params['dP'] / 1e6,
self.inv.best_params['base_flux'],
self.inv.best_params['pressure_coeff'] * 1e7
]
# Normalize for comparison
true_norm = np.array(true_vals) / np.abs(true_vals)
best_norm = np.array(best_vals) / np.array(true_vals)
x_pos = np.arange(len(param_names))
width = 0.35
ax4.bar(x_pos - width/2, np.ones(len(param_names)), width,
label='True (normalized)', color='red', alpha=0.7)
ax4.bar(x_pos + width/2, best_norm, width,
label='Best-fit / True', color='steelblue', alpha=0.7)
ax4.set_xticks(x_pos)
ax4.set_xticklabels(param_names)
ax4.set_ylabel('Normalized value')
ax4.set_title('Parameter Recovery')
ax4.legend()
ax4.axhline(y=1, color='black', linestyle='--', alpha=0.5)
ax4.grid(True, alpha=0.3, axis='y')
# 5. Misfit summary
ax5 = fig.add_subplot(gs[1, 2])
ax5.axis('off')
# Calculate misfits
def_misfit = self.inv.misfit(self.inv.params_to_array(self.inv.best_params),
weight_gas=0)
gas_misfit = self.inv.misfit(self.inv.params_to_array(self.inv.best_params),
weight_deform=0)
total_misfit = self.inv.misfit(self.inv.params_to_array(self.inv.best_params))
summary_text = (
"Joint Inversion Summary\n"
"─" * 30 + "\n\n"
f"Source Parameters:\n"
f" Position: ({self.inv.best_params['x0']:.0f}, "
f"{self.inv.best_params['y0']:.0f}) m\n"
f" Depth: {self.inv.best_params['depth']:.0f} m\n"
f" Radius: {self.inv.best_params['radius']:.0f} m\n"
f" ΔP: {self.inv.best_params['dP']/1e6:.1f} MPa\n\n"
f"Gas Parameters:\n"
f" Base flux: {self.inv.best_params['base_flux']:.1f} t/day\n"
f" P coefficient: {self.inv.best_params['pressure_coeff']:.2e}\n\n"
f"─" * 30 + "\n"
f"Deformation χ²: {def_misfit:.2f}\n"
f"Gas χ²: {gas_misfit:.2f}\n"
f"Total χ²: {total_misfit:.2f}\n"
)
ax5.text(0.1, 0.9, summary_text, transform=ax5.transAxes,
fontsize=11, verticalalignment='top',
fontfamily='monospace',
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))
return fig
def main():
"""Main function to run the joint inversion demonstration."""
print("=" * 60)
print("Volcano Deformation & Gas Monitoring Joint Inversion")
print("=" * 60)
print("\nThis program demonstrates joint inversion of:")
print(" 1. GPS deformation data (Mogi point source model)")
print(" 2. SO2 gas emission data (pressure-dependent model)")
print()
# Create inversion problem
print("Setting up inversion problem...")
inv = JointInversion(n_stations=25, noise_deform=0.003, noise_gas=15)
# Run optimization
print("\nRunning differential evolution optimization...")
best_params, result = inv.run_optimization()
print(f"Optimization complete. Final misfit: {result.fun:.4f}")
# Create visualization
viz = VolcanoVisualization(inv)
# Plot main results
print("\nGenerating visualization...")
fig1 = viz.plot_joint_inversion_comparison()
# Run MCMC for uncertainty quantification
print("\nRunning MCMC for uncertainty quantification...")
print("(This may take a moment...)")
chain, acc_rate = inv.run_mcmc(n_samples=15000, n_burnin=5000)
print(f"MCMC complete. Acceptance rate: {acc_rate:.2%}")
# Plot MCMC results
fig2 = viz.plot_mcmc_results(chain)
# Print results comparison
print("\n" + "=" * 60)
print("RESULTS COMPARISON")
print("=" * 60)
print(f"\n{'Parameter':<15} {'True':>12} {'Best-fit':>12} {'Unit':>10}")
print("-" * 55)
params_display = [
('x₀', inv.true_params['x0'], best_params['x0'], 'm'),
('y₀', inv.true_params['y0'], best_params['y0'], 'm'),
('Depth', inv.true_params['depth'], best_params['depth'], 'm'),
('Radius', inv.true_params['radius'], best_params['radius'], 'm'),
('ΔP', inv.true_params['dP']/1e6, best_params['dP']/1e6', 'MPa'),
('Base flux', inv.true_params['base_flux'], best_params['base_flux'], 't/day'),
]
for name, true, best, unit in params_display:
print(f"{name:<15} {true:>12.1f} {best:>12.1f} {unit:>10}")
# Show all plots
plt.show()
print("\n" + "=" * 60)
print("Joint inversion analysis complete!")
print("=" * 60)
if __name__ == "__main__":
main()
"""
Volcano Deformation and Gas Monitoring Joint Inversion
=======================================================
Physical Models:
1. Mogi point source for deformation (elastic half-space theory)
2. Pressure-dependent gas emission model (solubility-controlled degassing)
Author: Geophysical Inversion System
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, FancyArrowPatch
from matplotlib.collections import PatchCollection
import matplotlib.gridspec as gridspec
from scipy.optimize import minimize, differential_evolution
from scipy.stats import norm
import warnings
warnings.filterwarnings('ignore')
# =============================================================================
# Physical Constants
# =============================================================================
G_SHEAR = 30e9 # Shear modulus (Pa) - typical crustal value
NU = 0.25 # Poisson's ratio (dimensionless)
RHO_ROCK = 2700 # Rock density (kg/m³)
class MogiSource:
"""
Mogi point source model for volcanic deformation.
Based on Mogi (1958) - models surface displacement from a pressurized
spherical magma chamber in an elastic half-space.
Physical assumptions:
- Spherical pressure source
- Homogeneous, isotropic elastic medium
- Small deformations (linear elasticity)
- Source radius << source depth
"""
def __init__(self, x0=0, y0=0, depth=5000, radius=500, dP=10e6):
"""
Initialize Mogi source parameters.
Parameters
----------
x0, y0 : float
Horizontal position of source center (m)
depth : float
Depth to center of spherical source (m)
radius : float
Radius of spherical source (m)
dP : float
Pressure change (Pa), positive for inflation
"""
self.x0 = x0
self.y0 = y0
self.depth = depth
self.radius = radius
self.dP = dP
def compute_displacement(self, x, y):
"""
Compute surface displacement at observation points.
The Mogi solution gives:
u_r = (C * r) / R³ (radial horizontal)
u_z = (C * d) / R³ (vertical)
where C = (3 * a³ * ΔP * (1-ν)) / (4 * G)
R = √(r² + d²)
Parameters
----------
x, y : arrays
Observation point coordinates (m)
Returns
-------
ux, uy, uz : arrays
Displacement components (m)
"""
# Horizontal distance from source
dx = x - self.x0
dy = y - self.y0
r = np.sqrt(dx**2 + dy**2)
# 3D distance from source center
R = np.sqrt(r**2 + self.depth**2)
R = np.maximum(R, 1e-10) # Avoid division by zero
# Mogi source strength coefficient
# Includes (1-ν) factor for compressible material
C = (3 * self.radius**3 * self.dP * (1 - NU)) / (4 * G_SHEAR)
# Displacement components
ux = C * dx / R**3
uy = C * dy / R**3
uz = C * self.depth / R**3
return ux, uy, uz
def compute_volume_change(self):
"""
Compute volume change of the source.
For a spherical source, volume change relates to pressure change as:
ΔV = (π * a³ * ΔP * (1-ν)) / G
Returns
-------
dV : float
Volume change (m³)
"""
dV = (np.pi * self.radius**3 * self.dP * (1 - NU)) / G_SHEAR
return dV
def compute_stress_at_surface(self, x, y):
"""
Estimate surface stress change (simplified).
Returns approximate radial stress at surface.
"""
dx = x - self.x0
dy = y - self.y0
r = np.sqrt(dx**2 + dy**2)
R = np.sqrt(r**2 + self.depth**2)
# Simplified stress estimate
C = (3 * self.radius**3 * self.dP * (1 - NU)) / (4 * G_SHEAR)
sigma_r = C * G_SHEAR / R**3
return sigma_r
class GasEmissionModel:
"""
Physics-based model for volcanic gas emissions.
Models gas flux based on:
1. Magma volume and gas content
2. Pressure-dependent gas solubility (Henry's law behavior)
3. Decompression-driven exsolution
Key physics:
- Gas solubility in magma follows: C ∝ P^(1/n)
- Exsolution occurs when pressure drops below saturation
- Flux is proportional to magma volume and pressure change rate
"""
def __init__(self, base_flux=100, gas_coeff=1e-7,
solubility_exp=0.5, efficiency=0.8):
"""
Initialize gas emission model.
Parameters
----------
base_flux : float
Background/outgassing flux (t/day)
gas_coeff : float
Scaling coefficient for pressure-driven emissions
solubility_exp : float
Solubility law exponent (typically 0.5 for CO2, 1 for H2O)
efficiency : float
Degassing efficiency (0-1)
"""
self.base_flux = base_flux
self.gas_coeff = gas_coeff
self.solubility_exp = solubility_exp
self.efficiency = efficiency
def compute_flux(self, pressure_change, source_volume):
"""
Compute gas flux based on thermodynamic model.
The flux model combines:
1. Background degassing (steady state)
2. Pressure-driven emissions (transient)
For pressure increase (inflation):
- Less gas exsolves, flux may decrease slightly
For pressure decrease (deflation):
- More gas exsolves due to decompression
Parameters
----------
pressure_change : float
Pressure change (Pa)
source_volume : float
Source volume (m³)
Returns
-------
flux : float
Gas flux (t/day)
"""
# Pressure effect: uses power-law solubility relation
# |ΔP|^(1/n) gives amount of gas that can exsolve
p_magnitude = np.abs(pressure_change) ** self.solubility_exp
# Volume normalization (per km³ of magma)
volume_factor = (source_volume / 1e9) ** (2/3) # Surface area scaling
# Pressure direction effect
# Decompression (negative dP) enhances degassing
if pressure_change < 0:
direction_factor = 1.3 # Enhanced degassing
else:
direction_factor = 0.8 # Suppressed degassing
# Total flux calculation
pressure_flux = (self.gas_coeff * p_magnitude * volume_factor *
direction_factor * self.efficiency)
flux = self.base_flux + pressure_flux
return max(flux, 1.0) # Ensure positive flux
def compute_gas_mass(self, pressure_change, source_volume, time_days=1):
"""
Compute total gas mass released over a time period.
Parameters
----------
pressure_change : float
Pressure change (Pa)
source_volume : float
Source volume (m³)
time_days : float
Time period (days)
Returns
-------
mass : float
Total gas mass (tonnes)
"""
flux = self.compute_flux(pressure_change, source_volume)
return flux * time_days
class JointInversion:
"""
Joint inversion of deformation and gas emission data.
Combines multiple data types to better constrain volcanic source
parameters using weighted least-squares minimization.
Objective function:
Φ = w_d * Φ_deform + w_g * Φ_gas + Φ_reg
where:
- Φ_deform: deformation misfit (χ²)
- Φ_gas: gas emission misfit (χ²)
- Φ_reg: regularization term
"""
def __init__(self, n_stations=20, noise_deform=0.003, noise_gas=12):
"""
Initialize the joint inversion problem.
Parameters
----------
n_stations : int
Number of GPS monitoring stations
noise_deform : float
Deformation measurement noise (m, 1-sigma)
noise_gas : float
Gas flux measurement noise (t/day, 1-sigma)
"""
self.n_stations = n_stations
self.noise_deform = noise_deform
self.noise_gas = noise_gas
# "True" source parameters for synthetic test
self.true_params = {
'x0': 800, # Source x-position (m)
'y0': -400, # Source y-position (m)
'depth': 4500, # Source depth (m)
'radius': 700, # Source radius (m)
'dP': 18e6, # Pressure change (Pa) = 18 MPa
'base_flux': 180, # Base gas flux (t/day)
'gas_coeff': 2.5e-7 # Gas pressure coefficient
}
# Parameter bounds for inversion
self.bounds = {
'x0': (-3000, 3000),
'y0': (-3000, 3000),
'depth': (2000, 8000),
'radius': (200, 1500),
'dP': (1e6, 40e6),
'base_flux': (50, 400),
'gas_coeff': (1e-8, 1e-6)
}
# Initialize storage
self.best_params = None
self.chain = None
# Generate synthetic observations
self._generate_synthetic_data()
def _generate_synthetic_data(self):
"""Generate synthetic observation data for testing."""
np.random.seed(42)
# Create station network (distributed around expected source)
# Use a combination of radial and grid patterns
r = np.random.uniform(800, 7000, self.n_stations)
theta = np.random.uniform(0, 2*np.pi, self.n_stations)
self.station_x = r * np.cos(theta)
self.station_y = r * np.sin(theta)
# True Mogi source
mogi_true = MogiSource(
x0=self.true_params['x0'],
y0=self.true_params['y0'],
depth=self.true_params['depth'],
radius=self.true_params['radius'],
dP=self.true_params['dP']
)
# Compute true deformation
ux_true, uy_true, uz_true = mogi_true.compute_displacement(
self.station_x, self.station_y
)
# Add measurement noise to deformation
self.obs_ux = ux_true + np.random.normal(0, self.noise_deform, self.n_stations)
self.obs_uy = uy_true + np.random.normal(0, self.noise_deform, self.n_stations)
self.obs_uz = uz_true + np.random.normal(0, self.noise_deform, self.n_stations)
# Compute true gas flux
gas_true = GasEmissionModel(
base_flux=self.true_params['base_flux'],
gas_coeff=self.true_params['gas_coeff']
)
source_volume = (4/3) * np.pi * mogi_true.radius**3
true_flux = gas_true.compute_flux(mogi_true.dP, source_volume)
# Gas observations with spatial variability and noise
# Simulates varying atmospheric conditions at different stations
spatial_var = 1 + 0.1 * np.sin(theta) # Wind direction effect
self.obs_gas = (true_flux * spatial_var +
np.random.normal(0, self.noise_gas, self.n_stations))
self.obs_gas = np.maximum(self.obs_gas, 5) # Ensure positive
# Store true values for comparison
self.true_ux = ux_true
self.true_uy = uy_true
self.true_uz = uz_true
self.true_flux = true_flux
# Store station distances for plotting
self.station_r = np.sqrt(self.station_x**2 + self.station_y**2)
def forward_model(self, params):
"""
Run forward model to compute predicted observations.
Parameters
----------
params : dict or array
Model parameters
Returns
-------
pred_ux, pred_uy, pred_uz, pred_flux : arrays
Predicted observations
"""
if isinstance(params, np.ndarray):
params = self._array_to_params(params)
# Create Mogi source
mogi = MogiSource(
x0=params['x0'],
y0=params['y0'],
depth=params['depth'],
radius=params['radius'],
dP=params['dP']
)
# Predict deformation
pred_ux, pred_uy, pred_uz = mogi.compute_displacement(
self.station_x, self.station_y
)
# Create gas model
gas_model = GasEmissionModel(
base_flux=params['base_flux'],
gas_coeff=params['gas_coeff']
)
# Predict gas flux
source_volume = (4/3) * np.pi * mogi.radius**3
pred_flux_value = gas_model.compute_flux(mogi.dP, source_volume)
pred_flux = np.full(self.n_stations, pred_flux_value)
return pred_ux, pred_uy, pred_uz, pred_flux
def objective_function(self, params, w_deform=1.0, w_gas=1.0):
"""
Compute objective function for optimization.
Uses weighted sum of normalized χ² misfits:
Φ = w_d * χ²_deform + w_g * χ²_gas
Parameters
----------
params : array
Model parameters (as array)
w_deform : float
Weight for deformation data
w_gas : float
Weight for gas data
Returns
-------
phi : float
Total objective function value
"""
params_dict = self._array_to_params(params)
# Forward predictions
pred_ux, pred_uy, pred_uz, pred_flux = self.forward_model(params_dict)
# Deformation misfit (χ² normalized by variance)
residual_ux = (self.obs_ux - pred_ux) / self.noise_deform
residual_uy = (self.obs_uy - pred_uy) / self.noise_deform
residual_uz = (self.obs_uz - pred_uz) / self.noise_deform
chi2_deform = (np.sum(residual_ux**2) +
np.sum(residual_uy**2) +
np.sum(residual_uz**2)) / (3 * self.n_stations)
# Gas misfit (χ² normalized by variance)
residual_gas = (self.obs_gas - pred_flux) / self.noise_gas
chi2_gas = np.sum(residual_gas**2) / self.n_stations
# Weighted total
phi = w_deform * chi2_deform + w_gas * chi2_gas
return phi
def _array_to_params(self, array):
"""Convert parameter array to dictionary."""
return {
'x0': array[0],
'y0': array[1],
'depth': array[2],
'radius': array[3],
'dP': array[4],
'base_flux': array[5],
'gas_coeff': array[6]
}
def _params_to_array(self, params):
"""Convert parameter dictionary to array."""
return np.array([
params['x0'],
params['y0'],
params['depth'],
params['radius'],
params['dP'],
params['base_flux'],
params['gas_coeff']
])
def run_optimization(self, method='differential_evolution',
w_deform=1.0, w_gas=1.0):
"""
Run optimization to find best-fit parameters.
Parameters
----------
method : str
Optimization method ('differential_evolution' or 'L-BFGS-B')
w_deform : float
Weight for deformation data
w_gas : float
Weight for gas data
Returns
-------
best_params : dict
Best-fit parameter values
result : OptimizeResult
Full optimization result
"""
bounds_list = [
self.bounds['x0'],
self.bounds['y0'],
self.bounds['depth'],
self.bounds['radius'],
self.bounds['dP'],
self.bounds['base_flux'],
self.bounds['gas_coeff']
]
# Objective with weights
def obj(x):
return self.objective_function(x, w_deform, w_gas)
if method == 'differential_evolution':
result = differential_evolution(
obj,
bounds_list,
seed=42,
maxiter=1000,
tol=1e-8,
polish=True,
workers=-1,
updating='deferred',
popsize=20
)
else:
# Initial guess (center of bounds)
x0 = np.array([(b[0] + b[1])/2 for b in bounds_list])
result = minimize(
obj,
x0,
method='L-BFGS-B',
bounds=bounds_list,
options={'maxiter': 1000}
)
self.best_params = self._array_to_params(result.x)
return self.best_params, result
def run_mcmc(self, n_samples=10000, n_burnin=3000):
"""
Run MCMC sampling for uncertainty quantification.
Uses adaptive Metropolis-Hastings algorithm.
Parameters
----------
n_samples : int
Total number of MCMC samples
n_burnin : int
Number of burn-in samples to discard
Returns
-------
chain : array
Posterior samples, shape (n_samples - n_burnin, n_params)
acceptance_rate : float
MCMC acceptance rate
"""
n_params = 7
bounds_list = [self.bounds[k] for k in
['x0', 'y0', 'depth', 'radius', 'dP', 'base_flux', 'gas_coeff']]
# Initialize from center of bounds
current = np.array([(b[0] + b[1])/2 for b in bounds_list])
current_misfit = self.objective_function(current)
# Adaptive step sizes (tuned for each parameter)
step_sizes = np.array([400, 400, 800, 150, 3e6, 40, 3e-8])
# Storage
chain = np.zeros((n_samples, n_params))
n_accepted = 0
for i in range(n_samples):
# Propose new state
proposal = current + np.random.normal(0, step_sizes)
# Enforce bounds
in_bounds = True
for j in range(n_params):
if not (bounds_list[j][0] <= proposal[j] <= bounds_list[j][1]):
in_bounds = False
break
if in_bounds:
proposal_misfit = self.objective_function(proposal)
# Metropolis-Hastings acceptance criterion
# Accept if misfit decreases, or with probability exp(-ΔΦ)
log_alpha = current_misfit - proposal_misfit
if np.log(np.random.random()) < log_alpha:
current = proposal.copy()
current_misfit = proposal_misfit
n_accepted += 1
chain[i] = current
# Adapt step sizes during burn-in
if (i + 1) % 200 == 0 and i < n_burnin:
rate = n_accepted / (i + 1)
if rate < 0.15:
step_sizes *= 0.7
elif rate > 0.45:
step_sizes *= 1.3
# Remove burn-in period
self.chain = chain[n_burnin:]
acceptance_rate = n_accepted / n_samples
return self.chain, acceptance_rate
def compute_parameter_uncertainties(self):
"""
Compute parameter uncertainties from MCMC chain.
Returns
-------
uncertainties : dict
Dictionary with mean, std, and 95% CI for each parameter
"""
if self.chain is None:
raise ValueError("Run MCMC first to generate samples")
param_names = ['x0', 'y0', 'depth', 'radius', 'dP', 'base_flux', 'gas_coeff']
uncertainties = {}
for i, name in enumerate(param_names):
values = self.chain[:, i]
uncertainties[name] = {
'mean': np.mean(values),
'std': np.std(values),
'ci_low': np.percentile(values, 2.5),
'ci_high': np.percentile(values, 97.5)
}
return uncertainties
class VolcanoVisualization:
"""
Comprehensive visualization for volcano monitoring results.
"""
def __init__(self, inversion):
"""
Initialize visualization.
Parameters
----------
inversion : JointInversion
Inversion results to visualize
"""
self.inv = inversion
# Color scheme
self.colors = {
'observed': '#2E86AB',
'predicted': '#A23B72',
'true': '#28A745',
'source': '#DC3545',
'contour': '#F18F01'
}
def plot_deformation_field(self, ax=None):
"""
Plot deformation field with vectors and contours.
"""
if ax is None:
fig, ax = plt.subplots(figsize=(10, 9))
# Create grid for contours
n_grid = 80
x_range = np.linspace(-8000, 8000, n_grid)
y_range = np.linspace(-8000, 8000, n_grid)
X, Y = np.meshgrid(x_range, y_range)
# Compute deformation field from best-fit model
mogi = MogiSource(
x0=self.inv.best_params['x0'],
y0=self.inv.best_params['y0'],
depth=self.inv.best_params['depth'],
radius=self.inv.best_params['radius'],
dP=self.inv.best_params['dP']
)
ux, uy, uz = mogi.compute_displacement(X, Y)
# Vertical displacement contours
levels = np.linspace(uz.min(), uz.max(), 25)
contour = ax.contourf(X, Y, uz * 100, levels=levels * 100,
cmap='RdBu_r', alpha=0.75)
cbar = plt.colorbar(contour, ax=ax, shrink=0.8)
cbar.set_label('Vertical displacement (cm)', fontsize=10)
# Horizontal displacement vectors (quiver plot)
skip = 6
magnitude = np.sqrt(ux**2 + uy**2)
scale_factor = np.max(magnitude) * 15
ax.quiver(X[::skip, ::skip], Y[::skip, ::skip],
ux[::skip, ::skip], uy[::skip, ::skip],
scale=scale_factor, color='black', alpha=0.6,
width=0.003, headwidth=4)
# Source locations
ax.scatter(self.inv.best_params['x0'], self.inv.best_params['y0'],
s=350, c=self.colors['source'], marker='*',
edgecolors='black', linewidths=1.5,
label='Best-fit source', zorder=10)
ax.scatter(self.inv.true_params['x0'], self.inv.true_params['y0'],
s=350, c=self.colors['true'], marker='*',
edgecolors='black', linewidths=1.5,
label='True source', zorder=10)
# Observation stations
ax.scatter(self.inv.station_x, self.inv.station_y,
s=80, c='white', edgecolors='black', linewidths=1.5,
marker='^', label='GPS stations', zorder=8)
# Observed displacement vectors at stations
scale_obs = np.max(np.sqrt(self.inv.obs_ux**2 + self.inv.obs_uy**2)) * 8
ax.quiver(self.inv.station_x, self.inv.station_y,
self.inv.obs_ux, self.inv.obs_uy,
scale=scale_obs, color=self.colors['observed'],
width=0.005, headwidth=3, alpha=0.8,
label='Observed disp.')
ax.set_xlabel('Easting (m)', fontsize=11)
ax.set_ylabel('Northing (m)', fontsize=11)
ax.set_title('Surface Deformation Field', fontsize=13, fontweight='bold')
ax.legend(loc='upper right', fontsize=9)
ax.set_aspect('equal')
ax.grid(True, alpha=0.3, linestyle='--')
return ax
def plot_gas_observations(self, ax=None):
"""
Plot gas emission observations and model predictions.
"""
if ax is None:
fig, ax = plt.subplots(figsize=(10, 6))
# Observed gas vs distance
ax.scatter(self.inv.station_r / 1000, self.inv.obs_gas,
s=70, c=self.colors['observed'], alpha=0.7,
edgecolors='black', linewidths=1,
label='Observed SO₂', zorder=5)
# Model predictions
_, _, _, pred_flux = self.inv.forward_model(self.inv.best_params)
pred_flux_val = pred_flux[0]
ax.axhline(y=pred_flux_val, color=self.colors['predicted'],
linestyle='--', linewidth=2.5,
label=f'Predicted: {pred_flux_val:.1f} t/day')
ax.axhline(y=self.inv.true_flux, color=self.colors['true'],
linestyle=':', linewidth=2.5,
label=f'True: {self.inv.true_flux:.1f} t/day')
# Uncertainty band
ax.axhspan(pred_flux_val - self.inv.noise_gas * 2,
pred_flux_val + self.inv.noise_gas * 2,
alpha=0.2, color=self.colors['predicted'],
label='95% confidence')
ax.set_xlabel('Distance from summit (km)', fontsize=11)
ax.set_ylabel('SO₂ flux (t/day)', fontsize=11)
ax.set_title('Gas Emission Observations', fontsize=13, fontweight='bold')
ax.legend(loc='upper right', fontsize=9)
ax.grid(True, alpha=0.3, linestyle='--')
ax.set_ylim(0, None)
return ax
def plot_cross_section(self, ax=None):
"""
Plot vertical cross-section through the volcano.
"""
if ax is None:
fig, ax = plt.subplots(figsize=(12, 6))
# Profile line
x_prof = np.linspace(-8000, 8000, 200)
# True model
mogi_true = MogiSource(
x0=self.inv.true_params['x0'],
y0=self.inv.true_params['y0'],
depth=self.inv.true_params['depth'],
radius=self.inv.true_params['radius'],
dP=self.inv.true_params['dP']
)
_, _, uz_true = mogi_true.compute_displacement(x_prof, np.zeros_like(x_prof))
# Best-fit model
mogi_best = MogiSource(
x0=self.inv.best_params['x0'],
y0=self.inv.best_params['y0'],
depth=self.inv.best_params['depth'],
radius=self.inv.best_params['radius'],
dP=self.inv.best_params['dP']
)
_, _, uz_best = mogi_best.compute_displacement(x_prof, np.zeros_like(x_prof))
# Ground surface
ax.fill_between(x_prof, -10000, 0, color='#8B4513', alpha=0.3)
ax.axhline(y=0, color='#654321', linewidth=3)
# Magma chambers
true_circle = plt.Circle(
(self.inv.true_params['x0'], -self.inv.true_params['depth']),
self.inv.true_params['radius'],
color=self.colors['true'], alpha=0.6, label='True chamber'
)
best_circle = plt.Circle(
(self.inv.best_params['x0'], -self.inv.best_params['depth']),
self.inv.best_params['radius'],
color=self.colors['predicted'], alpha=0.6,
edgecolor='black', linewidth=2, label='Best-fit chamber'
)
ax.add_patch(true_circle)
ax.add_patch(best_circle)
# Displacement profiles (secondary axis)
ax2 = ax.twinx()
ax2.plot(x_prof, uz_true * 100, color=self.colors['true'],
linewidth=2.5, linestyle='-', label='True disp.')
ax2.plot(x_prof, uz_best * 100, color=self.colors['predicted'],
linewidth=2.5, linestyle='--', label='Best-fit disp.')
ax2.set_ylabel('Vertical displacement (cm)', fontsize=11, color='#444444')
ax2.tick_params(axis='y', labelcolor='#444444')
ax2.axhline(y=0, color='gray', linestyle=':', alpha=0.5)
# Gas emission indicators (arrows)
n_arrows = 7
arrow_x = np.linspace(-4000, 4000, n_arrows)
arrow_height = np.linspace(150, 400, n_arrows)
for i, (x, h) in enumerate(zip(arrow_x, arrow_height)):
alpha = 0.4 + 0.4 * (1 - abs(x) / 4000)
ax.annotate('', xy=(x, h), xytext=(x, 20),
arrowprops=dict(arrowstyle='->', color='orange',
lw=1.5, alpha=alpha))
ax.text(0, 450, 'Gas Emissions', ha='center', fontsize=10,
color='orange', fontweight='bold')
ax.set_xlabel('Distance (m)', fontsize=11)
ax.set_ylabel('Elevation (m)', fontsize=11)
ax.set_title('Cross-Section View', fontsize=13, fontweight='bold')
ax.set_xlim(-8000, 8000)
ax.set_ylim(-8000, 800)
# Combined legend
lines1, labels1 = ax.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax.legend(lines1 + lines2, labels1 + labels2, loc='lower right', fontsize=9)
ax.grid(True, alpha=0.3, linestyle='--')
return ax
def plot_mcmc_distributions(self, chain):
"""
Plot MCMC posterior distributions for all parameters.
"""
param_names = ['x₀ (m)', 'y₀ (m)', 'Depth (m)', 'Radius (m)',
'ΔP (MPa)', 'Base flux (t/d)', 'Gas coeff (×10⁻⁷)']
# Scale chain for display
chain_scaled = chain.copy()
chain_scaled[:, 4] /= 1e6 # Pa to MPa
chain_scaled[:, 6] *= 1e7 # Scale coefficient
true_values = [
self.inv.true_params['x0'],
self.inv.true_params['y0'],
self.inv.true_params['depth'],
self.inv.true_params['radius'],
self.inv.true_params['dP'] / 1e6,
self.inv.true_params['base_flux'],
self.inv.true_params['gas_coeff'] * 1e7
]
fig, axes = plt.subplots(3, 3, figsize=(14, 12))
axes = axes.flatten()
for i in range(7):
ax = axes[i]
# Histogram
ax.hist(chain_scaled[:, i], bins=35, density=True,
alpha=0.7, color='steelblue', edgecolor='black')
# True value
ax.axvline(true_values[i], color='red', linestyle='--',
linewidth=2.5, label='True')
# Median and CI
median = np.median(chain_scaled[:, i])
ci_low = np.percentile(chain_scaled[:, i], 2.5)
ci_high = np.percentile(chain_scaled[:, i], 97.5)
ax.axvline(median, color='green', linestyle='-',
linewidth=2, label='Median')
ax.axvspan(ci_low, ci_high, alpha=0.2, color='green',
label='95% CI')
ax.set_xlabel(param_names[i], fontsize=10)
ax.set_ylabel('Density', fontsize=10)
ax.legend(fontsize=8, loc='best')
ax.grid(True, alpha=0.3)
# Depth vs Pressure correlation
ax = axes[7]
ax.scatter(chain_scaled[:, 2], chain_scaled[:, 4],
alpha=0.3, s=5, c='steelblue')
ax.scatter(true_values[2], true_values[4],
c='red', s=150, marker='*', zorder=5, label='True')
ax.set_xlabel('Depth (m)', fontsize=10)
ax.set_ylabel('ΔP (MPa)', fontsize=10)
ax.set_title('Depth vs Pressure Trade-off', fontsize=11)
ax.legend(fontsize=9)
ax.grid(True, alpha=0.3)
# Misfit evolution
ax = axes[8]
misfits = [self.inv.objective_function(chain[i])
for i in range(0, len(chain), 50)]
ax.plot(np.arange(len(misfits)) * 50, misfits,
color='steelblue', linewidth=1.5)
ax.set_xlabel('Sample', fontsize=10)
ax.set_ylabel('Misfit (χ²)', fontsize=10)
ax.set_title('MCMC Convergence', fontsize=11)
ax.grid(True, alpha=0.3)
plt.tight_layout()
return fig
def plot_comprehensive_summary(self):
"""
Create comprehensive summary figure with all results.
"""
fig = plt.figure(figsize=(18, 14))
gs = gridspec.GridSpec(3, 3, figure=fig, hspace=0.35, wspace=0.3)
# 1. Deformation map
ax1 = fig.add_subplot(gs[0, 0])
self.plot_deformation_field(ax=ax1)
# 2. Gas observations
ax2 = fig.add_subplot(gs[0, 1])
self.plot_gas_observations(ax=ax2)
# 3. Cross-section
ax3 = fig.add_subplot(gs[0, 2])
self.plot_cross_section(ax=ax3)
# 4. Parameter comparison bar chart
ax4 = fig.add_subplot(gs[1, :2])
param_labels = ['x₀', 'y₀', 'Depth', 'Radius', 'ΔP', 'Base flux', 'Gas coeff']
# Normalized values (best-fit / true)
true_vals = [
self.inv.true_params['x0'],
self.inv.true_params['y0'],
self.inv.true_params['depth'],
self.inv.true_params['radius'],
self.inv.true_params['dP'] / 1e6,
self.inv.true_params['base_flux'],
self.inv.true_params['gas_coeff'] * 1e7
]
best_vals = [
self.inv.best_params['x0'],
self.inv.best_params['y0'],
self.inv.best_params['depth'],
self.inv.best_params['radius'],
self.inv.best_params['dP'] / 1e6,
self.inv.best_params['base_flux'],
self.inv.best_params['gas_coeff'] * 1e7
]
ratios = np.array(best_vals) / np.array(true_vals)
x_pos = np.arange(len(param_labels))
bars = ax4.bar(x_pos, ratios, color='steelblue', alpha=0.8,
edgecolor='black', linewidth=1.5)
ax4.axhline(y=1, color='red', linestyle='--', linewidth=2)
# Color bars based on accuracy
for bar, ratio in zip(bars, ratios):
if 0.9 <= ratio <= 1.1:
bar.set_color('green')
elif 0.8 <= ratio <= 1.2:
bar.set_color('orange')
else:
bar.set_color('red')
ax4.set_xticks(x_pos)
ax4.set_xticklabels(param_labels, fontsize=10)
ax4.set_ylabel('Best-fit / True', fontsize=11)
ax4.set_title('Parameter Recovery (ratio to true value)',
fontsize=12, fontweight='bold')
ax4.grid(True, alpha=0.3, axis='y')
ax4.set_ylim(0, max(1.5, max(ratios) * 1.1))
# 5. Residual plots
ax5 = fig.add_subplot(gs[1, 2])
pred_ux, pred_uy, pred_uz, pred_flux = self.inv.forward_model(
self.inv.best_params
)
residuals_uz = (self.inv.obs_uz - pred_uz) * 100 # cm
ax5.scatter(self.inv.station_r / 1000, residuals_uz,
c='steelblue', s=60, alpha=0.7, edgecolors='black')
ax5.axhline(y=0, color='red', linestyle='--', linewidth=2)
ax5.set_xlabel('Distance (km)', fontsize=10)
ax5.set_ylabel('Residual (cm)', fontsize=10)
ax5.set_title('Vertical Displacement Residuals', fontsize=11)
ax5.grid(True, alpha=0.3)
# 6. Summary text box
ax6 = fig.add_subplot(gs[2, :])
ax6.axis('off')
# Calculate misfits
def_misfit = self.inv.objective_function(
self.inv._params_to_array(self.inv.best_params), w_gas=0
)
gas_misfit = self.inv.objective_function(
self.inv._params_to_array(self.inv.best_params), w_deform=0
)
total_misfit = self.inv.objective_function(
self.inv._params_to_array(self.inv.best_params)
)
summary = (
"JOINT INVERSION SUMMARY\n"
"═" * 90 + "\n\n"
"SOURCE PARAMETERS (Deformation Model - Mogi Point Source)\n"
"─" * 90 + "\n"
f"{'Parameter':<20} {'True Value':>15} {'Best-fit':>15} {'Error %':>12}\n"
f"{'x-position (m)':<20} {self.inv.true_params['x0']:>15.1f} "
f"{self.inv.best_params['x0']:>15.1f} "
f"{100*abs(self.inv.best_params['x0']-self.inv.true_params['x0'])/abs(self.inv.true_params['x0']):>11.1f}%\n"
f"{'y-position (m)':<20} {self.inv.true_params['y0']:>15.1f} "
f"{self.inv.best_params['y0']:>15.1f} "
f"{100*abs(self.inv.best_params['y0']-self.inv.true_params['y0'])/abs(self.inv.true_params['y0']):>11.1f}%\n"
f"{'Depth (m)':<20} {self.inv.true_params['depth']:>15.1f} "
f"{self.inv.best_params['depth']:>15.1f} "
f"{100*abs(self.inv.best_params['depth']-self.inv.true_params['depth'])/self.inv.true_params['depth']:>11.1f}%\n"
f"{'Radius (m)':<20} {self.inv.true_params['radius']:>15.1f} "
f"{self.inv.best_params['radius']:>15.1f} "
f"{100*abs(self.inv.best_params['radius']-self.inv.true_params['radius'])/self.inv.true_params['radius']:>11.1f}%\n"
f"{'Pressure (MPa)':<20} {self.inv.true_params['dP']/1e6:>15.2f} "
f"{self.inv.best_params['dP']/1e6:>15.2f} "
f"{100*abs(self.inv.best_params['dP']-self.inv.true_params['dP'])/self.inv.true_params['dP']:>11.1f}%\n\n"
"GAS EMISSION PARAMETERS\n"
"─" * 90 + "\n"
f"{'Base flux (t/day)':<20} {self.inv.true_params['base_flux']:>15.1f} "
f"{self.inv.best_params['base_flux']:>15.1f} "
f"{100*abs(self.inv.best_params['base_flux']-self.inv.true_params['base_flux'])/self.inv.true_params['base_flux']:>11.1f}%\n\n"
"MISFIT STATISTICS\n"
"─" * 90 + "\n"
f"Deformation χ²: {def_misfit:>10.3f} Gas χ²: {gas_misfit:>10.3f} Total χ²: {total_misfit:>10.3f}\n"
)
ax6.text(0.02, 0.95, summary, transform=ax6.transAxes,
fontsize=10, verticalalignment='top',
fontfamily='monospace',
bbox=dict(boxstyle='round,pad=0.5', facecolor='lightyellow',
edgecolor='gray', alpha=0.9))
return fig
def main():
"""Main execution function."""
print("=" * 70)
print(" VOLCANO DEFORMATION & GAS MONITORING JOINT INVERSION")
print("=" * 70)
print("\nPhysical Models Used:")
print(" • Deformation: Mogi point source (elastic half-space)")
print(" • Gas: Pressure-dependent solubility model")
print()
# Initialize inversion problem
print("[1/4] Setting up inversion problem...")
inv = JointInversion(
n_stations=25,
noise_deform=0.003, # 3 mm noise
noise_gas=12 # 12 t/day noise
)
# Run optimization
print("[2/4] Running differential evolution optimization...")
best_params, opt_result = inv.run_optimization(
method='differential_evolution',
w_deform=1.0,
w_gas=0.8
)
print(f" Optimization complete. Final misfit: {opt_result.fun:.4f}")
# Run MCMC for uncertainty analysis
print("[3/4] Running MCMC for uncertainty quantification...")
chain, acc_rate = inv.run_mcmc(n_samples=12000, n_burnin=4000)
print(f" MCMC complete. Acceptance rate: {acc_rate:.1%}")
# Compute uncertainties
uncertainties = inv.compute_parameter_uncertainties()
# Generate visualizations
print("[4/4] Generating visualizations...")
viz = VolcanoVisualization(inv)
# Main summary figure
fig1 = viz.plot_comprehensive_summary()
# MCMC results figure
fig2 = viz.plot_mcmc_distributions(chain)
# Print results
print("\n" + "=" * 70)
print("RESULTS SUMMARY")
print("=" * 70)
param_info = [
('x₀ (m)', 'x0', '{:.1f}'),
('y₀ (m)', 'y0', '{:.1f}'),
('Depth (m)', 'depth', '{:.1f}'),
('Radius (m)', 'radius', '{:.1f}'),
('ΔP (MPa)', 'dP', '{:.2f}'),
('Base flux (t/d)', 'base_flux', '{:.1f}'),
('Gas coeff', 'gas_coeff', '{:.2e}')
]
print(f"\n{'Parameter':<15} {'True':>12} {'Best-fit':>12} "
f"{'Median':>12} {'Std':>12}")
print("-" * 65)
for label, key, fmt in param_info:
true_val = self.inv.true_params[key]
best_val = self.inv.best_params[key]
median = uncertainties[key]['mean']
std = uncertainties[key]['std']
if key == 'dP':
true_val /= 1e6
best_val /= 1e6
median /= 1e6
std /= 1e6
print(f"{label:<15} {fmt.format(true_val):>12} {fmt.format(best_val):>12} "
f"{fmt.format(median):>12} {fmt.format(std):>12}")
plt.show()
print("\n" + "=" * 70)
print("Joint inversion analysis complete!")
print("=" * 70)
if __name__ == "__main__":
main()