lenstronomy.Util package

Submodules

lenstronomy.Util.analysis_util module

lenstronomy.Util.analysis_util.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

lenstronomy.Util.analysis_util.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

lenstronomy.Util.analysis_util.ellipticities(I_xy, x, y)[source]

compute ellipticities of a light distribution

Parameters
  • I_xy

  • x

  • y

Returns

lenstronomy.Util.analysis_util.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

lenstronomy.Util.analysis_util.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

lenstronomy.Util.analysis_util.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.analysis_util.radial_profile(light_grid, x_grid, y_grid, center_x=0, center_y=0, n=None)[source]
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

lenstronomy.Util.class_creator module

lenstronomy.Util.class_creator.create_class_instances(lens_model_list=None, z_lens=None, z_source=None, lens_redshift_list=None, kwargs_interp=None, multi_plane=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, 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)[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.

  • lens_redshift_list

  • multi_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

  • 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

  • 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)

Returns

lenstronomy.Util.class_creator.create_im_sim(multi_band_list, multi_band_type, kwargs_model, bands_compute=None, likelihood_mask_list=None, band_index=0, kwargs_pixelbased=None)[source]
Parameters

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

Parameters

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

Returns

MultiBand class instance

lenstronomy.Util.class_creator.create_image_model(kwargs_data, kwargs_psf, kwargs_numerics, kwargs_model, likelihood_mask=None)[source]
Parameters
  • kwargs_data – ImageData keyword arguments

  • kwargs_psf – PSF keyword arguments

  • kwargs_model – model keyword arguments

Returns

ImageLinearFit() instance

lenstronomy.Util.constants module

lenstronomy.Util.constants.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

lenstronomy.Util.correlation.correlation_2D(image)[source]

#TODO document normalization output in units

Parameters

image – 2d image

Returns

2d fourier transform

lenstronomy.Util.correlation.power_spectrum_1d(image)[source]
Parameters

image – 2d numpy array

Returns

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

lenstronomy.Util.correlation.power_spectrum_2d(image)[source]
Parameters

image – 2d numpy array

Returns

2d power spectrum in frequency units of the pixels

lenstronomy.Util.data_util module

lenstronomy.Util.data_util.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

lenstronomy.Util.data_util.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

lenstronomy.Util.data_util.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)

lenstronomy.Util.data_util.cps2magnitude(cps, magnitude_zero_point)[source]
Parameters
  • cps – float, count-per-second

  • magnitude_zero_point – magnitude zero point

Returns

magnitude for given counts

lenstronomy.Util.data_util.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.data_util.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

lenstronomy.Util.data_util.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

lenstronomy.Util.derivative_util module

routines to compute derivatives of spherical functions

lenstronomy.Util.derivative_util.d_phi_dx(x, y)[source]

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

Parameters
  • x

  • y

Returns

lenstronomy.Util.derivative_util.d_phi_dxx(x, y)[source]

second derivative of the orientation angle

Parameters
  • x

  • y

Returns

lenstronomy.Util.derivative_util.d_phi_dxy(x, y)[source]

second derivative of the orientation angle in dxdy

Parameters
  • x

  • y

Returns

lenstronomy.Util.derivative_util.d_phi_dy(x, y)[source]

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

Parameters
  • x

  • y

Returns

lenstronomy.Util.derivative_util.d_phi_dyy(x, y)[source]

second derivative of the orientation angle in dydy

Parameters
  • x

  • y

Returns

lenstronomy.Util.derivative_util.d_r_dx(x, y)[source]

derivative of r with respect to x :param x: :param y: :return:

lenstronomy.Util.derivative_util.d_r_dxx(x, y)[source]

second derivative dr/dxdx :param x: :param y: :return:

lenstronomy.Util.derivative_util.d_r_dxy(x, y)[source]

second derivative dr/dxdx :param x: :param y: :return:

lenstronomy.Util.derivative_util.d_r_dy(x, y)[source]

differential dr/dy

