signature:
def luminosity_within_ellipse_in_units ( self , major_axis : dim . Length , unit_luminosity = 'eps' , kpc_per_arcsec = None , exposure_time = None ) :
    """Compute the total luminosity of the galaxy ' s light profiles , within an ellipse of specified major axis . This
 is performed via integration of each light profile and is centred , oriented and aligned with each light
 model ' s individual geometry .
 See * light _ profiles . luminosity _ within _ ellipse * for details of how this is performed .
 Parameters
 major _ axis : float
 The major - axis radius of the ellipse .
 unit _ luminosity : str
 The units the luminosity is returned in ( eps | counts ) .
 exposure _ time : float
 The exposure time of the observation , which converts luminosity from electrons per second units to counts ."""

implementation:
if self . has_light_profile :
    return sum ( map ( lambda p : p . luminosity_within_ellipse_in_units ( major_axis = major_axis , unit_luminosity = unit_luminosity , kpc_per_arcsec = kpc_per_arcsec , exposure_time = exposure_time ) , self . light_profiles ) )
else :
    return None


signature:
def convergence_from_grid ( self , grid ) :
    """Compute the summed convergence of the galaxy ' s mass profiles using a grid of Cartesian ( y , x ) coordinates .
 If the galaxy has no mass profiles , a grid of zeros is returned .
 See * profiles . mass _ profiles * module for details of how this is performed .
 Parameters
 grid : ndarray
 The ( y , x ) coordinates in the original reference frame of the grid ."""

implementation:
if self . has_mass_profile :
    return sum ( map ( lambda p : p . convergence_from_grid ( grid ) , self . mass_profiles ) )
else :
    return np . zeros ( ( grid . shape [ 0 ] , ) )


signature:
def deflections_from_grid ( self , grid ) :
    """Compute the summed ( y , x ) deflection angles of the galaxy ' s mass profiles using a grid of Cartesian ( y , x ) coordinates .
 If the galaxy has no mass profiles , two grid of zeros are returned .
 See * profiles . mass _ profiles * module for details of how this is performed .
 Parameters
 grid : ndarray
 The ( y , x ) coordinates in the original reference frame of the grid ."""

implementation:
if self . has_mass_profile :
    return sum ( map ( lambda p : p . deflections_from_grid ( grid ) , self . mass_profiles ) )
else :
    return np . full ( ( grid . shape [ 0 ] , 2 ) , 0.0 )


signature:
def mass_within_circle_in_units ( self , radius , unit_mass = 'angular' , kpc_per_arcsec = None , critical_surface_density = None ) :
    """Compute the total angular mass of the galaxy ' s mass profiles within a circle of specified radius .
 See * profiles . mass _ profiles . mass _ within _ circle * for details of how this is performed .
 Parameters
 radius : float
 The radius of the circle to compute the dimensionless mass within .
 unit _ mass : str
 The units the mass is returned in ( angular | solMass ) .
 critical _ surface _ density : float
 The critical surface mass density of the strong lens configuration , which converts mass from angulalr units to physical units ( e . g . solar masses ) ."""

implementation:
if self . has_mass_profile :
    return sum ( map ( lambda p : p . mass_within_circle_in_units ( radius = radius , unit_mass = unit_mass , kpc_per_arcsec = kpc_per_arcsec , critical_surface_density = critical_surface_density ) , self . mass_profiles ) )
else :
    return None


signature:
def mass_within_ellipse_in_units ( self , major_axis , unit_mass = 'angular' , kpc_per_arcsec = None , critical_surface_density = None ) :
    """Compute the total angular mass of the galaxy ' s mass profiles within an ellipse of specified major _ axis .
 See * profiles . mass _ profiles . angualr _ mass _ within _ ellipse * for details of how this is performed .
 Parameters
 major _ axis : float
 The major - axis radius of the ellipse .
 units _ luminosity : str
 The units the luminosity is returned in ( eps | counts ) .
 exposure _ time : float
 The exposure time of the observation , which converts luminosity from electrons per second units to counts ."""

implementation:
if self . has_mass_profile :
    return sum ( map ( lambda p : p . mass_within_ellipse_in_units ( major_axis = major_axis , unit_mass = unit_mass , kpc_per_arcsec = kpc_per_arcsec , critical_surface_density = critical_surface_density ) , self . mass_profiles ) )
else :
    return None


signature:
def einstein_radius_in_units ( self , unit_length = 'arcsec' , kpc_per_arcsec = None ) :
    """The Einstein Radius of this galaxy , which is the sum of Einstein Radii of its mass profiles .
 If the galaxy is composed of multiple ellipitcal profiles with different axis - ratios , this Einstein Radius may be inaccurate . This is because the differently oriented ellipses of each mass profile"""

implementation:
if self . has_mass_profile :
    return sum ( map ( lambda p : p . einstein_radius_in_units ( unit_length = unit_length , kpc_per_arcsec = kpc_per_arcsec ) , self . mass_profiles ) )
else :
    return None


signature:
def einstein_mass_in_units ( self , unit_mass = 'angular' , critical_surface_density = None ) :
    """The Einstein Mass of this galaxy , which is the sum of Einstein Radii of its mass profiles .
 If the galaxy is composed of multiple ellipitcal profiles with different axis - ratios , this Einstein Mass may be inaccurate . This is because the differently oriented ellipses of each mass profile"""

implementation:
if self . has_mass_profile :
    return sum ( map ( lambda p : p . einstein_mass_in_units ( unit_mass = unit_mass , critical_surface_density = critical_surface_density ) , self . mass_profiles ) )
else :
    return None


signature:
def contributions_from_model_image_and_galaxy_image ( self , model_image , galaxy_image , minimum_value = 0.0 ) :
    """Compute the contribution map of a galaxy , which represents the fraction of flux in each pixel that the galaxy is attributed to contain , scaled to the * contribution _ factor * hyper - parameter .
 This is computed by dividing that galaxy ' s flux by the total flux in that pixel , and then scaling by the maximum flux such that the contribution map ranges between 0 and 1.
 Parameters
 model _ image : ndarray
 The best - fit model image to the observed image from a previous analysis phase . This provides the total light attributed to each image pixel by the model .
 galaxy _ image : ndarray
 A model image of the galaxy ( from light profiles or an inversion ) from a previous analysis phase .
 minimum _ value : float
 The minimum contribution value a pixel must contain to not be rounded to 0."""

implementation:
contributions = np . divide ( galaxy_image , np . add ( model_image , self . contribution_factor ) )
contributions = np . divide ( contributions , np . max ( contributions ) )
contributions [ contributions < minimum_value ] = 0.0
return contributions


signature:
def hyper_noise_from_contributions ( self , noise_map , contributions ) :
    """Compute a scaled galaxy hyper noise - map from a baseline noise - map .
 This uses the galaxy contribution map and the * noise _ factor * and * noise _ power * hyper - parameters .
 Parameters
 noise _ map : ndarray
 The observed noise - map ( before scaling ) .
 contributions : ndarray
 The galaxy contribution map ."""

implementation: return self . noise_factor * ( noise_map * contributions ) ** self . noise_power


signature:
def frame_at_coordinates_jit ( coordinates , mask , mask_index_array , psf ) :
    """Compute the frame ( indexes of pixels light is blurred into ) and psf _ frame ( psf kernel values of those pixels ) for a given coordinate in a masks and its PSF .
 Parameters
 coordinates : ( int , int )
 The coordinates of mask _ index _ array on which the frame should be centred
 psf _ shape : ( int , int )
 The shape of the psf for which this frame will be used"""

implementation:
psf_shape = psf . shape
psf_max_size = psf_shape [ 0 ] * psf_shape [ 1 ]
half_x = int ( psf_shape [ 0 ] / 2 )
half_y = int ( psf_shape [ 1 ] / 2 )
frame = - 1 * np . ones ( ( psf_max_size ) )
psf_frame = - 1.0 * np . ones ( ( psf_max_size ) )
count = 0
for i in range ( psf_shape [ 0 ] ) :
    for j in range ( psf_shape [ 1 ] ) :
        x = coordinates [ 0 ] - half_x + i
        y = coordinates [ 1 ] - half_y + j
        if 0 <= x < mask_index_array . shape [ 0 ] and 0 <= y < mask_index_array . shape [ 1 ] :
            value = mask_index_array [ x , y ]
            if value >= 0 and not mask [ x , y ] :
                frame [ count ] = value
                psf_frame [ count ] = psf [ i , j ]
                count += 1
return frame , psf_frame


signature:
def convolve_image ( self , image_array , blurring_array ) :
    """For a given 1D regular array and blurring array , convolve the two using this convolver .
 Parameters
 image _ array : ndarray
 1D array of the regular values which are to be blurred with the convolver ' s PSF .
 blurring _ array : ndarray
 1D array of the blurring regular values which blur into the regular - array after PSF convolution ."""

implementation: return self . convolve_jit ( image_array , self . image_frame_indexes , self . image_frame_psfs , self . image_frame_lengths , blurring_array , self . blurring_frame_indexes , self . blurring_frame_psfs , self . blurring_frame_lengths )


signature:
def intensities_of_galaxies_from_grid ( grid , galaxies ) :
    """Compute the intensities of a list of galaxies from an input grid , by summing the individual intensities of each galaxy ' s light profile .
 If the input grid is a * grids . SubGrid * , the intensites is calculated on the sub - grid and binned - up to the original regular grid by taking the mean value of every set of sub - pixels .
 If no galaxies are entered into the function , an array of all zeros is returned .
 Parameters
 grid : RegularGrid
 The grid ( regular or sub ) of ( y , x ) arc - second coordinates at the centre of every unmasked pixel which the intensities are calculated on .
 galaxies : [ galaxy . Galaxy ]
 The galaxies whose light profiles are used to compute the surface densities ."""

implementation:
if galaxies :
    return sum ( map ( lambda g : g . intensities_from_grid ( grid ) , galaxies ) )
else :
    return np . full ( ( grid . shape [ 0 ] ) , 0.0 )


signature:
def convergence_of_galaxies_from_grid ( grid , galaxies ) :
    """Compute the convergence of a list of galaxies from an input grid , by summing the individual convergence of each galaxy ' s mass profile .
 If the input grid is a * grids . SubGrid * , the convergence is calculated on the sub - grid and binned - up to the original regular grid by taking the mean value of every set of sub - pixels .
 If no galaxies are entered into the function , an array of all zeros is returned .
 Parameters
 grid : RegularGrid
 The grid ( regular or sub ) of ( y , x ) arc - second coordinates at the centre of every unmasked pixel which the convergence is calculated on .
 galaxies : [ galaxy . Galaxy ]
 The galaxies whose mass profiles are used to compute the convergence ."""

implementation:
if galaxies :
    return sum ( map ( lambda g : g . convergence_from_grid ( grid ) , galaxies ) )
else :
    return np . full ( ( grid . shape [ 0 ] ) , 0.0 )


signature:
def potential_of_galaxies_from_grid ( grid , galaxies ) :
    """Compute the potential of a list of galaxies from an input grid , by summing the individual potential of each galaxy ' s mass profile .
 If the input grid is a * grids . SubGrid * , the surface - density is calculated on the sub - grid and binned - up to the original regular grid by taking the mean value of every set of sub - pixels .
 If no galaxies are entered into the function , an array of all zeros is returned .
 Parameters
 grid : RegularGrid
 The grid ( regular or sub ) of ( y , x ) arc - second coordinates at the centre of every unmasked pixel which the potential is calculated on .
 galaxies : [ galaxy . Galaxy ]
 The galaxies whose mass profiles are used to compute the surface densities ."""

implementation:
if galaxies :
    return sum ( map ( lambda g : g . potential_from_grid ( grid ) , galaxies ) )
else :
    return np . full ( ( grid . shape [ 0 ] ) , 0.0 )


signature:
def deflections_of_galaxies_from_grid ( grid , galaxies ) :
    """Compute the deflections of a list of galaxies from an input grid , by summing the individual deflections of each galaxy ' s mass profile .
 If the input grid is a * grids . SubGrid * , the potential is calculated on the sub - grid and binned - up to the original regular grid by taking the mean value of every set of sub - pixels .
 If no galaxies are entered into the function , an array of all zeros is returned .
 Parameters
 grid : RegularGrid
 The grid ( regular or sub ) of ( y , x ) arc - second coordinates at the centre of every unmasked pixel which the deflections is calculated on .
 galaxies : [ galaxy . Galaxy ]
 The galaxies whose mass profiles are used to compute the surface densities ."""

