lenstronomy.Sampling package

Subpackages

Submodules

lenstronomy.Sampling.likelihood module

class LikelihoodModule(kwargs_data_joint, kwargs_model, param_class, image_likelihood=True, check_bounds=True, check_matched_source_position=False, astrometric_likelihood=False, image_position_likelihood=False, source_position_likelihood=False, image_position_uncertainty=0.004, check_positive_flux=False, source_position_tolerance=0.001, source_position_sigma=0.001, force_no_add_image=False, source_marg=False, linear_prior=None, restrict_image_number=False, max_num_images=None, bands_compute=None, time_delay_likelihood=False, image_likelihood_mask_list=None, flux_ratio_likelihood=False, kwargs_flux_compute=None, prior_lens=None, prior_source=None, prior_extinction=None, prior_lens_light=None, prior_ps=None, prior_special=None, prior_lens_kde=None, prior_source_kde=None, prior_lens_light_kde=None, prior_ps_kde=None, prior_special_kde=None, prior_extinction_kde=None, prior_lens_lognormal=None, prior_source_lognormal=None, prior_extinction_lognormal=None, prior_lens_light_lognormal=None, prior_ps_lognormal=None, prior_special_lognormal=None, custom_logL_addition=None, kwargs_pixelbased=None, kinematic_2d_likelihood=False, kin_lens_idx=0, kin_lens_light_idx=0, tracer_likelihood=False, tracer_likelihood_mask=None)[source]

Bases: object

This class contains the routines to run a MCMC process.

the key components are: - imSim_class: an instance of a class that simulates one (or more) images and returns the likelihood, such as ImageModel(), Multiband(), MultiExposure() - param_class: instance of a Param() class that can cast the sorted list of parameters that are sampled into the conventions of the imSim_class

Additional arguments are supported for adding a time-delay likelihood etc (see __init__ definition)

__init__(kwargs_data_joint, kwargs_model, param_class, image_likelihood=True, check_bounds=True, check_matched_source_position=False, astrometric_likelihood=False, image_position_likelihood=False, source_position_likelihood=False, image_position_uncertainty=0.004, check_positive_flux=False, source_position_tolerance=0.001, source_position_sigma=0.001, force_no_add_image=False, source_marg=False, linear_prior=None, restrict_image_number=False, max_num_images=None, bands_compute=None, time_delay_likelihood=False, image_likelihood_mask_list=None, flux_ratio_likelihood=False, kwargs_flux_compute=None, prior_lens=None, prior_source=None, prior_extinction=None, prior_lens_light=None, prior_ps=None, prior_special=None, prior_lens_kde=None, prior_source_kde=None, prior_lens_light_kde=None, prior_ps_kde=None, prior_special_kde=None, prior_extinction_kde=None, prior_lens_lognormal=None, prior_source_lognormal=None, prior_extinction_lognormal=None, prior_lens_light_lognormal=None, prior_ps_lognormal=None, prior_special_lognormal=None, custom_logL_addition=None, kwargs_pixelbased=None, kinematic_2d_likelihood=False, kin_lens_idx=0, kin_lens_light_idx=0, tracer_likelihood=False, tracer_likelihood_mask=None)[source]

Initializing class.

Parameters:
  • param_class – instance of a Param() class that can cast the sorted list of parameters that are sampled into the conventions of the imSim_class

  • image_likelihood – bool, option to compute the imaging likelihood

  • source_position_likelihood – bool, if True, ray-traces image positions back to source plane and evaluates relative errors in respect ot the position_uncertainties in the image plane

  • check_bounds – bool, option to punish the hard bounds in parameter space

  • check_matched_source_position – bool, option to check whether point source position of solver finds a solution to match all the image positions in the same source plane coordinate

  • astrometric_likelihood – bool, additional likelihood term of the predicted vs modelled point source position

  • image_position_uncertainty – float, 1-sigma Gaussian uncertainty on the point source position (only used if point_source_likelihood=True)

  • check_positive_flux – bool, option to punish models that do not have all positive linear amplitude parameters

  • source_position_tolerance – float, punishment of check_solver occurs when image positions are predicted further away than this number

  • image_likelihood_mask_list – list of boolean 2d arrays of size of images marking the pixels to be evaluated in the likelihood

  • force_no_add_image – bool, if True: computes ALL image positions of the point source. If there are more images predicted than modelled, a punishment occurs

  • source_marg – marginalization addition on the imaging likelihood based on the covariance of the inferred linear coefficients

  • linear_prior – float or list of floats (when multi-linear setting is chosen) indicating the range of linear amplitude priors when computing the marginalization term.

  • restrict_image_number – bool, if True: computes ALL image positions of the point source. If there are more images predicted than indicated in max_num_images, a punishment occurs

  • max_num_images – int, see restrict_image_number

  • bands_compute – list of bools with same length as data objects, indicates which “band” to include in the fitting

  • time_delay_likelihood – bool, if True computes the time-delay likelihood of the FIRST point source

  • kwargs_flux_compute – keyword arguments of how to compute the image position fluxes (see FluxRatioLikeliood)

  • custom_logL_addition – a definition taking as arguments (kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_ps, kwargs_special, kwargs_extinction) and returns a logL (punishing) value.

  • kwargs_pixelbased – keyword arguments with various settings related to the pixel-based solver (see SLITronomy documentation)

  • kinematic_2d_likelihood – bool, option to compute the kinematic likelihood

  • tracer_likelihood – option to perform likelihood on tracer quantity derived from imaging or spectroscopy

