---
title: 'Lenstronomy: Python Lensing Framework'
url: https://www.emergentmind.com/topics/lenstronomy-framework
type: topic
---

# Lenstronomy: Python Lensing Framework

Lenstronomy is an open-source, Astropy-affiliated Python framework for forward modeling and analysis of strong gravitational lensing data, targeting both galaxy- and cluster-scale regimes. Designed around modular, interchangeable components, it enables precise and reproducible inference of mass distributions, light profiles, and cosmological parameters by integrating high-performance algorithms, linear and non-linear modeling, state-of-the-art inference techniques, and an expanding ecosystem of specialized extensions. Lenstronomy has provided the foundation for a broad range of contemporary research, including Hubble constant determinations, dark matter substructure constraints, and the characterization of galactic and cluster lens morphologies [2106.05976], [1803.09746].

## 1. Modular Architecture and Core Components

Lenstronomy's architecture explicitly separates the strong lensing forward-modeling pipeline into discrete, interchangeable modules, each responsible for a fundamental modeling aspect [2106.05976], [1803.09746]:

- **LensModel**: Implements a registry of analytic 2D mass profiles—Singular Isothermal Sphere (SIS), Singular Isothermal Ellipsoid (SIE), Elliptical Power-Law (EPL), Navarro–Frenk–White (NFW), point mass, external shear—as well as composite and multi-plane lenses. Each profile exposes methods for computing convergence, deflection angles, lensing potentials, and solves the thin-lens equation $\boldsymbol{\beta} = \boldsymbol{\theta} - \nabla\psi(\boldsymbol{\theta})$.
- **LightModel**: Provides parametric surface-brightness models (SERSIC, EXP, GAUSSIAN), as well as basis expansions (SHAPELETS, PIXELATED) for both lens and source light distributions.
- **PSF**: Supports both analytic (Gaussian) and empirical (PIXEL) point spread function models via `lenstronomy.ImSim.psf.PSF`, with functionality for PSF reconstruction.
- **Data classes**: Central is `ImagingData`, encapsulating the image array, noise map, mask, and pixel scale; variants exist for IFU and time-delay data.
- **Fitting/Sampling**: Exposed through a unified `FittingSequence` interface, offering global optimization (Particle Swarm—PSO, Nelder–Mead, BFGS) and posterior sampling (affine-invariant MCMC via emcee).
- **ImageModel**: The glue class that combines mass, light, PSF, and data modules to implement forward models and likelihood calculations.

Each model component is configured with its own parameter dictionary (Python dict), and parameter transformations, priors, and bounds are managed via dedicated `ParameterLens`, `ParameterSource` classes. This modular layering allows for rapid extension and custom profile integration without monolithic code modifications [2106.05976].

## 2. Mathematical and Algorithmic Foundations

The fundamental mathematical core is built upon the standard thin-lens formulation:
\[
\boldsymbol{\beta} = \boldsymbol{\theta} - \nabla\psi(\boldsymbol{\theta})
\]
where $\psi$ is the (possibly multi-component) lensing potential derived by summing contributions from active mass profiles.

The image-plane pixel values $d_i$ are modeled as:
\[
m_i(\{p\}) = \mathrm{PSF} \otimes \Big[ I_\mathrm{lens\ light}(\boldsymbol{\theta}_i; p_l) + I_\mathrm{source}(\boldsymbol{\theta}_i - \boldsymbol{\alpha}(\boldsymbol{\theta}_i; p_m); p_s) \Big]
\]
and compared to the observed data with a Gaussian likelihood:
\[
\log L = -\frac{1}{2} \sum_i \frac{(d_i - m_i)^2}{\sigma_i^2} + \text{const}
\]
For extended sources with linear basis sets (e.g., pixel, shapelet, starlet), the forward model is expressed as $m = \mathrm{PSF} \cdot D s$, with $D$ the ray-tracing and pixel-mapping operator and $s$ the vector of linear coefficients.

The regularized maximum posterior solution is obtained via:
\[
(D^T N^{-1} D + \lambda R)\, \hat s = D^T N^{-1} d
\]
where $R$ encodes the regularization (e.g., Tikhonov), and $\lambda$ is the regularization weight. High-dimensional inference is tractable as the linear subproblems are solved exactly while sampling only the non-linear parameters (mass, PSF, regularization strength, etc.) with optimization or MCMC [2106.05976], [1803.09746].

## 3. Inference, Optimization, and Data Flow

Lenstronomy abstracts optimization and inference across the following workflow [2106.05976]:

- **Global optimization**: Initial exploration and approximation of the maximum likelihood region with PSO or Nelder–Mead.
- **Posterior sampling**: Emcee affine-invariant MCMC, with parameter vectorization and storage of full chains, supporting uncertainty propagation and credible interval extraction.
- **Likelihood calculation**: Encapsulated in the `lenstronomy.LensModel.likelihood` module and wrapped by `FittingSequence`, this module consistently computes per-pixel $\chi^2$ residuals between model and data.
- **Data structures**: Model and data objects are instantiated via documented APIs, with parameter input by Python dicts. End-to-end workflow is orchestrated by `FittingSequence`, which manages the calling order, parameter passing, and results collation.
- **Parameters**: All model parameters, including lens mass, light distributions, PSF kernel, and regularization strengths, can be freely or hierarchically varied. The forward model is always evaluable at arbitrary parameter vectors.