implementation:
if len ( galaxies ) > 0 :
    deflections = sum ( map ( lambda galaxy : galaxy . deflections_from_grid ( grid ) , galaxies ) )
else :
    deflections = np . full ( ( grid . shape [ 0 ] , 2 ) , 0.0 )
if isinstance ( grid , grids . SubGrid ) :
    return np . asarray ( [ grid . regular_data_1d_from_sub_data_1d ( deflections [ : , 0 ] ) , grid . regular_data_1d_from_sub_data_1d ( deflections [ : , 1 ] ) ] ) . T
return deflections


signature:
def deflections_of_galaxies_from_sub_grid ( sub_grid , galaxies ) :
    """Compute the deflections of a list of galaxies from an input sub - grid , by summing the individual deflections of each galaxy ' s mass profile .
 The deflections are calculated on the sub - grid and binned - up to the original regular grid by taking the mean value of every set of sub - pixels .
 If no galaxies are entered into the function , an array of all zeros is returned .
 Parameters
 sub _ grid : RegularGrid
 The grid ( regular or sub ) of ( y , x ) arc - second coordinates at the centre of every unmasked pixel which the deflections is calculated on .
 galaxies : [ galaxy . Galaxy ]
 The galaxies whose mass profiles are used to compute the surface densities ."""

implementation:
if galaxies :
    return sum ( map ( lambda galaxy : galaxy . deflections_from_grid ( sub_grid ) , galaxies ) )
else :
    return np . full ( ( sub_grid . shape [ 0 ] , 2 ) , 0.0 )


signature:
def blurred_image_1d_from_1d_unblurred_and_blurring_images ( unblurred_image_1d , blurring_image_1d , convolver ) :
    """For a 1D masked image and 1D blurring image ( the regions outside the mask whose light blurs into the mask after PSF convolution ) , use both to compute the blurred image within the mask via PSF convolution .
 The convolution uses each image ' s convolver ( * See ccd . convolution * ) .
 Parameters
 unblurred _ image _ 1d : ndarray
 The 1D masked datas which is blurred .
 blurring _ image _ 1d : ndarray
 The 1D masked blurring image which is used for blurring .
 convolver : ccd . convolution . ConvolverImage
 The image - convolver which performs the convolution in 1D ."""

implementation: return convolver . convolve_image ( image_array = unblurred_image_1d , blurring_array = blurring_image_1d )


signature:
def evidence_from_inversion_terms ( chi_squared , regularization_term , log_curvature_regularization_term , log_regularization_term , noise_normalization ) :
    """Compute the evidence of an inversion ' s fit to the datas , where the evidence includes a number of terms which quantify the complexity of an inversion ' s reconstruction ( see the * inversion * module ) :
 Likelihood = - 0.5 * [ Chi _ Squared _ Term + Regularization _ Term + Log ( Covariance _ Regularization _ Term ) -
 Log ( Regularization _ Matrix _ Term ) + Noise _ Term ]
 Parameters
 chi _ squared : float
 The chi - squared term of the inversion ' s fit to the observed datas .
 regularization _ term : float
 The regularization term of the inversion , which is the sum of the difference between reconstructed flux of every pixel multiplied by the regularization coefficient .
 log _ curvature _ regularization _ term : float
 The log of the determinant of the sum of the curvature and regularization matrices .
 log _ regularization _ term : float
 The log of the determinant o the regularization matrix .
 noise _ normalization : float
 The normalization noise _ map - term for the observed datas ' s noise - map ."""

implementation: return - 0.5 * ( chi_squared + regularization_term + log_curvature_regularization_term - log_regularization_term + noise_normalization )


signature:
def blurred_image_of_planes_from_1d_images_and_convolver ( total_planes , image_plane_image_1d_of_planes , image_plane_blurring_image_1d_of_planes , convolver , map_to_scaled_array ) :
    """For a tracer , extract the image - plane image of every plane and blur it with the PSF .
 If none of the galaxies in a plane have a light profie or pixelization ( and thus don ' t have an image ) a * None * is used .
 Parameters
 total _ planes : int
 The total number of planes that blurred images are computed for .
 image _ plane _ image _ 1d _ of _ planes : [ ndarray ]
 For every plane , the 1D image - plane image .
 image _ plane _ blurring _ image _ 1d _ of _ planes : [ ndarray ]
 For every plane , the 1D image - plane blurring image .
 convolver : hyper . ccd . convolution . ConvolverImage
 Class which performs the PSF convolution of a masked image in 1D .
 map _ to _ scaled _ array : func
 A function which maps a masked image from 1D to 2D ."""

implementation:
blurred_image_of_planes = [ ]
for plane_index in range ( total_planes ) : # If all entries are zero , there was no light profile / pixeization
    if np . count_nonzero ( image_plane_image_1d_of_planes [ plane_index ] ) > 0 :
        blurred_image_1d_of_plane = blurred_image_1d_from_1d_unblurred_and_blurring_images ( unblurred_image_1d = image_plane_image_1d_of_planes [ plane_index ] , blurring_image_1d = image_plane_blurring_image_1d_of_planes [ plane_index ] , convolver = convolver )
        blurred_image_of_plane = map_to_scaled_array ( array_1d = blurred_image_1d_of_plane )
        blurred_image_of_planes . append ( blurred_image_of_plane )
    else :
        blurred_image_of_planes . append ( None )
return blurred_image_of_planes


signature:
def unmasked_blurred_image_of_planes_from_padded_grid_stack_and_psf ( planes , padded_grid_stack , psf ) :
    """For lens data , compute the unmasked blurred image of every unmasked unblurred image of each plane . To do this , this function iterates over all planes to extract their unmasked unblurred images .
 If a galaxy in a plane has a pixelization , the unmasked image is returned as None , as as the inversion ' s model image cannot be mapped to an unmasked version .
 This relies on using the lens data ' s padded - grid , which is a grid of ( y , x ) coordinates which extends over the entire image as opposed to just the masked region .
 This returns a list , where each list index corresponds to [ plane _ index ] .
 Parameters
 planes : [ plane . Plane ]
 The list of planes the unmasked blurred images are computed using .
 padded _ grid _ stack : grids . GridStack
 A padded - grid _ stack , whose padded grid is used for PSF convolution .
 psf : ccd . PSF
 The PSF of the image used for convolution ."""

implementation:
unmasked_blurred_image_of_planes = [ ]
for plane in planes :
    if plane . has_pixelization :
        unmasked_blurred_image_of_plane = None
    else :
        unmasked_blurred_image_of_plane = padded_grid_stack . unmasked_blurred_image_from_psf_and_unmasked_image ( psf = psf , unmasked_image_1d = plane . image_plane_image_1d )
    unmasked_blurred_image_of_planes . append ( unmasked_blurred_image_of_plane )
return unmasked_blurred_image_of_planes


signature:
def unmasked_blurred_image_of_planes_and_galaxies_from_padded_grid_stack_and_psf ( planes , padded_grid_stack , psf ) :
    """For lens data , compute the unmasked blurred image of every unmasked unblurred image of every galaxy in each plane . To do this , this function iterates over all planes and then galaxies to extract their unmasked unblurred images .
 If a galaxy in a plane has a pixelization , the unmasked image of that galaxy in the plane is returned as None as as the inversion ' s model image cannot be mapped to an unmasked version .
 This relies on using the lens data ' s padded - grid , which is a grid of ( y , x ) coordinates which extends over the entire image as opposed to just the masked region .
 This returns a list of lists , where each list index corresponds to [ plane _ index ] [ galaxy _ index ] .
 Parameters
 planes : [ plane . Plane ]
 The list of planes the unmasked blurred images are computed using .
 padded _ grid _ stack : grids . GridStack
 A padded - grid _ stack , whose padded grid is used for PSF convolution .
 psf : ccd . PSF
 The PSF of the image used for convolution ."""

implementation: return [ plane . unmasked_blurred_image_of_galaxies_from_psf ( padded_grid_stack , psf ) for plane in planes ]


signature:
def contribution_maps_1d_from_hyper_images_and_galaxies ( hyper_model_image_1d , hyper_galaxy_images_1d , hyper_galaxies , hyper_minimum_values ) :
    """For a fitting hyper _ galaxy _ image , hyper _ galaxy model image , list of hyper galaxies images and model hyper galaxies , compute
 their contribution maps , which are used to compute a scaled - noise _ map map . All quantities are masked 1D arrays .
 The reason this is separate from the * contributions _ from _ fitting _ hyper _ images _ and _ hyper _ galaxies * function is that
 each hyper _ galaxy image has a list of hyper galaxies images and associated hyper galaxies ( one for each galaxy ) . Thus ,
 this function breaks down the calculation of each 1D masked contribution map and returns them in the same datas
 structure ( 2 lists with indexes [ image _ index ] [ contribution _ map _ index ] .
 Parameters
 hyper _ model _ image _ 1d : ndarray
 The best - fit model image to the datas ( e . g . from a previous analysis phase ) .
 hyper _ galaxy _ images _ 1d : [ ndarray ]
 The best - fit model image of each hyper galaxy to the datas ( e . g . from a previous analysis phase ) .
 hyper _ galaxies : [ galaxy . Galaxy ]
 The hyper galaxies which represent the model components used to scale the noise _ map , which correspond to
 individual galaxies in the image .
 hyper _ minimum _ values : [ float ]
 The minimum value of each hyper _ galaxy - image contribution map , which ensure zero ' s don ' t impact the scaled noise - map ."""

implementation:
# noinspection PyArgumentList
return list ( map ( lambda hyper_galaxy , hyper_galaxy_image_1d , hyper_minimum_value : hyper_galaxy . contributions_from_model_image_and_galaxy_image ( model_image = hyper_model_image_1d , galaxy_image = hyper_galaxy_image_1d , minimum_value = hyper_minimum_value ) , hyper_galaxies , hyper_galaxy_images_1d , hyper_minimum_values ) )


signature:
def scaled_noise_map_from_hyper_galaxies_and_contribution_maps ( contribution_maps , hyper_galaxies , noise_map ) :
    """For a contribution map and noise - map , use the model hyper galaxies to compute a scaled noise - map .
 Parameters
 contribution _ maps : ndarray
 The image ' s list of 1D masked contribution maps ( e . g . one for each hyper galaxy )
 hyper _ galaxies : [ galaxy . Galaxy ]
 The hyper galaxies which represent the model components used to scale the noise _ map , which correspond to
 individual galaxies in the image .
 noise _ map : ccd . NoiseMap or ndarray
 An array describing the RMS standard deviation error in each pixel , preferably in units of electrons per
 second ."""

implementation:
scaled_noise_maps = list ( map ( lambda hyper_galaxy , contribution_map : hyper_galaxy . hyper_noise_from_contributions ( noise_map = noise_map , contributions = contribution_map ) , hyper_galaxies , contribution_maps ) )
return noise_map + sum ( scaled_noise_maps )


signature:
def rectangular_neighbors_from_shape ( shape ) :
    """Compute the neighbors of every pixel as a list of the pixel index ' s each pixel shares a vertex with .
 The uniformity of the rectangular grid ' s geometry is used to compute this ."""

implementation:
pixels = shape [ 0 ] * shape [ 1 ]
pixel_neighbors = - 1 * np . ones ( shape = ( pixels , 4 ) )
pixel_neighbors_size = np . zeros ( pixels )
pixel_neighbors , pixel_neighbors_size = compute_corner_neighbors ( pixel_neighbors , pixel_neighbors_size , shape , pixels )
pixel_neighbors , pixel_neighbors_size = compute_top_edge_neighbors ( pixel_neighbors , pixel_neighbors_size , shape , pixels )
pixel_neighbors , pixel_neighbors_size = compute_left_edge_neighbors ( pixel_neighbors , pixel_neighbors_size , shape , pixels )
pixel_neighbors , pixel_neighbors_size = compute_right_edge_neighbors ( pixel_neighbors , pixel_neighbors_size , shape , pixels )
pixel_neighbors , pixel_neighbors_size = compute_bottom_edge_neighbors ( pixel_neighbors , pixel_neighbors_size , shape , pixels )
pixel_neighbors , pixel_neighbors_size = compute_central_neighbors ( pixel_neighbors , pixel_neighbors_size , shape , pixels )
return pixel_neighbors , pixel_neighbors_size