property kwargs_imaging

Dictionary of imaging model keyword arguments.

Returns:

kwargs_imaging

logL(args, verbose=False)[source]

Routine to compute X2 given variable parameters for a MCMC/PSO chain.

Parameters:
  • args (tuple or list of floats) – ordered parameter values that are being sampled

  • verbose (boolean) – if True, makes print statements about individual likelihood components

Returns:

log likelihood of the data given the model (natural logarithm)

log_likelihood(kwargs_return, verbose=False)[source]
Parameters:
  • kwargs_return (keyword arguments) – need to contain ‘kwargs_lens’, ‘kwargs_source’, ‘kwargs_lens_light’, ‘kwargs_ps’, ‘kwargs_special’. These entries themselves are lists of keyword argument of the parameters entering the model to be evaluated

  • verbose (boolean) – if True, makes print statements about individual likelihood components

Returns:

  • logL (float) log likelihood of the data given the model (natural logarithm)

static check_bounds(args, lowerLimit, upperLimit, verbose=False)[source]

Checks whether the parameter vector has left its bound, if so, adds a big number.

property num_data
Returns:

number of independent data points in the combined fitting

property param_limits
effective_num_data_points(**kwargs)[source]

Returns the effective number of data points considered in the X2 estimation to compute the reduced X2 value.

likelihood(a)[source]
negativelogL(a)[source]

For minimizer function, the negative value of the logl value is requested.

Parameters:

a – array of parameters

Returns:

-logL

lenstronomy.Sampling.parameters module

class Param(kwargs_model, kwargs_fixed_lens=None, kwargs_fixed_source=None, kwargs_fixed_lens_light=None, kwargs_fixed_ps=None, kwargs_fixed_special=None, kwargs_fixed_extinction=None, kwargs_fixed_tracer_source=None, kwargs_lower_lens=None, kwargs_lower_source=None, kwargs_lower_lens_light=None, kwargs_lower_ps=None, kwargs_lower_special=None, kwargs_lower_extinction=None, kwargs_lower_tracer_source=None, kwargs_upper_lens=None, kwargs_upper_source=None, kwargs_upper_lens_light=None, kwargs_upper_ps=None, kwargs_upper_special=None, kwargs_upper_extinction=None, kwargs_upper_tracer_source=None, kwargs_lens_init=None, linear_solver=True, joint_lens_with_lens=[], joint_lens_light_with_lens_light=[], joint_source_with_source=[], joint_lens_with_light=[], joint_source_with_point_source=[], joint_lens_light_with_point_source=[], joint_extinction_with_lens_light=[], joint_lens_with_source_light=[], joint_source_light_with_tracer=None, mass_scaling_list=None, point_source_offset=False, general_scaling=None, num_point_source_list=None, image_plane_source_list=None, solver_type='NONE', Ddt_sampling=None, source_size=False, num_tau0=0, lens_redshift_sampling_indexes=None, source_redshift_sampling_indexes=None, source_grid_offset=False, kinematic_sampling=None, num_shapelet_lens=0, log_sampling_lens=[])[source]

Bases: object

Class that handles the parameter constraints. In particular when different model profiles share joint constraints.

Options between same model classes:

‘joint_lens_with_lens’:list [[i_lens, k_lens, [‘param_name1’, ‘param_name2’, …]], […], …], joint parameter between two lens models

‘joint_lens_light_with_lens_light’:list [[i_lens_light, k_lens_light, [‘param_name1’, ‘param_name2’, …]], […], …], joint parameter between two lens light models, the second adopts the value of the first

‘joint_source_with_source’:list [[i_source, k_source, [‘param_name1’, ‘param_name2’, …]], […], …], joint parameter between two source surface brightness models, the second adopts the value of the first

Options between different model classes:

‘joint_lens_with_light’: list [[i_light, k_lens, [‘param_name1’, ‘param_name2’, …]], […], …], joint parameter between lens model and lens light model

‘joint_source_with_point_source’: list [[i_point_source, k_source], […], …], joint position parameter between source light model and point source

‘joint_lens_light_with_point_source’: list [[i_point_source, k_lens_light], […], …], joint position parameter between lens model and lens light model

‘joint_extinction_with_lens_light’: list [[i_lens_light, k_extinction, [‘param_name1’, ‘param_name2’, …]], […], …], joint parameters between the lens surface brightness and the optical depth models

‘joint_lens_with_source_light’: [[i_source, k_lens, [‘param_name1’, ‘param_name2’, …]], […], …], joint parameter between lens model and source light model. Samples light model parameter only.

‘mass_scaling_list’: e.g. [False, 1, 1, False, 2, False, 1, …] Links lens models to have their masses scaled together. In this example, masses with False are not scaled, masses labeled 1 are scaled together, and those labeled 2 are scaled together independent of 1, etc.

‘general_scaling’: { ‘param1’: [False, 1, 1, False, 1, …], ‘param2’: [1, 1, 1, False, 2, 2, …] } Generalized parameter scaling. Input should be a dictionary mapping parameter names to the masks defining which lens models are scaled together, in the same format as for ‘mass_scaling_list’. For each scaled parameter, two special params will be added called ‘${param}_scale_factor’ and ‘${param}_scale_pow’, defining the scaling and power-law of each.

Each scale will be modified as param = param_scale_factor * param**param_scale_pow.

For example, say we want to jointly constrain the sigma0 and Rs parameters of some lens models indexed by i, like so:

\[\begin{split}\sigma_{0,i} = \sigma_0^{ref} L_i^\alpha \\ r_{cut,i} = r_{cut}^{ref} L_i^\beta\end{split}\]

To do this we can add the following. The lens models corresponding to entries of 1 will be scaled together, and those corresponding to False will not be. As in mass_scaling_list, subsets of models can be scaled independently by marking them 2, 3, etc.

>>> scaling = ['general_scaling': {
>>>     'sigma0': [False, 1, 1, False, 1, ...],
>>>     'Rs': [False, 1, 1, False, 1, ...],
>>> }]

Then we can choose to fix the power-law and vary the scale factor like so:

>>> fixed_special = {'sigma0_scale_pow': [2], 'Rs_scale_pow': [1]}
>>> kwargs_special_init = {'sigma0_scale_factor': [17.0], 'Rs_scale_factor': [8]}
>>> kwargs_special_sigma = {'sigma0_scale_factor': [10.0], 'Rs_scale_factor': [3]}
>>> kwargs_lower_special = {'sigma0_scale_factor': [0.5], 'Rs_scale_factor': [1]}
>>> kwargs_upper_special = {'sigma0_scale_factor': [40], 'Rs_scale_factor': [20]}
>>> special_params = [kwargs_special_init, kwargs_special_sigma, fixed_special, kwargs_lower_special, kwargs_upper_special]

hierarchy is as follows: 1. Point source parameters are inferred 2. Lens light joint parameters are set 3. Lens model joint constraints are set 4. Lens model solver is applied 5. Joint source and point source is applied

Alternatively to the format of the linking of parameters with IDENTICAL names as listed above as: [[i_1, k_2, [‘param_name1’, ‘param_name2’, …]], […], …] the following format of the arguments are supported to join parameters with DIFFERENT names: [[i_1, k_2, {‘param_old1’: ‘param_new1’, ‘ra_0’: ‘center_x’}], […], …] Log10 sampling of the lens parameters : ‘log_sampling_lens’: [[i_lens, [‘param_name1’, ‘param_name2’, …]], […], …], Sample the log10 of the lens model parameters.

