lenstronomy.Util package

Submodules

lenstronomy.Util.analysis_util module

half_light_radius(lens_light, x_grid, y_grid, center_x=0, center_y=0)[source]
Parameters:
  • lens_light – array of surface brightness

  • x_grid – x-axis coordinates

  • y_grid – y-axis coordinates

  • center_x – center of light

  • center_y – center of light

Returns:

radial_profile(light_grid, x_grid, y_grid, center_x=0, center_y=0, n=None)[source]

Computes radial profile.

Parameters:
  • light_grid – array of surface brightness

  • x_grid – x-axis coordinates

  • y_grid – y-axis coordinates

  • center_x – center of light

  • center_y – center of light

  • n – number of discrete steps

Returns:

I(r), r with r in units of the coordinate grid

azimuthal_average(image, center=None)[source]

Calculate the azimuthally averaged radial profile.

image - The 2D image center - The [x,y] pixel coordinates used as the center. The default is None, which then uses the center of the image (including fractional pixels). :return: I(r) (averaged), r of bin edges in units of pixels of the 2D image

moments(I_xy_input, x, y)[source]

Compute quadrupole moments from a light distribution.

Parameters:
  • I_xy_input – light distribution

  • x – x-coordinates of I_xy

  • y – y-coordinates of I_xy

Returns:

Q_xx, Q_xy, Q_yy

ellipticities(I_xy, x_grid, y_grid, num_iterative=30, iterative=False, center_x=0, center_y=0)[source]
Parameters:
  • I_xy – surface brightness I(x, y) as array

  • x_grid – x-coordinates in same shape as I_xy

  • y_grid – y-coordinates in same shape as I_xy

  • iterative (boolean) – if True iteratively adopts an eccentric mask to overcome edge effects

  • num_iterative (int) – number of iterative changes in ellipticity

Returns:

e1, e2 eccentricities

bic_model(logL, num_data, num_param)[source]

Bayesian information criteria.

Parameters:
  • logL – log likelihood value

  • num_data – numbers of data

  • num_param – numbers of model parameters

Returns:

BIC value

profile_center(kwargs_list, center_x=None, center_y=None)[source]

Utility routine that results in the centroid estimate for the profile estimates.

Parameters:
  • kwargs_list – light parameter keyword argument list (can be light or mass)

  • center_x – None or center

  • center_y – None or center

Returns:

center_x, center_y

lenstronomy.Util.class_creator module

