Create a dark matter halo profile inference: lensing/rotation data fusion, models, and…
- User
Create a dark matter halo profile inference: lensing/rotation data fusion, models, and uncertainties.
Assistant
Create a dark matter halo profile inference: lensing/rotation data fusion, models, and uncertainties.
The user wants a comprehensive implementation of dark matter halo profile inference. This is a sophisticated astrophysics/cosmology problem that involves:
Dark Matter Halo Profiles: Common models include:
Data Fusion from Two Sources:
Statistical Inference:
Let me create a comprehensive implementation that:
Key physics:
Let me write a complete, well-structured code:
"""
Dark Matter Halo Profile Inference
==================================
A comprehensive implementation for inferring dark matter halo profiles
by fusing weak lensing and rotation curve data.
Author: Physics Simulation
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import quad, cumulative_trapezoid
from scipy.interpolate import interp1d
import emcee
import corner
from dataclasses import dataclass
from typing import Callable, Tuple, Dict, List
import warnings
warnings.filterwarnings('ignore')
# Physical constants
G = 4.30091e-6 # Gravitational constant in kpc (km/s)^2 M_sun^-1
C_LIGHT = 299792.458 # Speed of light in km/s
# ... rest of implementation
Let me write the full implementation: This is a fascinating astrophysical inference problem! I'll create a comprehensive dark matter halo profile inference system that fuses weak gravitational lensing and rotation curve data using Bayesian methods.
This comprehensive implementation includes:
emceeThe code demonstrates the power of combining different astrophysical probes - rotation curves excel at constraining the inner halo structure while weak lensing constrains the total mass and outer profile.
"""
Dark Matter Halo Profile Inference
==================================
Fuses weak lensing and rotation curve data to infer halo parameters
using Bayesian MCMC with proper uncertainty quantification.
Physical Models:
- NFW (Navarro-Frenk-White) profile
- Einasto profile
- Burkert profile
- Generalized NFW (gNFW) profile
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import quad, cumulative_trapezoid
from scipy.interpolate import interp1d
from scipy.optimize import minimize
import emcee
import corner
from dataclasses import dataclass, field
from typing import Callable, Tuple, Dict, List, Optional
from enum import Enum
import warnings
warnings.filterwarnings('ignore')
# =============================================================================
# Physical Constants
# =============================================================================
G = 4.30091e-6 # Gravitational constant [kpc (km/s)^2 M_sun^-1]
C_LIGHT = 299792.458 # Speed of light [km/s]
PC_TO_KPC = 1e-3 # parsec to kiloparsec
# =============================================================================
# Halo Profile Models
# =============================================================================
class HaloModel(Enum):
"""Supported dark matter halo models"""
NFW = "NFW"
EINASTO = "Einasto"
BURKERT = "Burkert"
GNFW = "Generalized NFW"
CORED_NFW = "Cored NFW"
@dataclass
class HaloParameters:
"""Parameters defining a dark matter halo"""
rho_s: float # Scale density [M_sun kpc^-3]
r_s: float # Scale radius [kpc]
# Additional parameters for extended models
alpha: float = 0.0 # Einasto index / gNFW inner slope
r_core: float = 0.0 # Core radius for cored profiles
# Derived quantities (computed)
M200: float = field(init=False)
c200: float = field(init=False)
r200: float = field(init=False)
def __post_init__(self):
"""Compute derived quantities"""
# These will be computed based on the model
pass
class DarkMatterHalo:
"""
Class implementing various dark matter halo density profiles
with associated gravitational physics.
"""
def __init__(self, model: HaloModel):
self.model = model
self.param_names = self._get_param_names()
def _get_param_names(self) -> List[str]:
"""Get parameter names for the model"""
base_names = ['rho_s', 'r_s']
if self.model == HaloModel.EINASTO:
return base_names + ['alpha']
elif self.model == HaloModel.GNFW:
return base_names + ['alpha'] # alpha is inner slope
elif self.model in [HaloModel.BURKERT, HaloModel.CORED_NFW]:
return base_names + ['r_core']
return base_names
def density(self, r: np.ndarray, params: Dict[str, float]) -> np.ndarray:
"""
Compute the 3D density profile ρ(r)
Parameters
----------
r : array
Radial distance [kpc]
params : dict
Halo parameters
Returns
-------
rho : array
Density [M_sun kpc^-3]
"""
rho_s = params['rho_s']
r_s = params['r_s']
if self.model == HaloModel.NFW:
# NFW: ρ(r) = ρ_s / [(r/r_s)(1 + r/r_s)^2]
x = r / r_s
return rho_s / (x * (1 + x)**2)
elif self.model == HaloModel.EINASTO:
# Einasto: ρ(r) = ρ_s * exp(-2/α * [(r/r_s)^α - 1])
alpha = params.get('alpha', 0.17)
x = r / r_s
return rho_s * np.exp(-2/alpha * (x**alpha - 1))
elif self.model == HaloModel.BURKERT:
# Burkert: ρ(r) = ρ_s / [(1 + r/r_s)(1 + (r/r_s)^2)]
x = r / r_s
return rho_s / ((1 + x) * (1 + x**2))
elif self.model == HaloModel.GNFW:
# Generalized NFW: ρ(r) = ρ_s / [(r/r_s)^α * (1 + r/r_s)^(3-α)]
alpha = params.get('alpha', 1.0)
x = r / r_s
return rho_s / (x**alpha * (1 + x)**(3 - alpha))
elif self.model == HaloModel.CORED_NFW:
# Cored NFW: ρ(r) = ρ_s / [(1 + (r_core/r)^2)(1 + r/r_s)^2] * r_s/r
r_core = params.get('r_core', r_s * 0.1)
x = r / r_s
return rho_s * x / ((1 + (r_core/r)**2) * (1 + x)**2)
else:
raise ValueError(f"Unknown model: {self.model}")
def enclosed_mass(self, r: np.ndarray, params: Dict[str, float],
r_max: float = 1000.0) -> np.ndarray:
"""
Compute enclosed mass M(<r) by integrating density
M(r) = 4π ∫_0^r ρ(r') r'^2 dr'
"""
# Use numerical integration
r_fine = np.logspace(-3, np.log10(r_max), 1000)
rho_fine = self.density(r_fine, params)
# Integrate: 4π ∫ ρ(r) r² dr
integrand = 4 * np.pi * rho_fine * r_fine**2
M_cumul = cumulative_trapezoid(integrand, r_fine, initial=0)
# Interpolate to requested radii
M_interp = interp1d(r_fine, M_cumul, fill_value='extrapolate')
return M_interp(r)
def circular_velocity(self, r: np.ndarray, params: Dict[str, float]) -> np.ndarray:
"""
Compute circular velocity v_c(r)
v_c²(r) = G * M(<r) / r
"""
M_enc = self.enclosed_mass(r, params)
v_c = np.sqrt(G * M_enc / r)
return v_c
def surface_density(self, R: np.ndarray, params: Dict[str, float]) -> np.ndarray:
"""
Compute projected surface density Σ(R)
Σ(R) = 2 ∫_R^∞ ρ(r) * r / √(r² - R²) dr
"""
Sigma = np.zeros_like(R)
for i, R_val in enumerate(R):
# Integrate from R to infinity
def integrand(z):
r = np.sqrt(R_val**2 + z**2)
return self.density(np.atleast_1d(r), params)[0]
# Use finite upper limit for numerical stability
z_max = 5000.0 # kpc
result, _ = quad(integrand, 0, z_max, limit=100)
Sigma[i] = 2 * result
return Sigma
def excess_surface_density(self, R: np.ndarray,
params: Dict[str, float]) -> np.ndarray:
"""
Compute excess surface density ΔΣ(R)
ΔΣ(R) = Σ̄(<R) - Σ(R)
where Σ̄(<R) = (2/R²) ∫_0^R Σ(R') R' dR'
"""
Sigma = self.surface_density(R, params)
# Compute mean surface density within R
Sigma_mean = np.zeros_like(R)
for i, R_val in enumerate(R):
R_fine = np.linspace(0.01, R_val, 50)
Sigma_fine = self.surface_density(R_fine, params)
integral = np.trapezoid(Sigma_fine * R_fine, R_fine)
Sigma_mean[i] = 2 * integral / R_val**2
return Sigma_mean - Sigma
def shear(self, R: np.ndarray, params: Dict[str, float],
Sigma_crit: float) -> np.ndarray:
"""
Compute tangential shear γ_t(R)
γ_t = ΔΣ(R) / Σ_crit
"""
DeltaSigma = self.excess_surface_density(R, params)
return DeltaSigma / Sigma_crit
def convergence(self, R: np.ndarray, params: Dict[str, float],
Sigma_crit: float) -> np.ndarray:
"""
Compute lensing convergence κ(R)
κ = Σ(R) / Σ_crit
"""
Sigma = self.surface_density(R, params)
return Sigma / Sigma_crit
def compute_M200(self, params: Dict[str, float],
rho_crit: float = 277.5) -> Tuple[float, float, float]:
"""
Compute M200, r200, and concentration c200
M200 = 200 * (4π/3) * ρ_crit * r200³
"""
# Find r200 where <ρ> = 200 * ρ_crit
def objective(r200):
M = self.enclosed_mass(np.array([r200]), params)[0]
rho_mean = 3 * M / (4 * np.pi * r200**3)
return (rho_mean / rho_crit - 200)**2
result = minimize(objective, x0=params['r_s'] * 5, method='Nelder-Mead')
r200 = result.x[0]
M200 = self.enclosed_mass(np.array([r200]), params)[0]
c200 = r200 / params['r_s']
return M200, r200, c200
# =============================================================================
# Data Simulation
# =============================================================================
@dataclass
class RotationCurveData:
"""Rotation curve observations"""
r: np.ndarray # Radial distance [kpc]
v_rot: np.ndarray # Rotation velocity [km/s]
v_err: np.ndarray # Velocity uncertainty [km/s]
v_stars: Optional[np.ndarray] = None # Stellar contribution
v_gas: Optional[np.ndarray] = None # Gas contribution
@dataclass
class LensingData:
"""Weak lensing observations"""
R: np.ndarray # Projected radius [kpc]
gamma_t: np.ndarray # Tangential shear
gamma_err: np.ndarray # Shear uncertainty
z_lens: float = 0.3 # Lens redshift
z_source: float = 0.8 # Source redshift
Sigma_crit: float = field(init=False)
def __post_init__(self):
"""Compute critical surface density"""
# Simplified cosmology for Σ_crit calculation
# In practice, use full cosmology calculations
D_l = self._angular_diameter_distance(self.z_lens)
D_s = self._angular_diameter_distance(self.z_source)
D_ls = self._angular_diameter_distance(self.z_lens, self.z_source)
self.Sigma_crit = (C_LIGHT**2 / (4 * np.pi * G)) * (D_s / (D_l * D_ls))
self.Sigma_crit *= 1e-6 # Convert to M_sun/kpc²
def _angular_diameter_distance(self, z1: float, z2: float = None) -> float:
"""Compute angular diameter distance [Mpc] (simplified)"""
# Simple approximation - use proper cosmology in practice
if z2 is None:
return 3000 * z1 / (1 + z1)
else:
return 3000 * (z2 - z1) / (1 + z2)
class DataSimulator:
"""
Simulate realistic rotation curve and lensing observations
for testing the inference pipeline.
"""
def __init__(self, halo_model: HaloModel, seed: int = 42):
self.halo = DarkMatterHalo(halo_model)
np.random.seed(seed)
def simulate_rotation_curve(self, params: Dict[str, float],
r_range: Tuple[float, float] = (0.5, 50),
n_points: int = 30,
velocity_error: float = 5.0,
include_baryons: bool = True) -> RotationCurveData:
"""Simulate rotation curve data"""
r = np.linspace(r_range[0], r_range[1], n_points)
# DM contribution
v_dm = self.halo.circular_velocity(r, params)
# Add baryonic contributions (simplified)
if include_baryons:
# Stellar disk (exponential)
M_star = params.get('M_star', 5e10) # M_sun
R_d = params.get('R_d', 3.0) # kpc
v_stars = self._disk_rotation(r, M_star, R_d)
# Gas disk (extended)
M_gas = params.get('M_gas', 1e10)
R_gas = params.get('R_gas', 10.0)
v_gas = self._disk_rotation(r, M_gas, R_gas)
else:
v_stars = np.zeros_like(r)
v_gas = np.zeros_like(r)
# Total rotation curve (quadrature sum)
v_total = np.sqrt(v_dm**2 + v_stars**2 + v_gas**2)
# Add noise
v_err = np.ones_like(r) * velocity_error
v_obs = v_total + np.random.normal(0, velocity_error, n_points)
return RotationCurveData(r=r, v_rot=v_obs, v_err=v_err,
v_stars=v_stars, v_gas=v_gas)
def simulate_lensing(self, params: Dict[str, float],
R_range: Tuple[float, float] = (50, 500),
n_points: int = 25,
z_lens: float = 0.3,
z_source: float = 0.8,
shear_error_fraction: float = 0.15) -> LensingData:
"""Simulate weak lensing data"""
R = np.logspace(np.log10(R_range[0]), np.log10(R_range[1]), n_points)
# Compute lensing signal
lensing_data = LensingData(
R=R,
gamma_t=np.zeros(n_points),
gamma_err=np.zeros(n_points),
z_lens=z_lens,
z_source=z_source
)
gamma_t = self.halo.shear(R, params, lensing_data.Sigma_crit)
# Add noise (shape noise + measurement error)
gamma_err = np.abs(gamma_t) * shear_error_fraction
gamma_obs = gamma_t + np.random.normal(0, gamma_err)
lensing_data.gamma_t = gamma_obs
lensing_data.gamma_err = gamma_err
return lensing_data
def _disk_rotation(self, r: np.ndarray, M_disk: float,
R_disk: float) -> np.ndarray:
"""Compute rotation curve for exponential disk"""
y = r / (2 * R_disk)
# Modified Bessel functions (approximation)
I0 = np.cosh(y)
I1 = np.sinh(y) / y
I1[~np.isfinite(I1)] = 0.5
K0 = np.exp(-y)
K1 = (1 + y) * np.exp(-y) / y
K1[~np.isfinite(K1)] = 1.0
# Freeman (1970) formula
bess_sum = I0 * K0 - I1 * K1
v2 = (4 * np.pi * G * M_disk * r**2 / (2 * R_disk**3)) * bess_sum
return np.sqrt(np.abs(v2))
# =============================================================================
# Bayesian Inference
# =============================================================================
class HaloInference:
"""
Bayesian inference for dark matter halo parameters
using MCMC (emcee) with joint lensing + rotation curve likelihood.
"""
def __init__(self, halo_model: HaloModel,
rot_data: Optional[RotationCurveData] = None,
lens_data: Optional[LensingData] = None):
self.halo = DarkMatterHalo(halo_model)
self.rot_data = rot_data
self.lens_data = lens_data
self.model = halo_model
self.samples = None
self.best_fit = None
def log_prior(self, params_array: np.ndarray,
param_names: List[str]) -> float:
"""
Compute log prior probability
Priors:
- log(rho_s): Uniform [-10, 10] (in log10 M_sun/kpc³)
- log(r_s): Uniform [-1, 2] (in log10 kpc)
- alpha: Uniform [0, 3] (for Einasto/gNFW)
- r_core: Uniform [0, 50] kpc
"""
params = dict(zip(param_names, params_array))
# Parameter bounds
if 'rho_s' in params:
log_rho_s = np.log10(params['rho_s'])
if not (-10 < log_rho_s < 10):
return -np.inf
if 'r_s' in params:
if not (0.1 < params['r_s'] < 100):
return -np.inf
if 'alpha' in params:
if not (0.01 < params['alpha'] < 3):
return -np.inf
if 'r_core' in params:
if not (0.01 < params['r_core'] < 50):
return -np.inf
# Apply weak priors based on typical halo properties
log_prior = 0.0
# Gaussian prior on r_s centered at 20 kpc
if 'r_s' in params:
log_prior += -0.5 * ((params['r_s'] - 20) / 15)**2
return log_prior
def log_likelihood_rotation(self, params: Dict[str, float]) -> float:
"""
Log-likelihood for rotation curve data
L_rot = -0.5 * Σ [(v_obs - v_model)² / σ²]
"""
if self.rot_data is None:
return 0.0
v_model = self.halo.circular_velocity(self.rot_data.r, params)
# Add baryonic contribution if available
v_total = v_model.copy()
if self.rot_data.v_stars is not None:
v_total = np.sqrt(v_total**2 + self.rot_data.v_stars**2)
if self.rot_data.v_gas is not None:
v_total = np.sqrt(v_total**2 + self.rot_data.v_gas**2)
chi2 = np.sum(((self.rot_data.v_rot - v_total) / self.rot_data.v_err)**2)
return -0.5 * chi2
def log_likelihood_lensing(self, params: Dict[str, float]) -> float:
"""
Log-likelihood for weak lensing data
L_lens = -0.5 * Σ [(γ_obs - γ_model)² / σ_γ²]
"""
if self.lens_data is None:
return 0.0
gamma_model = self.halo.shear(self.lens_data.R, params,
self.lens_data.Sigma_crit)
chi2 = np.sum(((self.lens_data.gamma_t - gamma_model) /
self.lens_data.gamma_err)**2)
return -0.5 * chi2
def log_likelihood(self, params_array: np.ndarray,
param_names: List[str]) -> float:
"""Combined log-likelihood"""
params = dict(zip(param_names, params_array))
ll_rot = self.log_likelihood_rotation(params)
ll_lens = self.log_likelihood_lensing(params)
return ll_rot + ll_lens
def log_posterior(self, params_array: np.ndarray,
param_names: List[str]) -> float:
"""Log posterior = log prior + log likelihood"""
lp = self.log_prior(params_array, param_names)
if not np.isfinite(lp):
return -np.inf
ll = self.log_likelihood(params_array, param_names)
if not np.isfinite(ll):
return -np.inf
return lp + ll
def run_mcmc(self, n_walkers: int = 32, n_steps: int = 2000,
n_burn: int = 500, initial_guess: Optional[Dict] = None):
"""
Run MCMC sampling using emcee
"""
param_names = self.halo.param_names
n_params = len(param_names)
# Initial guess
if initial_guess is None:
initial_guess = {
'rho_s': 1e7, # M_sun/kpc³
'r_s': 20.0, # kpc
'alpha': 0.17 if self.model == HaloModel.EINASTO else 1.0,
'r_core': 2.0
}
# Starting positions for walkers
p0 = np.zeros((n_walkers, n_params))
for i, name in enumerate(param_names):
val = initial_guess.get(name, 1.0)
p0[:, i] = val * (1 + 0.1 * np.random.randn(n_walkers))
# Ensure positive
p0[:, i] = np.abs(p0[:, i])
# Run MCMC
sampler = emcee.EnsembleSampler(
n_walkers, n_params, self.log_posterior,
args=(param_names,)
)
print(f"Running MCMC with {n_walkers} walkers for {n_steps} steps...")
sampler.run_mcmc(p0, n_steps, progress=True)
# Remove burn-in
self.samples = sampler.get_chain(discard=n_burn, flat=True)
# Compute best fit (median of posteriors)
self.best_fit = {}
for i, name in enumerate(param_names):
self.best_fit[name] = np.median(self.samples[:, i])
self.best_fit[f'{name}_err'] = np.std(self.samples[:, i])
# Store chain for diagnostics
self.chain = sampler.get_chain(discard=n_burn)
self.sampler = sampler
return self.samples
def compute_model_comparison(self) -> Dict[str, float]:
"""
Compute Bayesian model comparison metrics
- Log evidence (approximate)
- BIC (Bayesian Information Criterion)
- AIC (Akaike Information Criterion)
"""
if self.samples is None:
raise ValueError("Run MCMC first!")
param_names = self.halo.param_names
n_params = len(param_names)
# Get maximum likelihood
log_likes = []
for sample in self.samples[:1000]: # Subsample for speed
ll = self.log_likelihood(sample, param_names)
log_likes.append(ll)
max_ll = np.max(log_likes)
# Count data points
n_data = 0
if self.rot_data is not None:
n_data += len(self.rot_data.r)
if self.lens_data is not None:
n_data += len(self.lens_data.R)
# BIC = -2*ln(L_max) + k*ln(n)
bic = -2 * max_ll + n_params * np.log(n_data)
# AIC = -2*ln(L_max) + 2k
aic = -2 * max_ll + 2 * n_params
# Approximate evidence using harmonic mean
# (WARNING: This can be unstable - use nested sampling for production)
log_likes_all = np.array([
self.log_likelihood(s, param_names) for s in self.samples
])
log_evidence = -np.log(np.mean(np.exp(-log_likes_all - max_ll))) + max_ll
return {
'log_evidence': log_evidence,
'BIC': bic,
'AIC': aic,
'max_log_likelihood': max_ll,
'n_params': n_params,
'n_data': n_data
}
# =============================================================================
# Visualization
# =============================================================================
class HaloVisualizer:
"""Visualization tools for halo inference results"""
def __init__(self, inference: HaloInference):
self.inference = inference
self.halo = inference.halo
def plot_corner(self, save_path: Optional[str] = None):
"""Plot corner plot of parameter posteriors"""
if self.inference.samples is None:
raise ValueError("Run MCMC first!")
param_names = self.halo.param_names
labels = {
'rho_s': r'$\rho_s$ [M$_\odot$/kpc$^3$]',
'r_s': r'$r_s$ [kpc]',
'alpha': r'$\alpha$',
'r_core': r'$r_{core}$ [kpc]'
}
# Transform samples for better visualization
samples_plot = self.inference.samples.copy()
# Log-transform rho_s
rho_idx = param_names.index('rho_s')
samples_plot[:, rho_idx] = np.log10(samples_plot[:, rho_idx])
corner_labels = [labels.get(p, p) for p in param_names]
corner_labels[rho_idx] = r'$\log_{10}(\rho_s)$'
fig = corner.corner(
samples_plot,
labels=corner_labels,
quantiles=[0.16, 0.5, 0.84],
show_titles=True,
title_fmt='.2f',
title_kwargs={'fontsize': 12}
)
plt.tight_layout()
if save_path:
plt.savefig(save_path, dpi=150, bbox_inches='tight')
plt.show()
def plot_fits(self, save_path: Optional[str] = None):
"""Plot rotation curve and lensing fits with uncertainties"""
fig, axes = plt.subplots(2, 2, figsize=(14, 12))
best_fit = self.inference.best_fit
samples = self.inference.samples
param_names = self.halo.param_names
# Subsample for uncertainty bands
n_samples = min(200, len(samples))
sample_indices = np.random.choice(len(samples), n_samples, replace=False)
# --- Panel 1: Rotation Curve ---
ax = axes[0, 0]
rot_data = self.inference.rot_data
if rot_data is not None:
r_plot = np.linspace(0.1, 60, 100)
# Compute model curves for samples
v_curves = []
for idx in sample_indices:
params = dict(zip(param_names, samples[idx]))
v_dm = self.halo.circular_velocity(r_plot, params)
v_total = v_dm.copy()
if rot_data.v_stars is not None:
v_total = np.sqrt(v_total**2 + rot_data.v_stars[0]**2 *
(r_plot/rot_data.r[0])**0)
if rot_data.v_gas is not None:
v_total = np.sqrt(v_total**2 + rot_data.v_gas[0]**2 *
(r_plot/rot_data.r[0])**0)
v_curves.append(v_total)
v_curves = np.array(v_curves)
# Plot uncertainty band
v_lower = np.percentile(v_curves, 16, axis=0)
v_upper = np.percentile(v_curves, 84, axis=0)
ax.fill_between(r_plot, v_lower, v_upper, alpha=0.3,
color='navy', label='68% credible region')
# Plot best fit
params_bf = {k: v for k, v in best_fit.items()
if not k.endswith('_err')}
v_dm_bf = self.halo.circular_velocity(r_plot, params_bf)
v_total_bf = v_dm_bf.copy()
if rot_data.v_stars is not None:
v_stars_interp = interp1d(rot_data.r, rot_data.v_stars,
fill_value='extrapolate')
v_total_bf = np.sqrt(v_total_bf**2 + v_stars_interp(r_plot)**2)
if rot_data.v_gas is not None:
v_gas_interp = interp1d(rot_data.r, rot_data.v_gas,
fill_value='extrapolate')
v_total_bf = np.sqrt(v_total_bf**2 + v_gas_interp(r_plot)**2)
ax.plot(r_plot, v_total_bf, 'b-', lw=2, label='Best fit')
ax.plot(r_plot, v_dm_bf, 'b--', lw=1.5, label='DM only')
# Plot data
ax.errorbar(rot_data.r, rot_data.v_rot, yerr=rot_data.v_err,
fmt='ko', capsize=3, label='Data')
ax.set_xlabel('Radius [kpc]', fontsize=12)
ax.set_ylabel(r'$v_{rot}$ [km/s]', fontsize=12)
ax.set_xlim(0, 60)
ax.legend(loc='lower right')
ax.grid(True, alpha=0.3)
ax.set_title('Rotation Curve', fontsize=14)
# --- Panel 2: Lensing Shear ---
ax = axes[0, 1]
lens_data = self.inference.lens_data
if lens_data is not None:
R_plot = np.logspace(1, 2.7, 100)
# Compute shear curves for samples
gamma_curves = []
for idx in sample_indices:
params = dict(zip(param_names, samples[idx]))
gamma = self.halo.shear(R_plot, params, lens_data.Sigma_crit)
gamma_curves.append(gamma)
gamma_curves = np.array(gamma_curves)
# Uncertainty band
gamma_lower = np.percentile(gamma_curves, 16, axis=0)
gamma_upper = np.percentile(gamma_curves, 84, axis=0)
ax.fill_between(R_plot, gamma_lower, gamma_upper, alpha=0.3,
color='darkgreen', label='68% credible region')
# Best fit
params_bf = {k: v for k, v in best_fit.items()
if not k.endswith('_err')}
gamma_bf = self.halo.shear(R_plot, params_bf, lens_data.Sigma_crit)
ax.loglog(R_plot, gamma_bf, 'g-', lw=2, label='Best fit')
# Data
ax.errorbar(lens_data.R, lens_data.gamma_t, yerr=lens_data.gamma_err,
fmt='ko', capsize=3, label='Data')
ax.set_xlabel('Projected Radius [kpc]', fontsize=12)
ax.set_ylabel(r'$\gamma_t$', fontsize=12)
ax.legend(loc='upper right')
ax.grid(True, alpha=0.3, which='both')
ax.set_title('Weak Lensing Shear', fontsize=14)
# --- Panel 3: Density Profile ---
ax = axes[1, 0]
r_plot = np.logspace(-1, 2.5, 100)
# Plot density profiles
rho_curves = []
for idx in sample_indices:
params = dict(zip(param_names, samples[idx]))
rho = self.halo.density(r_plot, params)
rho_curves.append(rho)
rho_curves = np.array(rho_curves)
rho_lower = np.percentile(rho_curves, 16, axis=0)
rho_upper = np.percentile(rho_curves, 84, axis=0)
ax.fill_between(r_plot, rho_lower, rho_upper, alpha=0.3,
color='purple', label='68% credible region')
params_bf = {k: v for k, v in best_fit.items() if not k.endswith('_err')}
rho_bf = self.halo.density(r_plot, params_bf)
ax.loglog(r_plot, rho_bf, 'purple', lw=2, label='Best fit')
ax.axvline(params_bf['r_s'], color='gray', ls='--',
label=f'$r_s$ = {params_bf["r_s"]:.1f} kpc')
ax.set_xlabel('Radius [kpc]', fontsize=12)
ax.set_ylabel(r'$\rho(r)$ [M$_\odot$/kpc$^3$]', fontsize=12)
ax.legend(loc='upper right')
ax.grid(True, alpha=0.3, which='both')
ax.set_title('3D Density Profile', fontsize=14)
# --- Panel 4: Enclosed Mass ---
ax = axes[1, 1]
M_curves = []
for idx in sample_indices:
params = dict(zip(param_names, samples[idx]))
M = self.halo.enclosed_mass(r_plot, params)
M_curves.append(M)
M_curves = np.array(M_curves)
M_lower = np.percentile(M_curves, 16, axis=0)
M_upper = np.percentile(M_curves, 84, axis=0)
ax.fill_between(r_plot, M_lower/1e12, M_upper/1e12, alpha=0.3,
color='darkred', label='68% credible region')
M_bf = self.halo.enclosed_mass(r_plot, params_bf)
ax.semilogx(r_plot, M_bf/1e12, 'darkred', lw=2, label='Best fit')
# Mark characteristic radii
M200, r200, c200 = self.halo.compute_M200(params_bf)
ax.axvline(r200, color='orange', ls='--',
label=f'$r_{{200}}$ = {r200:.1f} kpc')
ax.axhline(M200/1e12, color='orange', ls=':',
label=f'$M_{{200}}$ = {M200/1e12:.2f} × 10¹² M$_\odot$')
ax.set_xlabel('Radius [kpc]', fontsize=12)
ax.set_ylabel(r'$M(<r)$ [10$^{12}$ M$_\odot$]', fontsize=12)
ax.legend(loc='lower right')
ax.grid(True, alpha=0.3)
ax.set_title('Enclosed Mass', fontsize=14)
plt.tight_layout()
if save_path:
plt.savefig(save_path, dpi=150, bbox_inches='tight')
plt.show()
def plot_chain(self, save_path: Optional[str] = None):
"""Plot MCMC chain diagnostics"""
if self.inference.chain is None:
raise ValueError("Run MCMC first!")
chain = self.inference.chain
param_names = self.halo.param_names
n_params = len(param_names)
fig, axes = plt.subplots(n_params, 1, figsize=(12, 2.5*n_params),
sharex=True)
if n_params == 1:
axes = [axes]
for i, (ax, name) in enumerate(zip(axes, param_names)):
ax.plot(chain[:, :, i], alpha=0.5, lw=0.5)
ax.set_ylabel(name, fontsize=11)
ax.grid(True, alpha=0.3)
axes[-1].set_xlabel('Step', fontsize=12)
plt.suptitle('MCMC Chain Evolution', fontsize=14, y=1.02)
plt.tight_layout()
if save_path:
plt.savefig(save_path, dpi=150, bbox_inches='tight')
plt.show()
# =============================================================================
# Model Comparison Utilities
# =============================================================================
def compare_models(rot_data: RotationCurveData, lens_data: LensingData,
models: List[HaloModel] = None,
n_steps: int = 1500) -> Dict[str, Dict]:
"""
Compare different halo models using Bayesian evidence
"""
if models is None:
models = [HaloModel.NFW, HaloModel.EINASTO,
HaloModel.BURKERT, HaloModel.GNFW]
results = {}
for model in models:
print(f"\n{'='*50}")
print(f"Running inference for {model.value} model")
print('='*50)
inference = HaloInference(model, rot_data, lens_data)
# Set appropriate initial guesses
if model == HaloModel.EINASTO:
initial = {'rho_s': 1e7, 'r_s': 20.0, 'alpha': 0.17}
elif model == HaloModel.GNFW:
initial = {'rho_s': 1e7, 'r_s': 20.0, 'alpha': 1.2}
else:
initial = {'rho_s': 1e7, 'r_s': 20.0}
inference.run_mcmc(n_steps=n_steps, initial_guess=initial)
metrics = inference.compute_model_comparison()
results[model.value] = {
'inference': inference,
'metrics': metrics,
'best_fit': inference.best_fit
}
print(f"\nResults for {model.value}:")
print(f" BIC: {metrics['BIC']:.1f}")
print(f" AIC: {metrics['AIC']:.1f}")
print(f" Best fit parameters:")
for k, v in inference.best_fit.items():
if not k.endswith('_err'):
print(f" {k}: {v:.3g} ± {inference.best_fit[k+'_err']:.3g}")
# Print comparison summary
print("\n" + "="*60)
print("MODEL COMPARISON SUMMARY")
print("="*60)
print(f"{'Model':<15} {'BIC':<12} {'AIC':<12} {'ΔBIC':<10}")
print("-"*60)
bic_min = min(r['metrics']['BIC'] for r in results.values())
for model_name, res in sorted(results.items(),
key=lambda x: x[1]['metrics']['BIC']):
delta_bic = res['metrics']['BIC'] - bic_min
print(f"{model_name:<15} {res['metrics']['BIC']:<12.1f} "
f"{res['metrics']['AIC']:<12.1f} {delta_bic:<10.1f}")
return results
# =============================================================================
# Main Execution
# =============================================================================
def main():
"""
Main execution: Simulate data, run inference, visualize results
"""
print("="*70)
print(" DARK MATTER HALO PROFILE INFERENCE")
print(" Lensing + Rotation Curve Data Fusion")
print("="*70)
# -------------------------------------------------------------------------
# Step 1: Define true halo parameters
# -------------------------------------------------------------------------
print("\n[1] Setting up true halo parameters...")
true_params = {
'rho_s': 8.5e6, # M_sun/kpc³
'r_s': 22.0, # kpc
'alpha': 0.18, # Einasto index (for Einasto model)
'M_star': 5e10, # M_sun (baryons)
'R_d': 3.5, # kpc (stellar disk scale length)
'M_gas': 1.2e10, # M_sun
'R_gas': 8.0 # kpc
}
print(f" True scale density: {true_params['rho_s']:.2e} M_sun/kpc³")
print(f" True scale radius: {true_params['r_s']:.1f} kpc")
# -------------------------------------------------------------------------
# Step 2: Simulate observational data
# -------------------------------------------------------------------------
print("\n[2] Simulating observations...")
simulator = DataSimulator(HaloModel.EINASTO, seed=42)
# Rotation curve (inner region)
rot_data = simulator.simulate_rotation_curve(
true_params,
r_range=(0.5, 45),
n_points=35,
velocity_error=4.0,
include_baryons=True
)
print(f" Simulated {len(rot_data.r)} rotation curve points")
# Weak lensing (outer region)
lens_data = simulator.simulate_lensing(
true_params,
R_range=(40, 400),
n_points=25,
z_lens=0.25,
z_source=0.75,
shear_error_fraction=0.12
)
print(f" Simulated {len(lens_data.R)} lensing points")
print(f" Critical surface density: {lens_data.Sigma_crit:.2e} M_sun/kpc²")
# -------------------------------------------------------------------------
# Step 3: Run Bayesian inference
# -------------------------------------------------------------------------
print("\n[3] Running Bayesian inference (NFW model)...")
inference = HaloInference(HaloModel.NFW, rot_data, lens_data)
initial_guess = {
'rho_s': 5e6,
'r_s': 25.0
}
inference.run_mcmc(
n_walkers=32,
n_steps=2000,
n_burn=500,
initial_guess=initial_guess
)
# -------------------------------------------------------------------------
# Step 4: Report results
# -------------------------------------------------------------------------
print("\n[4] Inference Results:")
print("-" * 50)
for name in inference.halo.param_names:
val = inference.best_fit[name]
err = inference.best_fit[f'{name}_err']
true_val = true_params.get(name, 'N/A')
print(f" {name:8s}: {val:10.3g} ± {err:8.2g} (true: {true_val})")
# Compute derived quantities
halo = DarkMatterHalo(HaloModel.NFW)
params_bf = {k: v for k, v in inference.best_fit.items()
if not k.endswith('_err')}
M200, r200, c200 = halo.compute_M200(params_bf)
print(f"\n Derived quantities:")
print(f" M_200 = {M200:.2e} M_sun")
print(f" r_200 = {r200:.1f} kpc")
print(f" c_200 = {c200:.2f}")
metrics = inference.compute_model_comparison()
print(f"\n Model metrics:")
print(f" BIC = {metrics['BIC']:.1f}")
print(f" AIC = {metrics['AIC']:.1f}")
# -------------------------------------------------------------------------
# Step 5: Model Comparison
# -------------------------------------------------------------------------
print("\n[5] Comparing different halo models...")
comparison_results = compare_models(
rot_data, lens_data,
models=[HaloModel.NFW, HaloModel.EINASTO, HaloModel.BURKERT],
n_steps=1500
)
# -------------------------------------------------------------------------
# Step 6: Visualization
# -------------------------------------------------------------------------
print("\n[6] Generating visualizations...")
visualizer = HaloVisualizer(inference)
# Corner plot
visualizer.plot_corner()
# Fit plots
visualizer.plot_fits()
# Chain diagnostics
visualizer.plot_chain()
# -------------------------------------------------------------------------
# Step 7: Visualize best model comparison
# -------------------------------------------------------------------------
print("\n[7] Visualizing model comparison...")
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
# Rotation curves for all models
ax = axes[0]
r_plot = np.linspace(0.5, 50, 100)
colors = {'NFW': 'blue', 'Einasto': 'green', 'Burkert': 'red'}
for model_name, res in comparison_results.items():
inf = res['inference']
params = {k: v for k, v in res['best_fit'].items() if not k.endswith('_err')}
halo_temp = DarkMatterHalo(HaloModel[model_name.upper()])
v_dm = halo_temp.circular_velocity(r_plot, params)
# Add baryons
v_stars = inf.rot_data.v_stars
v_gas = inf.rot_data.v_gas
if v_stars is not None:
v_stars_interp = interp1d(inf.rot_data.r, v_stars, fill_value='extrapolate')
v_dm = np.sqrt(v_dm**2 + v_stars_interp(r_plot)**2)
if v_gas is not None:
v_gas_interp = interp1d(inf.rot_data.r, v_gas, fill_value='extrapolate')
v_dm = np.sqrt(v_dm**2 + v_gas_interp(r_plot)**2)
ax.plot(r_plot, v_dm, color=colors.get(model_name, 'black'),
lw=2, label=model_name)
ax.errorbar(rot_data.r, rot_data.v_rot, yerr=rot_data.v_err,
fmt='ko', capsize=3, zorder=10)
ax.set_xlabel('Radius [kpc]', fontsize=12)
ax.set_ylabel(r'$v_{rot}$ [km/s]', fontsize=12)
ax.set_title('Rotation Curve: Model Comparison', fontsize=14)
ax.legend()
ax.grid(True, alpha=0.3)
# BIC comparison
ax = axes[1]
model_names = list(comparison_results.keys())
bic_values = [comparison_results[m]['metrics']['BIC'] for m in model_names]
bars = ax.bar(model_names, bic_values, color=[colors.get(m, 'gray') for m in model_names],
edgecolor='black', linewidth=1.5)
# Mark minimum BIC
min_bic = min(bic_values)
ax.axhline(min_bic, color='red', ls='--', lw=2, label=f'Min BIC = {min_bic:.0f}')
ax.set_ylabel('BIC', fontsize=12)
ax.set_title('Bayesian Information Criterion', fontsize=14)
ax.legend()
ax.grid(True, alpha=0.3, axis='y')
# Add ΔBIC labels
for i, (name, bar) in enumerate(zip(model_names, bars)):
delta = bic_values[i] - min_bic
ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 20,
f'Δ={delta:.0f}', ha='center', fontsize=10)
plt.tight_layout()
plt.show()
print("\n" + "="*70)
print(" INFERENCE COMPLETE")
print("="*70)
return inference, comparison_results
if __name__ == "__main__":
inference, comparison = main()