signature:
def voronoi_neighbors_from_pixels_and_ridge_points ( pixels , ridge_points ) :
    """Compute the neighbors of every pixel as a list of the pixel index ' s each pixel shares a vertex with .
 The ridge points of the Voronoi grid are used to derive this .
 Parameters
 ridge _ points : scipy . spatial . Voronoi . ridge _ points
 Each Voronoi - ridge ( two indexes representing a pixel mapping _ matrix ) ."""

implementation:
pixel_neighbors_size = np . zeros ( shape = ( pixels ) )
for ridge_index in range ( ridge_points . shape [ 0 ] ) :
    pair0 = ridge_points [ ridge_index , 0 ]
    pair1 = ridge_points [ ridge_index , 1 ]
    pixel_neighbors_size [ pair0 ] += 1
    pixel_neighbors_size [ pair1 ] += 1
pixel_neighbors_index = np . zeros ( shape = ( pixels ) )
pixel_neighbors = - 1 * np . ones ( shape = ( pixels , int ( np . max ( pixel_neighbors_size ) ) ) )
for ridge_index in range ( ridge_points . shape [ 0 ] ) :
    pair0 = ridge_points [ ridge_index , 0 ]
    pair1 = ridge_points [ ridge_index , 1 ]
    pixel_neighbors [ pair0 , int ( pixel_neighbors_index [ pair0 ] ) ] = pair1
    pixel_neighbors [ pair1 , int ( pixel_neighbors_index [ pair1 ] ) ] = pair0
    pixel_neighbors_index [ pair0 ] += 1
    pixel_neighbors_index [ pair1 ] += 1
return pixel_neighbors , pixel_neighbors_size


signature:
def for_data_and_tracer ( cls , lens_data , tracer , padded_tracer = None ) :
    """Fit lens data with a model tracer , automatically determining the type of fit based on the properties of the galaxies in the tracer .
 Parameters
 lens _ data : lens _ data . LensData or lens _ data . LensDataHyper
 The lens - images that is fitted .
 tracer : ray _ tracing . TracerNonStack
 The tracer , which describes the ray - tracing and strong lens configuration .
 padded _ tracer : ray _ tracing . Tracer or None
 A tracer with an identical strong lens configuration to the tracer above , but using the lens data ' s padded grid _ stack such that unmasked model - images can be computed ."""

implementation:
if tracer . has_light_profile and not tracer . has_pixelization :
    return LensProfileFit ( lens_data = lens_data , tracer = tracer , padded_tracer = padded_tracer )
elif not tracer . has_light_profile and tracer . has_pixelization :
    return LensInversionFit ( lens_data = lens_data , tracer = tracer , padded_tracer = None )
elif tracer . has_light_profile and tracer . has_pixelization :
    return LensProfileInversionFit ( lens_data = lens_data , tracer = tracer , padded_tracer = None )
else :
    raise exc . FittingException ( 'The fit routine did not call a Fit class - check the ' 'properties of the tracer' )


signature:
def cache ( func ) :
    """Caches results of a call to a grid function . If a grid that evaluates to the same byte value is passed into the same
 function of the same instance as previously then the cached result is returned .
 Parameters
 func
 Some instance method that takes a grid as its argument
 Returns
 result
 Some result , either newly calculated or recovered from the cache"""

implementation:
def wrapper ( instance : GeometryProfile , grid : np . ndarray , * args , ** kwargs ) :
    if not hasattr ( instance , "cache" ) :
        instance . cache = { }
    key = ( func . __name__ , grid . tobytes ( ) )
    if key not in instance . cache :
        instance . cache [ key ] = func ( instance , grid )
    return instance . cache [ key ]
return wrapper


signature:
def grid_to_grid_radii ( self , grid ) :
    """Convert a grid of ( y , x ) coordinates to a grid of their circular radii .
 If the coordinates have not been transformed to the profile ' s centre , this is performed automatically .
 Parameters
 grid : TransformedGrid ( ndarray )
 The ( y , x ) coordinates in the reference frame of the profile ."""

implementation: return np . sqrt ( np . add ( np . square ( grid [ : , 0 ] ) , np . square ( grid [ : , 1 ] ) ) )


signature:
def grid_to_grid_cartesian ( self , grid , radius ) :
    """Convert a grid of ( y , x ) coordinates with their specified circular radii to their original ( y , x ) Cartesian
 coordinates .
 Parameters
 grid : TransformedGrid ( ndarray )
 The ( y , x ) coordinates in the reference frame of the profile .
 radius : ndarray
 The circular radius of each coordinate from the profile center ."""

implementation:
grid_thetas = np . arctan2 ( grid [ : , 0 ] , grid [ : , 1 ] )
cos_theta , sin_theta = self . grid_angle_to_profile ( grid_thetas = grid_thetas )
return np . multiply ( radius [ : , None ] , np . vstack ( ( sin_theta , cos_theta ) ) . T )


signature:
def transform_grid_to_reference_frame ( self , grid ) :
    """Transform a grid of ( y , x ) coordinates to the reference frame of the profile , including a translation to its centre .
 Parameters
 grid : ndarray
 The ( y , x ) coordinates in the original reference frame of the grid ."""

implementation:
transformed = np . subtract ( grid , self . centre )
return transformed . view ( TransformedGrid )


signature:
def transform_grid_from_reference_frame ( self , grid ) :
    """Transform a grid of ( y , x ) coordinates from the reference frame of the profile to the original observer reference frame , including a translation from the profile ' s centre .
 Parameters
 grid : TransformedGrid ( ndarray )
 The ( y , x ) coordinates in the reference frame of the profile ."""

implementation:
transformed = np . add ( grid , self . centre )
return transformed . view ( TransformedGrid )


signature:
def cos_and_sin_from_x_axis ( self ) :
    """Determine the sin and cosine of the angle between the profile ' s ellipse and the positive x - axis , counter - clockwise ."""

implementation:
phi_radians = np . radians ( self . phi )
return np . cos ( phi_radians ) , np . sin ( phi_radians )


signature:
def grid_angle_to_profile ( self , grid_thetas ) :
    """The angle between each angle theta on the grid and the profile , in radians .
 Parameters
 grid _ thetas : ndarray
 The angle theta counter - clockwise from the positive x - axis to each coordinate in radians ."""

implementation:
theta_coordinate_to_profile = np . add ( grid_thetas , - self . phi_radians )
return np . cos ( theta_coordinate_to_profile ) , np . sin ( theta_coordinate_to_profile )


signature:
def rotate_grid_from_profile ( self , grid_elliptical ) :
    """Rotate a grid of elliptical ( y , x ) coordinates from the reference frame of the profile back to the unrotated coordinate grid reference frame ( coordinates are not shifted back to their original centre ) .
 This routine is used after computing deflection angles in the reference frame of the profile , so that the deflection angles can be re - rotated to the frame of the original coordinates before performing ray - tracing .
 Parameters
 grid _ elliptical : TransformedGrid ( ndarray )
 The ( y , x ) coordinates in the reference frame of an elliptical profile ."""

implementation:
y = np . add ( np . multiply ( grid_elliptical [ : , 1 ] , self . sin_phi ) , np . multiply ( grid_elliptical [ : , 0 ] , self . cos_phi ) )
x = np . add ( np . multiply ( grid_elliptical [ : , 1 ] , self . cos_phi ) , - np . multiply ( grid_elliptical [ : , 0 ] , self . sin_phi ) )
return np . vstack ( ( y , x ) ) . T


signature:
def grid_to_elliptical_radii ( self , grid ) :
    """Convert a grid of ( y , x ) coordinates to an elliptical radius .
 If the coordinates have not been transformed to the profile ' s geometry , this is performed automatically .
 Parameters
 grid : TransformedGrid ( ndarray )
 The ( y , x ) coordinates in the reference frame of the elliptical profile ."""

implementation: return np . sqrt ( np . add ( np . square ( grid [ : , 1 ] ) , np . square ( np . divide ( grid [ : , 0 ] , self . axis_ratio ) ) ) )


signature:
def grid_to_eccentric_radii ( self , grid ) :
    """Convert a grid of ( y , x ) coordinates to an eccentric radius , which is ( 1.0 / axis _ ratio ) * elliptical radius and used to define light profile half - light radii using circular radii .
 If the coordinates have not been transformed to the profile ' s geometry , this is performed automatically .
 Parameters
 grid : TransformedGrid ( ndarray )
 The ( y , x ) coordinates in the reference frame of the elliptical profile ."""

implementation: return np . multiply ( np . sqrt ( self . axis_ratio ) , self . grid_to_elliptical_radii ( grid ) ) . view ( np . ndarray )


signature:
def transform_grid_to_reference_frame ( self , grid ) :
    """Transform a grid of ( y , x ) coordinates to the reference frame of the profile , including a translation to its centre and a rotation to it orientation .
 Parameters
 grid : ndarray
 The ( y , x ) coordinates in the original reference frame of the grid ."""

implementation:
if self . __class__ . __name__ . startswith ( "Spherical" ) :
    return super ( ) . transform_grid_to_reference_frame ( grid )
shifted_coordinates = np . subtract ( grid , self . centre )
radius = np . sqrt ( np . sum ( shifted_coordinates ** 2.0 , 1 ) )
theta_coordinate_to_profile = np . arctan2 ( shifted_coordinates [ : , 0 ] , shifted_coordinates [ : , 1 ] ) - self . phi_radians
transformed = np . vstack ( ( radius * np . sin ( theta_coordinate_to_profile ) , radius * np . cos ( theta_coordinate_to_profile ) ) ) . T
return transformed . view ( TransformedGrid )


signature:
def transform_grid_from_reference_frame ( self , grid ) :
    """Transform a grid of ( y , x ) coordinates from the reference frame of the profile to the original observer reference frame , including a rotation to its original orientation and a translation from the profile ' s centre .
 Parameters
 grid : TransformedGrid ( ndarray )
 The ( y , x ) coordinates in the reference frame of the profile ."""

implementation:
if self . __class__ . __name__ . startswith ( "Spherical" ) :
    return super ( ) . transform_grid_from_reference_frame ( grid )
y = np . add ( np . add ( np . multiply ( grid [ : , 1 ] , self . sin_phi ) , np . multiply ( grid [ : , 0 ] , self . cos_phi ) ) , self . centre [ 0 ] )
x = np . add ( np . add ( np . multiply ( grid [ : , 1 ] , self . cos_phi ) , - np . multiply ( grid [ : , 0 ] , self . sin_phi ) ) , self . centre [ 1 ] )
return np . vstack ( ( y , x ) ) . T


signature:
def mapping_matrix_from_sub_to_pix ( sub_to_pix , pixels , regular_pixels , sub_to_regular , sub_grid_fraction ) :
    """Computes the mapping matrix , by iterating over the known mappings between the sub - grid and pixelization .
 Parameters
 sub _ to _ pix : ndarray
 The mappings between the observed regular ' s sub - pixels and pixelization ' s pixels .
 pixels : int
 The number of pixels in the pixelization .
 regular _ pixels : int
 The number of datas pixels in the observed datas and thus on the regular grid .
 sub _ to _ regular : ndarray
 The mappings between the observed regular ' s sub - pixels and observed regular ' s pixels .
 sub _ grid _ fraction : float
 The fractional area each sub - pixel takes up in an regular - pixel ."""

implementation:
mapping_matrix = np . zeros ( ( regular_pixels , pixels ) )
for sub_index in range ( sub_to_regular . shape [ 0 ] ) :
    mapping_matrix [ sub_to_regular [ sub_index ] , sub_to_pix [ sub_index ] ] += sub_grid_fraction
return mapping_matrix


signature:
def voronoi_regular_to_pix_from_grids_and_geometry ( regular_grid , regular_to_nearest_pix , pixel_centres , pixel_neighbors , pixel_neighbors_size ) :
    """Compute the mappings between a set of regular - grid pixels and pixelization pixels , using information on how regular pixels map to their closest pixelization pixel on the image - plane pix - grid and the pixelization ' s pixel centres .
 To determine the complete set of regular - pixel to pixelization pixel mappings , we must pair every regular - pixel to its nearest pixel . Using a full nearest neighbor search to do this is slow , thus the pixel neighbors ( derived via the Voronoi grid ) are used to localize each nearest neighbor search via a graph search .
 Parameters
 regular _ grid : RegularGrid
 The grid of ( y , x ) arc - second coordinates at the centre of every unmasked pixel , which has been traced to to an irregular grid via lens .
 regular _ to _ nearest _ pix : ndarray
 A 1D array that maps every regular - grid pixel to its nearest pix - grid pixel ( as determined on the unlensed 2D array ) .
 pixel _ centres : ndarray
 The ( y , x ) centre of every Voronoi pixel in arc - seconds .
 pixel _ neighbors : ndarray
 An array of length ( voronoi _ pixels ) which provides the index of all neighbors of every pixel in the Voronoi grid ( entries of - 1 correspond to no neighbor ) .
 pixel _ neighbors _ size : ndarray
 An array of length ( voronoi _ pixels ) which gives the number of neighbors of every pixel in the Voronoi grid ."""