create_class_instances(lens_model_list=None, z_lens=None, z_source=None, z_source_convention=None, lens_redshift_list=None, lens_profile_kwargs_list=None, multi_plane=False, distance_ratio_sampling=False, cosmology_sampling=False, cosmology_model='FlatLambdaCDM', observed_convention_index=None, source_light_model_list=None, source_light_profile_kwargs_list=None, lens_light_model_list=None, lens_light_profile_kwargs_list=None, point_source_model_list=None, point_source_redshift_list=None, fixed_magnification_list=None, point_source_frame_list=None, additional_images_list=None, kwargs_lens_eqn_solver=None, source_deflection_scaling_list=None, source_redshift_list=None, cosmo=None, index_lens_model_list=None, index_source_light_model_list=None, index_lens_light_model_list=None, index_point_source_model_list=None, optical_depth_model_list=None, optical_depth_profile_kwargs_list=None, index_optical_depth_model_list=None, band_index=0, tau0_index_list=None, all_models=False, point_source_magnification_limit=None, decouple_multi_plane=False, kwargs_multiplane_model=None, kwargs_multiplane_model_point_source=None, tracer_source_model_list=None, tracer_source_band=0, tracer_partition=None, tracer_type='LINEAR')[source]
Parameters:
  • lens_model_list – list of strings indicating the type of lens models

  • z_lens – redshift of the deflector (for single lens plane mode, but only relevant when computing physical quantities)

  • z_source – redshift of source (for single source plane mode, or for multiple source planes the redshift of the point source). In regard to this redshift the reduced deflection angles are defined in the lens model.

  • z_source_convention – float, redshift of a source to define the reduced deflection angles of the lens models. If None, ‘z_source’ is used.

  • lens_redshift_list – None or list of floats in the same order of the lens_model_list

  • lens_profile_kwargs_list – list of dicts, keyword arguments used to initialize deflector profile classes in the same order of the lens_model_list. If any of the profile_kwargs are None, then that profile will be initialized using default settings.

  • multi_plane – bool, if True, computes the lensing quantities in multi-plane mode

  • distance_ratio_sampling – bool, if True, samples the distance ratios in multi-lens-plane

  • cosmology_sampling – bool, if True, samples the cosmology in multi-lens-plane

  • cosmology_model – string, name of the cosmology model to be used in the multi-lens-plane mode

  • observed_convention_index

  • source_light_model_list – list of strings indicating the type of source light models

  • source_light_profile_kwargs_list – list of dicts, keyword arguments used to initialize source light profile classes in the same order of the source_light_model_list. If any of the profile_kwargs are None, then that profile will be initialized using default settings.

  • lens_light_model_list – list of strings indicating the type of lens light models

  • lens_light_profile_kwargs_list – list of dicts, keyword arguments used to initialize lens light profile classes in the same order of the lens_light_model_list. If any of the profile_kwargs are None, then that profile will be initialized using default settings.

  • point_source_model_list – list of strings indicating the type of point source models

  • fixed_magnification_list – list of bool. Indicates which point source classes in the same order of point_source_model_list should have fixed magnification. Only relevant for the LENSED_POSITION point source type. If set to True, then “source_amp” is a parameter instead of “point_amp”, and the magnification is calculated from the lens models.

  • point_source_frame_list – Unused, as it was not working correctly previously

  • additional_images_list – list of bool. Indicates which point source classes in the same order of the point_source_model_list should use the lens equation solver to solve for additional images. Only relevant for the LENSED_POSITION point source type.

  • kwargs_lens_eqn_solver – keyword arguments specifying the numerical settings for the lens equation solver see LensEquationSolver() class for details

  • source_deflection_scaling_list – List of floats for each source ligth model (optional, and only applicable for single-plane lensing. The factors re-scale the reduced deflection angles described from the lens model. =1 means identical source position as without this option. This option enables multiple source planes. The geometric difference between the different source planes needs to be pre-computed and is cosmology dependent.

  • source_redshift_list – list of redshifts for the source model profiles in the same order of the source_light_model_list

  • cosmo – astropy.cosmology instance

  • index_lens_model_list – list of list of ints, indicating which lens models are in each band. For example [[0, 2], [1, 3]] indicates that band 0 uses lens models 0 and 2, and band 1 uses lens models 1 and 3 from the lens_model_list

  • index_source_light_model_list – list of list of ints, indicating which source light models are in each band.

  • index_lens_light_model_list – optional, list of list of all model indexes for each modeled band

  • index_point_source_model_list – optional, list of list of all model indexes for each modeled band

  • optical_depth_model_list – list of strings indicating the optical depth model to compute (differential) extinctions from the source

  • optical_depth_profile_kwargs_list – list of dicts, keyword arguments used to initialize light model profile classes in the same order of the optical_depth_model_list. If any of the profile_kwargs are None, then that profile will be initialized using default settings.

  • index_optical_depth_model_list – list of list of ints, indicates which optical depth models are in each band.

  • band_index – int, index of band to consider. Has an effect if only partial models are considered for a specific band

  • tau0_index_list – list of integers of the specific extinction scaling parameter tau0 for each band

  • all_models – bool, if True, will make class instances of all models ignoring potential keywords that are excluding specific models as indicated.

  • point_source_magnification_limit – float >0 or None, if set and additional images are computed, then it will cut the point sources computed to the limiting (absolute) magnification

  • decouple_multi_plane – bool; if True, creates an instance of MultiPlaneDecoupled

  • kwargs_multiplane_model – keyword arguments used to create an instance of MultiPlaneDecoupled if decouple_multi_plane is True

  • kwargs_multiplane_model_point_source – keyword arguments used to create an option MultiPlaneDecoupled class for the lensed point source to be treated separately from the rest of the imaging data

  • tracer_source_model_list – list of tracer source models (not used in this function)

  • tracer_source_band – integer, list index of source surface brightness band to apply tracer model to

  • tracer_partition (None or list) – in case of tracer models for specific sub-parts of the surface brightness model [[list of light profiles, list of tracer profiles], [list of light profiles, list of tracer profiles], […], …]

  • tracer_type – string with options ‘LINEAR’ or ‘LOG’, to determine how tracers are summed between components

  • point_source_redshift_list – list of redshifts of point sources (default None, i.e. all point sources at the same redshift following the source convention)

Returns:

lens_model_class, source_model_class, lens_light_model_class, point_source_class, extinction_class

create_image_model(kwargs_data, kwargs_psf, kwargs_numerics, kwargs_model, image_likelihood_mask=None)[source]
Parameters:
  • kwargs_data – ImageData keyword arguments

  • kwargs_psf – PSF keyword arguments

  • kwargs_numerics – numerics keyword arguments for Numerics() class

  • kwargs_model – model keyword arguments

  • image_likelihood_mask – image likelihood mask (same size as image_data with 1 indicating being evaluated and 0 being left out)

Returns:

ImageLinearFit() instance

create_im_sim(multi_band_list, multi_band_type, kwargs_model, bands_compute=None, image_likelihood_mask_list=None, band_index=0, kwargs_pixelbased=None, linear_solver=True)[source]
Parameters:
  • multi_band_list – list of [[kwargs_data, kwargs_psf, kwargs_numerics], [], ..]

  • multi_band_type – string, option when having multiple imaging data sets modelled simultaneously. Options are: - ‘multi-linear’: linear amplitudes are inferred on single data set - ‘linear-joint’: linear amplitudes ae jointly inferred - ‘single-band’: single band

  • kwargs_model – model keyword arguments

  • bands_compute – (optional), bool list to indicate which band to be included in the modeling

  • image_likelihood_mask_list – list of image likelihood mask (same size as image_data with 1 indicating being evaluated and 0 being left out)

  • band_index – integer, index of the imaging band to model (only applied when using ‘single-band’ as option)

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

  • linear_solver – bool, if True (default) fixes the linear amplitude parameters ‘amp’ (avoid sampling) such that they get overwritten by the linear solver solution.

Returns:

MultiBand class instance

lenstronomy.Util.constants module

delay_arcsec2days(delay_arcsec, ddt)[source]

Given a delay in arcsec^2 and a Delay distance, the delay is computed in days.

Parameters:
  • delay_arcsec – gravitational delay in units of arcsec^2 (e.g. Fermat potential)

  • ddt – Time delay distance (in units of Mpc)

Returns:

time-delay in units of days

lenstronomy.Util.coolest_interface module

lenstronomy.Util.coolest_read_util module

shapelet_amp_coolest_to_lenstronomy(value)[source]

Transforms shapelets coefficients from COOLEST conventions (x to the right) to lenstronomy conventions (x following ra, to the left)

Parameters:

value – amplitude of the shapelet (float or np.array) in COOLEST conventions

Returns:

amplitude of the shapelet (float or np.array) in lenstronomy conventions

degree_coolest_to_radian_lenstronomy(value)[source]

Transform an angle in degree in COOLEST conventions (from y to negative x - aka East of North) into an angle in radian in lenstronomy conventions (from x to y with x pointing to the left - aka North of East)

Parameters:

value – float, angle in COOLEST conventions

Returns:

float, angle in lenstronomy conventions

qphi_coolest_to_e1e2_lenstronomy(q, phi)[source]

Transform q and phi (axis ratio, position angle East-of-North) to e1,e2 in lenstronomy.

Parameters:
  • q – float, axis ratio

  • phi – float, position angle in COOLEST conventions

Returns:

e1, e2, lenstronomy usual ellipticity parameters

gamma_phi_coolest_to_g1_g2_lenstronomy(gamma_ext, phi_ext)[source]

Transform gamma_ext and phi_ext (shear strength, position angle East-of-North) to gamma1,gamma2 in lenstronomy.

Parameters:
  • gamma_ext – float, shear strenght

  • phi_ext – float, shear angle in COOLEST conventions

Returns:

gamma1, gamma2, lenstronomy usual shear parameters

ellibounds_coolest_to_lenstronomy(q_down, q_up, phi_down, phi_up)[source]

Transforms upper and lower bounds on coolest ellipticity parameters (q, phi) towards lenstronomy bound on e1, e2 The mapping can not be perfect but it’s the best we can do.

Parameters:
  • q_down – float, lower bound of axis ratio

  • q_up – float, upper bound of axis ratio

  • phi_down – float, lower bound of position angle in COOLEST conventions

  • phi_up – float, upper bound of position angle in COOLEST conventions

Returns:

e1_down, e1_up, e2_down, e2_up, bounds for lenstronomy usual ellipticity parameters

shearbounds_coolest_to_lenstronomy(gamma_ext_down, gamma_ext_up, phi_ext_down, phi_ext_up)[source]

Transforms upper and lower bounds on coolest shear parameters (gamma_ext, phi_ext) towards lenstronomy bounds on gamma_1, gamma_2 The mapping can not be perfect but it’s the best we can do.

Parameters:
  • gamma_ext_down – float, lower bound of shear strenght

  • gamma_ext_up – float, upper bound of shear strenght

  • phi_ext_down – float, lower bound of shear position angle in COOLEST conventions

  • phi_ext_up – float, upper bound of shear position angle in COOLEST conventions

Returns:

gamma1_down, gamma1_up, gamma2_down, gamma2_up ; bounds for lenstronomy usual shear parameters

update_kwargs_shear(shear_idx, lens_model_list, kwargs_lens, kwargs_lens_init, kwargs_lens_up, kwargs_lens_down, kwargs_lens_fixed, kwargs_lens_sigma, cleaning=False)[source]

Update the lens model list and kwargs with SHEAR mass model (gamma_ext - phi_ext)

Parameters:
  • shear_idx – coolest.template.classes.profiles.mass.ExternalShear object

  • lens_model_list – the usual lenstronomy lens_model_list

  • kwargs_lens – the usual lenstronomy kwargs

  • kwargs_lens_init – the usual lenstronomy kwargs

  • kwargs_lens_up – the usual lenstronomy kwargs

  • kwargs_lens_down – the usual lenstronomy kwargs

  • kwargs_lens_fixed – the usual lenstronomy kwargs

  • kwargs_lens_sigma – the usual lenstronomy kwargs

  • cleaning – bool, if True, will update the empty fields with default values + cleans the kwargs_fixed

Returns:

updated list and kwargs

update_kwargs_convergence(convergence, lens_model_list, kwargs_lens, kwargs_lens_init, kwargs_lens_up, kwargs_lens_down, kwargs_lens_fixed, kwargs_lens_sigma, cleaning=False)[source]

Update the lens model list and kwargs with CONVERGENCE mass model (gamma_ext - phi_ext)

Parameters:
  • profile – coolest.template.classes.profiles.mass.ConvergenceSheet object

  • lens_model_list – the usual lenstronomy lens_model_list

  • kwargs_lens – the usual lenstronomy kwargs

  • kwargs_lens_init – the usual lenstronomy kwargs

  • kwargs_lens_up – the usual lenstronomy kwargs

  • kwargs_lens_down – the usual lenstronomy kwargs

  • kwargs_lens_fixed – the usual lenstronomy kwargs

  • kwargs_lens_sigma – the usual lenstronomy kwargs

  • cleaning – bool, if True, will update the empty fields with default values + cleans the kwargs_fixed

Returns:

updated list and kwargs

update_kwargs_pemd(mass, lens_model_list, kwargs_lens, kwargs_lens_init, kwargs_lens_up, kwargs_lens_down, kwargs_lens_fixed, kwargs_lens_sigma, cleaning=False, use_epl=True)[source]

Update the lens list and kwargs with PEMD mass model.

Parameters:
  • mass – coolest.template.classes.profiles.mass.PEMD object

  • lens_model_list – the usual lenstronomy lens_model_list

  • kwargs_lens – the usual lenstronomy kwargs

  • kwargs_lens_init – the usual lenstronomy kwargs

  • kwargs_lens_up – the usual lenstronomy kwargs

  • kwargs_lens_down – the usual lenstronomy kwargs

  • kwargs_lens_fixed – the usual lenstronomy kwargs

  • kwargs_lens_sigma – the usual lenstronomy kwargs

  • cleaning – bool, if True, will update the empty fields with default values + cleans the kwargs_fixed

  • use_epl – bool, if True the elliptical power-law profile is ‘EPL’ instead of ‘PEMD’

Returns:

updated list and kwargs

update_kwargs_sie(mass, lens_model_list, kwargs_lens, kwargs_lens_init, kwargs_lens_up, kwargs_lens_down, kwargs_lens_fixed, kwargs_lens_sigma, cleaning=False)[source]

Update the lens list and kwargs with SIE mass model.

Parameters:
  • mass – coolest.template.classes.profiles.mass.SIE object

  • lens_model_list – the usual lenstronomy lens_model_list

  • kwargs_lens – the usual lenstronomy kwargs

  • kwargs_lens_init – the usual lenstronomy kwargs

  • kwargs_lens_up – the usual lenstronomy kwargs

  • kwargs_lens_down – the usual lenstronomy kwargs

  • kwargs_lens_fixed – the usual lenstronomy kwargs

  • kwargs_lens_sigma – the usual lenstronomy kwargs

  • cleaning – bool, if True, will update the empty fields with default values + cleans the kwargs_fixed

Returns:

updated list and kwargs

update_kwargs_sersic(light, light_model_list, kwargs_light, kwargs_light_init, kwargs_light_up, kwargs_light_down, kwargs_light_fixed, kwargs_light_sigma, cleaning=False)[source]

Update the source list and kwargs with SERSIC_ELLISPE light model.

Parameters:
  • light – coolest.template.classes.profiles.light.Sersic object

  • light_model_list – the usual lenstronomy lens_light_model_list or source_light_model_list

  • kwargs_light – the usual lenstronomy kwargs

  • kwargs_light_init – the usual lenstronomy kwargs

  • kwargs_light_up – the usual lenstronomy kwargs

  • kwargs_light_down – the usual lenstronomy kwargs

  • kwargs_light_fixed – the usual lenstronomy kwargs

  • kwargs_light_sigma – the usual lenstronomy kwargs

  • cleaning – bool, if True, will update the empty fields with default values + cleans the kwargs_fixed

Returns:

updated list and kwargs

update_kwargs_shapelets(light, light_model_list, kwargs_light, kwargs_light_init, kwargs_light_up, kwargs_light_down, kwargs_light_fixed, kwargs_light_sigma, cleaning=False)[source]

Update the source list and kwargs with SHAPELETS light model.

Parameters:
  • light – coolest.template.classes.profiles.light.Shapelets object

  • light_model_list – the usual lenstronomy lens_light_model_list or source_light_model_list

  • kwargs_light – the usual lenstronomy kwargs

  • kwargs_light_init – the usual lenstronomy kwargs

  • kwargs_light_up – the usual lenstronomy kwargs

  • kwargs_light_down – the usual lenstronomy kwargs

  • kwargs_light_fixed – the usual lenstronomy kwargs

  • kwargs_light_sigma – the usual lenstronomy kwargs

  • cleaning – bool, if True, will update the empty fields with default values + cleans the kwargs_fixed

Returns:

updated list and kwargs

update_kwargs_lensed_ps(light, ps_model_list, kwargs_ps, kwargs_ps_init, kwargs_ps_up, kwargs_ps_down, kwargs_ps_fixed, kwargs_ps_sigma, cleaning=False)[source]

Update the source list and kwargs with lensed point source “LENSED_POSITION” light model.

Parameters:
  • light – coolest.template.classes.profiles.lightLensedPS object

  • ps_model_list – the usual lenstronomy point_source_model_list

  • kwargs_ps – the usual lenstronomy kwargs

  • kwargs_ps_init – the usual lenstronomy kwargs

  • kwargs_ps_up – the usual lenstronomy kwargs

  • kwargs_ps_down – the usual lenstronomy kwargs

  • kwargs_ps_fixed – the usual lenstronomy kwargs

  • kwargs_ps_sigma – the usual lenstronomy kwargs

  • cleaning – bool, if True, will update the empty fields with default values + cleans the kwargs_fixed

Returns:

updated list and kwargs

lenstronomy.Util.coolest_update_util module

lenstronomy.Util.correlation module

correlation_2D(image)[source]

#TODO document normalization output in units

Parameters:

image – 2d image

Returns:

2d fourier transform

power_spectrum_2d(image)[source]
Parameters:

image – 2d numpy array

Returns:

2d power spectrum in frequency units of the pixels

power_spectrum_1d(image)[source]
Parameters:

image – 2d numpy array

Returns:

1d radially averaged power spectrum of image in frequency units of pixels, radius in units of pixels

lenstronomy.Util.cosmo_util module

get_astropy_cosmology(cosmology_model='FlatLambdaCDM', param_kwargs={})[source]

Return an instance of a astropy.cosmology class.

Parameters:
  • cosmology_model (str) – string, name of the cosmology model

  • param_kwargs (dict) – keyword arguments of the cosmology class

Returns:

instance of a astropy.cosmology class

lenstronomy.Util.data_util module

bkg_noise(readout_noise, exposure_time, sky_brightness, pixel_scale, num_exposures=1)[source]

Computes the expected Gaussian background noise of a pixel in units of counts/second.

Parameters:
  • readout_noise – noise added per readout

  • exposure_time – exposure time per exposure (in seconds)

  • sky_brightness – counts per second per unit arcseconds square

  • pixel_scale – size of pixel in units arcseonds

  • num_exposures – number of exposures (with same exposure time) to be co-added

Returns:

estimated Gaussian noise sqrt(variance)

flux_noise(cps_pixel, exposure_time)[source]

Computes the variance of the shot noise Gaussian approximation of Poisson noise term.

Parameters:
  • cps_pixel – counts per second of the intensity per pixel unit

  • exposure_time – total exposure time (in units seconds or equivalent unit as cps_pixel)

Returns:

sqrt(variance) of pixel value

magnitude2cps(magnitude, magnitude_zero_point)[source]

Converts an apparent magnitude to counts per second.

The zero point of an instrument, by definition, is the magnitude of an object that produces one count (or data number, DN) per second. The magnitude of an arbitrary object producing DN counts in an observation of length EXPTIME is therefore: m = -2.5 x log10(DN / EXPTIME) + ZEROPOINT

Parameters:
  • magnitude – astronomical magnitude

  • magnitude_zero_point – magnitude zero point (astronomical magnitude with 1 count per second)

Returns:

counts per second of astronomical object

cps2magnitude(cps, magnitude_zero_point)[source]
Parameters:
  • cps – float, count-per-second

  • magnitude_zero_point – magnitude zero point

Returns:

magnitude for given counts

absolute2apparent_magnitude(absolute_magnitude, d_parsec)[source]

Converts absolute to apparent magnitudes.

Parameters:
  • absolute_magnitude – absolute magnitude of object

  • d_parsec – distance to object in units parsec

Returns:

apparent magnitude

adu2electrons(adu, ccd_gain)[source]

Converts analog-to-digital units into electron counts.

Parameters:
  • adu – counts in analog-to-digital unit

  • ccd_gain – CCD gain, meaning how many electrons are counted per unit ADU

Returns:

counts in electrons

electrons2adu(electrons, ccd_gain)[source]

Converts electron counts into analog-to-digital unit.

Parameters:
  • electrons – number of electrons received on detector

  • ccd_gain – CCD gain, meaning how many electrons are counted per unit ADU

Returns:

adu value in Analog-to-digital units corresponding to electron count

lenstronomy.Util.derivative_util module

Routines to compute derivatives of spherical functions.

d_r_dx(x, y)[source]

Derivative of r with respect to x :param x:

Parameters:

y

Returns:

d_r_dy(x, y)[source]

Differential dr/dy.

Parameters:
  • x

  • y

Returns:

d_r_dxx(x, y)[source]

Second derivative dr/dxdx :param x:

Parameters:

y

Returns:

d_r_dyy(x, y)[source]

Second derivative dr/dxdx :param x:

Parameters:

y

Returns:

d_r_dxy(x, y)[source]

Second derivative dr/dxdx :param x:

Parameters:

y

Returns:

d_phi_dx(x, y)[source]

Angular derivative in respect to x when phi = arctan2(y, x)

Parameters:
  • x

  • y

Returns:

d_phi_dy(x, y)[source]

Angular derivative in respect to y when phi = arctan2(y, x)

Parameters:
  • x

  • y

Returns:

d_phi_dxx(x, y)[source]

Second derivative of the orientation angle.

Parameters:
  • x

  • y

Returns:

d_phi_dyy(x, y)[source]

Second derivative of the orientation angle in dydy.

Parameters:
  • x

  • y

Returns:

d_phi_dxy(x, y)[source]

Second derivative of the orientation angle in dxdy.

Parameters:
  • x

  • y

Returns:

d_x_diffr_dx(x, y)[source]

Derivative of d(x/r)/dx equivalent to second order derivatives dr_dxx.

Parameters:
  • x

  • y

Returns:

d_y_diffr_dy(x, y)[source]

Derivative of d(y/r)/dy equivalent to second order derivatives dr_dyy.

Parameters:
  • x

  • y

Returns:

d_y_diffr_dx(x, y)[source]

Derivative of d(y/r)/dx equivalent to second order derivatives dr_dxy.

Parameters:
  • x

  • y

Returns:

d_x_diffr_dy(x, y)[source]

Derivative of d(x/r)/dy equivalent to second order derivatives dr_dyx.

Parameters:
  • x

  • y

Returns:

lenstronomy.Util.image_util module

add_layer2image(grid2d, x_pos, y_pos, kernel, order=1)[source]

Adds a kernel on the grid2d image at position x_pos, y_pos with an interpolated subgrid pixel shift of order=order.

Parameters:
  • grid2d – 2d pixel grid (i.e. image)

  • x_pos – x-position center (pixel coordinate) of the layer to be added

  • y_pos – y-position center (pixel coordinate) of the layer to be added

  • kernel – the layer to be added to the image

  • order – interpolation order for sub-pixel shift of the kernel to be added

Returns:

image with added layer, cut to original size

add_layer2image_int(grid2d, x_pos, y_pos, kernel)[source]

Adds a kernel on the grid2d image at position x_pos, y_pos at integer positions of pixel.

Parameters:
  • grid2d – 2d pixel grid (i.e. image)

  • x_pos – x-position center (pixel coordinate) of the layer to be added

  • y_pos – y-position center (pixel coordinate) of the layer to be added

  • kernel – the layer to be added to the image

Returns:

image with added layer

add_background(image, sigma_bkd)[source]

Generates background noise to image. To generate a noisy image with background noise, generate image_noisy = image + add_background(image, sigma_bkd)

Parameters:
  • image – pixel values of image

  • sigma_bkd – background noise (sigma)

Returns:

a realisation of Gaussian noise of the same size as image

add_poisson(image, exp_time)[source]

Generates a poison (or Gaussian) distributed noise with mean given by surface brightness. To generate a noisy image with Poisson noise, perform image_noisy = image + add_poisson(image, exp_time)

Parameters:
  • image – pixel values (photon counts per unit exposure time)

  • exp_time – exposure time

Returns:

Poisson noise realization of input image

rotateImage(img, angle)[source]

Querries scipy.ndimage.rotate routine :param img: image to be rotated :param angle: angle to be rotated (radian) :return: rotated image.

shift_image(img, shift)[source]

Queries scipy.ndimage.shift routine.

Parameters:
  • img – image to be shifted

  • shift – sequence containing x and y shift in pixels

Returns:

shifted image

re_size_array(x_in, y_in, input_values, x_out, y_out)[source]

Resizes 2d array (i.e. image) to new coordinates. So far only works with square output aligned with coordinate axis.

Parameters:
  • x_in

  • y_in

  • input_values

  • x_out

  • y_out

Returns:

symmetry_average(image, symmetry)[source]

Symmetry averaged image.

Parameters:
  • image

  • symmetry

Returns:

findOverlap(x_mins, y_mins, min_distance)[source]

Finds overlapping solutions, deletes multiples and deletes non-solutions and if it is not a solution, deleted as well.

coord_in_image(x_coord, y_coord, num_pix, delta_pix)[source]

checks whether image positions are within the pixel image in units of arcsec if not: remove it

Returns:

image positions within the pixel image

re_size(image, factor=1)[source]

Re-sizes image with nx x ny to nx/factor x ny/factor.

Parameters:
  • image – 2d image with shape (nx,ny)

  • factor – integer >=1

Returns:

rebin_image(bin_size, image, wht_map, sigma_bkg, ra_coords, dec_coords, idex_mask)[source]

Re-bins pixels, updates cutout image, wht_map, sigma_bkg, coordinates, PSF.

Parameters:

bin_size – number of pixels (per axis) to merge

Returns:

rebin_coord_transform(factor, x_at_radec_0, y_at_radec_0, transform_pix2coord, transform_coord2pix)[source]

Adopt coordinate system and transformation between angular and pixel coordinates of a re-binned image.

stack_images(image_list, wht_list, sigma_list)[source]

Stacks images and saves new image as a fits file.

Returns:

cut_edges(image, num_pix)[source]

Cuts out the edges of a 2d image and returns re-sized image to num_pix center is well defined for odd pixel sizes.

Parameters:
  • image – 2d numpy array

  • num_pix – square size of cut out image

Returns:

cutout image with size num_pix

radial_profile(data, center)[source]

Computes radial profile.

Parameters:
  • data – 2d numpy array

  • center – center [x, y] from which pixel to compute the radial profile

Returns:

radial profile (in units pixel)

gradient_map(image)[source]

Computes gradients of images with the sobel transform.

Parameters:

image – 2d numpy array

Returns:

array of same size as input, with gradients between neighboring pixels

lenstronomy.Util.kernel_util module

Routines that manipulate convolution kernels.

de_shift_kernel(kernel, shift_x, shift_y, iterations=20, fractional_step_size=1)[source]

De-shifts a shifted kernel to the center of a pixel. This is performed iteratively.

The input kernel is the solution of a linear interpolated shift of a sharper kernel centered in the middle of the pixel. To find the de-shifted kernel, we perform an iterative correction of proposed de-shifted kernels and compare its shifted version with the input kernel.

Parameters:
  • kernel – (shifted) kernel, e.g. a star in an image that is not centered in the pixel grid

  • shift_x – x-offset relative to the center of the pixel (sub-pixel shift)

  • shift_y – y-offset relative to the center of the pixel (sub-pixel shift)

  • iterations – number of repeated iterations of shifting a new de-shifted kernel and apply corrections

  • fractional_step_size (float (0, 1]) – correction factor relative to previous proposal (can be used for stability

Returns:

de-shifted kernel such that the interpolated shift boy (shift_x, shift_y) results in the input kernel

center_kernel(kernel, iterations=20)[source]

Given a kernel that might not be perfectly centered, this routine computes its light weighted center and then moves the center in an iterative process such that it is centered.

Parameters:
  • kernel – 2d array (odd numbers)

  • iterations – int, number of iterations

Returns:

centered kernel

kernel_make_odd(kernel_even)[source]

Converts an even-sized kernel into an odd-sized kernel using quadratic interpolation.

Parameters:

kernel_even – n x n kernel with n even, centered

Returns:

even kernel with n+1 x n+1 centered

kernel_norm(kernel)[source]
Parameters:

kernel

Returns:

normalisation of the psf kernel

subgrid_kernel(kernel, subgrid_res, odd=False, num_iter=100)[source]

Creates a higher resolution kernel with subgrid resolution as an interpolation of the original kernel in an iterative approach.

Parameters:
  • kernel (2d numpy array with square odd size) – initial kernel

  • subgrid_res (integer) – subgrid resolution required

  • odd (boolean) – forces odd axis size return (-1 in size if even)

  • num_iter (integer) – number of iterations in the de-shifting and enhancement

Returns:

kernel with higher resolution (larger)

Return type:

2d numpy array with n x subgrid size (-1 if result is even and odd=True)

kernel_pixelsize_change(kernel, delta_pix_in, delta_pix_out)[source]

Change the pixel size of a given kernel.

Parameters:
  • kernel

  • delta_pix_in

  • delta_pix_out

Returns:

cut_psf(psf_data, psf_size, normalisation=True)[source]

Cut the psf properly.

Parameters:
  • psf_data – image of PSF

  • psf_size – size of psf

Returns:

re-sized and re-normalized PSF

pixel_kernel(point_source_kernel, subgrid_res=7)[source]

Converts a pixelised kernel of a point source to a kernel representing a uniform extended pixel.

Parameters:
  • point_source_kernel

  • subgrid_res

Returns:

convolution kernel for an extended pixel

kernel_average_pixel(kernel_super, supersampling_factor)[source]

Computes the effective convolution kernel assuming a uniform surface brightness on the scale of a pixel.

Parameters:
  • kernel_super – supersampled PSF of a point source (odd number per axis

  • supersampling_factor – supersampling factor (int)

Returns:

kernel_gaussian_grid(x_grid, y_grid, sigma)[source]

Gaussian kernel.

Parameters:
  • x – x-coordinate grid

  • y – y-coordinate grid

  • sigma – standard deviation of Gaussian

Returns:

2d kernel

kernel_gaussian(num_pix, delta_pix, fwhm)[source]

Gaussian kernel.

Parameters:
  • num_pix – number of pixels

  • delta_pix – pixel scale

  • fwhm – full width at half maximum

Returns:

2d kernel

kernel_moffat_grid(x, y, fwhm, moffat_beta)[source]

Moffat kernel.

Parameters:
  • x – x-coordinate grid

  • y – y-coordinate grid

  • fwhm – full width at half maximum

  • moffat_beta – beta of Moffat profile

Returns:

2d kernel

kernel_moffat(num_pix, delta_pix, fwhm, moffat_beta)[source]

Moffat kernel.

Parameters:
  • delta_pix – pixel scale of kernel

  • num_pix – number of pixels per axis of the kernel

  • fwhm – full width at half maximum

  • moffat_beta – beta of Moffat profile

Returns:

2d kernel

split_kernel(kernel_super, supersampling_kernel_size, supersampling_factor, normalized=True)[source]

Pixel kernel and subsampling kernel such that the convolution of both applied on an image can be performed, i.e. smaller subsampling PSF and hole in larger PSF.

Parameters:
  • kernel_super – super-sampled kernel

  • supersampling_kernel_size – size of super-sampled PSF in units of degraded pixels

  • normalized – if True, preserves the sum of low and high-res kernels to be the sum of the original kernel, else, conserves local density

Returns:

degraded kernel with hole and super-sampled kernel

degrade_kernel(kernel_super, degrading_factor)[source]
Parameters:
  • kernel_super – higher resolution kernel (odd number per axis)

  • degrading_factor – degrading factor (effectively the super-sampling resolution of the kernel given

Returns:

degraded kernel with odd axis number with the sum of the flux/values in the kernel being preserved

averaging_even_kernel(kernel_high_res, subgrid_res)[source]

Makes a lower resolution kernel based on the kernel_high_res (odd numbers) and the subgrid_res (even number), both meant to be centered.

Parameters:
  • kernel_high_res – high resolution kernel with even subsampling resolution, centered

  • subgrid_res – subsampling resolution (even number)

Returns:

averaged undersampling kernel

cutout_source(x_pos, y_pos, image, kernelsize, shift=True)[source]

Cuts out point source (e.g. PSF estimate) out of image and shift it to the center of a pixel.

Parameters:
  • x_pos

  • y_pos

  • image

  • kernelsize

Returns:

fwhm_kernel(kernel)[source]
Parameters:

kernel

Returns:

estimate_amp(data, x_pos, y_pos, psf_kernel)[source]

Estimates the amplitude of a point source located at x_pos, y_pos.

Parameters:
  • data

  • x_pos

  • y_pos

  • psf_kernel

Returns:

mge_kernel(kernel, order=5)[source]

Azimutal Multi-Gaussian expansion of a pixelized kernel.

Parameters:

kernel – 2d numpy array

Returns:

match_kernel_size(image, size)[source]

Matching kernel/image to a dedicated size by either expanding the image with zeros at the edges or chopping of the edges.

Parameters:
  • image – 2d array (square with odd number of pixels)

  • size – integer (odd number)

Returns:

image with matched size, either by cutting or by adding zeros in the outskirts

lenstronomy.Util.kin_sampling_util module

class KinNNImageAlign(spectra_inputs, imaging_inputs, kin_nn_inputs)[source]

Bases: object

Class to rotate and interpolate SKiNN image (which is built along x-axis) to be on the grid of the spectral data (e.g., MUSE), rotated to match light distribution as defined by the lens model main function is interp_image() which will output a 2D image interpolated on the spectra grid.

__init__(spectra_inputs, imaging_inputs, kin_nn_inputs)[source]

Initialize input data.

Parameters:
  • spectra_inputs – dictionary which encodes grid and transformation information for kinematic data :’image’: contains 2d image used to calculate grid coordinates :’transform_pix2angle’: transformation matrix to convert from pixel xy to ra/dec :’ra_at_xy0’: ra coordinate at pixel (0,0) :’dec_at_xy0’: dec coordinate at pixel (0,0)

  • imaging_inputs – dictionary which encodes grid and transformation information for imaging data :’image’: contains 2d image used to calculate grid coordinates :’transform_pix2angle’: transformation matrix to convert from pixel xy to ra/dec :’ra_at_xy0’: ra coordinate at pixel (0,0) :’dec_at_xy0’: dec coordinate at pixel (0,0) :’ellipse_PA’: position angle of ellipse axis relative to x direction :’offset_x’: how many pixels to offset the center of the grid to match the kinNN center (x-direction) :’offset_y’: how many pixels to offset the center of the grid to match the kinNN center (y-direction)

  • kin_nn_inputs – dictionary which encodes grid information for NN output data :’image’: contains 2d image used to calculate grid coordinates :’delta_pix’: pixel size

update(spectra_inputs=None, imaging_inputs=None, kin_nn_inputs=None, update_npix=False)[source]

Update with inputs.

write_npix()[source]

Check that images are squared and write the keyword ‘npix’.

pix_coords(input_set, flatten=True)[source]

Simple function to give pixel coordinates of grid.

Parameters:

input_set – dictionary from above (e.g. spectra_inputs) which completely describes grid transformation :boolean flatten: default True; if True, return 1D flattened output, if False, return 2D grid :return pixel coordinates of grid

radec_to_xy(ra, dec, xy_to_radec_matrix, ra_atxy0, dec_atxy0)[source]

Converts from radec to pixel coordinates.

Parameters:
  • ra – ra coordinate to transform

  • dec – dec coordinate to transform

  • xy_to_radec_matrix – transformation matrix to convert from pixel xy to ra/dec

  • ra_atxy0 – ra coordinate at pixel (0,0)

  • dec_atxy0 – dec coordinate at pixel (0,0)

Returns:

x and y coordinates

xy_to_radec(x, y, xy_to_radec_matrix, ra_atxy0, dec_atxy0)[source]

Converts from pixel coordinates to radec.

Parameters:
  • x – x coordinate to transform

  • y – y coordinate to transform

  • xy_to_radec_matrix – transformation matrix to convert from pixel xy to ra/dec

  • ra_atxy0 – ra coordinate at pixel (0,0)

  • dec_atxy0 – dec coordinate at pixel (0,0)

Returns:

ra and dec coordinates

rotate_imaging_into_kin_nn(imaging_x, imaging_y, ellipse_pa_to_imagingx_angle, delta_pix_imaging, delta_pix_kin_nn, npix_imaging, npix_kin_nn, offsetx=0, offsety=0)[source]

Rotates and rescales from the x,y imaging coordinate system into the NN coordinate system.

Parameters:
  • imaging_x – imaging x coordinate to transform

  • imaging_y – imaging y coordinate to transform

  • ellipse_pa_to_imagingx_angle – (radians) position angle of ellipse major axis relative to x in the imaging coordinate system

  • delta_pix_imaging – pixel size of imaging image

  • delta_pix_kin_nn – pixel size of NN image

  • npix_imaging – number of pixels on a side of the imaging image

  • npix_kin_nn – number of pixels on a side of the NN image

  • offsetx – how many pixels to offset the center of the grid to match the kinNN center (x-direction)

  • offsety – how many pixels to offset the center of the grid to match the kinNN center (y-direction)

Returns:

x and y coordinates in NN coordinate system

plot_contour_and_grid(xcoords, ycoords, orig_image, color, alpha=0.4)[source]

Plotting function for visualization of a grid with a single ellipse contour.

Parameters:
  • xcoords – grid x coordinates, flattened

  • ycoords – grid y coordinates, flattened

  • orig_image – original 2D image

  • color – plotting color

  • alpha – plotting alpha

spectragrid_in_radec()[source]

Calculates ra and dec coordinates of spectra input coordinate grid.

Returns:

ra and dec coordinates

spectragrid_in_imagingxy()[source]

Calculates x and y coordinates in the imaging coordinate system of the original spectra input grid.

Returns:

x and y coordinates

spectragrid_in_kin_nn_xy()[source]

Calculates x and y coordinates in the NN coordinate system of the original spectra input grid.

Returns:

x and y coordinates

interp_image()[source]

Interpolates kinNN image at the coordinates of the transformed spectra grid.

Returns:

interpolated image which lines up with spectra coordinates

lenstronomy.Util.magnification_finite_util module

auto_raytracing_grid_size(source_fwhm_parcsec, grid_size_scale=0.005, power=1.0)[source]

This function returns the size of a ray tracing grid in units of arcsec appropriate for magnification computations with finite-size background sources. This fit is calibrated for source sizes (interpreted as the FWHM of a Gaussian) in the range 0.1 -100 pc.

Parameters:

source_fwhm_parcsec – the full width at half max of a Gaussian background source

Returns:

an appropriate grid size for finite-size background magnification computation

auto_raytracing_grid_resolution(source_fwhm_parcsec, grid_resolution_scale=0.0002, ref=10.0, power=1.0)[source]

This function returns a resolution factor in units arcsec/pixel appropriate for magnification computations with finite-size background sources. This fit is calibrated for source sizes (interpreted as the FWHM of a Gaussian) in the range 0.1-100 pc.

Parameters:

source_fwhm_parcsec – the full width at half max of a Gaussian background source

Returns:

an appropriate grid resolution for finite-size background magnification computation

setup_mag_finite(grid_radius_arcsec, grid_resolution, source_model, kwargs_source)[source]

Sets up the ray tracing grid and source light model for magnification_finite_adaptive and plot_quasar_images routines.

This new updates allows for more flexibility in the source light model by requiring the user to specify the source light mode, grid size and grid resolution before calling the function.

The functions auto_raytrracing_grid_size and auto_raytracing_grid_resolution give good estimates for appropriate parameter choices for grid_radius_arcsec and grid_resolution.

Parameters:
  • grid_radius_arcsec – the size of the ray tracing region in arcsec; if not specified, an appropriate value will be estimated from the source size

  • grid_resolution – the grid resolution in units arcsec/pixel; if not specified, an appropriate value will be estimated from the source size

  • source_model – instance of LightModel for the source :kwargs_source: keyword arguments for the light profile corresponding to the desired LightModel instance

lenstronomy.Util.mask_util module

mask_center_2d(center_x, center_y, r, x_grid, y_grid)[source]
Parameters:
  • center_x – x-coordinate of center position of circular mask

  • center_y – y-coordinate of center position of circular mask

  • r – radius of mask in pixel values

  • x_grid – x-coordinate grid

  • y_grid – y-coordinate grid

Returns:

mask array of shape x_grid with =0 inside the radius and =1 outside

Return type:

array of size of input grid with integers 0 or 1

mask_azimuthal(x, y, center_x, center_y, r)[source]

Azimuthal mask with =1 inside radius and =0 outside.

Parameters:
  • x – x-coordinates (1d or 2d array numpy array)

  • y – y-coordinates (1d or 2d array numpy array)

  • center_x – center of azimuthal mask in x

  • center_y – center of azimuthal mask in y

  • r – radius of azimuthal mask

Returns:

array with zeros outside r and ones inside azimuthal radius r

Return type:

array of size of input grid with integers 0 or 1

mask_ellipse(x, y, center_x, center_y, a, b, angle)[source]
Parameters:
  • x – x-coordinates of pixels

  • y – y-coordinates of pixels

  • center_x – center of mask

  • center_y – center of mask

  • a – major axis

  • b – minor axis

  • angle – angle of major axis

Returns:

mask (list of zeros and ones)

Return type:

array of size of input grid with integers 0 or 1

mask_eccentric(x, y, center_x, center_y, e1, e2, r)[source]

Elliptical mask with eccentricities as input.

Parameters:
  • x – x-coordinate array

  • y – y-coordinate array

  • center_x – center in x

  • center_y – center in y

  • e1 – eccentricity e1

  • e2 – eccentricity e2

  • r – radius of mask

Returns:

mask (list of zeros and ones)

Return type:

array of size of input grid with integers 0 or 1

mask_half_moon(x, y, center_x, center_y, r_in, r_out, phi0=0, delta_phi=6.283185307179586)[source]
Parameters:
  • x

  • y

  • center_x

  • center_y

  • r_in

  • r_out

  • phi0

  • delta_phi

Returns:

Return type:

array of size of input grid with integers 0 or 1

lenstronomy.Util.multi_gauss_expansion module

gaussian(R, sigma, amp)[source]
Parameters:
  • R – radius

  • sigma – gaussian sigma

  • amp – normalization

Returns:

Gaussian function

mge_1d(r_array, flux_r, N=20, linspace=False)[source]
Parameters:
  • r_array – list or radii (numpy array)

  • flux_r – list of flux values (numpy array)

  • N – number of Gaussians

Returns:

amplitudes and Gaussian sigmas for the best 1d flux profile

de_projection_3d(amplitudes, sigmas)[source]

De-projects a gaussian (or list of multiple Gaussians from a 2d projected to a 3d profile) :param amplitudes:

Parameters:

sigmas

Returns:

lenstronomy.Util.numba_util module

jit(nopython=True, cache=True, parallel=False, fastmath=False, error_model='numpy', inline='never')[source]

lenstronomy.Util.package_util module

exporter(export_self=False)[source]

Export utility, modified from https://stackoverflow.com/a/41895194 Returns export decorator, __all__ list

laconic()[source]

Activate laconic / super-shortcut mode.

Usage:

import lenstronomy as ls ls.laconic()

lens_model = ls.LensModel(…) source_model = ls.LightModel(…) image_model = ls.ImageModel(…)

short(_laconic=False)[source]

Activate shortcut mode.

Usage:

import lenstronomy as ls ls.short()

lens_model = ls.LensModel.lens_model.LensModel(…) source_model = ls.LightModel.light_model.LightModel(…) image_model = ls.ImSim.image_model.ImageModel(…)

lenstronomy.Util.param_util module

cart2polar(x, y, center_x=0, center_y=0)[source]

Transforms cartesian coords [x,y] into polar coords [r,phi] in the frame of the lens center.

Parameters:
  • x (array of size (n)) – set of x-coordinates

  • y (array of size (n)) – set of x-coordinates

  • center_x (float) – rotation point

  • center_y (float) – rotation point

Returns:

array of same size with coords [r,phi]

polar2cart(r, phi, center)[source]

Transforms polar coords [r,phi] into cartesian coords [x,y] in the frame of the lense center.

Parameters:
  • r (array of size n or float) – radial coordinate (distance) to the center

  • phi (array of size n or float) – angular coordinate

  • center (array of size (2)) – rotation point

Returns:

array of same size with coords [x,y]

Raises:

AttributeError, KeyError

shear_polar2cartesian(phi, gamma)[source]
Parameters:
  • phi – shear angle (radian)

  • gamma – shear strength

Returns:

shear components gamma1, gamma2

shear_cartesian2polar(gamma1, gamma2)[source]
Parameters:
  • gamma1 – cartesian shear component

  • gamma2 – cartesian shear component

Returns:

shear angle, shear strength

phi_q2_ellipticity(phi, q)[source]

Transforms orientation angle and axis ratio into complex ellipticity moduli e1, e2.

Parameters:
  • phi – angle of orientation (in radian)

  • q – axis ratio minor axis / major axis

Returns:

eccentricities e1 and e2 in complex ellipticity moduli

ellipticity2phi_q(e1, e2)[source]

Transforms complex ellipticity moduli in orientation angle and axis ratio.

Parameters:
  • e1 – eccentricity in x-direction

  • e2 – eccentricity in xy-direction

Returns:

angle in radian, axis ratio (minor/major)

transform_e1e2_product_average_old(x, y, e1, e2, center_x, center_y)[source]

Maps the coordinates x, y with eccentricities e1 e2 into a new elliptical coordinate system such that R = sqrt(R_major * R_minor)

Parameters:
  • x – x-coordinate

  • y – y-coordinate

  • e1 – eccentricity

  • e2 – eccentricity

  • center_x – center of distortion

  • center_y – center of distortion

Returns:

distorted coordinates x’, y’

transform_e1e2_product_average(x, y, e1, e2, center_x, center_y)[source]

Maps the coordinates x, y with eccentricities e1 e2 into a new elliptical coordinate system such that R = sqrt(R_major * R_minor)

Parameters:
  • x – x-coordinate

  • y – y-coordinate

  • e1 – eccentricity

  • e2 – eccentricity

  • center_x – center of distortion

  • center_y – center of distortion

Returns:

distorted coordinates x’, y’

elliptical_distortion_product_average(x, y, e1, e2, center_x, center_y)[source]

Maps the coordinates x, y with eccentricities e1 e2 into a new elliptical coordinate system such with same coordinate orientation.

Parameters:
  • x – x-coordinate

  • y – y-coordinate

  • e1 – eccentricity

  • e2 – eccentricity

  • center_x – center of distortion

  • center_y – center of distortion

Returns:

distorted coordinates x’, y’

transform_e1e2_square_average(x, y, e1, e2, center_x, center_y)[source]

Maps the coordinates x, y with eccentricities e1 e2 into a new elliptical coordinate system such that R = sqrt(R_major**2 + R_minor**2)

Parameters:
  • x – x-coordinate

  • y – y-coordinate

  • e1 – eccentricity

  • e2 – eccentricity

  • center_x – center of distortion

  • center_y – center of distortion

Returns:

distorted coordinates x’, y’

lenstronomy.Util.primary_beam_util module

primary_beam_value_at_coords(x_pos, y_pos, primary_beam, order=3)[source]

Interpolate the primary beam values at specified pixel coordinates. The coordinates falling outside the image are assigned to constant zero.

Parameters:
  • x_pos – array or scalar of x-pixel-coordinates.

  • y_pos – array or scalar of y-pixel-coordinates.

  • primary_beam – the primary_beam map

  • order – the order of the spline interpolation

Returns:

a numpy array of the interpolated primary beam values

lenstronomy.Util.prob_density module

class SkewGaussian[source]

Bases: object

Class for the Skew Gaussian distribution.

pdf(x, e=0.0, w=1.0, a=0.0)[source]

probability density function see: https://en.wikipedia.org/wiki/Skew_normal_distribution

Parameters:
  • x – input value

  • e

  • w

  • a

Returns:

pdf_skew(x, mu, sigma, skw)[source]

Function with different parameterisation.

Parameters:
  • x

  • mu – mean

  • sigma – sigma

  • skw – skewness

Returns:

map_mu_sigma_skw(mu, sigma, skw)[source]

Map to parameters e, w, a.

Parameters:
  • mu – mean

  • sigma – standard deviation

  • skw – skewness

Returns:

e, w, a

class KDE1D(values)[source]

Bases: object

Class that allows to compute likelihoods based on a 1-d posterior sample.

__init__(values)[source]
Parameters:

values – 1d numpy array of points representing a PDF

likelihood(x)[source]
Parameters:

x – position where to evaluate the density

Returns:

likelihood given the sample distribution

compute_lower_upper_errors(sample, num_sigma=1)[source]

Computes the upper and lower sigma from the median value. This functions gives good error estimates for skewed pdf’s.

Parameters:
  • sample – 1-D sample

  • num_sigma – integer, number of sigmas to be returned

Returns:

median, lower_sigma, upper_sigma

lenstronomy.Util.sampling_util module

unit2uniform(x, vmin, vmax)[source]

Mapping from uniform distribution on parameter space to uniform distribution on unit hypercube.

uniform2unit(theta, vmin, vmax)[source]

Mapping from uniform distribution on unit hypercube to uniform distribution on parameter space.

cube2args_uniform(cube, lowers, uppers, num_dims, copy=False)[source]

Mapping from uniform distribution on unit hypercube ‘cube’ to uniform distribution on parameter space.

Parameters:
  • cube – list or 1D-array of parameter values on unit hypercube

  • lowers – lower bounds for each parameter

  • uppers – upper bounds for each parameter

  • num_dims – parameter space dimension (= number of parameters)

  • copy – If False, this function modifies ‘cube’ in-place. Default to False.

Returns:

hypercube mapped to parameters space

cube2args_gaussian(cube, lowers, uppers, means, sigmas, num_dims, copy=False)[source]

Mapping from uniform distribution on unit hypercube ‘cube’ to truncated gaussian distribution on parameter space, with mean ‘mu’ and std dev ‘sigma’.

Parameters:
  • cube – list or 1D-array of parameter values on unit hypercube

  • lowers – lower bounds for each parameter

  • uppers – upper bounds for each parameter

  • means – gaussian mean for each parameter

  • sigmas – gaussian std deviation for each parameter

  • num_dims – parameter space dimension (= number of parameters)

  • copy – If False, this function modifies ‘cube’ in-place. Default to False.

Returns:

hypercube mapped to parameters space

scale_limits(lowers, uppers, scale)[source]
sample_ball(p0, std, size=1, dist='uniform')[source]

Produce a ball of walkers around an initial parameter value. this routine is from the emcee package as it became deprecated there.

Parameters:
  • p0 – The initial parameter values (array).

  • std – The axis-aligned standard deviation (array).

  • size – The number of samples to produce.

  • dist – string, specifies the distribution being sampled, supports ‘uniform’ and ‘normal’

sample_ball_truncated(mean, sigma, lower_limit, upper_limit, size)[source]

Samples gaussian ball with truncation at lower and upper limit of the distribution.

Parameters:
  • mean – numpy array, mean of the distribution to be sampled

  • sigma – numpy array, sigma of the distribution to be sampled

  • lower_limit – numpy array, lower bound of to be sampled distribution

  • upper_limit – numpy array, upper bound of to be sampled distribution

  • size – number of tuples to be sampled

Returns:

realization of truncated normal distribution with shape (size, dim(parameters))

lenstronomy.Util.simulation_util module

data_configure_simple(num_pix, delta_pix, exposure_time=None, background_rms=None, center_ra=0, center_dec=0, inverse=False)[source]

Configures the data keyword arguments with a coordinate grid centered at zero.

Parameters:
  • num_pix – number of pixel (num_pix x num_pix)

  • delta_pix – pixel size (in angular units)

  • exposure_time – exposure time

  • background_rms – background noise (Gaussian sigma)

  • center_ra – RA at the center of the image

  • center_dec – DEC at the center of the image

  • inverse – if True, coordinate system is ra to the left, if False, to the right

Returns:

keyword arguments that can be used to construct a Data() class instance of lenstronomy

simulate_simple(image_model_class, kwargs_lens=None, kwargs_source=None, kwargs_lens_light=None, kwargs_ps=None, no_noise=False, source_add=True, lens_light_add=True, point_source_add=True)[source]
Parameters:
  • image_model_class

  • kwargs_lens

  • kwargs_source

  • kwargs_lens_light

  • kwargs_ps

  • no_noise

  • source_add

  • lens_light_add

  • point_source_add

Returns:

lenstronomy.Util.util module

merge_dicts(*dict_args)[source]

Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts.

isiterable(obj)[source]

Returns True if the given object is iterable.

approx_theta_E(ximg, yimg)[source]
sort_image_index(ximg, yimg, xref, yref)[source]
Parameters:
  • ximg – x coordinates to sort

  • yimg – y coordinates to sort

  • xref – reference x coordinate

  • yref – reference y coordinate

Returns:

indexes such that ximg[indexes],yimg[indexes] matches xref,yref

rotate(xcoords, ycoords, angle)[source]
Parameters:
  • xcoords – x points

  • ycoords – y points

  • angle – angle in radians

Returns:

x points and y points rotated ccw by angle theta

map_coord2pix(ra, dec, x_0, y_0, transform_matrix)[source]

This routines performs a linear transformation between two coordinate systems. Mainly used to transform angular into pixel coordinates in an image.

Parameters:
  • ra – ra coordinates

  • dec – dec coordinates

  • x_0 – pixel value in x-axis of ra,dec = 0,0

  • y_0 – pixel value in y-axis of ra,dec = 0,0

  • transform_matrix – 2x2 matrix to transform angular to pixel coordinates

Returns:

transformed coordinate systems of input ra and dec

array2image(array, nx=0, ny=0)[source]

Returns the information contained in a 1d array into an n*n 2d array (only works when length of array is n**2, or nx and ny are provided)

Parameters:

array (array of size n**2) – image values

Returns:

2d array

Raises:

AttributeError, KeyError

image2array(image)[source]

Returns the information contained in a 2d array into an n*n 1d array.

Parameters:

image (array of size (n,n)) – image values

Returns:

1d array

Raises:

AttributeError, KeyError

array2cube(array, n_1, n_23)[source]

Returns the information contained in a 1d array of shape (n_1*n_23*n_23) into 3d array with shape (n_1, sqrt(n_23), sqrt(n_23))

Parameters:
  • array (1d array) – image values

  • n_1 (int) – first dimension of returned array

  • n_23 (int) – square of second and third dimensions of returned array

Returns:

3d array

Raises:

ValueError – when n_23 is not a perfect square

cube2array(cube)[source]

Returns the information contained in a 3d array of shape (n_1, n_2, n_3) into 1d array with shape (n_1*n_2*n_3)

Parameters:

cube (3d array) – image values

Returns:

1d array

make_grid(num_pix, delta_pix, subgrid_res=1, left_lower=False)[source]

Creates pixel grid (in 1d arrays of x- and y- positions) default coordinate frame is such that (0,0) is in the center of the coordinate grid.

Parameters:
  • num_pix – number of pixels per axis Give an integers for a square grid, or a 2-length sequence (first, second axis length) for a non-square grid.

  • delta_pix – pixel size

  • subgrid_res – sub-pixel resolution (default=1)

Returns:

x, y position information in two 1d arrays

make_grid_transformed(num_pix, transform_pix2angle)[source]

Returns grid with linear transformation (delta_pix and rotation)

Parameters:
  • num_pix – number of Pixels

  • transform_pix2angle – 2-by-2 matrix to map a pixel to a coordinate

Returns:

coordinate grid

make_grid_with_coordtransform(num_pix, delta_pix, subgrid_res=1, center_ra=0, center_dec=0, left_lower=False, inverse=True)[source]

Same as make_grid routine, but returns the transformation matrix and shift between coordinates and pixel.

Parameters:
  • num_pix – number of pixels per axis

  • delta_pix – pixel scale per axis

  • subgrid_res – super-sampling resolution relative to the stated pixel size

  • center_ra – center of the grid

  • center_dec – center of the grid

  • left_lower – sets the zero point at the lower left corner of the pixels

  • inverse – bool, if true sets East as left, otherwise East is righrt

Returns:

ra_grid, dec_grid, ra_at_xy_0, dec_at_xy_0, x_at_radec_0, y_at_radec_0, transform_pix2coord, transform_coord2pix

grid_from_coordinate_transform(nx, ny, transform_pix2coord, ra_at_xy_0, dec_at_xy_0)[source]

Return a grid in x and y coordinates that satisfy the coordinate system.

Parameters:
  • nx – number of pixels in x-axis

  • ny – number of pixels in y-axis

  • transform_pix2coord – transformation matrix (2x2) of pixels into coordinate displacements

  • ra_at_xy_0 – RA coordinate at (x,y) = (0,0)

  • dec_at_xy_0 – DEC coordinate at (x,y) = (0,0)

Returns:

RA coordinate grid, DEC coordinate grid

get_axes(x, y)[source]

Computes the axis x and y of a given 2d grid.

Parameters:
  • x

  • y

Returns:

averaging(grid, num_grid, num_pix)[source]

Resize 2d pixel grid with numGrid to num_pix and averages over the pixels.

Parameters:
  • grid – higher resolution pixel grid

  • numGrid – number of pixels per axis in the high resolution input image

  • num_pix – lower number of pixels per axis in the output image (numGrid/num_pix is integer number)

Returns:

averaged pixel grid

displaceAbs(x, y, source_pos_x, source_pos_y)[source]

Calculates a grid of distances to the observer in angel.

Parameters:
  • x (numpy array) – cartesian coordinates

  • y (numpy array) – cartesian coordinates

  • source_pos_x (float) – source position

  • source_pos_y (float) – source position

Returns:

array of displacement

Raises:

AttributeError, KeyError

get_distance(x_mins, y_mins, x_true, y_true)[source]
Parameters:
  • x_mins

  • y_mins

  • x_true

  • y_true

Returns:

compare_distance(x_mapped, y_mapped)[source]
Parameters:
  • x_mapped – array of x-positions of remapped catalogue image

  • y_mapped – array of y-positions of remapped catalogue image

Returns:

sum of distance square of positions

min_square_dist(x_1, y_1, x_2, y_2)[source]

Return minimum of quadratic distance of pairs (x1, y1) to pairs (x2, y2)

Parameters:
  • x_1

  • y_1

  • x_2

  • y_2

Returns:

selectBest(array, criteria, num_select, highest=True)[source]
Parameters:
  • array – numpy array to be selected from

  • criteria – criteria of selection

  • highest – bool, if false the lowest will be selected

  • num_select – number of elements to be selected

Returns:

select_best(array, criteria, num_select, highest=True)[source]
Parameters:
  • array – numpy array to be selected from

  • criteria – criteria of selection

  • highest – bool, if false the lowest will be selected

  • num_select – number of elements to be selected

Returns:

points_on_circle(radius, num_points, connect_ends=True)[source]

Returns a set of uniform points around a circle.

Parameters:
  • radius – radius of the circle

  • num_points – number of points on the circle

  • connect_ends – boolean, if True, start and end point are the same

Returns:

x-coords, y-coords of points on the circle

local_minima_2d(a, x, y)[source]

Finds (local) minima in a 2d grid applies less rigid criteria for maximum without second-order tangential minima criteria.

Parameters:
  • a (numpy array with length num_pix**2 in float) – 1d array of displacements from the source positions

  • x (numpy array with length num_pix**2 in float) – 1d coordinate grid in x-direction

  • y (numpy array with length num_pix**2 in float) – 1d coordinate grid in x-direction

Returns:

array of indices of local minima, values of those minima

Raises:

AttributeError, KeyError

neighbor_select(a, x, y)[source]

#TODO replace by from scipy.signal import argrelextrema for speed up >>> from scipy.signal import argrelextrema >>> x = np.array([2, 1, 2, 3, 2, 0, 1, 0]) >>> argrelextrema(x, np.greater) (array([3, 6]),) >>> y = np.array([[1, 2, 1, 2], … [2, 2, 0, 0], … [5, 3, 4, 4]]) … >>> argrelextrema(y, np.less, axis=1) (array([0, 2]), array([2, 1]))

finds (local) minima in a 2d grid

Parameters:

a (numpy array with length num_pix**2 in float) – 1d array of displacements from the source positions

Returns:

array of indices of local minima, values of those minima

Raises:

AttributeError, KeyError

fwhm2sigma(fwhm)[source]
Parameters:

fwhm – full-width-half-max value

Returns:

gaussian sigma (sqrt(var))

sigma2fwhm(sigma)[source]
Parameters:

sigma

Returns:

hyper2F2_array(a, b, c, d, x)[source]
Parameters:
  • a

  • b

  • c

  • d

  • x

Returns:

make_subgrid(ra_coord, dec_coord, subgrid_res=2)[source]

Return a grid with subgrid resolution.

Parameters:
  • ra_coord

  • dec_coord

  • subgrid_res

Returns:

convert_bool_list(n, k=None)[source]

Returns a bool list of the length of the lens models.

if k = None: returns bool list with True’s if k is int, returns bool list with False’s but k’th is True if k is a list of int, e.g. [0, 3, 5], returns a bool list with True’s in the integers listed and False elsewhere if k is a boolean list, checks for size to match the numbers of models and returns it

Parameters:
  • n – integer, total length of output boolean list

  • k – None, int, or list of ints

Returns:

bool list

Module contents