__init__(kwargs_model, kwargs_fixed_lens=None, kwargs_fixed_source=None, kwargs_fixed_lens_light=None, kwargs_fixed_ps=None, kwargs_fixed_special=None, kwargs_fixed_extinction=None, kwargs_fixed_tracer_source=None, kwargs_lower_lens=None, kwargs_lower_source=None, kwargs_lower_lens_light=None, kwargs_lower_ps=None, kwargs_lower_special=None, kwargs_lower_extinction=None, kwargs_lower_tracer_source=None, kwargs_upper_lens=None, kwargs_upper_source=None, kwargs_upper_lens_light=None, kwargs_upper_ps=None, kwargs_upper_special=None, kwargs_upper_extinction=None, kwargs_upper_tracer_source=None, kwargs_lens_init=None, linear_solver=True, joint_lens_with_lens=[], joint_lens_light_with_lens_light=[], joint_source_with_source=[], joint_lens_with_light=[], joint_source_with_point_source=[], joint_lens_light_with_point_source=[], joint_extinction_with_lens_light=[], joint_lens_with_source_light=[], joint_source_light_with_tracer=None, mass_scaling_list=None, point_source_offset=False, general_scaling=None, num_point_source_list=None, image_plane_source_list=None, solver_type='NONE', Ddt_sampling=None, source_size=False, num_tau0=0, lens_redshift_sampling_indexes=None, source_redshift_sampling_indexes=None, source_grid_offset=False, kinematic_sampling=None, num_shapelet_lens=0, log_sampling_lens=[])[source]
Parameters:
  • kwargs_model – keyword arguments to describe all model components used in class_creator.create_class_instances()

  • kwargs_fixed_lens – fixed parameters for lens model (keyword argument list)

  • kwargs_fixed_source – fixed parameters for source model (keyword argument list)

  • kwargs_fixed_lens_light – fixed parameters for lens light model (keyword argument list)

  • kwargs_fixed_ps – fixed parameters for point source model (keyword argument list)

  • kwargs_fixed_special – fixed parameters for special model parameters (keyword arguments)

  • kwargs_fixed_extinction – fixed parameters for extinction model parameters (keyword argument list)

  • kwargs_fixed_tracer_source – fixed parameters for tracer source model parameters (keyword argument list)

  • kwargs_lower_lens – lower limits for parameters of lens model (keyword argument list)

  • kwargs_lower_source – lower limits for parameters of source model (keyword argument list)

  • kwargs_lower_lens_light – lower limits for parameters of lens light model (keyword argument list)

  • kwargs_lower_ps – lower limits for parameters of point source model (keyword argument list)

  • kwargs_lower_special – lower limits for parameters of special model parameters (keyword arguments)

  • kwargs_lower_extinction – lower limits for parameters of extinction model (keyword argument list)

  • kwargs_lower_tracer_source – lower limits for parameters of tracer source model (keyword argument list)

  • kwargs_upper_lens – upper limits for parameters of lens model (keyword argument list)

  • kwargs_upper_source – upper limits for parameters of source model (keyword argument list)

  • kwargs_upper_lens_light – upper limits for parameters of lens light model (keyword argument list)

  • kwargs_upper_ps – upper limits for parameters of point source model (keyword argument list)

  • kwargs_upper_special – upper limits for parameters of special model parameters (keyword arguments)

  • kwargs_upper_extinction – upper limits for parameters of extinction model (keyword argument list)

  • kwargs_upper_tracer_source – upper limits for parameters of tracer source model (keyword argument list)

  • kwargs_lens_init – initial guess of lens model keyword arguments (only relevant as the starting point of the non-linear solver)

  • linear_solver – bool, if True; avoids sampling the linear amplitude parameters ‘amp’ such that they get overwritten by the linear solver solution. Fixed ‘amp’ parameters will be overwritten if linear_solver = True.

  • joint_lens_with_lens – list [[i_lens, k_lens, [‘param_name1’, ‘param_name2’, …]], […], …], joint parameter between two lens models

  • joint_lens_light_with_lens_light – list [[i_lens_light, k_lens_light, [‘param_name1’, ‘param_name2’, …]], […], …], joint parameter between two lens light models, the second adopts the value of the first

  • joint_source_with_source – [[i_source, k_source, [‘param_name1’, ‘param_name2’, …]], […], …], joint parameter between two source surface brightness models, the second adopts the value of the first

  • joint_lens_with_light – list [[i_light, k_lens, [‘param_name1’, ‘param_name2’, …]], […], …], joint parameter between lens model and lens light model

  • joint_source_with_point_source – list [[i_point_source, k_source], […], …], joint position parameter between lens model and source light model

  • joint_lens_light_with_point_source – list [[i_point_source, k_lens_light], […], …], joint position parameter between lens model and lens light model

  • joint_extinction_with_lens_light – list [[i_lens_light, k_extinction, [‘param_name1’, ‘param_name2’, …]], […], …], joint parameters between the lens surface brightness and the optical depth models

  • joint_lens_with_source_light – [[i_source, k_lens, [‘param_name1’, ‘param_name2’, …]], […], …], joint parameter between lens model and source light model. Samples light model parameter only.

  • joint_source_light_with_tracer – [[i_source_light, k_tracer_source, [‘param_name1’, ‘param_name2’, …]], […], …] joint parameter between tracer source models and source light models

  • mass_scaling_list – boolean list of length of lens model list (optional) models with identical integers will be scaled with the same additional scaling factor. First integer starts with 1 (not 0)

  • general_scaling – { ‘param_1’: [list of booleans/integers defining which model to fit], ‘param_2’: [..], ..}

  • point_source_offset – bool, if True, adds relative offsets ot the modeled image positions relative to the time-delay and lens equation solver

  • num_point_source_list – list of number of point sources per point source model class

  • image_plane_source_list – optional, list of booleans for the source_light components. If a component is set =True it will parameterized the positions in the image plane and ray-trace the parameters back to the source position on the fly during the fitting.

  • solver_type – string, option for specific solver type see detailed instruction of the Solver4Point and Solver2Point classes

  • Ddt_sampling – bool, if True, samples the time-delay distance D_dt (in units of Mpc)

  • source_size – bool, if True, samples a source size parameters to be evaluated in the flux ratio likelihood

  • num_tau0 – integer, number of different optical depth re-normalization factors

  • lens_redshift_sampling_indexes – list of integers corresponding to the lens model components whose redshifts are a free parameter (only has an effect in multi-plane lensing) with same indexes indicating joint redshift, in ascending numbering e.g. [-1, 0, 0, 1, 0, 2], -1 indicating not sampled fixed indexes

  • source_redshift_sampling_indexes – list of integers corresponding to the source model components whose redshifts are a free parameter (only has an effect in multi-plane lensing) with same indexes indicating joint redshift, in ascending numbering e.g. [-1, 0, 0, 1, 0, 2], -1 indicating not sampled fixed indexes. These indexes are the sample as for the lens

  • source_grid_offset – optional, if True when using a pixel-based modelling (e.g. with STARLETS-like profiles), adds two additional sampled parameters describing RA/Dec offsets between data coordinate grid and pixelated source plane coordinate grid.

  • num_shapelet_lens – number of shapelet coefficients in the ‘SHAPELETS_CART’ or ‘SHAPELETS_POLAR’ mass profile.

  • log_sampling_lens – Sample the log10 of the lens model parameters. Format : [[i_lens, [‘param_name1’, ‘param_name2’, …]], […], …],