implementation:
regular_to_pix = np . zeros ( ( regular_grid . shape [ 0 ] ) )
for regular_index in range ( regular_grid . shape [ 0 ] ) :
    nearest_pix_pixel_index = regular_to_nearest_pix [ regular_index ]
    while True :
        nearest_pix_pixel_center = pixel_centres [ nearest_pix_pixel_index ]
        sub_to_nearest_pix_distance = ( regular_grid [ regular_index , 0 ] - nearest_pix_pixel_center [ 0 ] ) ** 2 + ( regular_grid [ regular_index , 1 ] - nearest_pix_pixel_center [ 1 ] ) ** 2
        closest_separation_from_pix_neighbor = 1.0e8
        for neighbor_index in range ( pixel_neighbors_size [ nearest_pix_pixel_index ] ) :
            neighbor = pixel_neighbors [ nearest_pix_pixel_index , neighbor_index ]
            separation_from_neighbor = ( regular_grid [ regular_index , 0 ] - pixel_centres [ neighbor , 0 ] ) ** 2 + ( regular_grid [ regular_index , 1 ] - pixel_centres [ neighbor , 1 ] ) ** 2
            if separation_from_neighbor < closest_separation_from_pix_neighbor :
                closest_separation_from_pix_neighbor = separation_from_neighbor
                closest_neighbor_index = neighbor_index
        neighboring_pix_pixel_index = pixel_neighbors [ nearest_pix_pixel_index , closest_neighbor_index ]
        sub_to_neighboring_pix_distance = closest_separation_from_pix_neighbor
        if sub_to_nearest_pix_distance <= sub_to_neighboring_pix_distance :
            regular_to_pix [ regular_index ] = nearest_pix_pixel_index
            break
        else :
            nearest_pix_pixel_index = neighboring_pix_pixel_index
return regular_to_pix


signature:
def voronoi_sub_to_pix_from_grids_and_geometry ( sub_grid , regular_to_nearest_pix , sub_to_regular , pixel_centres , pixel_neighbors , pixel_neighbors_size ) :
    """Compute the mappings between a set of sub - grid pixels and pixelization pixels , using information on how the regular pixels hosting each sub - pixel map to their closest pixelization pixel on the image - plane pix - grid and the pixelization ' s pixel centres .
 To determine the complete set of sub - pixel to pixelization pixel mappings , we must pair every sub - pixel to its nearest pixel . Using a full nearest neighbor search to do this is slow , thus the pixel neighbors ( derived via the Voronoi grid ) are used to localize each nearest neighbor search by using a graph search .
 Parameters
 regular _ grid : RegularGrid
 The grid of ( y , x ) arc - second coordinates at the centre of every unmasked pixel , which has been traced to to an irregular grid via lens .
 regular _ to _ nearest _ pix : ndarray
 A 1D array that maps every regular - grid pixel to its nearest pix - grid pixel ( as determined on the unlensed 2D array ) .
 pixel _ centres : ( float , float )
 The ( y , x ) centre of every Voronoi pixel in arc - seconds .
 pixel _ neighbors : ndarray
 An array of length ( voronoi _ pixels ) which provides the index of all neighbors of every pixel in the Voronoi grid ( entries of - 1 correspond to no neighbor ) .
 pixel _ neighbors _ size : ndarray
 An array of length ( voronoi _ pixels ) which gives the number of neighbors of every pixel in the Voronoi grid ."""

implementation:
sub_to_pix = np . zeros ( ( sub_grid . shape [ 0 ] ) )
for sub_index in range ( sub_grid . shape [ 0 ] ) :
    nearest_pix_pixel_index = regular_to_nearest_pix [ sub_to_regular [ sub_index ] ]
    while True :
        nearest_pix_pixel_center = pixel_centres [ nearest_pix_pixel_index ]
        sub_to_nearest_pix_distance = ( sub_grid [ sub_index , 0 ] - nearest_pix_pixel_center [ 0 ] ) ** 2 + ( sub_grid [ sub_index , 1 ] - nearest_pix_pixel_center [ 1 ] ) ** 2
        closest_separation_from_pix_to_neighbor = 1.0e8
        for neighbor_index in range ( pixel_neighbors_size [ nearest_pix_pixel_index ] ) :
            neighbor = pixel_neighbors [ nearest_pix_pixel_index , neighbor_index ]
            separation_from_neighbor = ( sub_grid [ sub_index , 0 ] - pixel_centres [ neighbor , 0 ] ) ** 2 + ( sub_grid [ sub_index , 1 ] - pixel_centres [ neighbor , 1 ] ) ** 2
            if separation_from_neighbor < closest_separation_from_pix_to_neighbor :
                closest_separation_from_pix_to_neighbor = separation_from_neighbor
                closest_neighbor_index = neighbor_index
        neighboring_pix_pixel_index = pixel_neighbors [ nearest_pix_pixel_index , closest_neighbor_index ]
        sub_to_neighboring_pix_distance = closest_separation_from_pix_to_neighbor
        if sub_to_nearest_pix_distance <= sub_to_neighboring_pix_distance :
            sub_to_pix [ sub_index ] = nearest_pix_pixel_index
            break
        else :
            nearest_pix_pixel_index = neighboring_pix_pixel_index
return sub_to_pix


signature:
def luminosity_within_circle_in_units ( self , radius : dim . Length , unit_luminosity = 'eps' , kpc_per_arcsec = None , exposure_time = None ) :
    """Integrate the light profile to compute the total luminosity within a circle of specified radius . This is centred on the light profile ' s centre .
 The following units for mass can be specified and output :
 - Electrons per second ( default ) - ' eps ' .
 - Counts - ' counts ' ( multiplies the luminosity in electrons per second by the exposure time ) .
 Parameters
 radius : float
 The radius of the circle to compute the dimensionless mass within .
 unit _ luminosity : str
 The units the luminosity is returned in ( eps | counts ) .
 exposure _ time : float or None
 The exposure time of the observation , which converts luminosity from electrons per second units to counts ."""

implementation:
if not isinstance ( radius , dim . Length ) :
    radius = dim . Length ( value = radius , unit_length = 'arcsec' )
profile = self . new_profile_with_units_converted ( unit_length = radius . unit_length , unit_luminosity = unit_luminosity , kpc_per_arcsec = kpc_per_arcsec , exposure_time = exposure_time )
luminosity = quad ( profile . luminosity_integral , a = 0.0 , b = radius , args = ( 1.0 , ) ) [ 0 ]
return dim . Luminosity ( luminosity , unit_luminosity )


signature:
def luminosity_within_ellipse_in_units ( self , major_axis , unit_luminosity = 'eps' , kpc_per_arcsec = None , exposure_time = None ) :
    """Integrate the light profiles to compute the total luminosity within an ellipse of specified major axis . This is centred on the light profile ' s centre .
 The following units for mass can be specified and output :
 - Electrons per second ( default ) - ' eps ' .
 - Counts - ' counts ' ( multiplies the luminosity in electrons per second by the exposure time ) .
 Parameters
 major _ axis : float
 The major - axis radius of the ellipse .
 unit _ luminosity : str
 The units the luminosity is returned in ( eps | counts ) .
 exposure _ time : float or None
 The exposure time of the observation , which converts luminosity from electrons per second units to counts ."""

implementation:
if not isinstance ( major_axis , dim . Length ) :
    major_axis = dim . Length ( major_axis , 'arcsec' )
profile = self . new_profile_with_units_converted ( unit_length = major_axis . unit_length , unit_luminosity = unit_luminosity , kpc_per_arcsec = kpc_per_arcsec , exposure_time = exposure_time )
luminosity = quad ( profile . luminosity_integral , a = 0.0 , b = major_axis , args = ( self . axis_ratio , ) ) [ 0 ]
return dim . Luminosity ( luminosity , unit_luminosity )


signature:
def luminosity_integral ( self , x , axis_ratio ) :
    """Routine to integrate the luminosity of an elliptical light profile .
 The axis ratio is set to 1.0 for computing the luminosity within a circle"""

implementation:
r = x * axis_ratio
return 2 * np . pi * r * self . intensities_from_grid_radii ( x )


signature:
def intensities_from_grid_radii ( self , grid_radii ) :
    """Calculate the intensity of the Gaussian light profile on a grid of radial coordinates .
 Parameters
 grid _ radii : float
 The radial distance from the centre of the profile . for each coordinate on the grid ."""

implementation: return np . multiply ( np . divide ( self . intensity , self . sigma * np . sqrt ( 2.0 * np . pi ) ) , np . exp ( - 0.5 * np . square ( np . divide ( grid_radii , self . sigma ) ) ) )


signature:
def intensities_from_grid_radii ( self , grid_radii ) :
    """Calculate the intensity of the Sersic light profile on a grid of radial coordinates .
 Parameters
 grid _ radii : float
 The radial distance from the centre of the profile . for each coordinate on the grid ."""

implementation:
np . seterr ( all = 'ignore' )
return np . multiply ( self . intensity , np . exp ( np . multiply ( - self . sersic_constant , np . add ( np . power ( np . divide ( grid_radii , self . effective_radius ) , 1. / self . sersic_index ) , - 1 ) ) ) )


signature:
def intensity_prime ( self ) :
    """Overall intensity normalisation in the rescaled Core - Sersic light profiles ( electrons per second )"""

implementation: return self . intensity_break * ( 2.0 ** ( - self . gamma / self . alpha ) ) * np . exp ( self . sersic_constant * ( ( ( 2.0 ** ( 1.0 / self . alpha ) ) * self . radius_break ) / self . effective_radius ) ** ( 1.0 / self . sersic_index ) )


signature:
def intensities_from_grid_radii ( self , grid_radii ) :
    """Calculate the intensity of the cored - Sersic light profile on a grid of radial coordinates .
 Parameters
 grid _ radii : float
 The radial distance from the centre of the profile . for each coordinate on the grid ."""

implementation: return np . multiply ( np . multiply ( self . intensity_prime , np . power ( np . add ( 1 , np . power ( np . divide ( self . radius_break , grid_radii ) , self . alpha ) ) , ( self . gamma / self . alpha ) ) ) , np . exp ( np . multiply ( - self . sersic_constant , ( np . power ( np . divide ( np . add ( np . power ( grid_radii , self . alpha ) , ( self . radius_break ** self . alpha ) ) , ( self . effective_radius ** self . alpha ) ) , ( 1.0 / ( self . alpha * self . sersic_index ) ) ) ) ) ) )


signature:
def luminosities_of_galaxies_within_circles_in_units ( self , radius : dim . Length , unit_luminosity = 'eps' , exposure_time = None ) :
    """Compute the total luminosity of all galaxies in this plane within a circle of specified radius .
 See * galaxy . light _ within _ circle * and * light _ profiles . light _ within _ circle * for details of how this is performed .
 Parameters
 radius : float
 The radius of the circle to compute the dimensionless mass within .
 units _ luminosity : str
 The units the luminosity is returned in ( eps | counts ) .
 exposure _ time : float
 The exposure time of the observation , which converts luminosity from electrons per second units to counts ."""

implementation: return list ( map ( lambda galaxy : galaxy . luminosity_within_circle_in_units ( radius = radius , unit_luminosity = unit_luminosity , kpc_per_arcsec = self . kpc_per_arcsec , exposure_time = exposure_time ) , self . galaxies ) )


signature:
def luminosities_of_galaxies_within_ellipses_in_units ( self , major_axis : dim . Length , unit_luminosity = 'eps' , exposure_time = None ) :
    """Compute the total luminosity of all galaxies in this plane within a ellipse of specified major - axis .
 The value returned by this integral is dimensionless , and a conversion factor can be specified to convert it to a physical value ( e . g . the photometric zeropoint ) .
 See * galaxy . light _ within _ ellipse * and * light _ profiles . light _ within _ ellipse * for details
 of how this is performed .
 Parameters
 major _ axis : float
 The major - axis radius of the ellipse .
 units _ luminosity : str
 The units the luminosity is returned in ( eps | counts ) .
 exposure _ time : float
 The exposure time of the observation , which converts luminosity from electrons per second units to counts ."""