Parameters
  • x

  • y

Returns

lenstronomy.Util.derivative_util.d_r_dyy(x, y)[source]

second derivative dr/dxdx :param x: :param y: :return:

lenstronomy.Util.derivative_util.d_x_diffr_dx(x, y)[source]

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

Parameters
  • x

  • y

Returns

lenstronomy.Util.derivative_util.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.derivative_util.d_y_diffr_dx(x, y)[source]

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

Parameters
  • x

  • y

Returns

lenstronomy.Util.derivative_util.d_y_diffr_dy(x, y)[source]

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

Parameters
  • x

  • y

Returns

lenstronomy.Util.image_util module

lenstronomy.Util.image_util.add_background(image, sigma_bkd)[source]

adds background noise to image :param image: pixel values of image :param sigma_bkd: background noise (sigma) :return: a realisation of Gaussian noise of the same size as image

lenstronomy.Util.image_util.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 :param grid2d: 2d pixel grid (i.e. image) :param x_pos: x-position center (pixel coordinate) of the layer to be added :param y_pos: y-position center (pixel coordinate) of the layer to be added :param kernel: the layer to be added to the image :param order: interpolation order for sub-pixel shift of the kernel to be added :return: image with added layer, cut to original size

lenstronomy.Util.image_util.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 :param grid2d: 2d pixel grid (i.e. image) :param x_pos: x-position center (pixel coordinate) of the layer to be added :param y_pos: y-position center (pixel coordinate) of the layer to be added :param kernel: the layer to be added to the image :return: image with added layer

lenstronomy.Util.image_util.add_poisson(image, exp_time)[source]

adds a poison (or Gaussian) distributed noise with mean given by surface brightness :param image: pixel values (photon counts per unit exposure time) :param exp_time: exposure time :return: Poisson noise realization of input image

lenstronomy.Util.image_util.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

Parameters

imcoord ((n,4) numpy array) – image coordinate (in units of angels) [[x,y,delta,magnification][…]]

Returns

image positions within the pixel image

lenstronomy.Util.image_util.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. :param image: 2d numpy array :param num_pix: square size of cut out image :return: cutout image with size numPix

lenstronomy.Util.image_util.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

lenstronomy.Util.image_util.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.image_util.radial_profile(data, center=None)[source]

computes radial profile

Parameters
  • data – 2d numpy array

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

Returns

radial profile (in units pixel)

lenstronomy.Util.image_util.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

lenstronomy.Util.image_util.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. :param x_in: :param y_in: :param input_values: :param x_out: :param y_out: :return:

lenstronomy.Util.image_util.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 :param bin_size: :param ra_0: :param dec_0: :param x_0: :param y_0: :param Matrix: :param Matrix_inv: :return:

lenstronomy.Util.image_util.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

lenstronomy.Util.image_util.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

lenstronomy.Util.image_util.stack_images(image_list, wht_list, sigma_list)[source]

stacks images and saves new image as a fits file :param image_name_list: list of image_names to be stacked :return:

lenstronomy.Util.image_util.symmetry_average(image, symmetry)[source]

symmetry averaged image :param image: :param symmetry: :return:

lenstronomy.Util.kernel_util module

routines that manipulate convolution kernels

lenstronomy.Util.kernel_util.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

lenstronomy.Util.kernel_util.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

lenstronomy.Util.kernel_util.cut_psf(psf_data, psf_size)[source]

cut the psf properly :param psf_data: image of PSF :param psf_size: size of psf :return: re-sized and re-normalized PSF

lenstronomy.Util.kernel_util.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 :param x_pos: :param y_pos: :param image: :param kernelsize: :return:

lenstronomy.Util.kernel_util.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

lenstronomy.Util.kernel_util.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

lenstronomy.Util.kernel_util.estimate_amp(data, x_pos, y_pos, psf_kernel)[source]

estimates the amplitude of a point source located at x_pos, y_pos :param data: :param x_pos: :param y_pos: :param psf_kernel: :return:

lenstronomy.Util.kernel_util.fwhm_kernel(kernel)[source]
Parameters

kernel

Returns

lenstronomy.Util.kernel_util.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

lenstronomy.Util.kernel_util.kernel_gaussian(kernel_numPix, deltaPix, fwhm)[source]
lenstronomy.Util.kernel_util.kernel_norm(kernel)[source]
Parameters

kernel

Returns

normalisation of the psf kernel

lenstronomy.Util.kernel_util.kernel_pixelsize_change(kernel, deltaPix_in, deltaPix_out)[source]

change the pixel size of a given kernel :param kernel: :param deltaPix_in: :param deltaPix_out: :return:

lenstronomy.Util.kernel_util.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.kernel_util.mge_kernel(kernel, order=5)[source]

azimutal Multi-Gaussian expansion of a pixelized kernel

Parameters

kernel – 2d numpy array

Returns

lenstronomy.Util.kernel_util.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

lenstronomy.Util.kernel_util.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

lenstronomy.Util.kernel_util.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 – initial kernel

  • subgrid_res – subgrid resolution required

Returns

kernel with higher resolution (larger)

lenstronomy.Util.mask_util module

lenstronomy.Util.mask_util.mask_azimuthal(x, y, center_x, center_y, r)[source]
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

lenstronomy.Util.mask_util.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

lenstronomy.Util.mask_util.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)

lenstronomy.Util.mask_util.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

lenstronomy.Util.multi_gauss_expansion module

lenstronomy.Util.multi_gauss_expansion.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: :param sigmas: :return:

lenstronomy.Util.multi_gauss_expansion.gaussian(R, sigma, amp)[source]
Parameters
  • R – radius

  • sigma – gaussian sigma

  • amp – normalization

Returns

Gaussian function

lenstronomy.Util.multi_gauss_expansion.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

lenstronomy.Util.numba_util module

lenstronomy.Util.numba_util.generated_jit(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

lenstronomy.Util.numba_util.jit(nopython=True, cache=True, parallel=False, fastmath=False, error_model='numpy', inline='never')[source]
lenstronomy.Util.numba_util.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.

lenstronomy.Util.numba_util.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

lenstronomy.Util.numba_util.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

lenstronomy.Util.param_util.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]

lenstronomy.Util.param_util.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)

lenstronomy.Util.param_util.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

lenstronomy.Util.param_util.polar2cart(r, phi, center)[source]

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

Parameters
  • coord (array of size (n,2)) – set of coordinates

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

Returns

array of same size with coords [x,y]

Raises

AttributeError, KeyError

lenstronomy.Util.param_util.shear_cartesian2polar(gamma1, gamma2)[source]
Parameters
  • gamma1 – cartesian shear component

  • gamma2 – cartesian shear component

Returns

shear angle, shear strength

lenstronomy.Util.param_util.shear_polar2cartesian(phi, gamma)[source]
Parameters
  • phi – shear angle (radian)

  • gamma – shear strength

Returns

shear components gamma1, gamma2

lenstronomy.Util.param_util.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’

lenstronomy.Util.param_util.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 lenstronomy.Util.prob_density.KDE1D(values)[source]

Bases: object

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

likelihood(x)[source]
Parameters

x – position where to evaluate the density

Returns

likelihood given the sample distribution

class lenstronomy.Util.prob_density.SkewGaussian[source]

Bases: object

class for the Skew Gaussian distribution

map_mu_sigma_skw(mu, sigma, skw)[source]

map to parameters e, w, a :param mu: mean :param sigma: standard deviation :param skw: skewness :return: e, w, a

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

probability density function see: https://en.wikipedia.org/wiki/Skew_normal_distribution :param x: input value :param e: :param w: :param a: :return:

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

function with different parameterisation :param x: :param mu: mean :param sigma: sigma :param skw: skewness :return:

lenstronomy.Util.prob_density.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 :param sample: 1-D sample :param num_sigma: integer, number of sigmas to be returned :return: median, lower_sigma, upper_sigma

lenstronomy.Util.sampling_util module

lenstronomy.Util.sampling_util.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

lenstronomy.Util.sampling_util.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

lenstronomy.Util.sampling_util.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’

lenstronomy.Util.sampling_util.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.sampling_util.scale_limits(lowers, uppers, scale)[source]
lenstronomy.Util.sampling_util.uniform2unit(theta, vmin, vmax)[source]

mapping from uniform distribution on unit hypercube to uniform distribution on parameter space

lenstronomy.Util.sampling_util.unit2uniform(x, vmin, vmax)[source]

mapping from uniform distribution on parameter space to uniform distribution on unit hypercube

lenstronomy.Util.simulation_util module

lenstronomy.Util.simulation_util.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

lenstronomy.Util.simulation_util.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

lenstronomy.Util.util.approx_theta_E(ximg, yimg)[source]
lenstronomy.Util.util.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

lenstronomy.Util.util.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

lenstronomy.Util.util.averaging(grid, numGrid, numPix)[source]

resize 2d pixel grid with numGrid to numPix and averages over the pixels :param grid: higher resolution pixel grid :param numGrid: number of pixels per axis in the high resolution input image :param numPix: lower number of pixels per axis in the output image (numGrid/numPix is integer number) :return:

lenstronomy.Util.util.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

lenstronomy.Util.util.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 lenght of output boolean list

  • k – None, int, or list of ints

Returns

bool list

lenstronomy.Util.util.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

lenstronomy.Util.util.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

lenstronomy.Util.util.fwhm2sigma(fwhm)[source]
Parameters

fwhm – full-widt-half-max value

Returns

gaussian sigma (sqrt(var))

lenstronomy.Util.util.get_axes(x, y)[source]

computes the axis x and y of a given 2d grid :param x: :param y: :return:

lenstronomy.Util.util.get_distance(x_mins, y_mins, x_true, y_true)[source]
Parameters
  • x_mins

  • y_mins

  • x_true

  • y_true

Returns

lenstronomy.Util.util.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

lenstronomy.Util.util.hyper2F2_array(a, b, c, d, x)[source]
Parameters
  • a

  • b

  • c

  • d

  • x

Returns

lenstronomy.Util.util.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

lenstronomy.Util.util.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

lenstronomy.Util.util.make_grid_transformed(numPix, Mpix2Angle)[source]

returns grid with linear transformation (deltaPix and rotation) :param numPix: number of Pixels :param Mpix2Angle: 2-by-2 matrix to mat a pixel to a coordinate :return: coordinate grid

lenstronomy.Util.util.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

lenstronomy.Util.util.make_subgrid(ra_coord, dec_coord, subgrid_res=2)[source]

return a grid with subgrid resolution :param ra_coord: :param dec_coord: :param subgrid_res: :return:

lenstronomy.Util.util.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 :param ra: ra coordinates :param dec: dec coordinates :param x_0: pixel value in x-axis of ra,dec = 0,0 :param y_0: pixel value in y-axis of ra,dec = 0,0 :param M: 2x2 matrix to transform angular to pixel coordinates :return: transformed coordinate systems of input ra and dec

lenstronomy.Util.util.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.

lenstronomy.Util.util.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) :param x_1: :param y_1: :param x_2: :param y_2: :return:

lenstronomy.Util.util.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

lenstronomy.Util.util.points_on_circle(radius, num_points, connect_ends=True)[source]

returns a set of uniform points around a circle :param radius: radius of the circle :param num_points: number of points on the circle :param connect_ends: boolean, if True, start and end point are the same :return: x-coords, y-coords of points on the circle

lenstronomy.Util.util.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

lenstronomy.Util.util.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

lenstronomy.Util.util.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

lenstronomy.Util.util.sigma2fwhm(sigma)[source]
Parameters

sigma

Returns

lenstronomy.Util.util.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

Module contents