Build a strong lens time-delay cosmography pipeline: lens models, microlensing…
- User
Build a strong lens time-delay cosmography pipeline: lens models, microlensing corrections, and inference.
Assistant
Build a strong lens time-delay cosmography pipeline: lens models, microlensing corrections, and inference.
The user wants to build a strong lens time-delay cosmography pipeline. This is a complex, multi-step process in astrophysics used to measure the Hubble constant (). I need to outline the key stages of such a pipeline.
1. Understanding the Goal:
2. Deconstructing the Pipeline: A standard pipeline (like the H0LiCOW/TDCOSMO collaboration) involves three main ingredients:
Wait, the user specifically asked for "lens models, microlensing corrections, and inference". I should focus on these specific aspects while briefly mentioning the others for context.
Microlensing: This affects the light curves (flux anomalies) but is distinct from the macrolens model. It's crucial for accurate time-delay measurement if the source is a quasar (variable continuum) but less critical for supernovae (extended variable surface brightness). The prompt implies a general strong lensing context, so I should include it.
3. Structuring the Response:
lenstronomy or PyAutoLens as examples.4. Drafting the Content - Section by Section:
Step 2 (Lens Models): Need to mention the mass-light alignment, radial profile shapes (Power-law vs. NFW), and the role of the Stellar Velocity Dispersion (SVD) to break the mass-sheet degeneracy. Self-correction: Make sure to emphasize the Mass-Sheet Degeneracy (MSD) as it's the biggest headache in this field.
Step 3 (Microlensing): How do we handle it? Usually via inverse ray-tracing to create magnification maps. Then convolving the source random walk with the map. Or, if doing pure time delay, it's a contaminant to be removed or modeled as a Gaussian Process (GP) in the light curves.
Step 5 (Inference): is the output of the lens model. Posterior: .
5. Creating the Code Skeleton:
I cannot write a full, runnable C++ or complex Fortran pipeline in a single response. Python is the standard now. lenstronomy is the most accessible library for this.
I will write a Python script structure that:
LensModel (SPEMD + Shear).Source (Sersic).emcee or dynesty).Refining the Code:
lenstronomy handles point sources (quasars) vs extended sources. I will simulate a lensed quasar system.6. Refining the Microlensing Section:
7. Putting it together:
lenstronomy and emcee.Self-Correction during drafting:
kappa_star (convergence in stars).8. Final Review of the "Strong Pipeline" requirements:
kappa_star, gamma, s. Mention impact on Time Delays (Hubble constant bias).Let's write the Python code using lenstronomy syntax as it's the industry standard for this.
Structure:
This looks solid. I will ensure the distinction between Macro-modeling (for time delays) and Micro-modeling (for flux/light curve systematics) is clear.
Special Note on Microlensing: In cosmography, microlensing is often treated as a noise process in the light curves or a perturbation to flux ratios. I will focus on how to account for it to ensure unbiased time delays.
Let's generate the response. This is a comprehensive outline and implementation strategy for a Strong Lens Time-Delay Cosmography pipeline. This pipeline is designed to measure the Hubble Constant () by measuring the time delay between multiple images of a variable background source (e.g., a quasar) and combining that with a model of the lens galaxy's mass distribution.
We will use a Bayesian Hierarchical approach, utilizing Python libraries like lenstronomy (for modeling) and dynesty (for inference).
The fundamental equation governing time-delay cosmography relates the observed time delay between two images to the "Time-Delay Distance" and the difference in the Fermat potential :
Where:
A production-grade pipeline consists of four main stages:
You will need the following stack:
lenstronomy, dynesty, numpy, matplotlib, scipy, astropy.
Quasar microlensing occurs when stars in the lens galaxy move, causing uncorrelated flux variations in the images. This creates "random walks" in the light curves that are not intrinsic to the quasar. If uncorrected, this biases the time delay.
Strategy: We model the intrinsic quasar variability as a shared signal (e.g., a Gaussian Process or spline) and the microlensing as a separate, slower stochastic trend per image.
import numpy as np
from scipy.interpolate import splrep, splev
import emcee
# Conceptual Class for Time Delay Extraction
class TimeDelayExtractor:
def __init__(self, light_curves, errors):
"""
light_curves: dict {image_id: {'t': [], 'mag': []}}
"""
self.data = light_curves
self.errors = errors
def ln_likelihood(self, params):
"""
params: [delta_t_12, delta_t_13, ..., intrinsic_params..., microlensing_params...]
"""
# 1. Reconstruct the intrinsic light curve (using e.g. a spline)
# 2. Shift images by proposed delta_t to align with intrinsic curve
# 3. Add microlensing perturbation term (often modeled as low-order polynomial or GP)
# 4. Calculate chi-squared difference
pass
def run_sampler(self):
# Use MCMC (emcee) to marginalize over microlensing and get posterior of delta_t
pass
def get_delays(self):
# Returns mean and covariance matrix of time delays
return delay_mean, delay_cov
This step determines the mass distribution of the lens galaxy (usually an Elliptical Power Law + External Shear). We need to solve the lens equation: .
We perform this using lenstronomy.
from lenstronomy.Workflow.fitting_sequence import FittingSequence
from lenstronomy.Data.imaging_data import ImageData
from lenstronomy.Data.psf import PSF
from lenstronomy.LensModel.lens_model import LensModel
from lenstronomy.LightModel.light_model import LightModel
import lenstronomy.Plots.model_plot as model_plot
class LensModelingPipeline:
def __init__(self, image_data, psf_kernel, kwargs_data):
self.image_data = image_data
self.psf_kernel = psf_kernel
def setup_model(self):
# Lens Mass Model: Singular Power Law Ellipsoid (SPEP) + Shear
lens_model_list = ['SPEP', 'SHEAR']
# Lens Light Model: Sersic ellipse
lens_light_model_list = ['SERSIC_ELLIPSE']
# Source Light Model: Shapelets (good for irregular sources) or Sersic
source_light_model_list = ['SHAPELETS']
# PSF handling
kwargs_psf = {'psf_type': 'PIXEL', 'kernel_point_source': self.psf_kernel}
return lens_model_list, lens_light_model_list, source_light_model_list
def run_inference(self):
# Define fitting sequence: PSF fitting -> Light -> Mass
fitting_sequence = FittingSequence(...)
# Run Nested Sampling (Dynesty) to get posterior on mass parameters
chain_list = fitting_sequence.fit_sequence(...)
# Extract samples for lens mass parameters (theta_E, gamma, center, ellipticity)
return mass_posterior_samples
Now we combine the Time Delay () and the Lens Model ().
The likelihood is:
However, we must also include Stellar Kinematics to break the Mass-Sheet Degeneracy. (complex integral involving mass profile).
Here is the composite Inference Pipeline:
import dynesty
from astropy.cosmology import FlatLambdaCDM
class CosmographyInference:
def __init__(self, delay_posterior, lens_posterior, kinematics_data, z_lens, z_source):
self.delays = delay_posterior
self.lens = lens_posterior
self.kin = kinematics_data
self.z_l = z_lens
self.z_s = z_source
def log_likelihood(self, H0, kappa_ext, gamma_ppn, mass_params):
"""
H0: Hubble Constant
kappa_ext: External Convergence (Line of sight contamination)
gamma_ppn: Mass density slope (Post-Newtonian Parameter, relates to SPEP gamma)
mass_params: Specific realization of lens mass model
"""
# 1. Define Cosmology
cosmo = FlatLambdaCDM(H0=H0, Om0=0.3) # Assuming flat universe
# 2. Calculate Time Delay Distance D_dt
D_dt = cosmo.angular_diameter_distance_z1z2(self.z_l, self.z_s) * (1 + self.z_s)
# 3. Apply External Convergence Correction
# D_dt_eff = D_dt / (1 - kappa_ext)
D_dt_eff = D_dt / (1 - kappa_ext)
# 4. Calculate Model Time Delay from mass_params
# (Using lenstronomy util here is recommended in real code)
fermat_potential_diff = calculate_fermat_potential(mass_params)
# 5. Compare Observed vs Model
# Likelihood from Time Delay
model_delay = (D_dt_eff / 299792.458) * fermat_potential_diff
chi2_delay = np.sum((self.delays - model_delay)**2 / self.delays_err**2)
# 6. Likelihood from Kinematics (Velocity Dispersion)
# Requires anisotropy radius and aperture info
v_sigma_model = compute_velocity_dispersion(mass_params, H0)
chi2_kin = (self.kin - v_sigma_model)**2 / self.kin_err**2
return -0.5 * (chi2_delay + chi2_kin)
def run_dynesty(self):
# Run Nested Sampling over H0 and nuisance parameters (kappa_ext, etc)
sampler = dynesty.NestedSampler(self.log_likelihood, self.prior_transform, ndim=...)
sampler.run_nested()
return sampler.results
To make this pipeline "strong" (state-of-the-art), you must address the following:
The lens equation is invariant under the transformation: This means the same image configuration can be produced by different mass profiles, yielding different time delays. Solution:
Mass along the line of sight (unassociated with the main lens) adds convergence. Solution: Use deep wide-field imaging to count galaxies around the lens and compare to numerical simulations (like the Illustris or Millennium simulation) to statistically estimate .
Do not just subtract a polynomial.
PyCS (Python for Cosmic Surveys) are specialized for this.lenstronomy to fit the surface brightness of the lens and source. Obtain the posterior distribution of the mass parameters (, , ).PyCS or GPs to measure and its uncertainty, marginalizing over microlensing trends.This pipeline represents the standard methodology used by collaborations like TDCOSMO (Time Delay COSMOgraphy).