implementation: return list ( map ( lambda galaxy : galaxy . luminosity_within_ellipse_in_units ( major_axis = major_axis , unit_luminosity = unit_luminosity , kpc_per_arcsec = self . kpc_per_arcsec , exposure_time = exposure_time ) , self . galaxies ) )


signature:
def masses_of_galaxies_within_circles_in_units ( self , radius : dim . Length , unit_mass = 'angular' , critical_surface_density = None ) :
    """Compute the total mass of all galaxies in this plane within a circle of specified radius .
 See * galaxy . angular _ mass _ within _ circle * and * mass _ profiles . angular _ mass _ within _ circle * for details
 of how this is performed .
 Parameters
 radius : float
 The radius of the circle to compute the dimensionless mass within .
 units _ mass : str
 The units the mass is returned in ( angular | solMass ) .
 critical _ surface _ density : float
 The critical surface mass density of the strong lens configuration , which converts mass from angulalr units to physical units ( e . g . solar masses ) ."""

implementation: return list ( map ( lambda galaxy : galaxy . mass_within_circle_in_units ( radius = radius , unit_mass = unit_mass , kpc_per_arcsec = self . kpc_per_arcsec , critical_surface_density = critical_surface_density ) , self . galaxies ) )


signature:
def masses_of_galaxies_within_ellipses_in_units ( self , major_axis : dim . Length , unit_mass = 'angular' , critical_surface_density = None ) :
    """Compute the total mass of all galaxies in this plane within a ellipse of specified major - axis .
 See * galaxy . angular _ mass _ within _ ellipse * and * mass _ profiles . angular _ mass _ within _ ellipse * for details of how this is performed .
 Parameters
 major _ axis : float
 The major - axis radius of the ellipse .
 units _ luminosity : str
 The units the luminosity is returned in ( eps | counts ) .
 exposure _ time : float
 The exposure time of the observation , which converts luminosity from electrons per second units to counts ."""

implementation: return list ( map ( lambda galaxy : galaxy . mass_within_ellipse_in_units ( major_axis = major_axis , unit_mass = unit_mass , kpc_per_arcsec = self . kpc_per_arcsec , critical_surface_density = critical_surface_density ) , self . galaxies ) )


signature:
def trace_grid_stack_to_next_plane ( self ) :
    """Trace this plane ' s grid _ stacks to the next plane , using its deflection angles ."""

implementation:
def minus ( grid , deflections ) :
    return grid - deflections
return self . grid_stack . map_function ( minus , self . deflection_stack )


signature:
def yticks ( self ) :
    """Compute the yticks labels of this grid _ stack , used for plotting the y - axis ticks when visualizing an image"""

implementation: return np . linspace ( np . amin ( self . grid_stack . regular [ : , 0 ] ) , np . amax ( self . grid_stack . regular [ : , 0 ] ) , 4 )


signature:
def xticks ( self ) :
    """Compute the xticks labels of this grid _ stack , used for plotting the x - axis ticks when visualizing an image"""

implementation: return np . linspace ( np . amin ( self . grid_stack . regular [ : , 1 ] ) , np . amax ( self . grid_stack . regular [ : , 1 ] ) , 4 )


signature:
def unmasked_blurred_image_of_galaxies_from_psf ( self , padded_grid_stack , psf ) :
    """This is a utility function for the function above , which performs the iteration over each plane ' s galaxies and computes each galaxy ' s unmasked blurred image .
 Parameters
 padded _ grid _ stack
 psf : ccd . PSF
 The PSF of the image used for convolution ."""

implementation: return [ padded_grid_stack . unmasked_blurred_image_from_psf_and_unmasked_image ( psf , image ) if not galaxy . has_pixelization else None for galaxy , image in zip ( self . galaxies , self . image_plane_image_1d_of_galaxies ) ]


signature:
def trace_to_next_plane ( self ) :
    """Trace the positions to the next plane ."""

implementation: return list ( map ( lambda positions , deflections : np . subtract ( positions , deflections ) , self . positions , self . deflections ) )


signature:
def grid_arcsec_to_grid_pixels ( self , grid_arcsec ) :
    """Convert a grid of ( y , x ) arc second coordinates to a grid of ( y , x ) pixel values . Pixel coordinates are returned as floats such that they include the decimal offset from each pixel ' s top - left corner .
 The pixel coordinate origin is at the top left corner of the grid , such that the pixel [ 0,0 ] corresponds to highest y arc - second coordinate value and lowest x arc - second coordinate .
 The arc - second coordinate origin is defined by the class attribute origin , and coordinates are shifted to this origin before computing their 1D grid pixel indexes .
 Parameters
 grid _ arcsec : ndarray
 A grid of ( y , x ) coordinates in arc seconds ."""

implementation: return grid_util . grid_arcsec_1d_to_grid_pixels_1d ( grid_arcsec_1d = grid_arcsec , shape = self . shape , pixel_scales = self . pixel_scales , origin = self . origin )


signature:
def grid_arcsec_to_grid_pixel_centres ( self , grid_arcsec ) :
    """Convert a grid of ( y , x ) arc second coordinates to a grid of ( y , x ) pixel values . Pixel coordinates are returned as integers such that they map directly to the pixel they are contained within .
 The pixel coordinate origin is at the top left corner of the grid , such that the pixel [ 0,0 ] corresponds to higher y arc - second coordinate value and lowest x arc - second coordinate .
 The arc - second coordinate origin is defined by the class attribute origin , and coordinates are shifted to this origin before computing their 1D grid pixel indexes .
 Parameters
 grid _ arcsec : ndarray
 The grid of ( y , x ) coordinates in arc seconds ."""

implementation: return grid_util . grid_arcsec_1d_to_grid_pixel_centres_1d ( grid_arcsec_1d = grid_arcsec , shape = self . shape , pixel_scales = self . pixel_scales , origin = self . origin ) . astype ( 'int' )


signature:
def grid_arcsec_to_grid_pixel_indexes ( self , grid_arcsec ) :
    """Convert a grid of ( y , x ) arc second coordinates to a grid of ( y , x ) pixel 1D indexes . Pixel coordinates are returned as integers such that they are the pixel from the top - left of the 2D grid going rights and then downwards .
 For example :
 The pixel at the top - left , whose 2D index is [ 0,0 ] , corresponds to 1D index 0.
 The fifth pixel on the top row , whose 2D index is [ 0,5 ] , corresponds to 1D index 4.
 The first pixel on the second row , whose 2D index is [ 0,1 ] , has 1D index 10 if a row has 10 pixels .
 The arc - second coordinate origin is defined by the class attribute origin , and coordinates are shifted to this origin before computing their 1D grid pixel indexes .
 Parameters
 grid _ arcsec : ndarray
 The grid of ( y , x ) coordinates in arc seconds ."""

implementation: return grid_util . grid_arcsec_1d_to_grid_pixel_indexes_1d ( grid_arcsec_1d = grid_arcsec , shape = self . shape , pixel_scales = self . pixel_scales , origin = self . origin ) . astype ( 'int' )


signature:
def grid_pixels_to_grid_arcsec ( self , grid_pixels ) :
    """Convert a grid of ( y , x ) pixel coordinates to a grid of ( y , x ) arc second values .
 The pixel coordinate origin is at the top left corner of the grid , such that the pixel [ 0,0 ] corresponds to higher y arc - second coordinate value and lowest x arc - second coordinate .
 The arc - second coordinate origin is defined by the class attribute origin , and coordinates are shifted to this origin before computing their 1D grid pixel indexes .
 Parameters
 grid _ pixels : ndarray
 The grid of ( y , x ) coordinates in pixels ."""

implementation: return grid_util . grid_pixels_1d_to_grid_arcsec_1d ( grid_pixels_1d = grid_pixels , shape = self . shape , pixel_scales = self . pixel_scales , origin = self . origin )


signature:
def grid_1d ( self ) :
    """The arc second - grid of ( y , x ) coordinates of every pixel .
 This is defined from the top - left corner , such that the first pixel at location [ 0 , 0 ] will have a negative x value y value in arc seconds ."""

implementation: return grid_util . regular_grid_1d_from_shape_pixel_scales_and_origin ( shape = self . shape , pixel_scales = self . pixel_scales , origin = self . origin )


signature:
def grid_2d ( self ) :
    """The arc second - grid of ( y , x ) coordinates of every pixel .
 This is defined from the top - left corner , such that the first pixel at location [ 0 , 0 ] will have a negative x value y value in arc seconds ."""

implementation: return grid_util . regular_grid_2d_from_shape_pixel_scales_and_origin ( shape = self . shape , pixel_scales = self . pixel_scales , origin = self . origin )


signature:
def new_with_array ( self , array ) :
    """Parameters
 array : ndarray
 An ndarray
 Returns
 new _ array : ScaledSquarePixelArray
 A new instance of this class that shares all of this instances attributes with a new ndarray ."""

implementation:
arguments = vars ( self )
arguments . update ( { "array" : array } )
if 'centre' in arguments :
    arguments . pop ( "centre" )
return self . __class__ ( ** arguments )


signature:
def from_fits_with_pixel_scale ( cls , file_path , hdu , pixel_scale , origin = ( 0.0 , 0.0 ) ) :
    """Loads the image from a . fits file .
 Parameters
 file _ path : str
 The full path of the fits file .
 hdu : int
 The HDU number in the fits file containing the image image .
 pixel _ scale : float
 The arc - second to pixel conversion factor of each pixel ."""

implementation: return cls ( array_util . numpy_array_2d_from_fits ( file_path , hdu ) , pixel_scale , origin )


signature:
def single_value ( cls , value , shape , pixel_scale , origin = ( 0.0 , 0.0 ) ) :
    """Creates an instance of Array and fills it with a single value
 Parameters
 value : float
 The value with which the array should be filled
 shape : ( int , int )
 The shape of the array
 pixel _ scale : float
 The scale of a pixel in arc seconds
 Returns
 array : ScaledSquarePixelArray
 An array filled with a single value"""

implementation:
array = np . ones ( shape ) * value
return cls ( array , pixel_scale , origin )


signature:
def flatten ( self , order = 'C' ) :
    """Returns
 flat _ scaled _ array : ScaledSquarePixelArray
 A copy of this array flattened to 1D"""

implementation: return self . new_with_array ( super ( ScaledSquarePixelArray , self ) . flatten ( order ) )


signature:
def zoomed_scaled_array_around_mask ( self , mask , buffer = 1 ) :
    """Extract the 2D region of an array corresponding to the rectangle encompassing all unmasked values .
 This is used to extract and visualize only the region of an image that is used in an analysis .
 Parameters
 mask : mask . Mask
 The mask around which the scaled array is extracted .
 buffer : int
 The buffer of pixels around the extraction ."""

implementation: return self . new_with_array ( array = array_util . extracted_array_2d_from_array_2d_and_coordinates ( array_2d = self , y0 = mask . zoom_region [ 0 ] - buffer , y1 = mask . zoom_region [ 1 ] + buffer , x0 = mask . zoom_region [ 2 ] - buffer , x1 = mask . zoom_region [ 3 ] + buffer ) )


signature:
def resized_scaled_array_from_array ( self , new_shape , new_centre_pixels = None , new_centre_arcsec = None ) :
    """resized the array to a new shape and at a new origin .
 Parameters
 new _ shape : ( int , int )
 The new two - dimensional shape of the array ."""

implementation:
if new_centre_pixels is None and new_centre_arcsec is None :
    new_centre = ( - 1 , - 1 )
    # In Numba , the input origin must be the same image type as the origin , thus we cannot
    # pass ' None ' and instead use the tuple ( - 1 , - 1 ) .
elif new_centre_pixels is not None and new_centre_arcsec is None :
    new_centre = new_centre_pixels
elif new_centre_pixels is None and new_centre_arcsec is not None :
    new_centre = self . arc_second_coordinates_to_pixel_coordinates ( arc_second_coordinates = new_centre_arcsec )
else :
    raise exc . DataException ( 'You have supplied two centres (pixels and arc-seconds) to the resize scaled' 'array function' )
return self . new_with_array ( array = array_util . resized_array_2d_from_array_2d_and_resized_shape ( array_2d = self , resized_shape = new_shape , origin = new_centre ) )