property num_point_source_images
Returns:

total number of point source images

property linear_solver

Boolean to state whether linear solver is activated or not.

Returns:

boolean

args2kwargs(args, bijective=False)[source]
Parameters:
  • args – tuple of parameter values (float, strings, …)

  • bijective – boolean, if True (default) returns the parameters in the form as they are sampled (e.g. if image_plane_source_list is set =True it returns the position in the image plane coordinates), if False, returns the parameters in the form to render a model (e.g. image_plane_source_list positions are ray-traced back to the source plane).

Returns:

keyword arguments sorted in lenstronomy conventions

kwargs2args(kwargs_lens=None, kwargs_source=None, kwargs_lens_light=None, kwargs_ps=None, kwargs_special=None, kwargs_extinction=None, kwargs_tracer_source=None)[source]

Inverse of getParam function.

Parameters:
  • kwargs_lens – keyword arguments depending on model options

  • kwargs_source – keyword arguments depending on model options

  • kwargs_lens_light – lens light model keyword argument list

  • kwargs_ps – point source model keyword argument list

  • kwargs_special – special keyword arguments

  • kwargs_extinction – extinction model keyword argument list

  • kwargs_tracer_source – tracer of the source light keyword argument list

Returns:

numpy array of parameters

param_limits()[source]
Returns:

lower and upper limits of the arguments being sampled

num_param()[source]
Returns:

number of parameters involved (int), list of parameter names

num_param_linear()[source]
Returns:

number of linear basis set coefficients that are solved for

image2source_plane(kwargs_source, kwargs_lens, kwargs_special=None, image_plane=False)[source]

Maps the image plane position definition of the source plane.

Parameters:
  • kwargs_source – source light model keyword argument list

  • kwargs_lens – lens model keyword argument list

  • image_plane – boolean, if True, does not up map image plane parameters to source plane

Returns:

source light model keyword arguments with mapped position arguments from image to source plane

update_lens_scaling(kwargs_special, kwargs_lens, inverse=False)[source]

Multiplies the scaling parameters of the profiles.

Parameters:
  • kwargs_special – keyword arguments of the ‘special’ arguments

  • kwargs_lens – lens model keyword argument list

  • inverse – bool, if True, performs the inverse lens scaling for bijective transforms

Returns:

updated lens model keyword argument list

update_kwargs_model(kwargs_special)[source]

Updates model keyword arguments with redshifts being sampled.

Parameters:

kwargs_special – keyword arguments from SpecialParam() class return of sampling arguments

Returns:

kwargs_model, bool (True if kwargs_model has changed, else False)

check_solver(kwargs_lens, kwargs_ps)[source]

Test whether the image positions map back to the same source position :param kwargs_lens: lens model keyword argument list :param kwargs_ps: point source model keyword argument list :return: Euclidean distance between the ray-shooting of the image positions.

