Create a galaxy cluster weak lensing mass calibration with systematics.
- User
Create a galaxy cluster weak lensing mass calibration with systematics.
Assistant
Create a galaxy cluster weak lensing mass calibration with systematics.
1. Understand the Goal: The user wants code to perform a "galaxy cluster weak lensing mass calibration with systematics." This is a standard, yet complex, cosmological analysis task. It involves inferring the true mass of galaxy clusters from observed weak gravitational lensing data, while accounting for various observational and theoretical biases (systematics).
Identify Key Components:
numpy, scipy for math, matplotlib for plotting. emcee or dynesty for MCMC sampling are good, but for a code example, a simple scipy.optimize or a manually written Metropolis-Hastings might be clearer and faster to run. Actually, emcee is standard enough. Let's stick to scipy for optimization to keep dependencies low, or better yet, write a clean code structure that looks like a pipeline. I will provide a complete, runnable simulation + analysis script.Drafting the Code Structure:
Refining the Physics (Mental Check):
Addressing "Systematics" specifically: The prompt asks for "calibration with systematics." I need to simulate data with systematics (e.g., the clusters are actually offset), and then fit a model that includes parameters for those systematics to recover the true mass.
Writing the Code (Iterative refinement):
astropy if possible? No, keep it dependency-light. Write a simple function using scipy.integrate.quad for integral or just an approximation. Or, just hardcode a standard cosmology ().Structure of the Output:
Code Details - specific algorithms:
Refining the "Systematics" part for the User: I will focus on three main systematics common in the literature (e.g., DES, HSC analyses):
Final Polish: Make sure the code runs, plots the result, and prints the recovered mass and systematic parameters.
(Self-Correction during coding thought process): Calculating the full NFW from scratch in a script without external libraries like cluster-toolkit or lenstool is verbose. I will include a compact, vectorized implementation of the NFW projected surface density.
Algorithm for NFW projected mass: . If , (Wait, Wright & Brainerd is better). Use the standard formula involving terms.
Let's write the code.
Dependencies: numpy, scipy, matplotlib.pyplot.
NFW Implementation detail:
Need g(x) function:
If :
-- actually use or depending on . Wright & Brainerd Eq 12-14.
Let's use special functions to handle the math cleanly.
Scaling: I will assume a single richness bin for simplicity. Fitting a scaling relation usually requires multiple bins, which makes the code much longer. I will clarify that this code calibrates the mass for a specific richness bin, which is the building block of the full scaling relation analysis.
Let's finalize the code logic.
Imports Helper Class: Cosmology Helper Functions: NFW density, Mass-Concentration () * : Setup redshifts, richness, radial bins. * : Calculate with systematics. * : Create synthetic observation. * : Standard . * : Run minimizer.
Systematics Parameterization:
This looks solid. It covers the prompt's requirements: Mass calibration + Systematics.
One detail: Boost Factor / Contamination. Often clusters contain galaxies that are actually part of the cluster but treated as sources (diluting signal). I'll skip this for brevity as Miscentering and Shear Bias are the "big two". I'll mention it in text.
Double check the NFW math. . The analytical solution is standard. I'll implement it carefully.
Let's proceed. Here is a complete Python framework for performing a Galaxy Cluster Weak Lensing Mass Calibration.
This example simulates a realistic scenario where an observable (like cluster richness) is used as a proxy for mass, but the inference is biased unless systematic errors (Miscentering, Shear Bias, and Halo Concentration) are explicitly modeled and marginalized over.
The code performs three main steps:
The Physics (shear_profile_nfw):
Weak lensing measures the Excess Surface Density (). This is calculated by integrating the 3D NFW density profile along the line of sight. The code implements the analytical solution for this integral.
The Systematics:
The Inference (log_likelihood):
We don't just fit the mass (). We fit a vector of parameters .
When you run this, you will see a "corner plot".
log10(Mass). It should peak near the True value (14.5).Miscentering and Shear Bias. If the data quality is good, these should also peak near the true values (0.2 and -0.02).Algorithm for Miscentering: The integral . Since this is slow, I will use a simplified model for the demo: The observed signal is . Where is the profile evaluated at . This is a rough approximation but suitable for a demonstration. Actually, a better approximation for the demo is to simply say the profile is "smeared" or diluted. Let's stick to the "Two-Halo" + "One-Halo" + "Miscentering" formalism structure, even if I simplify the math for the code to run fast.
Plan:
scipy.optimize.minimize allowing Mass and Systematics to vary.scipy__init__theory_modelsimulate_datalog_likelihoodfitimport numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import quad
from scipy.optimize import minimize
import emcee # Standard library for MCMC
import corner # For plotting posterior distributions
# ---------------------------------------------------------
# 1. COSMOLOGY AND HELPER FUNCTIONS
# ---------------------------------------------------------
# For this example, we use a flat Lambda-CDM cosmology
# In a real analysis, use a library like CCL or Astropy
class SimpleCosmology:
def __init__(self, Omega_m=0.3, H0=70.0):
self.Omega_m = Omega_m
self.H0 = H0
self.rho_crit_0 = 2.775e11 * (H0 / 100.0)**2 # h^2 Msun / Mpc^3
def E(self, z):
# Dimensionless Hubble parameter
return np.sqrt(self.Omega_m * (1 + z)**3 + (1 - self.Omega_m))
def angular_diameter_distance(self, z):
# Simplified comoving distance calculation (integral of c/H0 * 1/E(z))
# Using simple numerical integration for demonstration
c = 299792.458 # km/s
integral, _ = quad(lambda zi: 1.0 / self.E(zi), 0, z)
return (c / self.H0) * integral / (1.0 + z)
def rho_crit(self, z):
return self.rho_crit_0 * self.E(z)**2
cosmo = SimpleCosmology()
# ---------------------------------------------------------
# 2. PHYSICS: NFW Profile & Systematics Models
# ---------------------------------------------------------
def nfw_concentration(mass, z):
"""
Mass-Concentration relation (Duffy et al. 2008 approximation).
Crucial for breaking the mass degeneracy in lensing.
"""
# Pivot mass 2e12 Msun, typical for M-c relations
return 5.71 * (mass / 2e12)**(-0.084) * (1 + z)**(-0.47)
def nfw_f_profile(r, rs, c):
"""
Analytic helper function for NFW surface density.
"""
x = r / rs
# Handle limits to avoid numerical errors
if x < 1e-5: return 0.0
if x < 1:
# Case x < 1
term = np.sqrt(1 - x**2)
return (1 / term) * np.arctanh(term)
elif x == 1:
# Case x = 1
return 1.0
else:
# Case x > 1
term = np.sqrt(x**2 - 1)
return (1 / term) * np.arctan(term)
def shear_profile_nfw(r, mass, c, z_cluster):
"""
Calculates the Differential Surface Density Delta_Sigma for an NFW halo.
Parameters:
r: Projected radius (Mpc)
mass: M200m (Msun)
c: Concentration
z_cluster: Cluster redshift
"""
rho_crit = cosmo.rho_crit(z_cluster)
r200 = (3 * mass / (4 * np.pi * 200 * rho_crit))**(1./3.)
rs = r200 / c
# Pre-calculate constants
factor = 2 * rho_crit * r200 * c / 3
# Vectorize the calculation over radii
dsigma = []
for R in r:
x = R / rs
if x < 1e-4:
dsigma.append(0) # Avoid singularity at R=0
continue
# Calculate g(x) and f(x) based on Wright & Brainerd (2000)
if x < 1:
f_x = nfw_f_profile(R, rs, c)
g_x = np.log(x/2) + f_x
elif x == 1:
g_x = 1 + np.log(0.5)
else:
f_x = nfw_f_profile(R, rs, c)
g_x = np.log(x/2) + f_x
# Delta Sigma = 2 * Sigma_c * g(x) * factor...
# actually DeltaSigma = 2 * integral (Sigma(R') R' dR') / R^2 - Sigma(R)
# The analytical solution for DeltaSigma (Excess Surface Density) is:
# DeltaSigma = factor * g(x) / x^2 - factor * f_x
# Wait, simplifying standard Eq:
# DeltaSigma(R) = (2/r) * int[ Sigma(R') R' dR' ] - Sigma(R)
# Analytical form often used (Eq 11-12 in Wright&Brainerd):
# Let's implement the standard Delta Sigma form directly
term1 = (np.log(x/2) + f_x) / x**2
term2 = f_x
val = factor * (2 * term1 - term2) # Check derivation, usually factor * g(x)/x^2 ?
# Let's stick to the robust 'cluster-toolkit' style implementation logic:
# DeltaSigma = 2 * rho_s * rs * g(x)
# Recalculating g(x) specifically for Delta Sigma (Excess Density)
if x == 1:
g_val = 1.0 / 3.0
else:
if x < 1:
atanh = np.arctanh(np.sqrt(1 - x*x))
g_val = (8 * atanh / (x**2 * np.sqrt(1 - x**2))) + \
(4 * np.log(x/2) / x**2) - \
(2 / x**2) + \
(4 * atanh / x**2 / np.sqrt(1 - x**2))
else:
atan = np.arctan(np.sqrt(x*x - 1))
g_val = (8 * atan / (x**2 * np.sqrt(x**2 - 1))) - \
(4 * np.log(x/2) / x**2) - \
(2 / x**2) + \
(4 * atan / x**2 / np.sqrt(x**2 - 1))
rho_s = rho_crit * 200.0 / 3.0 * c**3 / (np.log(1+c) - c/(1+c))
dsigma.append(2 * rho_s * rs * g_val)
return np.array(dsigma)
# ---------------------------------------------------------
# 3. SYSTEMATICS KERNELS
# ---------------------------------------------------------
def model_miscentering(r, profile, sigma_off):
"""
Convolve the ideal profile with a 2D Gaussian to simulate miscentering.
R_off follows a Rayleigh distribution.
In a full analysis, this is an integral convolution.
Here we approximate by generating a finely sampled grid and convolving.
"""
# For speed in MCMC, we often use pre-computed tables.
# Here, we do a numerical convolution for demonstration.
dr = r[1] - r[0]
# Pad arrays to avoid boundary effects
r_pad = np.linspace(0, r[-1]*2, len(r)*2)
# Interpolate profile to padded grid
prof_pad = np.interp(r_pad, r, profile, left=0, right=0)
# Create convolution kernel (Rayleigh distribution PDF projected onto 1D radius?)
# Actually, for DeltaSigma, the miscentering kernel is complex.
# We simplify: Smooth the profile slightly.
# True miscentering moves signal from small R to large R.
# Approximate kernel: Gaussian smoothing weighted by miscentering fraction
# (A rigorous implementation uses Hankel transforms)
kernel = np.exp(-0.5 * (r_pad / sigma_off)**2)
kernel /= np.sum(kernel)
convolved = np.convolve(prof_pad, kernel, mode='same')
return np.interp(r, r_pad, convolved)
# ---------------------------------------------------------
# 4. MAIN PIPELINE
# ---------------------------------------------------------
# A. SIMULATE DATA (Truth)
np.random.seed(42)
# Cluster Setup
z_cluster = 0.3
log_mass_true = 14.5 # log10(M200 / Msun)
mass_true = 10**log_mass_true
conc_true = nfw_concentration(mass_true, z_cluster)
# Radii Bins
radii = np.linspace(0.5, 5.0, 10) # Mpc
# Generate Ideal Signal
dsigma_ideal = shear_profile_nfw(radii, mass_true, conc_true, z_cluster)
# INJECT SYSTEMATICS
# 1. Miscentering: The cluster center is offset by ~0.2 Mpc on average
miscentering_sigma = 0.2 # Mpc
dsigma_mis = model_miscentering(radii, dsigma_ideal, miscentering_sigma)
# 2. Shear Calibration Bias: We underestimate shear by 2% (m = -0.02)
shear_bias_m = -0.02
dsigma_obs = dsigma_mis * (1 + shear_bias_m)
# 3. Shape Noise / Uncertainty
# Real errors depend on source density and shape noise. Assume 5% error here.
errors = 0.05 * dsigma_obs + 1e13 # Add small floor
dsigma_data = dsigma_obs + np.random.normal(0, errors)
# ---------------------------------------------------------
# 5. INFERENCE (Fitting Model to Data)
# ---------------------------------------------------------
def log_likelihood(theta):
"""
theta = [log10(Mass), Concentration, Miscentering Sigma, Shear Bias m]
"""
logm, c, sigma_off, m_bias = theta
# Priors (Uniform or Gaussian based on prior knowledge)
# Mass: 12 to 16
if not (13.0 < logm < 16.0): return -np.inf
# Concentration: Physical range
if not (1.0 < c < 10.0): return -np.inf
# Miscentering: 0 to 1 Mpc
if not (0.0 < sigma_off < 1.0): return -np.inf
# Shear bias: typically small
if not (-0.1 < m_bias < 0.1): return -np.inf
# Add Gaussian Prior on Concentration (Mass-Concentration relation)
# Helps break degeneracy. We assume we know the scatter (sigma=0.1 dex)
c_expected = nfw_concentration(10**logm, z_cluster)
prior_c = -0.5 * ((c - c_expected) / 0.3)**2
mass = 10**logm
# 1. Theory Prediction (NFW)
dsigma_model_ideal = shear_profile_nfw(radii, mass, c, z_cluster)
# 2. Apply Systematics Model (Forward modeling)
# Miscentering Convolution
dsigma_model_mis = model_miscentering(radii, dsigma_model_ideal, sigma_off)
# Shear Bias Correction (Model predicts truth, 'data' has bias, or vice versa)
# Here: Model = Truth. Data = Truth * (1+m).
# So: Residual = Data - Model*(1+m) ?
# Usually we calibrate the data: Data_Corr = Data / (1+m)
# Or we debias the model: Model_Obs = Model * (1+m)
# Let's assume our model predicts the observed signal given the bias parameter
model_prediction = dsigma_model_mis * (1 + m_bias)
# 3. Likelihood
# Chi-squared
residual = dsigma_data - model_prediction
chi2 = np.sum((residual / errors)**2)
return -0.5 * chi2 + prior_c
# Run MCMC
nwalkers = 32
ndim = 4
initial_pos = [14.3, 3.0, 0.1, 0.0] + 1e-2 * np.random.randn(nwalkers, ndim)
sampler = emcee.EnsembleSampler(nwalkers, ndim, log_likelihood)
print("Running MCMC...")
sampler.run_mcmc(initial_pos, 2000, progress=True);
# Process Chains
samples = sampler.get_chain(discard=500, thin=15, flat=True)
# ---------------------------------------------------------
# 6. RESULTS & VISUALIZATION
# ---------------------------------------------------------
# Plotting the Posterior
fig = corner.corner(samples,
labels=["log10(Mass)", "Concentration", "Miscentering $\sigma$", "Shear Bias $m$"],
truths=[log_mass_true, conc_true, miscentering_sigma, shear_bias_m],
quantiles=[0.16, 0.5, 0.84],
show_titles=True)
plt.suptitle("Mass Calibration with Systematics Posteriors")
plt.show()
# Print Final Mass Estimate
mcmc_mass = np.percentile(samples[:, 0], [16, 50, 84])
print(f"\nTrue Log Mass: {log_mass_true:.3f}")
print(f"Measured Log Mass: {mcmc_mass[1]:.3f} + {mcmc_mass[2]-mcmc_mass[1]:.3f} - {mcmc_mass[1]-mcmc_mass[0]:.3f}")