A representative flow is:
```python
fitting_seq = FittingSequence(data_class, psf_class, lens_light_model_class, source_light_model_class, lens_model_class)
# PSO for starting value:
kwargs_best, _ = fitting_seq.run_optimization(optimizer='PSO', kwargs_constraints=...)
# MCMC for posterior refinement:
chain_list = fitting_seq.run_mcmc(kwargs_best, n_burn=200, n_run=1000)
```
All subcomponents propagate uncertainties, and outputs include best-fit parameter sets as well as full chain diagnostics [2106.05976].

## 4. Affiliated Packages and Ecosystem Extensions

Lenstronomy's API and interface design have fostered a rich ecosystem of “affiliated” packages [2106.05976]:

- **SLITronomy** [2012.02802]: Wavelet-based (starlet) source-lens inversion plug-in, registering its own SLIT_STARLETS light model within the Lenstronomy LightModel module. SLITronomy implements $\ell_1$-regularized, sparsity-promoting inversion using the starlet transform, enabling high-fidelity source reconstructions at $\lesssim$1 s per inversion even for HST-sized cutouts. Key methods (e.g., `solve()`) dispatch to a convex optimization combining data-fidelity and starlet-domain sparsity priors.
- **lenstruction** [2001.07719]: Provides cluster-scale source reconstruction and local perturbative corrections (up to flexion) for multiply-imaged systems, with a forward-modeling approach building upon cluster lensing map inputs (HFF format).
- **pyHalo**: Realistic dark matter subhalo population generator, feeding substructure models to the core LensModel.
- **dolphin**, **hierArc**, **deeplenstronomy**, **baobab**: Large-scale modeling pipelines, hierarchical inference, or dataset simulation/interfaces for cosmological and machine learning studies.
- **galight**: Automated lens-galaxy light fitting algorithms.
- **h0rton**, **ovejero**: Bayesian deep learning pipelines for time-delay cosmography and hierarchical population inference.

This extensibility allows for research-grade analyses in time-delay cosmography, subhalo detection, cluster lensing corrections, and machine-learning dataset creation.

## 5. Representative Scientific Applications

Major research domains enabled by Lenstronomy include [2106.05976], [1803.09746]:

- **Time-delay cosmography**: Robust $H_0$ measurements from multiply imaged quasars. By combining lens modeling, time-delay analysis, and stellar dynamics, the overall uncertainty budget can be driven to a few percent, subject to assumptions on mass profiles and PSF modeling.
- **Dark matter substructure constraints**: By pixel-level modeling of finely resolved Einstein rings, subhalos to $\sim10^7\,M_\odot$ can be detected or ruled out, with detailed marginalization over host and line-of-sight halo populations.
- **Population-scale modeling**: Used to uniformly model large samples of quad lenses or cluster arcs, enabling systematic studies of mass–light misalignments, ellipticity distributions, and flux-ratio anomalies.
- **Extended source and light reconstruction**: Starlets, shapelets, and pixel-based basis sets allow for maximally flexible source morphologies across a range of wavelength regimes, including forthcoming 30 m–class telescope data.

Backend implementations are parallelized to efficiently leverage multicore CPUs for high-throughput inference across lens samples [1807.09278].

## 6. Implementation, Usage, and Best Practices

Lenstronomy is distributed under the MIT license. Installation and reproducibility are central priorities:

- **Installation**: Standard Python package managers are supported:
  ```
  $ pip install lenstronomy
  ```
- **Documentation and Examples**: Tutorials, API docs, and starter Jupyter notebooks are available at https://lenstronomy.readthedocs.io and https://github.com/sibirrer/lenstronomy_extensions.
- **Parameter management**: All parameters are input via well-documented dict APIs, enabling both script-based and notebook-driven workflows.
- **Performance**: The most expensive operations (supersampled ray-tracing, source inversion) are efficiently vectorized; e.g., SLITronomy starlet inversion achieves $\sim10^3\times$ speedup over naive implementations [2012.02802].
- **PSF modeling**: Empirical and iterative PSF modes should be adopted whenever feasible, and users are advised to propagate PSF model uncertainties through the full analysis, especially in time-delay cosmography contexts.
- **Automation**: Workflows can be fully automated (see uniform quad modeling in [1807.09278]) with minimal hand-tuning by leveraging decision-tree pipelines and robust priors.

The framework's combination of modularity, extensibility, validated mathematical algorithms, and performance-centric engineering underpin its role as the primary lens modeling engine in contemporary strong lensing research [2106.05976], [1803.09746].

Source: https://www.emergentmind.com/topics/lenstronomy-framework