signature:
def from_fits_with_pixel_scale ( cls , file_path , hdu , pixel_scales , origin = ( 0.0 , 0.0 ) ) :
    """Loads the image from a . fits file .
 Parameters
 file _ path : str
 The full path of the fits file .
 hdu : int
 The HDU number in the fits file containing the hyper .
 pixel _ scales : ( float , float )
 The arc - second to pixel conversion factor of each pixel ."""

implementation: return cls ( array_util . numpy_array_2d_from_fits ( file_path , hdu ) , pixel_scales , origin )


signature:
def fit_lens_data_with_sensitivity_tracers ( lens_data , tracer_normal , tracer_sensitive ) :
    """Fit lens data with a normal tracer and sensitivity tracer , to determine our sensitivity to a selection of \
 galaxy components . This factory automatically determines the type of fit based on the properties of the galaxies in the tracers .
 Parameters
 lens _ data : lens _ data . LensData or lens _ data . LensDataHyper
 The lens - images that is fitted .
 tracer _ normal : ray _ tracing . AbstractTracer
 A tracer whose galaxies have the same model components ( e . g . light profiles , mass profiles ) as the lens data that we are fitting .
 tracer _ sensitive : ray _ tracing . AbstractTracerNonStack
 A tracer whose galaxies have the same model components ( e . g . light profiles , mass profiles ) as the lens data that we are fitting , but also addition components ( e . g . mass clumps ) which we measure how sensitive we are too ."""

implementation:
if ( tracer_normal . has_light_profile and tracer_sensitive . has_light_profile ) and ( not tracer_normal . has_pixelization and not tracer_sensitive . has_pixelization ) :
    return SensitivityProfileFit ( lens_data = lens_data , tracer_normal = tracer_normal , tracer_sensitive = tracer_sensitive )
elif ( not tracer_normal . has_light_profile and not tracer_sensitive . has_light_profile ) and ( tracer_normal . has_pixelization and tracer_sensitive . has_pixelization ) :
    return SensitivityInversionFit ( lens_data = lens_data , tracer_normal = tracer_normal , tracer_sensitive = tracer_sensitive )
else :
    raise exc . FittingException ( 'The sensitivity_fit routine did not call a SensitivityFit class - check the ' 'properties of the tracers' )


signature:
def unmasked_for_shape_and_pixel_scale ( cls , shape , pixel_scale , invert = False ) :
    """Setup a mask where all pixels are unmasked .
 Parameters
 shape : ( int , int )
 The ( y , x ) shape of the mask in units of pixels .
 pixel _ scale : float
 The arc - second to pixel conversion factor of each pixel ."""

implementation:
mask = np . full ( tuple ( map ( lambda d : int ( d ) , shape ) ) , False )
if invert :
    mask = np . invert ( mask )
return cls ( array = mask , pixel_scale = pixel_scale )


signature:
def circular ( cls , shape , pixel_scale , radius_arcsec , centre = ( 0. , 0. ) , invert = False ) :
    """Setup a mask where unmasked pixels are within a circle of an input arc second radius and centre .
 Parameters
 shape : ( int , int )
 The ( y , x ) shape of the mask in units of pixels .
 pixel _ scale : float
 The arc - second to pixel conversion factor of each pixel .
 radius _ arcsec : float
 The radius ( in arc seconds ) of the circle within which pixels unmasked .
 centre : ( float , float )
 The centre of the circle used to mask pixels ."""

implementation:
mask = mask_util . mask_circular_from_shape_pixel_scale_and_radius ( shape , pixel_scale , radius_arcsec , centre )
if invert :
    mask = np . invert ( mask )
return cls ( array = mask . astype ( 'bool' ) , pixel_scale = pixel_scale )


signature:
def circular_annular ( cls , shape , pixel_scale , inner_radius_arcsec , outer_radius_arcsec , centre = ( 0. , 0. ) , invert = False ) :
    """Setup a mask where unmasked pixels are within an annulus of input inner and outer arc second radii and centre .
 Parameters
 shape : ( int , int )
 The ( y , x ) shape of the mask in units of pixels .
 pixel _ scale : float
 The arc - second to pixel conversion factor of each pixel .
 inner _ radius _ arcsec : float
 The radius ( in arc seconds ) of the inner circle outside of which pixels are unmasked .
 outer _ radius _ arcsec : float
 The radius ( in arc seconds ) of the outer circle within which pixels are unmasked .
 centre : ( float , float )
 The centre of the annulus used to mask pixels ."""

implementation:
mask = mask_util . mask_circular_annular_from_shape_pixel_scale_and_radii ( shape , pixel_scale , inner_radius_arcsec , outer_radius_arcsec , centre )
if invert :
    mask = np . invert ( mask )
return cls ( array = mask . astype ( 'bool' ) , pixel_scale = pixel_scale )


signature:
def circular_anti_annular ( cls , shape , pixel_scale , inner_radius_arcsec , outer_radius_arcsec , outer_radius_2_arcsec , centre = ( 0. , 0. ) , invert = False ) :
    """Setup a mask where unmasked pixels are outside an annulus of input inner and outer arc second radii , but within a second outer radius , and at a given centre .
 This mask there has two distinct unmasked regions ( an inner circle and outer annulus ) , with an inner annulus of masked pixels .
 Parameters
 shape : ( int , int )
 The ( y , x ) shape of the mask in units of pixels .
 pixel _ scale : float
 The arc - second to pixel conversion factor of each pixel .
 inner _ radius _ arcsec : float
 The radius ( in arc seconds ) of the inner circle inside of which pixels are unmasked .
 outer _ radius _ arcsec : float
 The radius ( in arc seconds ) of the outer circle within which pixels are masked and outside of which they are unmasked .
 outer _ radius _ 2 _ arcsec : float
 The radius ( in arc seconds ) of the second outer circle within which pixels are unmasked and outside of which they masked .
 centre : ( float , float )
 The centre of the anti - annulus used to mask pixels ."""

implementation:
mask = mask_util . mask_circular_anti_annular_from_shape_pixel_scale_and_radii ( shape , pixel_scale , inner_radius_arcsec , outer_radius_arcsec , outer_radius_2_arcsec , centre )
if invert :
    mask = np . invert ( mask )
return cls ( array = mask . astype ( 'bool' ) , pixel_scale = pixel_scale )


signature:
def elliptical ( cls , shape , pixel_scale , major_axis_radius_arcsec , axis_ratio , phi , centre = ( 0. , 0. ) , invert = False ) :
    """Setup a mask where unmasked pixels are within an ellipse of an input arc second major - axis and centre .
 Parameters
 shape : ( int , int )
 The ( y , x ) shape of the mask in units of pixels .
 pixel _ scale : float
 The arc - second to pixel conversion factor of each pixel .
 major _ axis _ radius _ arcsec : float
 The major - axis ( in arc seconds ) of the ellipse within which pixels are unmasked .
 axis _ ratio : float
 The axis - ratio of the ellipse within which pixels are unmasked .
 phi : float
 The rotation angle of the ellipse within which pixels are unmasked , ( counter - clockwise from the positive x - axis ) .
 centre : ( float , float )
 The centre of the ellipse used to mask pixels ."""

implementation:
mask = mask_util . mask_elliptical_from_shape_pixel_scale_and_radius ( shape , pixel_scale , major_axis_radius_arcsec , axis_ratio , phi , centre )
if invert :
    mask = np . invert ( mask )
return cls ( array = mask . astype ( 'bool' ) , pixel_scale = pixel_scale )


signature:
def elliptical_annular ( cls , shape , pixel_scale , inner_major_axis_radius_arcsec , inner_axis_ratio , inner_phi , outer_major_axis_radius_arcsec , outer_axis_ratio , outer_phi , centre = ( 0.0 , 0.0 ) , invert = False ) :
    """Setup a mask where unmasked pixels are within an elliptical annulus of input inner and outer arc second major - axis and centre .
 Parameters
 shape : ( int , int )
 The ( y , x ) shape of the mask in units of pixels .
 pixel _ scale : float
 The arc - second to pixel conversion factor of each pixel .
 inner _ major _ axis _ radius _ arcsec : float
 The major - axis ( in arc seconds ) of the inner ellipse within which pixels are masked .
 inner _ axis _ ratio : float
 The axis - ratio of the inner ellipse within which pixels are masked .
 inner _ phi : float
 The rotation angle of the inner ellipse within which pixels are masked , ( counter - clockwise from the positive x - axis ) .
 outer _ major _ axis _ radius _ arcsec : float
 The major - axis ( in arc seconds ) of the outer ellipse within which pixels are unmasked .
 outer _ axis _ ratio : float
 The axis - ratio of the outer ellipse within which pixels are unmasked .
 outer _ phi : float
 The rotation angle of the outer ellipse within which pixels are unmasked , ( counter - clockwise from the positive x - axis ) .
 centre : ( float , float )
 The centre of the elliptical annuli used to mask pixels ."""

implementation:
mask = mask_util . mask_elliptical_annular_from_shape_pixel_scale_and_radius ( shape , pixel_scale , inner_major_axis_radius_arcsec , inner_axis_ratio , inner_phi , outer_major_axis_radius_arcsec , outer_axis_ratio , outer_phi , centre )
if invert :
    mask = np . invert ( mask )
return cls ( array = mask . astype ( 'bool' ) , pixel_scale = pixel_scale )


signature:
def map_2d_array_to_masked_1d_array ( self , array_2d ) :
    """For a 2D array ( e . g . an image , noise _ map , etc . ) map it to a masked 1D array of valuees using this mask .
 Parameters
 array _ 2d : ndarray | None | float
 The 2D array to be mapped to a masked 1D array ."""

implementation:
if array_2d is None or isinstance ( array_2d , float ) :
    return array_2d
return mapping_util . map_2d_array_to_masked_1d_array_from_array_2d_and_mask ( self , array_2d )


signature:
def blurring_mask_for_psf_shape ( self , psf_shape ) :
    """Compute a blurring mask , which represents all masked pixels whose light will be blurred into unmasked pixels via PSF convolution ( see grid _ stack . RegularGrid . blurring _ grid _ from _ mask _ and _ psf _ shape ) .
 Parameters
 psf _ shape : ( int , int )
 The shape of the psf which defines the blurring region ( e . g . the shape of the PSF )"""

implementation:
if psf_shape [ 0 ] % 2 == 0 or psf_shape [ 1 ] % 2 == 0 :
    raise exc . MaskException ( "psf_size of exterior region must be odd" )
blurring_mask = mask_util . mask_blurring_from_mask_and_psf_shape ( self , psf_shape )
return Mask ( blurring_mask , self . pixel_scale )


signature:
def zoom_region ( self ) :
    """The zoomed rectangular region corresponding to the square encompassing all unmasked values .
 This is used to zoom in on the region of an image that is used in an analysis for visualization ."""

implementation:
# Have to convert mask to bool for invert function to work .
where = np . array ( np . where ( np . invert ( self . astype ( 'bool' ) ) ) )
y0 , x0 = np . amin ( where , axis = 1 )
y1 , x1 = np . amax ( where , axis = 1 )
return [ y0 , y1 + 1 , x0 , x1 + 1 ]


signature:
def data_vector_from_blurred_mapping_matrix_and_data ( blurred_mapping_matrix , image_1d , noise_map_1d ) :
    """Compute the hyper vector * D * from a blurred mapping matrix * f * and the 1D image * d * and 1D noise - map * \ sigma * ( see Warren & Dye 2003 ) .
 Parameters
 blurred _ mapping _ matrix : ndarray
 The matrix representing the blurred mappings between sub - grid pixels and pixelization pixels .
 image _ 1d : ndarray
 Flattened 1D array of the observed image the inversion is fitting .
 noise _ map _ 1d : ndarray
 Flattened 1D array of the noise - map used by the inversion during the fit ."""

implementation:
mapping_shape = blurred_mapping_matrix . shape
data_vector = np . zeros ( mapping_shape [ 1 ] )
for image_index in range ( mapping_shape [ 0 ] ) :
    for pix_index in range ( mapping_shape [ 1 ] ) :
        data_vector [ pix_index ] += image_1d [ image_index ] * blurred_mapping_matrix [ image_index , pix_index ] / ( noise_map_1d [ image_index ] ** 2.0 )
return data_vector