print_setting()[source]

Prints the setting of the parameter class.

Returns:

lenstronomy.Sampling.sampler module

class Sampler(likelihoodModule)[source]

Bases: object

class which executes the different sampling methods Available are: affine-invariant ensemble sampling with emcee, ensemble slice sampling with zeus and a Particle Swarm Optimizer. These are examples and depending on your problem, you might find other/better solutions. Feel free to sample with your convenient sampler!

__init__(likelihoodModule)[source]
Parameters:

likelihoodModule – instance of LikelihoodModule class

simplex(init_pos, n_iterations, method, print_key='SIMPLEX')[source]
Parameters:
  • init_pos – starting point for the optimization

  • n_iterations – maximum number of iterations

  • method – the optimization method, default is ‘Nelder-Mead’

Returns:

the best fit for the lens model using the optimization routine specified by method

pso(n_particles, n_iterations, lower_start=None, upper_start=None, threadCount=1, init_pos=None, mpi=False, print_key='PSO')[source]

Return the best fit for the lens model on catalogue basis with particle swarm optimizer.

Parameters:
  • n_particles – number of particles in the sampling process

  • n_iterations – number of iterations of the swarm

  • lower_start – numpy array, lower end parameter of the values of the starting particles

  • upper_start – numpy array, upper end parameter of the values of the starting particles

  • threadCount – number of threads in the computation (only applied if mpi=False)

  • init_pos – numpy array, position of the initial best guess model

  • mpi – bool, if True, makes instance of MPIPool to allow for MPI execution

  • print_key – string, prints the process name in the progress bar (optional)

Returns:

kwargs_result (of best fit), [lnlikelihood of samples, positions of samples, velocity of samples])

mcmc_emcee(n_walkers, n_run, n_burn, mean_start, sigma_start, mpi=False, progress=False, threadCount=1, initpos=None, backend_filename=None, start_from_backend=False)[source]

Run MCMC with emcee. For details, please have a look at the documentation of the emcee packager.

Parameters:
  • n_walkers (integer) – number of walkers in the emcee process

  • n_run (integer) – number of sampling (after burn-in) of the emcee

  • n_burn (integer) – number of burn-in iterations (those will not be saved in the output sample)

  • mean_start (numpy array of length the number of parameters) – mean of the parameter position of the initialising sample

  • sigma_start (numpy array of length the number of parameters) – spread of the parameter values (uncorrelated in each dimension) of the initialising sample

  • mpi (bool) – if True, initializes an MPIPool to allow for MPI execution of the sampler

  • progress (bool) – if True, prints the progress bar

  • threadCount (integer) – number of threats in multi-processing (not applicable for MPI)

  • initpos (numpy array of size num param x num walkser) – initial walker position to start sampling (optional)

  • backend_filename (string) – name of the HDF5 file where sampling state is saved (through emcee backend engine)

  • start_from_backend (bool) – if True, start from the state saved in backup_filename. Otherwise, create a new backup file with name backup_filename (any already existing file is overwritten!).

Returns:

samples, ln likelihood value of samples

Return type:

numpy 2d array, numpy 1d array

mcmc_zeus(n_walkers, n_run, n_burn, mean_start, sigma_start, mpi=False, threadCount=1, progress=False, initpos=None, backend_filename=None, **kwargs_zeus)[source]

Lightning fast MCMC with zeus: https://github.com/minaskar/zeus

For the full list of arguments for the EnsembleSampler and callbacks, see see the zeus docs.

If you use the zeus sampler, you should cite the following papers: 2105.03468, 2002.06212.

Parameters:
  • n_walkers (integer) – number of walkers per parameter

  • n_run (integer) – number of sampling steps

  • n_burn (integer) – number of burn-in steps

  • mean_start (numpy array of length the number of parameters) – mean of the parameter position of the initialising sample

  • sigma_start (numpy array of length the number of parameters) – spread of the parameter values (uncorrelated in each dimension) of the initialising sample

  • mpi (bool) – if True, initializes an MPIPool to allow for MPI execution of the sampler

  • progress (bool) –

  • initpos (numpy array of size num param x num walkser) – initial walker position to start sampling (optional)

  • backend_filename (string) – name of the HDF5 file where sampling state is saved (through zeus callback function)

Returns:

samples, ln likelihood value of samples

Return type:

numpy 2d array, numpy 1d array

lenstronomy.Sampling.special_param module

