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

azimuthalAverage(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, kwargs_interp=None, multi_plane=False, distance_ratio_sampling=False, observed_convention_index=None, source_light_model_list=None, lens_light_model_list=None, point_source_model_list=None, fixed_magnification_list=None, flux_from_point_source_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, index_optical_depth_model_list=None, band_index=0, tau0_index_list=None, all_models=False, point_source_magnification_limit=None, surface_brightness_smoothing=0.001, sersic_major_axis=None, tabulated_deflection_angles=None, tracer_source_model_list=None, tracer_source_band=0, tracer_partition=None)[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

  • 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

  • kwargs_interp – interpolation keyword arguments specifying the numerics. See description in the Interpolate() class. Only applicable for ‘INTERPOL’ and ‘INTERPOL_SCALED’ models.

  • observed_convention_index

  • source_light_model_list

  • lens_light_model_list

  • point_source_model_list

  • fixed_magnification_list

  • flux_from_point_source_list – list of bools (optional), if set, will only return image positions (for imaging modeling) for the subset of the point source lists that =True. This option enables to model

  • point_source_frame_list – list of lists mirroring the structure of the image positions. Integers correspond to the i’th list entry of index_lens_model_list indicating in which frame/band the image is appearing

  • additional_images_list

  • 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

  • cosmo – astropy.cosmology instance

  • index_lens_model_list

  • index_source_light_model_list

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

  • index_point_source_model_list

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

  • index_optical_depth_model_list

  • 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

  • surface_brightness_smoothing – float, smoothing scale of light profile (minimal distance to the center of a profile) this can help to avoid inaccuracies in the very center of a cuspy light profile

  • sersic_major_axis – boolean or None, if True, uses the semi-major axis as the definition of the Sersic half-light radius, if False, uses the product average of semi-major and semi-minor axis. If None, uses the convention in the lenstronomy yaml setting (which by default is =False)

  • tabulated_deflection_angles – a user-specified class with a call method that returns deflection angles given (x, y) coordinates on the sky. This class gets passed to the lens model class TabulatedDeflections

  • 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], […], …]

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.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.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.

coordInImage(x_coord, y_coord, num_pix, deltapix)[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, Mpix2coord, Mcoord2pix)[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 numPix 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 numPix

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_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, deltaPix_in, deltaPix_out)[source]

Change the pixel size of a given kernel.

Parameters:
  • kernel

  • deltaPix_in

  • deltaPix_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 – boolean, if True returns a split kernel that is area normalized=1 representing a convolution kernel

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.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]
overload(nopython=True, cache=True, parallel=False, fastmath=False, error_model='numpy')[source]

Wrapper around numba.generated_jit.

Allows you to redirect a function to another based on its type - see the Numba docs for more info

nan_to_num(x, posinf=10000000000.0, neginf=-10000000000.0, nan=0.0)[source]

Implements a Numba equivalent to np.nan_to_num (with copy=False!) array or scalar in Numba.

Behaviour is the same as np.nan_to_num with copy=False, although it only supports 1-dimensional arrays and scalar inputs.

nan_to_num_arr(x, posinf=10000000000.0, neginf=-10000000000.0, nan=0.0)[source]

Part of the Numba implementation of np.nan_to_num - see nan_to_num

nan_to_num_single(x, posinf=10000000000.0, neginf=-10000000000.0, nan=0.0)[source]

Part of the Numba implementation of np.nan_to_num - see nan_to_num

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(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_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.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(numPix, deltaPix, 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:
  • numPix – number of pixel (numPix x numPix)

  • deltaPix – 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, M)[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

  • M – 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(numPix, deltapix, 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:
  • numPix – 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.

  • deltapix – pixel size

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

Returns:

x, y position information in two 1d arrays

make_grid_transformed(numPix, Mpix2Angle)[source]

Returns grid with linear transformation (deltaPix and rotation)

Parameters:
  • numPix – number of Pixels

  • Mpix2Angle – 2-by-2 matrix to mat a pixel to a coordinate

Returns:

coordinate grid

make_grid_with_coordtransform(numPix, deltapix, 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:
  • numPix – number of pixels per axis

  • deltapix – 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, Mpix2coord, Mcoord2pix

grid_from_coordinate_transform(nx, ny, Mpix2coord, 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

  • Mpix2coord – 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, numGrid, numPix)[source]

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

Parameters:
  • grid – higher resolution pixel grid

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

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

Returns:

averaged pixel grid

displaceAbs(x, y, sourcePos_x, sourcePos_y)[source]

Calculates a grid of distances to the observer in angel.

Parameters:
  • x (numpy array) – cartesian coordinates

  • y (numpy array) – cartesian coordinates

  • sourcePos_x (float) – source position

  • sourcePos_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, numSelect, highest=True)[source]
Parameters:
  • array – numpy array to be selected from

  • criteria – criteria of selection

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

  • numSelect – 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 numPix**2 in float) – 1d array of displacements from the source positions

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

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

Returns:

array of indices of local minima, values of those minima

Raises:

AttributeError, KeyError

neighborSelect(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 numPix**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