signature:
def curvature_matrix_from_blurred_mapping_matrix ( blurred_mapping_matrix , noise_map_1d ) :
    """Compute the curvature matrix * F * from a blurred mapping matrix * f * and the 1D noise - map * \ sigma * ( see Warren & Dye 2003 ) .
 Parameters
 blurred _ mapping _ matrix : ndarray
 The matrix representing the blurred mappings between sub - grid pixels and pixelization pixels .
 noise _ map _ 1d : ndarray
 Flattened 1D array of the noise - map used by the inversion during the fit ."""

implementation:
flist = np . zeros ( blurred_mapping_matrix . shape [ 0 ] )
iflist = np . zeros ( blurred_mapping_matrix . shape [ 0 ] , dtype = 'int' )
return curvature_matrix_from_blurred_mapping_matrix_jit ( blurred_mapping_matrix , noise_map_1d , flist , iflist )


signature:
def curvature_matrix_from_blurred_mapping_matrix_jit ( blurred_mapping_matrix , noise_map_1d , flist , iflist ) :
    """Compute the curvature matrix * F * from a blurred mapping matrix * f * and the 1D noise - map * \ sigma * ( see Warren & Dye 2003 ) .
 Parameters
 blurred _ mapping _ matrix : ndarray
 The matrix representing the blurred mappings between sub - grid pixels and pixelization pixels .
 noise _ map _ 1d : ndarray
 Flattened 1D array of the noise - map used by the inversion during the fit .
 flist : ndarray
 NumPy array of floats used to store mappings for efficienctly calculation .
 iflist : ndarray
 NumPy array of integers used to store mappings for efficienctly calculation ."""

implementation:
curvature_matrix = np . zeros ( ( blurred_mapping_matrix . shape [ 1 ] , blurred_mapping_matrix . shape [ 1 ] ) )
for image_index in range ( blurred_mapping_matrix . shape [ 0 ] ) :
    index = 0
    for pixel_index in range ( blurred_mapping_matrix . shape [ 1 ] ) :
        if blurred_mapping_matrix [ image_index , pixel_index ] > 0.0 :
            flist [ index ] = blurred_mapping_matrix [ image_index , pixel_index ] / noise_map_1d [ image_index ]
            iflist [ index ] = pixel_index
            index += 1
    if index > 0 :
        for i1 in range ( index ) :
            for j1 in range ( index ) :
                ix = iflist [ i1 ]
                iy = iflist [ j1 ]
                curvature_matrix [ ix , iy ] += flist [ i1 ] * flist [ j1 ]
for i in range ( blurred_mapping_matrix . shape [ 1 ] ) :
    for j in range ( blurred_mapping_matrix . shape [ 1 ] ) :
        curvature_matrix [ i , j ] = curvature_matrix [ j , i ]
return curvature_matrix


signature:
def reconstructed_data_vector_from_blurred_mapping_matrix_and_solution_vector ( blurred_mapping_matrix , solution_vector ) :
    """Compute the reconstructed hyper vector from the blurrred mapping matrix * f * and solution vector * S * .
 Parameters
 blurred _ mapping _ matrix : ndarray
 The matrix representing the blurred mappings between sub - grid pixels and pixelization pixels ."""

implementation:
reconstructed_data_vector = np . zeros ( blurred_mapping_matrix . shape [ 0 ] )
for i in range ( blurred_mapping_matrix . shape [ 0 ] ) :
    for j in range ( solution_vector . shape [ 0 ] ) :
        reconstructed_data_vector [ i ] += solution_vector [ j ] * blurred_mapping_matrix [ i , j ]
return reconstructed_data_vector


signature:
def regularization_term ( self ) :
    """Compute the regularization term of an inversion . This term represents the sum of the difference in flux between every pair of neighboring pixels . This is computed as :
 s _ T * H * s = solution _ vector . T * regularization _ matrix * solution _ vector
 The term is referred to as * G _ l * in Warren & Dye 2003 , Nightingale & Dye 2015.
 The above works include the regularization _ matrix coefficient ( lambda ) in this calculation . In PyAutoLens , this is already in the regularization matrix and thus implicitly included in the matrix multiplication ."""

implementation: return np . matmul ( self . solution_vector . T , np . matmul ( self . regularization_matrix , self . solution_vector ) )


signature:
def log_determinant_of_matrix_cholesky ( matrix ) :
    """There are two terms in the inversion ' s Bayesian likelihood function which require the log determinant of a matrix . These are ( Nightingale & Dye 2015 , Nightingale , Dye and Massey 2018 ) :
 ln [ det ( F + H ) ] = ln [ det ( curvature _ reg _ matrix ) ]
 ln [ det ( H ) ] = ln [ det ( regularization _ matrix ) ]
 The curvature _ reg _ matrix is positive - definite , which means the above log determinants can be computed efficiently ( compared to using np . det ) by using a Cholesky decomposition first and summing the log of each diagonal term .
 Parameters
 matrix : ndarray
 The positive - definite matrix the log determinant is computed for ."""

implementation:
try :
    return 2.0 * np . sum ( np . log ( np . diag ( np . linalg . cholesky ( matrix ) ) ) )
except np . linalg . LinAlgError :
    raise exc . InversionException ( )


signature:
def constant_light_profiles ( self ) :
    """Returns
 light _ profiles : [ light _ profiles . LightProfile ]
 Light profiles with set variables"""

implementation: return [ value for value in self . __dict__ . values ( ) if galaxy . is_light_profile ( value ) ]


signature:
def constant_mass_profiles ( self ) :
    """Returns
 mass _ profiles : [ mass _ profiles . MassProfile ]
 Mass profiles with set variables"""

implementation: return [ value for value in self . __dict__ . values ( ) if galaxy . is_mass_profile ( value ) ]


signature:
def prior_models ( self ) :
    """Returns
 prior _ models : [ model _ mapper . PriorModel ]
 A list of the prior models ( e . g . variable profiles ) attached to this galaxy prior"""

implementation: return [ value for _ , value in filter ( lambda t : isinstance ( t [ 1 ] , pm . PriorModel ) , self . __dict__ . items ( ) ) ]


signature:
def profile_prior_model_dict ( self ) :
    """Returns
 profile _ prior _ model _ dict : { str : PriorModel }
 A dictionary mapping _ matrix instance variable names to variable profiles ."""

implementation: return { key : value for key , value in filter ( lambda t : isinstance ( t [ 1 ] , pm . PriorModel ) and is_profile_class ( t [ 1 ] . cls ) , self . __dict__ . items ( ) ) }


signature:
def constant_profile_dict ( self ) :
    """Returns
 constant _ profile _ dict : { str : geometry _ profiles . GeometryProfile }
 A dictionary mapping _ matrix instance variable names to profiles with set variables ."""

implementation: return { key : value for key , value in self . __dict__ . items ( ) if galaxy . is_light_profile ( value ) or galaxy . is_mass_profile ( value ) }


signature:
def prior_class_dict ( self ) :
    """Returns
 prior _ class _ dict : { Prior : class }
 A dictionary mapping _ matrix priors to the class associated with their prior model ."""

implementation: return { prior : cls for prior_model in self . prior_models for prior , cls in prior_model . prior_class_dict . items ( ) }


signature:
def instance_for_arguments ( self , arguments ) :
    """Create an instance of the associated class for a set of arguments
 Parameters
 arguments : { Prior : value }
 Dictionary mapping _ matrix priors to attribute analysis _ path and value pairs
 Returns
 An instance of the class"""

implementation:
profiles = { ** { key : value . instance_for_arguments ( arguments ) for key , value in self . profile_prior_model_dict . items ( ) } , ** self . constant_profile_dict }
try :
    redshift = self . redshift . instance_for_arguments ( arguments )
except AttributeError :
    redshift = self . redshift
pixelization = self . pixelization . instance_for_arguments ( arguments ) if isinstance ( self . pixelization , pm . PriorModel ) else self . pixelization
regularization = self . regularization . instance_for_arguments ( arguments ) if isinstance ( self . regularization , pm . PriorModel ) else self . regularization
hyper_galaxy = self . hyper_galaxy . instance_for_arguments ( arguments ) if isinstance ( self . hyper_galaxy , pm . PriorModel ) else self . hyper_galaxy
return galaxy . Galaxy ( redshift = redshift , pixelization = pixelization , regularization = regularization , hyper_galaxy = hyper_galaxy , ** profiles )


signature:
def gaussian_prior_model_for_arguments ( self , arguments ) :
    """Create a new galaxy prior from a set of arguments , replacing the priors of some of this galaxy prior ' s prior
 models with new arguments .
 Parameters
 arguments : dict
 A dictionary mapping _ matrix between old priors and their replacements .
 Returns
 new _ model : GalaxyModel
 A model with some or all priors replaced ."""

implementation:
new_model = copy . deepcopy ( self )
for key , value in filter ( lambda t : isinstance ( t [ 1 ] , pm . PriorModel ) , self . __dict__ . items ( ) ) :
    setattr ( new_model , key , value . gaussian_prior_model_for_arguments ( arguments ) )
return new_model


signature:
def plot_image ( image , plot_origin = True , mask = None , extract_array_from_mask = False , zoom_around_mask = False , should_plot_border = False , positions = None , as_subplot = False , units = 'arcsec' , kpc_per_arcsec = None , figsize = ( 7 , 7 ) , aspect = 'square' , cmap = 'jet' , norm = 'linear' , norm_min = None , norm_max = None , linthresh = 0.05 , linscale = 0.01 , cb_ticksize = 10 , cb_fraction = 0.047 , cb_pad = 0.01 , cb_tick_values = None , cb_tick_labels = None , title = 'Image' , titlesize = 16 , xlabelsize = 16 , ylabelsize = 16 , xyticksize = 16 , mask_pointsize = 10 , position_pointsize = 30 , grid_pointsize = 1 , output_path = None , output_format = 'show' , output_filename = 'image' ) :
    """Plot the observed image of the ccd data .
 Set * autolens . data . array . plotters . array _ plotters * for a description of all input parameters not described below .
 Parameters
 image : ScaledSquarePixelArray
 The image of the data .
 plot _ origin : True
 If true , the origin of the data ' s coordinate system is plotted as a ' x ' .
 image _ plane _ pix _ grid : ndarray or data . array . grid _ stacks . PixGrid
 If an adaptive pixelization whose pixels are formed by tracing pixels from the data , this plots those pixels over the immage ."""

implementation:
origin = get_origin ( array = image , plot_origin = plot_origin )
array_plotters . plot_array ( array = image , origin = origin , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , should_plot_border = should_plot_border , positions = positions , as_subplot = as_subplot , units = units , kpc_per_arcsec = kpc_per_arcsec , figsize = figsize , aspect = aspect , cmap = cmap , norm = norm , norm_min = norm_min , norm_max = norm_max , linthresh = linthresh , linscale = linscale , cb_ticksize = cb_ticksize , cb_fraction = cb_fraction , cb_pad = cb_pad , cb_tick_values = cb_tick_values , cb_tick_labels = cb_tick_labels , title = title , titlesize = titlesize , xlabelsize = xlabelsize , ylabelsize = ylabelsize , xyticksize = xyticksize , mask_pointsize = mask_pointsize , position_pointsize = position_pointsize , grid_pointsize = grid_pointsize , output_path = output_path , output_format = output_format , output_filename = output_filename )


signature:
def plot_ccd_subplot ( ccd_data , plot_origin = True , mask = None , extract_array_from_mask = False , zoom_around_mask = False , should_plot_border = False , positions = None , units = 'arcsec' , kpc_per_arcsec = None , figsize = None , aspect = 'square' , cmap = 'jet' , norm = 'linear' , norm_min = None , norm_max = None , linthresh = 0.05 , linscale = 0.01 , cb_ticksize = 10 , cb_fraction = 0.047 , cb_pad = 0.01 , cb_tick_values = None , cb_tick_labels = None , titlesize = 10 , xlabelsize = 10 , ylabelsize = 10 , xyticksize = 10 , mask_pointsize = 10 , position_pointsize = 30 , grid_pointsize = 1 , output_path = None , output_filename = 'ccd_data' , output_format = 'show' ) :
    """Plot the ccd data as a sub - plot of all its quantites ( e . g . the data , noise _ map - map , PSF , Signal - to _ noise - map , etc ) .
 Set * autolens . data . array . plotters . array _ plotters * for a description of all innput parameters not described below .
 Parameters
 ccd _ data : data . CCDData
 The ccd data , which includes the observed data , noise _ map - map , PSF , signal - to - noise _ map - map , etc .
 plot _ origin : True
 If true , the origin of the data ' s coordinate system is plotted as a ' x ' .
 image _ plane _ pix _ grid : ndarray or data . array . grid _ stacks . PixGrid
 If an adaptive pixelization whose pixels are formed by tracing pixels from the data , this plots those pixels over the immage .
 ignore _ config : bool
 If * False * , the config file general . ini is used to determine whether the subpot is plotted . If * True * , the config file is ignored ."""