class SpecialParam(Ddt_sampling=False, mass_scaling=False, num_scale_factor=1, general_scaling_params=None, kwargs_fixed=None, kwargs_lower=None, kwargs_upper=None, point_source_offset=False, source_size=False, num_images=0, num_tau0=0, num_z_sampling=0, source_grid_offset=False, kinematic_sampling=False, distance_ratio_sampling=False, num_lens_planes=1)[source]

Bases: object

Class that handles special parameters that are not directly part of a specific model component.

These includes cosmology relevant parameters, astrometric errors and overall scaling parameters.

__init__(Ddt_sampling=False, mass_scaling=False, num_scale_factor=1, general_scaling_params=None, kwargs_fixed=None, kwargs_lower=None, kwargs_upper=None, point_source_offset=False, source_size=False, num_images=0, num_tau0=0, num_z_sampling=0, source_grid_offset=False, kinematic_sampling=False, distance_ratio_sampling=False, num_lens_planes=1)[source]
Parameters:
  • Ddt_sampling – bool, if True, samples the time-delay distance D_dt (in units of Mpc)

  • mass_scaling – bool, if True, samples a mass scaling factor between different profiles

  • num_scale_factor – int, number of independent mass scaling factors being sampled

  • kwargs_fixed – keyword arguments, fixed parameters during sampling

  • kwargs_lower – keyword arguments, lower bound of parameters being sampled

  • kwargs_upper – keyword arguments, upper bound of parameters being sampled

  • point_source_offset – bool, if True, adds relative offsets ot the modeled image positions relative to the time-delay and lens equation solver

  • num_images – number of point source images such that the point source offset parameters match their numbers

  • source_size – bool, if True, samples a source size parameters to be evaluated in the flux ratio likelihood

  • num_tau0 – integer, number of different optical depth re-normalization factors

  • num_z_sampling – integer, number of different lens redshifts to be sampled

  • source_grid_offset – bool, if True, samples two parameters (x, y) for the offset of the pixelated source plane grid coordinates. Warning: this is only defined for pixel-based source modelling (e.g. ‘SLIT_STARLETS’ light profile)

  • kinematic_sampling – bool, if True, samples the kinematic parameters b_ani, incli, with cosmography D_dt (overrides _D_dt_sampling) and Dd

  • distance_ratio_sampling – bool, if True, the distance ratios will be sampled. Only applicable for multi-plane case, will turn-off Ddt_sampling by default as Ddt will be sampled as a ratio with a fiducial value in this option.

  • num_lens_planes – integer, number of lens planes when distance_ratio_sampling is True

sampled

get_params(args, i, impose_bound=False)[source]
Parameters:
  • args – argument list

  • i – integer, list index to start the read out for this class

  • impose_bound – bool, if True, imposes the lower and upper limits on the sampled parameters

Returns:

keyword arguments related to args, index after reading out arguments of this class

set_params(kwargs_special)[source]
Parameters:

kwargs_special – keyword arguments with parameter settings

Returns:

argument list of the sampled parameters extracted from kwargs_special

num_param()[source]
Returns:

integer, number of free parameters sampled (and managed) by this class, parameter names (list of strings)

lenstronomy.Sampling.param_group module

This module provides helper classes for managing sample parameters.

This is for internal use, if you are not modifying lenstronomy sampling to include new parameters you can safely ignore this.

class ModelParamGroup[source]

Bases: object

This abstract class represents any lenstronomy fitting parameters used in the Param class.

Subclasses should implement num_params(), set_params(), and get_params() to convert parameters from lenstronomy’s semantic dictionary format to a flattened array format and back.

This class also contains three static methods to easily aggregate groups of parameter classes, called compose_num_params(), compose_set_params(), and compose_get_params().

num_params()[source]

Tells the number of parameters that this group samples and their names.

Returns:

2-tuple of (num param, list of names)

set_params(kwargs)[source]

Converts lenstronomy semantic parameters in dictionary format into a flattened array of parameters.

The flattened array is for use in optimization algorithms, e.g. MCMC, Particle swarm, etc.

Returns:

flattened array of parameters as floats

get_params(args, i)[source]

Converts a flattened array of parameters back into a lenstronomy dictionary, starting at index i.

Parameters:
  • args (list) – flattened arguments to convert to lenstronomy format

  • i (int) – index to begin at in args

Returns:

dictionary of parameters

static compose_num_params(each_group, *args, **kwargs)[source]

Aggregates the number of parameters for a group of parameter groups, calling each instance’s num_params() method and combining the results.

Parameters:
  • each_group (list) – collection of parameter groups. Should each be subclasses of ModelParamGroup.

  • args – Extra arguments to be passed to each call of num_params()

  • kwargs – Extra keyword arguments to be passed to each call of num_params()

Returns:

As in each individual num_params(), a 2-tuple of (num params, list of param names)

static compose_set_params(each_group, param_kwargs, *args, **kwargs)[source]

Converts lenstronomy semantic arguments in dictionary format to a flattened list of floats for use in optimization/fitting algorithms. Combines the results for a set of arbitrarily many parameter groups.

Parameters:
  • each_group (list) – collection of parameter groups. Should each be subclasses of ModelParamGroup.

  • param_kwargs (dict) – the kwargs to process

  • args – Extra arguments to be passed to each call of set_params()

  • kwargs – Extra keyword arguments to be passed to each call of set_params()

Returns:

As in each individual set_params(), a list of floats

static compose_get_params(each_group, flat_args, i, *args, **kwargs)[source]

Converts a flattened array of parameters to lenstronomy semantic parameters in dictionary format. Combines the results for a set of arbitrarily many parameter groups.

Parameters:
  • each_group (list) – collection of parameter groups. Should each be subclasses of ModelParamGroup.

  • flat_args (list) – the input array of parameters

  • i (int) – the index in flat_args to start at

  • args – Extra arguments to be passed to each call of set_params()

  • kwargs – Extra keyword arguments to be passed to each call of set_params()

Returns:

As in each individual get_params(), a 2-tuple of (dictionary of params, new index)

class SingleParam(on)[source]

Bases: ModelParamGroup

Helper for handling parameters which are a single float.

Subclasses should define:

Parameters:
  • on (bool) – Whether this parameter is sampled

  • param_names – List of strings, the name of each parameter

  • _kwargs_lower – Dictionary. Lower bounds of each parameter

  • _kwargs_upper – Dictionary. Upper bounds of each parameter

__init__(on)[source]
Parameters:

on (bool) – Whether this paramter should be sampled

num_params(kwargs_fixed)[source]

Tells the number of parameters that this group samples and their names.

Parameters:

kwargs_fixed (dict) – Dictionary of fixed arguments

Returns:

2-tuple of (num param, list of names)

set_params(kwargs, kwargs_fixed)[source]

Converts lenstronomy semantic parameters in dictionary format into a flattened array of parameters.

The flattened array is for use in optimization algorithms, e.g. MCMC, Particle swarm, etc.

Parameters:
  • kwargs (dict) – lenstronomy parameters to flatten

  • kwargs_fixed (dict) – Dictionary of fixed arguments

Returns:

flattened array of parameters as floats

get_params(args, i, kwargs_fixed, kwargs_upper=None, kwargs_lower=None)[source]

Converts a flattened array of parameters back into a lenstronomy dictionary, starting at index i.

Parameters:
  • args (list) – flattened arguments to convert to lenstronomy format

  • i (int) – index to begin at in args

  • kwargs_fixed (dict) – Dictionary of fixed arguments

Returns:

dictionary of parameters

property kwargs_lower
property kwargs_upper
property on
class ArrayParam(on)[source]

Bases: ModelParamGroup

Helper for handling parameters which are an array of values. Examples include mass_scaling, which is an array of scaling parameters, and wavelet or gaussian decompositions which have different coefficients for each mode.

Subclasses should define:

Parameters:
  • on (bool) – Whether this parameter is sampled

  • param_names – Dictionary mapping the name of each parameter to the number of values needed.

  • _kwargs_lower – Dictionary. Lower bounds of each parameter

  • _kwargs_upper – Dictionary. Upper bounds of each parameter

__init__(on)[source]
Parameters:

on (bool) – Whether this paramter should be sampled

num_params(kwargs_fixed)[source]

Tells the number of parameters that this group samples and their names.

Parameters:

kwargs_fixed (dict) – Dictionary of fixed arguments

Returns:

2-tuple of (num param, list of names)

set_params(kwargs, kwargs_fixed)[source]

Converts lenstronomy semantic parameters in dictionary format into a flattened array of parameters.

The flattened array is for use in optimization algorithms, e.g. MCMC, Particle swarm, etc.

Parameters:
  • kwargs (dict) – lenstronomy parameters to flatten

  • kwargs_fixed (dict) – Dictionary of fixed arguments

Returns:

flattened array of parameters as floats

get_params(args, i, kwargs_fixed, kwargs_lower=None, kwargs_upper=None)[source]

Converts a flattened array of parameters back into a lenstronomy dictionary, starting at index i.

Parameters:
  • args (list) – flattened arguments to convert to lenstronomy format

  • i (int) – index to begin at in args

  • kwargs_fixed (dict) – Dictionary of fixed arguments

  • kwargs_lower (dict) – Dictionary of lower bounds

  • kwargs_upper (dict) – Dictionary of upper bounds

Returns:

dictionary of parameters

property kwargs_lower
property kwargs_upper
property on

Module contents