implementation:
rows , columns , figsize_tool = plotter_util . get_subplot_rows_columns_figsize ( number_subplots = 6 )
if figsize is None :
    figsize = figsize_tool
plt . figure ( figsize = figsize )
plt . subplot ( rows , columns , 1 )
plot_image ( ccd_data = ccd_data , plot_origin = plot_origin , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , should_plot_border = should_plot_border , positions = positions , as_subplot = True , units = units , kpc_per_arcsec = kpc_per_arcsec , figsize = figsize , aspect = aspect , cmap = cmap , norm = norm , norm_min = norm_min , norm_max = norm_max , linthresh = linthresh , linscale = linscale , cb_ticksize = cb_ticksize , cb_fraction = cb_fraction , cb_pad = cb_pad , cb_tick_values = cb_tick_values , cb_tick_labels = cb_tick_labels , titlesize = titlesize , xlabelsize = xlabelsize , ylabelsize = ylabelsize , xyticksize = xyticksize , mask_pointsize = mask_pointsize , position_pointsize = position_pointsize , grid_pointsize = grid_pointsize , output_path = output_path , output_format = output_format )
plt . subplot ( rows , columns , 2 )
plot_noise_map ( ccd_data = ccd_data , plot_origin = plot_origin , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , as_subplot = True , units = units , kpc_per_arcsec = kpc_per_arcsec , figsize = figsize , aspect = aspect , cmap = cmap , norm = norm , norm_min = norm_min , norm_max = norm_max , linthresh = linthresh , linscale = linscale , cb_ticksize = cb_ticksize , cb_fraction = cb_fraction , cb_pad = cb_pad , cb_tick_values = cb_tick_values , cb_tick_labels = cb_tick_labels , titlesize = titlesize , xlabelsize = xlabelsize , ylabelsize = ylabelsize , xyticksize = xyticksize , mask_pointsize = mask_pointsize , output_path = output_path , output_format = output_format )
plt . subplot ( rows , columns , 3 )
plot_psf ( ccd_data = ccd_data , as_subplot = True , units = units , kpc_per_arcsec = kpc_per_arcsec , figsize = figsize , aspect = aspect , cmap = cmap , norm = norm , norm_min = norm_min , norm_max = norm_max , linthresh = linthresh , linscale = linscale , cb_ticksize = cb_ticksize , cb_fraction = cb_fraction , cb_pad = cb_pad , cb_tick_values = cb_tick_values , cb_tick_labels = cb_tick_labels , titlesize = titlesize , xlabelsize = xlabelsize , ylabelsize = ylabelsize , xyticksize = xyticksize , output_path = output_path , output_format = output_format )
plt . subplot ( rows , columns , 4 )
plot_signal_to_noise_map ( ccd_data = ccd_data , plot_origin = plot_origin , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , as_subplot = True , units = units , kpc_per_arcsec = kpc_per_arcsec , figsize = figsize , aspect = aspect , cmap = cmap , norm = norm , norm_min = norm_min , norm_max = norm_max , linthresh = linthresh , linscale = linscale , cb_ticksize = cb_ticksize , cb_fraction = cb_fraction , cb_pad = cb_pad , cb_tick_values = cb_tick_values , cb_tick_labels = cb_tick_labels , titlesize = titlesize , xlabelsize = xlabelsize , ylabelsize = ylabelsize , xyticksize = xyticksize , mask_pointsize = mask_pointsize , output_path = output_path , output_format = output_format )
plt . subplot ( rows , columns , 5 )
plot_absolute_signal_to_noise_map ( ccd_data = ccd_data , plot_origin = plot_origin , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , as_subplot = True , units = units , kpc_per_arcsec = kpc_per_arcsec , figsize = figsize , aspect = aspect , cmap = cmap , norm = norm , norm_min = norm_min , norm_max = norm_max , linthresh = linthresh , linscale = linscale , cb_ticksize = cb_ticksize , cb_fraction = cb_fraction , cb_pad = cb_pad , cb_tick_values = cb_tick_values , cb_tick_labels = cb_tick_labels , titlesize = titlesize , xlabelsize = xlabelsize , ylabelsize = ylabelsize , xyticksize = xyticksize , mask_pointsize = mask_pointsize , output_path = output_path , output_format = output_format )
plt . subplot ( rows , columns , 6 )
plot_potential_chi_squared_map ( ccd_data = ccd_data , plot_origin = plot_origin , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , as_subplot = True , units = units , kpc_per_arcsec = kpc_per_arcsec , figsize = figsize , aspect = aspect , cmap = cmap , norm = norm , norm_min = norm_min , norm_max = norm_max , linthresh = linthresh , linscale = linscale , cb_ticksize = cb_ticksize , cb_fraction = cb_fraction , cb_pad = cb_pad , cb_tick_values = cb_tick_values , cb_tick_labels = cb_tick_labels , titlesize = titlesize , xlabelsize = xlabelsize , ylabelsize = ylabelsize , xyticksize = xyticksize , mask_pointsize = mask_pointsize , output_path = output_path , output_format = output_format )
plotter_util . output_subplot_array ( output_path = output_path , output_filename = output_filename , output_format = output_format )
plt . close ( )


signature:
def plot_ccd_individual ( ccd_data , plot_origin = True , mask = None , extract_array_from_mask = False , zoom_around_mask = False , positions = None , should_plot_image = False , should_plot_noise_map = False , should_plot_psf = False , should_plot_signal_to_noise_map = False , should_plot_absolute_signal_to_noise_map = False , should_plot_potential_chi_squared_map = False , units = 'arcsec' , output_path = None , output_format = 'png' ) :
    """Plot each attribute of the ccd data as individual figures one by one ( e . g . the data , noise _ map - map , PSF , Signal - to _ noise - map , etc ) .
 Set * autolens . data . array . plotters . array _ plotters * for a description of all innput parameters not described below .
 Parameters
 ccd _ data : data . CCDData
 The ccd data , which includes the observed data , noise _ map - map , PSF , signal - to - noise _ map - map , etc .
 plot _ origin : True
 If true , the origin of the data ' s coordinate system is plotted as a ' x ' ."""

implementation:
if should_plot_image :
    plot_image ( ccd_data = ccd_data , plot_origin = plot_origin , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , positions = positions , units = units , output_path = output_path , output_format = output_format )
if should_plot_noise_map :
    plot_noise_map ( ccd_data = ccd_data , plot_origin = plot_origin , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , units = units , output_path = output_path , output_format = output_format )
if should_plot_psf :
    plot_psf ( ccd_data = ccd_data , plot_origin = plot_origin , output_path = output_path , output_format = output_format )
if should_plot_signal_to_noise_map :
    plot_signal_to_noise_map ( ccd_data = ccd_data , plot_origin = plot_origin , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , units = units , output_path = output_path , output_format = output_format )
if should_plot_absolute_signal_to_noise_map :
    plot_absolute_signal_to_noise_map ( ccd_data = ccd_data , plot_origin = plot_origin , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , units = units , output_path = output_path , output_format = output_format )
if should_plot_potential_chi_squared_map :
    plot_potential_chi_squared_map ( ccd_data = ccd_data , plot_origin = plot_origin , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , units = units , output_path = output_path , output_format = output_format )


signature:
def norm_and_check ( source_tree , requested ) :
    """Normalise and check a backend path .
 Ensure that the requested backend path is specified as a relative path ,
 and resolves to a location under the given source tree .
 Return an absolute version of the requested path ."""

implementation:
if os . path . isabs ( requested ) :
    raise ValueError ( "paths must be relative" )
abs_source = os . path . abspath ( source_tree )
abs_requested = os . path . normpath ( os . path . join ( abs_source , requested ) )
# We have to use commonprefix for Python 2.7 compatibility . So we
# normalise case to avoid problems because commonprefix is a character
# based comparison : - (
norm_source = os . path . normcase ( abs_source )
norm_requested = os . path . normcase ( abs_requested )
if os . path . commonprefix ( [ norm_source , norm_requested ] ) != norm_source :
    raise ValueError ( "paths must be inside source tree" )
return abs_requested


signature:
def contained_in ( filename , directory ) :
    """Test if a file is located within the given directory ."""

implementation:
filename = os . path . normcase ( os . path . abspath ( filename ) )
directory = os . path . normcase ( os . path . abspath ( directory ) )
return os . path . commonprefix ( [ filename , directory ] ) == directory


signature:
def _build_backend ( ) :
    """Find and load the build backend"""

implementation:
# Add in - tree backend directories to the front of sys . path .
backend_path = os . environ . get ( 'PEP517_BACKEND_PATH' )
if backend_path :
    extra_pathitems = backend_path . split ( os . pathsep )
    sys . path [ : 0 ] = extra_pathitems
ep = os . environ [ 'PEP517_BUILD_BACKEND' ]
mod_path , _ , obj_path = ep . partition ( ':' )
try :
    obj = import_module ( mod_path )
except ImportError :
    raise BackendUnavailable ( traceback . format_exc ( ) )
if backend_path :
    if not any ( contained_in ( obj . __file__ , path ) for path in extra_pathitems ) :
        raise BackendInvalid ( "Backend was not loaded from backend-path" )
if obj_path :
    for path_part in obj_path . split ( '.' ) :
        obj = getattr ( obj , path_part )
return obj


signature:
def build_sdist ( sdist_directory , config_settings ) :
    """Invoke the mandatory build _ sdist hook ."""

implementation:
backend = _build_backend ( )
try :
    return backend . build_sdist ( sdist_directory , config_settings )
except getattr ( backend , 'UnsupportedOperation' , _DummyException ) :
    raise GotUnsupportedOperation ( traceback . format_exc ( ) )


signature:
def log_error ( self , e ) :
    """Print errors . Stop travis - ci from leaking api keys
 : param e : The error
 : return : None"""

implementation:
if not environ . get ( 'CI' ) :
    self . log_function ( e )
    if hasattr ( e , 'response' ) and hasattr ( e . response , 'text' ) :
        self . log_function ( e . response . text )


signature:
def _sleep ( self , seconds ) :
    """Sleep between requests , but don ' t force asynchronous code to wait
 : param seconds : The number of seconds to sleep
 : return : None"""

implementation:
for _ in range ( int ( seconds ) ) :
    if not self . force_stop :
        sleep ( 1 )


signature:
def get ( self , * args , ** kwargs ) :
    """An interface for get requests that handles errors more gracefully to
 prevent data loss"""

implementation:
try :
    req_func = self . session . get if self . session else requests . get
    req = req_func ( * args , ** kwargs )
    req . raise_for_status ( )
    self . failed_last = False
    return req
except requests . exceptions . RequestException as e :
    self . log_error ( e )
    for i in range ( 1 , self . num_retries ) :
        sleep_time = self . retry_rate * i
        self . log_function ( "Retrying in %s seconds" % sleep_time )
        self . _sleep ( sleep_time )
        try :
            req = requests . get ( * args , ** kwargs )
            req . raise_for_status ( )
            self . log_function ( "New request successful" )
            return req
        except requests . exceptions . RequestException :
            self . log_function ( "New request failed" )
    # Allows for the api to ignore one potentially bad request
    if not self . failed_last :
        self . failed_last = True
        raise ApiError ( e )
    else :
        raise FatalApiError ( e )


signature:
def node_edge ( self , node , edge , fields = None , params = None ) :
    """: param node :
 : param edge :
 : param fields :
 : param params :
 : return :"""

implementation:
if fields :
    fields = "," . join ( fields )
parameters = { "fields" : fields , "access_token" : self . key }
parameters = self . merge_params ( parameters , params )
return self . api_call ( '%s/%s' % ( node , edge ) , parameters )


signature:
def post ( self , post_id , fields = None , ** params ) :
    """: param post _ id :
 : param fields :
 : param params :
 : return :"""

implementation:
if fields :
    fields = "," . join ( fields )
parameters = { "fields" : fields , "access_token" : self . key }
parameters = self . merge_params ( parameters , params )
return self . api_call ( '%s' % post_id , parameters )