signature:
def geometry_from_grid ( self , grid , pixel_centres , pixel_neighbors , pixel_neighbors_size , buffer = 1e-8 ) :
    """Determine the geometry of the Voronoi pixelization , by alligning it with the outer - most coordinates on a grid plus a small buffer .
 Parameters
 grid : ndarray
 The ( y , x ) grid of coordinates which determine the Voronoi pixelization ' s geometry .
 pixel _ centres : ndarray
 The ( y , x ) centre of every Voronoi pixel in arc - seconds .
 origin : ( float , float )
 The arc - second origin of the Voronoi pixelization ' s coordinate system .
 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 : ndarrayy
 An array of length ( voronoi _ pixels ) which gives the number of neighbors of every pixel in the Voronoi grid ."""

implementation:
y_min = np . min ( grid [ : , 0 ] ) - buffer
y_max = np . max ( grid [ : , 0 ] ) + buffer
x_min = np . min ( grid [ : , 1 ] ) - buffer
x_max = np . max ( grid [ : , 1 ] ) + buffer
shape_arcsec = ( y_max - y_min , x_max - x_min )
origin = ( ( y_max + y_min ) / 2.0 , ( x_max + x_min ) / 2.0 )
return self . Geometry ( shape_arcsec = shape_arcsec , pixel_centres = pixel_centres , origin = origin , pixel_neighbors = pixel_neighbors , pixel_neighbors_size = pixel_neighbors_size )


signature:
def voronoi_from_pixel_centers ( pixel_centers ) :
    """Compute the Voronoi grid of the pixelization , using the pixel centers .
 Parameters
 pixel _ centers : ndarray
 The ( y , x ) centre of every Voronoi pixel ."""

implementation: return scipy . spatial . Voronoi ( np . asarray ( [ pixel_centers [ : , 1 ] , pixel_centers [ : , 0 ] ] ) . T , qhull_options = 'Qbb Qc Qx Qm' )


signature:
def neighbors_from_pixelization ( self , pixels , ridge_points ) :
    """Compute the neighbors of every Voronoi pixel as an ndarray 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: return pixelization_util . voronoi_neighbors_from_pixels_and_ridge_points ( pixels = pixels , ridge_points = np . asarray ( ridge_points ) )


signature:
def mapper_from_grid_stack_and_border ( self , grid_stack , border ) :
    """Setup a Voronoi mapper from an adaptive - magnification pixelization , as follows :
 1 ) ( before this routine is called ) , setup the ' pix ' grid as part of the grid - stack , which corresponds to a sparse set of pixels in the image - plane which are traced to form the pixel centres .
 2 ) If a border is supplied , relocate all of the grid - stack ' s regular , sub and pix grid pixels beyond the border .
 3 ) Determine the adaptive - magnification pixelization ' s pixel centres , by extracting them from the relocated pix grid .
 4 ) Use these pixelization centres to setup the Voronoi pixelization .
 5 ) Determine the neighbors of every Voronoi cell in the Voronoi pixelization .
 6 ) Setup the geometry of the pixelizatioon using the relocated sub - grid and Voronoi pixelization .
 7 ) Setup a Voronoi mapper from all of the above quantities .
 Parameters
 grid _ stack : grids . GridStack
 A collection of grid describing the observed image ' s pixel coordinates ( includes an image and sub grid ) .
 border : grids . RegularGridBorder
 The borders of the grid _ stacks ( defined by their image - plane masks ) ."""

implementation:
if border is not None :
    relocated_grids = border . relocated_grid_stack_from_grid_stack ( grid_stack )
else :
    relocated_grids = grid_stack
pixel_centres = relocated_grids . pix
pixels = pixel_centres . shape [ 0 ]
voronoi = self . voronoi_from_pixel_centers ( pixel_centres )
pixel_neighbors , pixel_neighbors_size = self . neighbors_from_pixelization ( pixels = pixels , ridge_points = voronoi . ridge_points )
geometry = self . geometry_from_grid ( grid = relocated_grids . sub , pixel_centres = pixel_centres , pixel_neighbors = pixel_neighbors , pixel_neighbors_size = pixel_neighbors_size )
return mappers . VoronoiMapper ( pixels = pixels , grid_stack = relocated_grids , border = border , voronoi = voronoi , geometry = geometry )


signature:
def plot_grid ( grid , axis_limits = None , points = None , as_subplot = False , units = 'arcsec' , kpc_per_arcsec = None , figsize = ( 12 , 8 ) , pointsize = 5 , pointcolor = 'k' , xyticksize = 16 , title = 'Grid' , titlesize = 16 , xlabelsize = 16 , ylabelsize = 16 , output_path = None , output_format = 'show' , output_filename = 'grid' ) :
    """Plot a grid of ( y , x ) Cartesian coordinates as a scatter plot of points .
 Parameters
 grid : data . array . grids . RegularGrid
 The ( y , x ) coordinates of the grid , in an array of shape ( total _ coordinates , 2 ) .
 axis _ limits : [ ]
 The axis limits of the figure on which the grid is plotted , following [ xmin , xmax , ymin , ymax ] .
 points : [ ]
 A set of points that are plotted in a different colour for emphasis ( e . g . to show the mappings between different planes ) .
 as _ subplot : bool
 Whether the grid is plotted as part of a subplot , in which case the grid figure is not opened / closed .
 units : str
 The units of the y / x axis of the plots , in arc - seconds ( ' arcsec ' ) or kiloparsecs ( ' kpc ' ) .
 kpc _ per _ arcsec : float
 The conversion factor between arc - seconds and kiloparsecs , required to plot the units in kpc .
 figsize : ( int , int )
 The size of the figure in ( rows , columns ) .
 pointsize : int
 The size of the points plotted on the grid .
 xyticksize : int
 The font size of the x and y ticks on the figure axes .
 title : str
 The text of the title .
 titlesize : int
 The size of of the title of the figure .
 xlabelsize : int
 The fontsize of the x axes label .
 ylabelsize : int
 The fontsize of the y axes label .
 output _ path : str
 The path on the hard - disk where the figure is output .
 output _ filename : str
 The filename of the figure that is output .
 output _ format : str
 The format the figue is output :
 ' show ' - display on computer screen .
 ' png ' - output to hard - disk as a png ."""

implementation:
plotter_util . setup_figure ( figsize = figsize , as_subplot = as_subplot )
grid = convert_grid_units ( grid_arcsec = grid , units = units , kpc_per_arcsec = kpc_per_arcsec )
plt . scatter ( y = np . asarray ( grid [ : , 0 ] ) , x = np . asarray ( grid [ : , 1 ] ) , s = pointsize , marker = '.' )
plotter_util . set_title ( title = title , titlesize = titlesize )
set_xy_labels ( units , kpc_per_arcsec , xlabelsize , ylabelsize , xyticksize )
set_axis_limits ( axis_limits )
plot_points ( grid , points , pointcolor )
plt . tick_params ( labelsize = xyticksize )
plotter_util . output_figure ( None , as_subplot , output_path , output_filename , output_format )
plotter_util . close_figure ( as_subplot = as_subplot )


signature:
def convert_grid_units ( grid_arcsec , units , kpc_per_arcsec ) :
    """Convert the grid from its input units ( arc - seconds ) to the input unit ( e . g . retain arc - seconds ) or convert to another set of units ( kiloparsecs ) .
 Parameters
 grid _ arcsec : ndarray or data . array . grids . RegularGrid
 The ( y , x ) coordinates of the grid in arc - seconds , in an array of shape ( total _ coordinates , 2 ) .
 units : str
 The units of the y / x axis of the plots , in arc - seconds ( ' arcsec ' ) or kiloparsecs ( ' kpc ' ) .
 kpc _ per _ arcsec : float
 The conversion factor between arc - seconds and kiloparsecs , required to plot the units in kpc ."""

implementation:
if units in 'arcsec' or kpc_per_arcsec is None :
    return grid_arcsec
elif units in 'kpc' :
    return grid_arcsec * kpc_per_arcsec


signature:
def set_xy_labels ( units , kpc_per_arcsec , xlabelsize , ylabelsize , xyticksize ) :
    """Set the x and y labels of the figure , and set the fontsize of those labels .
 The x and y labels are always the distance scales , thus the labels are either arc - seconds or kpc and depend on the units the figure is plotted in .
 Parameters
 units : str
 The units of the y / x axis of the plots , in arc - seconds ( ' arcsec ' ) or kiloparsecs ( ' kpc ' ) .
 kpc _ per _ arcsec : float
 The conversion factor between arc - seconds and kiloparsecs , required to plot the units in kpc .
 xlabelsize : int
 The fontsize of the x axes label .
 ylabelsize : int
 The fontsize of the y axes label .
 xyticksize : int
 The font size of the x and y ticks on the figure axes ."""

implementation:
if units in 'arcsec' or kpc_per_arcsec is None :
    plt . xlabel ( 'x (arcsec)' , fontsize = xlabelsize )
    plt . ylabel ( 'y (arcsec)' , fontsize = ylabelsize )
elif units in 'kpc' :
    plt . xlabel ( 'x (kpc)' , fontsize = xlabelsize )
    plt . ylabel ( 'y (kpc)' , fontsize = ylabelsize )
else :
    raise exc . PlottingException ( 'The units supplied to the plotted are not a valid string (must be pixels | ' 'arcsec | kpc)' )
plt . tick_params ( labelsize = xyticksize )


signature:
def plot_points ( grid , points , pointcolor ) :
    """Plot a subset of points in a different color , to highlight a specifc region of the grid ( e . g . how certain pixels map between different planes ) .
 Parameters
 grid : ndarray or data . array . grids . RegularGrid
 The ( y , x ) coordinates of the grid , in an array of shape ( total _ coordinates , 2 ) .
 points : [ ]
 A set of points that are plotted in a different colour for emphasis ( e . g . to show the mappings between different planes ) .
 pointcolor : str or None
 The color the points should be plotted . If None , the points are iterated through a cycle of colors ."""

implementation:
if points is not None :
    if pointcolor is None :
        point_colors = itertools . cycle ( [ "y" , "r" , "k" , "g" , "m" ] )
        for point_set in points :
            plt . scatter ( y = np . asarray ( grid [ point_set , 0 ] ) , x = np . asarray ( grid [ point_set , 1 ] ) , s = 8 , color = next ( point_colors ) )
    else :
        for point_set in points :
            plt . scatter ( y = np . asarray ( grid [ point_set , 0 ] ) , x = np . asarray ( grid [ point_set , 1 ] ) , s = 8 , color = pointcolor )


signature:
def grid_interpolate ( func ) :
    """Decorate a profile method that accepts a coordinate grid and returns a data grid .
 If an interpolator attribute is associated with the input grid then that interpolator is used to down sample the
 coordinate grid prior to calling the function and up sample the result of the function .
 If no interpolator attribute is associated with the input grid then the function is called as normal .
 Parameters
 func
 Some method that accepts a grid
 Returns
 decorated _ function
 The function with optional interpolation"""

implementation:
@ wraps ( func )
def wrapper ( profile , grid , grid_radial_minimum = None , * args , ** kwargs ) :
    if hasattr ( grid , "interpolator" ) :
        interpolator = grid . interpolator
        if grid . interpolator is not None :
            values = func ( profile , interpolator . interp_grid , grid_radial_minimum , * args , ** kwargs )
            if values . ndim == 1 :
                return interpolator . interpolated_values_from_values ( values = values )
            elif values . ndim == 2 :
                y_values = interpolator . interpolated_values_from_values ( values = values [ : , 0 ] )
                x_values = interpolator . interpolated_values_from_values ( values = values [ : , 1 ] )
                return np . asarray ( [ y_values , x_values ] ) . T
    return func ( profile , grid , grid_radial_minimum , * args , ** kwargs )
return wrapper


signature:
def unmasked_blurred_image_from_psf_and_unmasked_image ( self , psf , unmasked_image_1d ) :
    """For a padded grid - stack and psf , compute an unmasked blurred image from an unmasked unblurred image .
 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 .
 Parameters
 psf : ccd . PSF
 The PSF of the image used for convolution .
 unmasked _ image _ 1d : ndarray
 The 1D unmasked image which is blurred ."""

implementation:
blurred_image_1d = self . regular . convolve_array_1d_with_psf ( padded_array_1d = unmasked_image_1d , psf = psf )
return self . regular . scaled_array_2d_from_array_1d ( array_1d = blurred_image_1d )


signature:
def grid_stack_from_mask_sub_grid_size_and_psf_shape ( cls , mask , sub_grid_size , psf_shape ) :
    """Setup a grid - stack of grid _ stack from a mask , sub - grid size and psf - shape .
 Parameters
 mask : Mask
 The mask whose unmasked pixels ( * False * ) are used to generate the grid - stack ' s grid _ stack .
 sub _ grid _ size : int
 The size of a sub - pixel ' s sub - grid ( sub _ grid _ size x sub _ grid _ size ) .
 psf _ shape : ( int , int )
 the shape of the PSF used in the analysis , which defines the mask ' s blurring - region ."""

implementation:
regular_grid = RegularGrid . from_mask ( mask )
sub_grid = SubGrid . from_mask_and_sub_grid_size ( mask , sub_grid_size )
blurring_grid = RegularGrid . blurring_grid_from_mask_and_psf_shape ( mask , psf_shape )
return GridStack ( regular_grid , sub_grid , blurring_grid )


signature:
def from_shape_pixel_scale_and_sub_grid_size ( cls , shape , pixel_scale , sub_grid_size = 2 ) :
    """Setup a grid - stack of grid _ stack from a 2D array shape , a pixel scale and a sub - grid size .
 This grid corresponds to a fully unmasked 2D array .
 Parameters
 shape : ( int , int )
 The 2D shape of the array , where all pixels are used to generate the grid - stack ' s grid _ stack .
 pixel _ scale : float
 The size of each pixel in arc seconds .
 sub _ grid _ size : int
 The size of a sub - pixel ' s sub - grid ( sub _ grid _ size x sub _ grid _ size ) ."""

implementation:
regular_grid = RegularGrid . from_shape_and_pixel_scale ( shape = shape , pixel_scale = pixel_scale )
sub_grid = SubGrid . from_shape_pixel_scale_and_sub_grid_size ( shape = shape , pixel_scale = pixel_scale , sub_grid_size = sub_grid_size )
blurring_grid = np . array ( [ [ 0.0 , 0.0 ] ] )
return GridStack ( regular_grid , sub_grid , blurring_grid )


signature:
def padded_grid_stack_from_mask_sub_grid_size_and_psf_shape ( cls , mask , sub_grid_size , psf_shape ) :
    """Setup a grid - stack of masked grid _ stack from a mask , sub - grid size and psf - shape .
 Parameters
 mask : Mask
 The mask whose masked pixels the grid - stack are setup using .
 sub _ grid _ size : int
 The size of a sub - pixels sub - grid ( sub _ grid _ size x sub _ grid _ size ) .
 psf _ shape : ( int , int )
 The shape of the PSF used in the analysis , which defines the mask ' s blurring - region ."""

implementation:
regular_padded_grid = PaddedRegularGrid . padded_grid_from_shape_psf_shape_and_pixel_scale ( shape = mask . shape , psf_shape = psf_shape , pixel_scale = mask . pixel_scale )
sub_padded_grid = PaddedSubGrid . padded_grid_from_mask_sub_grid_size_and_psf_shape ( mask = mask , sub_grid_size = sub_grid_size , psf_shape = psf_shape )
# TODO : The blurring grid is not used when the grid mapper is called , the 0.0 0.0 stops errors inr ayT _ racing
# TODO : implement a more explicit solution
return GridStack ( regular = regular_padded_grid , sub = sub_padded_grid , blurring = np . array ( [ [ 0.0 , 0.0 ] ] ) )


signature:
def grid_stack_for_simulation ( cls , shape , pixel_scale , psf_shape , sub_grid_size = 2 ) :
    """Setup a grid - stack of grid _ stack for simulating an image of a strong lens , whereby the grid ' s use padded - grid _ stack to ensure that the PSF blurring in the simulation routine ( * ccd . PrepatoryImage . simulate * ) is not degraded due to edge effects .
 Parameters
 shape : ( int , int )
 The 2D shape of the array , where all pixels are used to generate the grid - stack ' s grid _ stack .
 pixel _ scale : float
 The size of each pixel in arc seconds .
 psf _ shape : ( int , int )
 The shape of the PSF used in the analysis , which defines how much the grid ' s must be masked to mitigate edge effects .
 sub _ grid _ size : int
 The size of a sub - pixel ' s sub - grid ( sub _ grid _ size x sub _ grid _ size ) ."""

implementation: return cls . padded_grid_stack_from_mask_sub_grid_size_and_psf_shape ( mask = msk . Mask ( array = np . full ( shape , False ) , pixel_scale = pixel_scale ) , sub_grid_size = sub_grid_size , psf_shape = psf_shape )


signature:
def new_grid_stack_with_pix_grid_added ( self , pix_grid , regular_to_nearest_pix ) :
    """Setup a grid - stack of grid _ stack using an existing grid - stack .
 The new grid - stack has the same grid _ stack ( regular , sub , blurring , etc . ) as before , but adds a pix - grid as a new attribute .
 Parameters
 pix _ grid : ndarray
 The grid of ( y , x ) arc - second coordinates of every image - plane pixelization grid used for adaptive pixelizations .
 regular _ to _ nearest _ pix : ndarray
 A 1D array that maps every regular - grid pixel to its nearest pix - grid pixel ."""

implementation:
pix = PixGrid ( arr = pix_grid , regular_to_nearest_pix = regular_to_nearest_pix )
return GridStack ( regular = self . regular , sub = self . sub , blurring = self . blurring , pix = pix )


signature:
def apply_function ( self , func ) :
    """Apply a function to all grid _ stack in the grid - stack .
 This is used by the * ray - tracing * module to easily apply tracing operations to all grid _ stack ."""

implementation:
if self . blurring is not None and self . pix is not None :
    return GridStack ( func ( self . regular ) , func ( self . sub ) , func ( self . blurring ) , func ( self . pix ) )
elif self . blurring is None and self . pix is not None :
    return GridStack ( func ( self . regular ) , func ( self . sub ) , self . blurring , func ( self . pix ) )
elif self . blurring is not None and self . pix is None :
    return GridStack ( func ( self . regular ) , func ( self . sub ) , func ( self . blurring ) , self . pix )
else :
    return GridStack ( func ( self . regular ) , func ( self . sub ) , self . blurring , self . pix )


signature:
def map_function ( self , func , * arg_lists ) :
    """Map a function to all grid _ stack in a grid - stack"""

implementation: return GridStack ( * [ func ( * args ) for args in zip ( self , * arg_lists ) ] )


signature:
def convolve_array_1d_with_psf ( self , padded_array_1d , psf ) :
    """Convolve a 1d padded array of values ( e . g . intensities before PSF blurring ) with a PSF , and then trim the convolved array to its original 2D shape .
 Parameters
 padded _ array _ 1d : ndarray
 A 1D array of values which were computed using the * PaddedRegularGrid * .
 psf : ndarray
 An array describing the PSF kernel of the image ."""

implementation:
padded_array_2d = mapping_util . map_unmasked_1d_array_to_2d_array_from_array_1d_and_shape ( array_1d = padded_array_1d , shape = self . mask . shape )
# noinspection PyUnresolvedReferences
blurred_padded_array_2d = psf . convolve ( array = padded_array_2d )
return mapping_util . map_2d_array_to_masked_1d_array_from_array_2d_and_mask ( array_2d = blurred_padded_array_2d , mask = np . full ( self . mask . shape , False ) )


signature:
def from_mask ( cls , mask ) :
    """Setup a regular - grid from a mask , wehere the center of every unmasked pixel gives the grid ' s ( y , x ) arc - second coordinates .
 Parameters
 mask : Mask
 The mask whose unmasked pixels are used to setup the regular - pixel grid ."""

implementation:
array = grid_util . regular_grid_1d_masked_from_mask_pixel_scales_and_origin ( mask = mask , pixel_scales = mask . pixel_scales )
return cls ( array , mask )


signature:
def from_shape_and_pixel_scale ( cls , shape , pixel_scale ) :
    """Setup a regular - grid from a 2D array shape and pixel scale . Here , the center of every pixel on the 2D array gives the grid ' s ( y , x ) arc - second coordinates .
 This is equivalent to using a 2D mask consisting entirely of unmasked pixels .
 Parameters
 shape : ( int , int )
 The 2D shape of the array , where all pixels are used to generate the grid - stack ' s grid _ stack .
 pixel _ scale : float
 The size of each pixel in arc seconds ."""

implementation:
mask = msk . Mask . unmasked_for_shape_and_pixel_scale ( shape = shape , pixel_scale = pixel_scale )
array = grid_util . regular_grid_1d_masked_from_mask_pixel_scales_and_origin ( mask = mask , pixel_scales = mask . pixel_scales )
return cls ( array , mask )


signature:
def blurring_grid_from_mask_and_psf_shape ( cls , mask , psf_shape ) :
    """Setup a blurring - grid from a mask , where a blurring grid consists of all pixels that are masked , but they are close enough to the unmasked pixels that a fraction of their light will be blurred into those pixels via PSF convolution . For example , if our mask is as follows :
 | x | x | x | x | x | x | x | x | x | x |
 | x | x | x | x | x | x | x | x | x | x | This is an ccd . Mask , where :
 | x | x | x | x | x | x | x | x | x | x |
 | x | x | x | x | x | x | x | x | x | x | x = True ( Pixel is masked and excluded from lens )
 | x | x | x | o | o | o | x | x | x | x | o = False ( Pixel is not masked and included in lens )
 | x | x | x | o | o | o | x | x | x | x |
 | x | x | x | o | o | o | x | x | x | x |
 | x | x | x | x | x | x | x | x | x | x |
 | x | x | x | x | x | x | x | x | x | x |
 | x | x | x | x | x | x | x | x | x | x |
 For a PSF of shape ( 3,3 ) , the following blurring mask is computed ( noting that only pixels that are direct neighbors of the unmasked pixels above will blur light into an unmasked pixel ) :
 | x | x | x | x | x | x | x | x | x | This is an example regular . Mask , where :
 | x | x | x | x | x | x | x | x | x |
 | x | x | o | o | o | o | o | x | x | x = True ( Pixel is masked and excluded from lens )
 | x | x | o | x | x | x | o | x | x | o = False ( Pixel is not masked and included in lens )
 | x | x | o | x | x | x | o | x | x |
 | x | x | o | x | x | x | o | x | x |
 | x | x | o | o | o | o | o | x | x |
 | x | x | x | x | x | x | x | x | x |
 | x | x | x | x | x | x | x | x | x |
 Thus , the blurring grid coordinates and indexes will be as follows :
 pixel _ scale = 1.0"
 < - - - - ve x + ve - - >
 y x
 | x | x | x | x | x | x | x | x | x | | blurring _ grid [ 0 ] = [ 2.0 , - 2.0 ] blurring _ grid [ 9 ] = [ - 1.0 , - 2.0]
 | x | x | x | x | x | x | x | x | x | | blurring _ grid [ 1 ] = [ 2.0 , - 1.0 ] blurring _ grid [ 10 ] = [ - 1.0 , 2.0]
 | x | x | 0 | 1 | 2 | 3 | 4 | x | x | + ve blurring _ grid [ 2 ] = [ 2.0 , 0.0 ] blurring _ grid [ 11 ] = [ - 2.0 , - 2.0]
 | x | x | 5 | x | x | x | 6 | x | x | y blurring _ grid [ 3 ] = [ 2.0 , 1.0 ] blurring _ grid [ 12 ] = [ - 2.0 , - 1.0]
 | x | x | 7 | x | x | x | 8 | x | x | - ve blurring _ grid [ 4 ] = [ 2.0 , 2.0 ] blurring _ grid [ 13 ] = [ - 2.0 , 0.0]
 | x | x | 9 | x | x | x | 10 | x | x | | blurring _ grid [ 5 ] = [ 1.0 , - 2.0 ] blurring _ grid [ 14 ] = [ - 2.0 , 1.0]
 | x | x | 11 | 12 | 13 | 14 | 15 | x | x | | blurring _ grid [ 6 ] = [ 1.0 , 2.0 ] blurring _ grid [ 15 ] = [ - 2.0 , 2.0]
 | x | x | x | x | x | x | x | x | x | \ / blurring _ grid [ 7 ] = [ 0.0 , - 2.0]
 | x | x | x | x | x | x | x | x | x | blurring _ grid [ 8 ] = [ 0.0 , 2.0]
 For a PSF of shape ( 5,5 ) , the following blurring mask is computed ( noting that pixels that are 2 pixels from an
 direct unmasked pixels now blur light into an unmasked pixel ) :
 | x | x | x | x | x | x | x | x | x | This is an example regular . Mask , where :
 | x | o | o | o | o | o | o | o | x |
 | x | o | o | o | o | o | o | o | x | x = True ( Pixel is masked and excluded from lens )
 | x | o | o | x | x | x | o | o | x | o = False ( Pixel is not masked and included in lens )
 | x | o | o | x | x | x | o | o | x |
 | x | o | o | x | x | x | o | o | x |
 | x | o | o | o | o | o | o | o | x |
 | x | o | o | o | o | o | o | o | x |
 | x | x | x | x | x | x | x | x | x |"""

implementation:
blurring_mask = mask . blurring_mask_for_psf_shape ( psf_shape )
return RegularGrid . from_mask ( blurring_mask )


signature:
def array_2d_from_array_1d ( self , array_1d ) :
    """Map a 1D array the same dimension as the grid to its original masked 2D array .
 Parameters
 array _ 1d : ndarray
 The 1D array which is mapped to its masked 2D array ."""

implementation: return mapping_util . map_masked_1d_array_to_2d_array_from_array_1d_shape_and_one_to_two ( array_1d = array_1d , shape = self . mask . shape , one_to_two = self . mask . masked_grid_index_to_pixel )


signature:
def scaled_array_2d_from_array_1d ( self , array_1d ) :
    """Map a 1D array the same dimension as the grid to its original masked 2D array and return it as a scaled array .
 Parameters
 array _ 1d : ndarray
 The 1D array of which is mapped to a 2D scaled array ."""

implementation: return scaled_array . ScaledSquarePixelArray ( array = self . array_2d_from_array_1d ( array_1d ) , pixel_scale = self . mask . pixel_scale , origin = self . mask . origin )


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

implementation: return np . linspace ( np . min ( self [ : , 0 ] ) , np . max ( self [ : , 0 ] ) , 4 )


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

implementation: return np . linspace ( np . min ( self [ : , 1 ] ) , np . max ( self [ : , 1 ] ) , 4 )


signature:
def from_mask_and_sub_grid_size ( cls , mask , sub_grid_size = 1 ) :
    """Setup a sub - grid of the unmasked pixels , using a mask and a specified sub - grid size . The center of every unmasked pixel ' s sub - pixels give the grid ' s ( y , x ) arc - second coordinates .
 Parameters
 mask : Mask
 The mask whose masked pixels are used to setup the sub - pixel grid _ stack .
 sub _ grid _ size : int
 The size ( sub _ grid _ size x sub _ grid _ size ) of each unmasked pixels sub - grid ."""

implementation:
sub_grid_masked = grid_util . sub_grid_1d_masked_from_mask_pixel_scales_and_sub_grid_size ( mask = mask , pixel_scales = mask . pixel_scales , sub_grid_size = sub_grid_size )
return SubGrid ( sub_grid_masked , mask , sub_grid_size )


signature:
def from_shape_pixel_scale_and_sub_grid_size ( cls , shape , pixel_scale , sub_grid_size ) :
    """Setup a sub - grid from a 2D array shape and pixel scale . Here , the center of every pixel on the 2D array gives the grid ' s ( y , x ) arc - second coordinates , where each pixel has sub - pixels specified by the sub - grid size .
 This is equivalent to using a 2D mask consisting entirely of unmasked pixels .
 Parameters
 shape : ( int , int )
 The 2D shape of the array , where all pixels are used to generate the grid - stack ' s grid _ stack .
 pixel _ scale : float
 The size of each pixel in arc seconds .
 sub _ grid _ size : int
 The size ( sub _ grid _ size x sub _ grid _ size ) of each unmasked pixels sub - grid ."""

implementation:
mask = msk . Mask . unmasked_for_shape_and_pixel_scale ( shape = shape , pixel_scale = pixel_scale )
sub_grid = grid_util . sub_grid_1d_masked_from_mask_pixel_scales_and_sub_grid_size ( mask = mask , pixel_scales = mask . pixel_scales , sub_grid_size = sub_grid_size )
return SubGrid ( sub_grid , mask , sub_grid_size )


signature:
def sub_array_2d_from_sub_array_1d ( self , sub_array_1d ) :
    """Map a 1D sub - array the same dimension as the sub - grid ( e . g . including sub - pixels ) to its original masked
 2D sub array .
 Parameters
 sub _ array _ 1d : ndarray
 The 1D sub _ array which is mapped to its masked 2D sub - array ."""

implementation:
sub_shape = ( self . mask . shape [ 0 ] * self . sub_grid_size , self . mask . shape [ 1 ] * self . sub_grid_size )
sub_one_to_two = self . mask . masked_sub_grid_index_to_sub_pixel ( sub_grid_size = self . sub_grid_size )
return mapping_util . map_masked_1d_array_to_2d_array_from_array_1d_shape_and_one_to_two ( array_1d = sub_array_1d , shape = sub_shape , one_to_two = sub_one_to_two )


signature:
def scaled_array_2d_with_sub_dimensions_from_sub_array_1d ( self , sub_array_1d ) :
    """Map a 1D sub - array the same dimension as the sub - grid to its original masked 2D sub - array and return it as
 a scaled array .
 Parameters
 sub _ array _ 1d : ndarray
 The 1D sub - array of which is mapped to a 2D scaled sub - array the dimensions ."""

implementation: return scaled_array . ScaledSquarePixelArray ( array = self . sub_array_2d_from_sub_array_1d ( sub_array_1d = sub_array_1d ) , pixel_scale = self . mask . pixel_scale / self . sub_grid_size , origin = self . mask . origin )


signature:
def scaled_array_2d_with_regular_dimensions_from_binned_up_sub_array_1d ( self , sub_array_1d ) :
    """Map a 1D sub - array the same dimension as the sub - grid to its original masked 2D sub - array and return it as
 a scaled array .
 Parameters
 sub _ array _ 1d : ndarray
 The 1D sub - array of which is mapped to a 2D scaled sub - array the dimensions ."""

implementation:
array_1d = self . regular_data_1d_from_sub_data_1d ( sub_array_1d = sub_array_1d )
return scaled_array . ScaledSquarePixelArray ( array = self . array_2d_from_array_1d ( array_1d = array_1d ) , pixel_scale = self . mask . pixel_scale , origin = self . mask . origin )


signature:
def regular_data_1d_from_sub_data_1d ( self , sub_array_1d ) :
    """For an input sub - gridded array , map its hyper - values from the sub - gridded values to a 1D regular grid of values by summing each set of each set of sub - pixels values and dividing by the total number of sub - pixels .
 Parameters
 sub _ array _ 1d : ndarray
 A 1D sub - gridded array of values ( e . g . the intensities , surface - densities , potential ) which is mapped to
 a 1d regular array ."""

implementation: return np . multiply ( self . sub_grid_fraction , sub_array_1d . reshape ( - 1 , self . sub_grid_length ) . sum ( axis = 1 ) )


signature:
def unmasked_sparse_to_sparse ( self ) :
    """The 1D index mappings between the unmasked sparse - grid and masked sparse grid ."""

implementation: return mapping_util . unmasked_sparse_to_sparse_from_mask_and_pixel_centres ( mask = self . regular_grid . mask , unmasked_sparse_grid_pixel_centres = self . unmasked_sparse_grid_pixel_centres , total_sparse_pixels = self . total_sparse_pixels ) . astype ( 'int' )


signature:
def sparse_to_unmasked_sparse ( self ) :
    """The 1D index mappings between the masked sparse - grid and unmasked sparse grid ."""

implementation: return mapping_util . sparse_to_unmasked_sparse_from_mask_and_pixel_centres ( total_sparse_pixels = self . total_sparse_pixels , mask = self . regular_grid . mask , unmasked_sparse_grid_pixel_centres = self . unmasked_sparse_grid_pixel_centres ) . astype ( 'int' )


signature:
def regular_to_sparse ( self ) :
    """The 1D index mappings between the regular - grid and masked sparse - grid ."""

implementation: return mapping_util . regular_to_sparse_from_sparse_mappings ( regular_to_unmasked_sparse = self . regular_to_unmasked_sparse , unmasked_sparse_to_sparse = self . unmasked_sparse_to_sparse ) . astype ( 'int' )


signature:
def sparse_grid ( self ) :
    """The ( y , x ) arc - second coordinates of the masked sparse - grid ."""

implementation: return mapping_util . sparse_grid_from_unmasked_sparse_grid ( unmasked_sparse_grid = self . unmasked_sparse_grid , sparse_to_unmasked_sparse = self . sparse_to_unmasked_sparse )


signature:
def padded_grid_from_shape_psf_shape_and_pixel_scale ( cls , shape , psf_shape , pixel_scale ) :
    """Setup a regular padded grid from a 2D array shape , psf - shape and pixel - scale .
 The center of every pixel is used to setup the grid ' s ( y , x ) arc - second coordinates , including padded pixels which are beyond the input shape but will blurred light into the 2D array ' s shape due to the psf .
 Parameters
 shape : ( int , int )
 The ( y , x ) shape of the masked - grid ' s 2D image in units of pixels .
 psf _ shape : ( int , int )
 The shape of the psf which defines the blurring region and therefore size of padding .
 pixel _ scale : float
 The scale of each pixel in arc seconds"""

implementation:
padded_shape = ( shape [ 0 ] + psf_shape [ 0 ] - 1 , shape [ 1 ] + psf_shape [ 1 ] - 1 )
padded_regular_grid = grid_util . regular_grid_1d_masked_from_mask_pixel_scales_and_origin ( mask = np . full ( padded_shape , False ) , pixel_scales = ( pixel_scale , pixel_scale ) )
padded_mask = msk . Mask . unmasked_for_shape_and_pixel_scale ( shape = padded_shape , pixel_scale = pixel_scale )
return PaddedRegularGrid ( arr = padded_regular_grid , mask = padded_mask , image_shape = shape )


signature:
def padded_blurred_image_2d_from_padded_image_1d_and_psf ( self , padded_image_1d , psf ) :
    """Compute a 2D padded blurred image from a 1D padded image .
 Parameters
 padded _ image _ 1d : ndarray
 A 1D unmasked image which is blurred with the PSF .
 psf : ndarray
 An array describing the PSF kernel of the image ."""

implementation:
padded_model_image_1d = self . convolve_array_1d_with_psf ( padded_array_1d = padded_image_1d , psf = psf )
return self . scaled_array_2d_from_array_1d ( array_1d = padded_model_image_1d )


signature:
def array_2d_from_array_1d ( self , padded_array_1d ) :
    """Map a padded 1D array of values to its original 2D array , trimming all edge values .
 Parameters
 padded _ array _ 1d : ndarray
 A 1D array of values which were computed using the * PaddedRegularGrid * ."""

implementation:
padded_array_2d = self . map_to_2d_keep_padded ( padded_array_1d )
pad_size_0 = self . mask . shape [ 0 ] - self . image_shape [ 0 ]
pad_size_1 = self . mask . shape [ 1 ] - self . image_shape [ 1 ]
return ( padded_array_2d [ pad_size_0 // 2 : self . mask . shape [ 0 ] - pad_size_0 // 2 , pad_size_1 // 2 : self . mask . shape [ 1 ] - pad_size_1 // 2 ] )


signature:
def map_to_2d_keep_padded ( self , padded_array_1d ) :
    """Map a padded 1D array of values to its padded 2D array .
 Parameters
 padded _ array _ 1d : ndarray
 A 1D array of values which were computed using the * PaddedRegularGrid * ."""

implementation: return mapping_util . map_unmasked_1d_array_to_2d_array_from_array_1d_and_shape ( array_1d = padded_array_1d , shape = self . mask . shape )


signature:
def padded_grid_from_mask_sub_grid_size_and_psf_shape ( cls , mask , sub_grid_size , psf_shape ) :
    """Setup an * PaddedSubGrid * for an input mask , sub - grid size and psf - shape .
 The center of every sub - pixel is used to setup the grid ' s ( y , x ) arc - second coordinates , including masked - pixels which are beyond the input shape but will have light blurred into them given the psf - shape .
 Parameters
 mask : Mask
 The mask whose masked pixels are used to setup the sub - pixel grid _ stack .
 sub _ grid _ size : int
 The size ( sub _ grid _ size x sub _ grid _ size ) of each image - pixels sub - grid .
 psf _ shape : ( int , int )
 The shape of the psf which defines the blurring region and therefore size of padding ."""

implementation:
padded_shape = ( mask . shape [ 0 ] + psf_shape [ 0 ] - 1 , mask . shape [ 1 ] + psf_shape [ 1 ] - 1 )
padded_sub_grid = grid_util . sub_grid_1d_masked_from_mask_pixel_scales_and_sub_grid_size ( mask = np . full ( padded_shape , False ) , pixel_scales = mask . pixel_scales , sub_grid_size = sub_grid_size )
padded_mask = msk . Mask . unmasked_for_shape_and_pixel_scale ( shape = padded_shape , pixel_scale = mask . pixel_scale )
return PaddedSubGrid ( arr = padded_sub_grid , mask = padded_mask , image_shape = mask . shape , sub_grid_size = sub_grid_size )


signature:
def relocated_grid_stack_from_grid_stack ( self , grid_stack ) :
    """Determine a set of relocated grid _ stack from an input set of grid _ stack , by relocating their pixels based on the borders .
 The blurring - grid does not have its coordinates relocated , as it is only used for computing analytic light - profiles and not inversion - grid _ stack .
 Parameters
 grid _ stack : GridStack
 The grid - stack , whose grid _ stack coordinates are relocated ."""

implementation:
border_grid = grid_stack . regular [ self ]
return GridStack ( regular = self . relocated_grid_from_grid_jit ( grid = grid_stack . regular , border_grid = border_grid ) , sub = self . relocated_grid_from_grid_jit ( grid = grid_stack . sub , border_grid = border_grid ) , blurring = None , pix = self . relocated_grid_from_grid_jit ( grid = grid_stack . pix , border_grid = border_grid ) )


signature:
def relocated_grid_from_grid_jit ( grid , border_grid ) :
    """Relocate the coordinates of a grid to its border if they are outside the border . This is performed as follows :
 1 ) Use the mean value of the grid ' s y and x coordinates to determine the origin of the grid .
 2 ) Compute the radial distance of every grid coordinate from the origin .
 3 ) For every coordinate , find its nearest pixel in the border .
 4 ) Determine if it is outside the border , by comparing its radial distance from the origin to its paid border pixel ' s radial distance .
 5 ) If its radial distance is larger , use the ratio of radial distances to move the coordinate to the border ( if its inside the border , do nothing ) ."""

implementation:
border_origin = np . zeros ( 2 )
border_origin [ 0 ] = np . mean ( border_grid [ : , 0 ] )
border_origin [ 1 ] = np . mean ( border_grid [ : , 1 ] )
border_grid_radii = np . sqrt ( np . add ( np . square ( np . subtract ( border_grid [ : , 0 ] , border_origin [ 0 ] ) ) , np . square ( np . subtract ( border_grid [ : , 1 ] , border_origin [ 1 ] ) ) ) )
border_min_radii = np . min ( border_grid_radii )
grid_radii = np . sqrt ( np . add ( np . square ( np . subtract ( grid [ : , 0 ] , border_origin [ 0 ] ) ) , np . square ( np . subtract ( grid [ : , 1 ] , border_origin [ 1 ] ) ) ) )
for pixel_index in range ( grid . shape [ 0 ] ) :
    if grid_radii [ pixel_index ] > border_min_radii :
        closest_pixel_index = np . argmin ( np . square ( grid [ pixel_index , 0 ] - border_grid [ : , 0 ] ) + np . square ( grid [ pixel_index , 1 ] - border_grid [ : , 1 ] ) )
        move_factor = border_grid_radii [ closest_pixel_index ] / grid_radii [ pixel_index ]
        if move_factor < 1.0 :
            grid [ pixel_index , : ] = move_factor * ( grid [ pixel_index , : ] - border_origin [ : ] ) + border_origin [ : ]
return grid


signature:
def set_defaults ( key ) :
    """Load a default value for redshift from config and set it as the redshift for source or lens galaxies that have
 falsey redshifts
 Parameters
 key : str
 Returns
 decorator
 A decorator that wraps the setter function to set defaults"""

implementation:
def decorator ( func ) :
    @ functools . wraps ( func )
    def wrapper ( phase , new_value ) :
        new_value = new_value or [ ]
        for item in new_value : # noinspection PyTypeChecker
            galaxy = new_value [ item ] if isinstance ( item , str ) else item
            galaxy . redshift = galaxy . redshift or conf . instance . general . get ( "redshift" , key , float )
        return func ( phase , new_value )
    return wrapper
return decorator


signature:
def run ( self , positions , pixel_scale , results = None ) :
    """Run this phase .
 Parameters
 pixel _ scale
 positions
 results : autofit . tools . pipeline . ResultsCollection
 An object describing the results of the last phase or None if no phase has been executed
 Returns
 result : AbstractPhase . Result
 A result object comprising the best fit model and other hyper ."""

implementation:
analysis = self . make_analysis ( positions = positions , pixel_scale = pixel_scale , results = results )
result = self . run_analysis ( analysis )
return self . make_result ( result , analysis )


signature:
def make_analysis ( self , positions , pixel_scale , results = None ) :
    """Create an lens object . Also calls the prior passing and lens _ data modifying functions to allow child
 classes to change the behaviour of the phase .
 Parameters
 pixel _ scale
 positions
 results : autofit . tools . pipeline . ResultsCollection
 The result from the previous phase
 Returns
 lens : Analysis
 An lens object that the non - linear optimizer calls to determine the fit of a set of values"""

implementation:
self . pass_priors ( results )
analysis = self . __class__ . Analysis ( positions = positions , pixel_scale = pixel_scale , cosmology = self . cosmology , results = results )
return analysis


signature:
def run ( self , data , results = None , mask = None , positions = None ) :
    """Run this phase .
 Parameters
 positions
 mask : Mask
 The default masks passed in by the pipeline
 results : autofit . tools . pipeline . ResultsCollection
 An object describing the results of the last phase or None if no phase has been executed
 data : scaled _ array . ScaledSquarePixelArray
 An lens _ data that has been masked
 Returns
 result : AbstractPhase . Result
 A result object comprising the best fit model and other hyper ."""

implementation:
analysis = self . make_analysis ( data = data , results = results , mask = mask , positions = positions )
result = self . run_analysis ( analysis )
return self . make_result ( result , analysis )


signature:
def make_analysis ( self , data , results = None , mask = None , positions = None ) :
    """Create an lens object . Also calls the prior passing and lens _ data modifying functions to allow child
 classes to change the behaviour of the phase .
 Parameters
 positions
 mask : Mask
 The default masks passed in by the pipeline
 data : im . CCD
 An lens _ data that has been masked
 results : autofit . tools . pipeline . ResultsCollection
 The result from the previous phase
 Returns
 lens : Analysis
 An lens object that the non - linear optimizer calls to determine the fit of a set of values"""

implementation:
mask = setup_phase_mask ( data = data , mask = mask , mask_function = self . mask_function , inner_mask_radii = self . inner_mask_radii )
if self . positions_threshold is not None and positions is not None :
    positions = list ( map ( lambda position_set : np . asarray ( position_set ) , positions ) )
elif self . positions_threshold is None :
    positions = None
elif self . positions_threshold is not None and positions is None :
    raise exc . PhaseException ( 'You have specified for a phase to use positions, but not input positions to the ' 'pipeline when you ran it.' )
lens_data = li . LensData ( ccd_data = data , mask = mask , sub_grid_size = self . sub_grid_size , image_psf_shape = self . image_psf_shape , positions = positions , interp_pixel_scale = self . interp_pixel_scale )
modified_image = self . modify_image ( image = lens_data . image , results = results )
lens_data = lens_data . new_lens_data_with_modified_image ( modified_image = modified_image )
if self . bin_up_factor is not None :
    lens_data = lens_data . new_lens_data_with_binned_up_ccd_data_and_mask ( bin_up_factor = self . bin_up_factor )
self . pass_priors ( results )
self . output_phase_info ( )
analysis = self . __class__ . Analysis ( lens_data = lens_data , cosmology = self . cosmology , positions_threshold = self . positions_threshold , results = results )
return analysis


signature:
def run ( self , galaxy_data , results = None , mask = None ) :
    """Run this phase .
 Parameters
 galaxy _ data
 mask : Mask
 The default masks passed in by the pipeline
 results : autofit . tools . pipeline . ResultsCollection
 An object describing the results of the last phase or None if no phase has been executed
 Returns
 result : AbstractPhase . Result
 A result object comprising the best fit model and other hyper ."""

implementation:
analysis = self . make_analysis ( galaxy_data = galaxy_data , results = results , mask = mask )
result = self . run_analysis ( analysis )
return self . make_result ( result , analysis )


signature:
def make_analysis ( self , galaxy_data , results = None , mask = None ) :
    """Create an lens object . Also calls the prior passing and lens _ data modifying functions to allow child
 classes to change the behaviour of the phase .
 Parameters
 galaxy _ data
 mask : Mask
 The default masks passed in by the pipeline
 results : autofit . tools . pipeline . ResultsCollection
 The result from the previous phase
 Returns
 lens : Analysis
 An lens object that the non - linear optimizer calls to determine the fit of a set of values"""

implementation:
mask = setup_phase_mask ( data = galaxy_data [ 0 ] , mask = mask , mask_function = self . mask_function , inner_mask_radii = None )
self . pass_priors ( results )
if self . use_intensities or self . use_convergence or self . use_potential :
    galaxy_data = gd . GalaxyFitData ( galaxy_data = galaxy_data [ 0 ] , mask = mask , sub_grid_size = self . sub_grid_size , use_intensities = self . use_intensities , use_convergence = self . use_convergence , use_potential = self . use_potential , use_deflections_y = self . use_deflections , use_deflections_x = self . use_deflections )
    return self . __class__ . AnalysisSingle ( galaxy_data = galaxy_data , cosmology = self . cosmology , results = results )
elif self . use_deflections :
    galaxy_data_y = gd . GalaxyFitData ( galaxy_data = galaxy_data [ 0 ] , mask = mask , sub_grid_size = self . sub_grid_size , use_intensities = self . use_intensities , use_convergence = self . use_convergence , use_potential = self . use_potential , use_deflections_y = self . use_deflections , use_deflections_x = False )
    galaxy_data_x = gd . GalaxyFitData ( galaxy_data = galaxy_data [ 1 ] , mask = mask , sub_grid_size = self . sub_grid_size , use_intensities = self . use_intensities , use_convergence = self . use_convergence , use_potential = self . use_potential , use_deflections_y = False , use_deflections_x = self . use_deflections )
    return self . __class__ . AnalysisDeflections ( galaxy_data_y = galaxy_data_y , galaxy_data_x = galaxy_data_x , cosmology = self . cosmology , results = results )


signature:
def run ( self , data , results = None , mask = None , positions = None ) :
    """Run a fit for each galaxy from the previous phase .
 Parameters
 data : LensData
 results : ResultsCollection
 Results from all previous phases
 mask : Mask
 The mask
 positions
 Returns
 results : HyperGalaxyResults
 A collection of results , with one item per a galaxy"""

implementation:
model_image = results . last . unmasked_model_image
galaxy_tuples = results . last . constant . name_instance_tuples_for_class ( g . Galaxy )
results_copy = copy . copy ( results . last )
for name , galaxy in galaxy_tuples :
    optimizer = self . optimizer . copy_with_name_extension ( name )
    optimizer . variable . hyper_galaxy = g . HyperGalaxy
    galaxy_image = results . last . unmasked_image_for_galaxy ( galaxy )
    optimizer . fit ( self . __class__ . Analysis ( data , model_image , galaxy_image ) )
    getattr ( results_copy . variable , name ) . hyper_galaxy = optimizer . variable . hyper_galaxy
    getattr ( results_copy . constant , name ) . hyper_galaxy = optimizer . constant . hyper_galaxy
return results_copy


signature:
def map_1d_indexes_to_2d_indexes_for_shape ( indexes_1d , shape ) :
    """For pixels on a 2D array of shape ( rows , colums ) , map an array of 1D pixel indexes to 2D pixel indexes .
 Indexing is defined from the top - left corner rightwards and downwards , whereby the top - left pixel on the 2D array
 corresponds to index 0 , the pixel to its right pixel 1 , and so on .
 For a 2D array of shape ( 3,3 ) , 1D pixel indexes are converted as follows :
 - 1D Pixel index 0 maps - > 2D pixel index [ 0,0 ] .
 - 1D Pixel index 1 maps - > 2D pixel index [ 0,1 ] .
 - 1D Pixel index 4 maps - > 2D pixel index [ 1,0 ] .
 - 1D Pixel index 8 maps - > 2D pixel index [ 2,2 ] .
 Parameters
 indexes _ 1d : ndarray
 The 1D pixel indexes which are mapped to 2D indexes .
 shape : ( int , int )
 The shape of the 2D array which the pixels are defined on .
 Returns
 ndarray
 An array of 2d pixel indexes with dimensions ( total _ indexes , 2 ) .
 Examples
 indexes _ 1d = np . array ( [ 0 , 1 , 2 , 5 ] )
 indexes _ 2d = map _ 1d _ indexes _ to _ 2d _ indexes _ for _ shape ( indexes _ 1d = indexes _ 1d , shape = ( 3,3 ) )"""

implementation:
indexes_2d = np . zeros ( ( indexes_1d . shape [ 0 ] , 2 ) )
for i , index_1d in enumerate ( indexes_1d ) :
    indexes_2d [ i , 0 ] = int ( index_1d / shape [ 1 ] )
    indexes_2d [ i , 1 ] = int ( index_1d % shape [ 1 ] )
return indexes_2d


signature:
def map_2d_indexes_to_1d_indexes_for_shape ( indexes_2d , shape ) :
    """For pixels on a 2D array of shape ( rows , colums ) , map an array of 2D pixel indexes to 1D pixel indexes .
 Indexing is defined from the top - left corner rightwards and downwards , whereby the top - left pixel on the 2D array
 corresponds to index 0 , the pixel to its right pixel 1 , and so on .
 For a 2D array of shape ( 3,3 ) , 2D pixel indexes are converted as follows :
 - 2D Pixel index [ 0,0 ] maps - > 1D pixel index 0.
 - 2D Pixel index [ 0,1 ] maps - > 2D pixel index 1.
 - 2D Pixel index [ 1,0 ] maps - > 2D pixel index 4.
 - 2D Pixel index [ 2,2 ] maps - > 2D pixel index 8.
 Parameters
 indexes _ 2d : ndarray
 The 2D pixel indexes which are mapped to 1D indexes .
 shape : ( int , int )
 The shape of the 2D array which the pixels are defined on .
 Returns
 ndarray
 An array of 1d pixel indexes with dimensions ( total _ indexes ) .
 Examples
 indexes _ 2d = np . array ( [ [ 0,0 ] , [ 1,0 ] , [ 2,0 ] , [ 2,2 ] ] )
 indexes _ 1d = map _ 1d _ indexes _ to _ 1d _ indexes _ for _ shape ( indexes _ 2d = indexes _ 2d , shape = ( 3,3 ) )"""

implementation:
indexes_1d = np . zeros ( indexes_2d . shape [ 0 ] )
for i in range ( indexes_2d . shape [ 0 ] ) :
    indexes_1d [ i ] = int ( ( indexes_2d [ i , 0 ] ) * shape [ 1 ] + indexes_2d [ i , 1 ] )
return indexes_1d


signature:
def sub_to_regular_from_mask ( mask , sub_grid_size ) :
    """" For pixels on a 2D array of shape ( rows , colums ) , compute a 1D array which , for every unmasked pixel on
 this 2D array , maps the 1D sub - pixel indexes to their 1D pixel indexes .
 For example , the following mappings from sub - pixels to 2D array pixels are :
 - sub _ to _ regular [ 0 ] = 0 - > The first sub - pixel maps to the first unmasked pixel on the regular 2D array .
 - sub _ to _ regular [ 3 ] = 0 - > The fourth sub - pixel maps to the first unmaksed pixel on the regular 2D array .
 - sub _ to _ regular [ 7 ] = 1 - > The eighth sub - pixel maps to the second unmasked pixel on the regular 2D array .
 The term ' regular ' is used because the regular - grid is defined as the grid of coordinates on the centre of every pixel on the 2D array . Thus , this array maps sub - pixels on a sub - grid to regular - pixels on a regular - grid .
 Parameters
 mask : ndarray
 A 2D array of bools , where * False * values mean unmasked and are therefore included as part of the sub - grid 2D array ' s regular grid and sub - grid .
 sub _ grid _ size : int
 The size of the sub - grid that each pixel of the 2D array is divided into .
 Returns
 ndarray
 An array of integers which maps every sub - pixel index to regular - pixel index with dimensions
 ( total _ unmasked _ pixels * sub _ grid _ size * * 2 ) .
 Examples
 mask = np . array ( [ [ True , False , True ] ,
 [ False , False , False ]
 [ True , False , True ] ] )
 sub _ to _ regular = sub _ to _ regular _ from _ mask ( mask = mask , sub _ grid _ size = 2)"""

implementation:
total_sub_pixels = mask_util . total_sub_pixels_from_mask_and_sub_grid_size ( mask = mask , sub_grid_size = sub_grid_size )
sub_to_regular = np . zeros ( shape = total_sub_pixels )
regular_index = 0
sub_index = 0
for y in range ( mask . shape [ 0 ] ) :
    for x in range ( mask . shape [ 1 ] ) :
        if not mask [ y , x ] :
            for y1 in range ( sub_grid_size ) :
                for x1 in range ( sub_grid_size ) :
                    sub_to_regular [ sub_index ] = regular_index
                    sub_index += 1
            regular_index += 1
return sub_to_regular


signature:
def map_2d_array_to_masked_1d_array_from_array_2d_and_mask ( mask , array_2d ) :
    """For a 2D array and mask , map the values of all unmasked pixels to a 1D array .
 The pixel coordinate origin is at the top left corner of the 2D array and goes right - wards and downwards , such
 that for an array of shape ( 3,3 ) where all pixels are unmasked :
 - pixel [ 0,0 ] of the 2D array will correspond to index 0 of the 1D array .
 - pixel [ 0,1 ] of the 2D array will correspond to index 1 of the 1D array .
 - pixel [ 1,0 ] of the 2D array will correspond to index 4 of the 1D array .
 Parameters
 mask : ndarray
 A 2D array of bools , where * False * values mean unmasked and are included in the mapping .
 array _ 2d : ndarray
 The 2D array of values which are mapped to a 1D array .
 Returns
 ndarray
 A 1D array of values mapped from the 2D array with dimensions ( total _ unmasked _ pixels ) .
 Examples
 mask = np . array ( [ [ True , False , True ] ,
 [ False , False , False ]
 [ True , False , True ] ] )
 array _ 2d = np . array ( [ [ 1.0 , 2.0 , 3.0 ] ,
 [4.0 , 5.0 , 6.0 ] ,
 [7.0 , 8.0 , 9.0 ] ] )
 array _ 1d = map _ 2d _ array _ to _ masked _ 1d _ array _ from _ array _ 2d _ and _ mask ( mask = mask , array _ 2d = array _ 2d )"""

implementation:
total_image_pixels = mask_util . total_regular_pixels_from_mask ( mask )
array_1d = np . zeros ( shape = total_image_pixels )
index = 0
for y in range ( mask . shape [ 0 ] ) :
    for x in range ( mask . shape [ 1 ] ) :
        if not mask [ y , x ] :
            array_1d [ index ] = array_2d [ y , x ]
            index += 1
return array_1d


signature:
def map_masked_1d_array_to_2d_array_from_array_1d_shape_and_one_to_two ( array_1d , shape , one_to_two ) :
    """For a 1D array that was computed by mapping unmasked values from a 2D array of shape ( rows , columns ) , map its values back to the original 2D array where masked values are set to zero .
 This uses a 1D array ' one _ to _ two ' where each index gives the 2D pixel indexes of the 1D array ' s unmasked pixels , for example :
 - If one _ to _ two [ 0 ] = [ 0,0 ] , the first value of the 1D array maps to the pixel [ 0,0 ] of the 2D array .
 - If one _ to _ two [ 1 ] = [ 0,1 ] , the second value of the 1D array maps to the pixel [ 0,1 ] of the 2D array .
 - If one _ to _ two [ 4 ] = [ 1,1 ] , the fifth value of the 1D array maps to the pixel [ 1,1 ] of the 2D array .
 Parameters
 array _ 1d : ndarray
 The 1D array of values which are mapped to a 2D array .
 shape : ( int , int )
 The shape of the 2D array which the pixels are defined on .
 one _ to _ two : ndarray
 An array describing the 2D array index that every 1D array index maps too .
 Returns
 ndarray
 A 2D array of values mapped from the 1D array with dimensions shape .
 Examples
 one _ to _ two = np . array ( [ [ 0,1 ] , [ 1,0 ] , [ 1,1 ] , [ 1,2 ] , [ 2,1 ] ] )
 array _ 1d = np . array ( [ [ 2.0 , 4.0 , 5.0 , 6.0 , 8.0 ] )
 array _ 2d = map _ masked _ 1d _ array _ to _ 2d _ array _ from _ array _ 1d _ shape _ and _ one _ to _ two ( array _ 1d = array _ 1d , shape = ( 3,3 ) ,
 one _ to _ two = one _ to _ two )"""

implementation:
array_2d = np . zeros ( shape )
for index in range ( len ( one_to_two ) ) :
    array_2d [ one_to_two [ index , 0 ] , one_to_two [ index , 1 ] ] = array_1d [ index ]
return array_2d


signature:
def map_unmasked_1d_array_to_2d_array_from_array_1d_and_shape ( array_1d , shape ) :
    """For a 1D array that was flattened from a 2D array of shape ( rows , columns ) , map its values back to the original 2D array .
 The pixel coordinate origin is at the top left corner of the 2D array and goes right - wards and downwards , such
 that for an array of shape ( 3,3 ) :
 - pixel 0 of the 1D array will correspond to index [ 0,0 ] of the 2D array .
 - pixel 1 of the 1D array will correspond to index [ 0,1 ] of the 2D array .
 - pixel 4 of the 1D array will correspond to index [ 1,0 ] of the 2D array .
 Parameters
 array _ 1d : ndarray
 The 1D array of values which are mapped to a 2D array .
 shape : ( int , int )
 The shape of the 2D array which the pixels are defined on .
 Returns
 ndarray
 A 2D array of values mapped from the 1D array with dimensions ( shape ) .
 Examples
 one _ to _ two = np . array ( [ [ 0,1 ] , [ 1,0 ] , [ 1,1 ] , [ 1,2 ] , [ 2,1 ] ] )
 array _ 1d = np . array ( [ [ 2.0 , 4.0 , 5.0 , 6.0 , 8.0 ] )
 array _ 2d = map _ masked _ 1d _ array _ to _ 2d _ array _ from _ array _ 1d _ shape _ and _ one _ to _ two ( array _ 1d = array _ 1d , shape = ( 3,3 ) ,
 one _ to _ two = one _ to _ two )"""

implementation:
array_2d = np . zeros ( shape )
index = 0
for y in range ( shape [ 0 ] ) :
    for x in range ( shape [ 1 ] ) :
        array_2d [ y , x ] = array_1d [ index ]
        index += 1
return array_2d


signature:
def sparse_to_unmasked_sparse_from_mask_and_pixel_centres ( total_sparse_pixels , mask , unmasked_sparse_grid_pixel_centres ) :
    """Determine the mapping between every masked pixelization - grid pixel and pixelization - grid pixel . This is
 performed by checking whether each pixelization - grid pixel is within the regular - masks , and mapping the indexes .
 Parameters
 total _ sparse _ pixels : int
 The total number of pixels in the pixelization grid which fall within the regular - masks .
 mask : ccd . masks . Mask
 The regular - masks within which pixelization pixels must be inside
 unmasked _ sparse _ grid _ pixel _ centres : ndarray
 The centres of the unmasked pixelization grid pixels ."""

implementation:
pix_to_full_pix = np . zeros ( total_sparse_pixels )
pixel_index = 0
for full_pixel_index in range ( unmasked_sparse_grid_pixel_centres . shape [ 0 ] ) :
    y = unmasked_sparse_grid_pixel_centres [ full_pixel_index , 0 ]
    x = unmasked_sparse_grid_pixel_centres [ full_pixel_index , 1 ]
    if not mask [ y , x ] :
        pix_to_full_pix [ pixel_index ] = full_pixel_index
        pixel_index += 1
return pix_to_full_pix


signature:
def unmasked_sparse_to_sparse_from_mask_and_pixel_centres ( mask , unmasked_sparse_grid_pixel_centres , total_sparse_pixels ) :
    """Determine the mapping between every pixelization - grid pixel and masked pixelization - grid pixel . This is
 performed by checking whether each pixelization - grid pixel is within the regular - masks , and mapping the indexes .
 Pixelization pixels are paired with the next masked pixel index . This may mean that a pixel is not paired with a
 pixel near it , if the next pixel is on the next row of the grid . This is not a problem , as it is only
 unmasked pixels that are referened when computing image _ to _ pix , which is what this array is used for .
 Parameters
 total _ sparse _ pixels : int
 The total number of pixels in the pixelization grid which fall within the regular - masks .
 mask : ccd . masks . Mask
 The regular - masks within which pixelization pixels must be inside
 unmasked _ sparse _ grid _ pixel _ centres : ndarray
 The centres of the unmasked pixelization grid pixels ."""

implementation:
total_unmasked_sparse_pixels = unmasked_sparse_grid_pixel_centres . shape [ 0 ]
unmasked_sparse_to_sparse = np . zeros ( total_unmasked_sparse_pixels )
pixel_index = 0
for unmasked_sparse_pixel_index in range ( total_unmasked_sparse_pixels ) :
    y = unmasked_sparse_grid_pixel_centres [ unmasked_sparse_pixel_index , 0 ]
    x = unmasked_sparse_grid_pixel_centres [ unmasked_sparse_pixel_index , 1 ]
    unmasked_sparse_to_sparse [ unmasked_sparse_pixel_index ] = pixel_index
    if not mask [ y , x ] :
        if pixel_index < total_sparse_pixels - 1 :
            pixel_index += 1
return unmasked_sparse_to_sparse


signature:
def regular_to_sparse_from_sparse_mappings ( regular_to_unmasked_sparse , unmasked_sparse_to_sparse ) :
    """Using the mapping between the regular - grid and unmasked pixelization grid , compute the mapping between each regular
 pixel and the masked pixelization grid .
 Parameters
 regular _ to _ unmasked _ sparse : ndarray
 The index mapping between every regular - pixel and masked pixelization pixel .
 unmasked _ sparse _ to _ sparse : ndarray
 The index mapping between every masked pixelization pixel and unmasked pixelization pixel ."""

implementation:
total_regular_pixels = regular_to_unmasked_sparse . shape [ 0 ]
regular_to_sparse = np . zeros ( total_regular_pixels )
for regular_index in range ( total_regular_pixels ) : # print ( regular _ index , regular _ to _ unmasked _ sparse [ regular _ index ] , unmasked _ sparse _ to _ sparse . shape [ 0 ] )
    regular_to_sparse [ regular_index ] = unmasked_sparse_to_sparse [ regular_to_unmasked_sparse [ regular_index ] ]
return regular_to_sparse


signature:
def sparse_grid_from_unmasked_sparse_grid ( unmasked_sparse_grid , sparse_to_unmasked_sparse ) :
    """Use the central arc - second coordinate of every unmasked pixelization grid ' s pixels and mapping between each
 pixelization pixel and unmasked pixelization pixel to compute the central arc - second coordinate of every masked
 pixelization grid pixel .
 Parameters
 unmasked _ sparse _ grid : ndarray
 The ( y , x ) arc - second centre of every unmasked pixelization grid pixel .
 sparse _ to _ unmasked _ sparse : ndarray
 The index mapping between every pixelization pixel and masked pixelization pixel ."""

implementation:
total_pix_pixels = sparse_to_unmasked_sparse . shape [ 0 ]
pix_grid = np . zeros ( ( total_pix_pixels , 2 ) )
for pixel_index in range ( total_pix_pixels ) :
    pix_grid [ pixel_index , 0 ] = unmasked_sparse_grid [ sparse_to_unmasked_sparse [ pixel_index ] , 0 ]
    pix_grid [ pixel_index , 1 ] = unmasked_sparse_grid [ sparse_to_unmasked_sparse [ pixel_index ] , 1 ]
return pix_grid


signature:
def extracted_array_2d_from_array_2d_and_coordinates ( array_2d , y0 , y1 , x0 , x1 ) :
    """Resize an array to a new size by extracting a sub - set of the array .
 The extracted input coordinates use NumPy convention , such that the upper values should be specified as + 1 the dimensions of the extracted array .
 In the example below , an array of size ( 5,5 ) is extracted using the coordinates y0 = 1 , y1 = 4 , x0 = 1 , x1 = 4 . This
 extracts an array of dimensions ( 2,2 ) and is equivalent to array _ 2d [ 1:4 , 1:4]
 Parameters
 array _ 2d : ndarray
 The 2D array that is an array is extracted from .
 y0 : int
 The lower row number ( e . g . the higher y - coodinate ) of the array that is extracted for the resize .
 y1 : int
 The upper row number ( e . g . the lower y - coodinate ) of the array that is extracted for the resize .
 x0 : int
 The lower column number ( e . g . the lower x - coodinate ) of the array that is extracted for the resize .
 x1 : int
 The upper column number ( e . g . the higher x - coodinate ) of the array that is extracted for the resize .
 Returns
 ndarray
 The extracted 2D array from the input 2D array .
 Examples
 array _ 2d = np . ones ( ( 5,5 ) )
 extracted _ array = extract _ array _ 2d ( array _ 2d = array _ 2d , y0 = 1 , y1 = 4 , x0 = 1 , x1 = 4)"""

implementation:
new_shape = ( y1 - y0 , x1 - x0 )
resized_array = np . zeros ( shape = new_shape )
for y_resized , y in enumerate ( range ( y0 , y1 ) ) :
    for x_resized , x in enumerate ( range ( x0 , x1 ) ) :
        resized_array [ y_resized , x_resized ] = array_2d [ y , x ]
return resized_array


signature:
def resized_array_2d_from_array_2d_and_resized_shape ( array_2d , resized_shape , origin = ( - 1 , - 1 ) , pad_value = 0.0 ) :
    """Resize an array to a new size around a central pixel .
 If the origin ( e . g . the central pixel ) of the resized array is not specified , the central pixel of the array is calculated automatically . For example , a ( 5,5 ) array ' s central pixel is ( 2,2 ) . For even dimensions the central pixel is assumed to be the lower indexed value , e . g . a ( 6,4 ) array ' s central pixel is calculated as ( 2,1 ) .
 The default origin is ( - 1 , - 1 ) because numba requires that the function input is the same type throughout the function , thus a default ' None ' value cannot be used .
 Parameters
 array _ 2d : ndarray
 The 2D array that is resized .
 resized _ shape : ( int , int )
 The ( y , x ) new pixel dimension of the trimmed array .
 origin : ( int , int )
 The oigin of the resized array , e . g . the central pixel around which the array is extracted .
 Returns
 ndarray
 The resized 2D array from the input 2D array .
 Examples
 array _ 2d = np . ones ( ( 5,5 ) )
 resize _ array = resize _ array _ 2d ( array _ 2d = array _ 2d , new _ shape = ( 2,2 ) , origin = ( 2 , 2 ) )"""

implementation:
y_is_even = int ( array_2d . shape [ 0 ] ) % 2 == 0
x_is_even = int ( array_2d . shape [ 1 ] ) % 2 == 0
if origin is ( - 1 , - 1 ) :
    if y_is_even :
        y_centre = int ( array_2d . shape [ 0 ] / 2 )
    elif not y_is_even :
        y_centre = int ( array_2d . shape [ 0 ] / 2 )
    if x_is_even :
        x_centre = int ( array_2d . shape [ 1 ] / 2 )
    elif not x_is_even :
        x_centre = int ( array_2d . shape [ 1 ] / 2 )
    origin = ( y_centre , x_centre )
resized_array = np . zeros ( shape = resized_shape )
if y_is_even :
    y_min = origin [ 0 ] - int ( resized_shape [ 0 ] / 2 )
    y_max = origin [ 0 ] + int ( ( resized_shape [ 0 ] / 2 ) ) + 1
elif not y_is_even :
    y_min = origin [ 0 ] - int ( resized_shape [ 0 ] / 2 )
    y_max = origin [ 0 ] + int ( ( resized_shape [ 0 ] / 2 ) ) + 1
if x_is_even :
    x_min = origin [ 1 ] - int ( resized_shape [ 1 ] / 2 )
    x_max = origin [ 1 ] + int ( ( resized_shape [ 1 ] / 2 ) ) + 1
elif not x_is_even :
    x_min = origin [ 1 ] - int ( resized_shape [ 1 ] / 2 )
    x_max = origin [ 1 ] + int ( ( resized_shape [ 1 ] / 2 ) ) + 1
for y_resized , y in enumerate ( range ( y_min , y_max ) ) :
    for x_resized , x in enumerate ( range ( x_min , x_max ) ) :
        if y >= 0 and y < array_2d . shape [ 0 ] and x >= 0 and x < array_2d . shape [ 1 ] :
            if y_resized >= 0 and y_resized < resized_shape [ 0 ] and x_resized >= 0 and x_resized < resized_shape [ 1 ] :
                resized_array [ y_resized , x_resized ] = array_2d [ y , x ]
        else :
            if y_resized >= 0 and y_resized < resized_shape [ 0 ] and x_resized >= 0 and x_resized < resized_shape [ 1 ] :
                resized_array [ y_resized , x_resized ] = pad_value
return resized_array


signature:
def bin_up_array_2d_using_mean ( array_2d , bin_up_factor ) :
    """Bin up an array to coarser resolution , by binning up groups of pixels and using their mean value to determine the value of the new pixel .
 If an array of shape ( 8,8 ) is input and the bin up size is 2 , this would return a new array of size ( 4,4 ) where every pixel was the mean of each collection of 2x2 pixels on the ( 8,8 ) array .
 If binning up the array leads to an edge being cut ( e . g . a ( 9,9 ) array binned up by 2 ) , an array is first extracted around the centre of that array .
 Parameters
 array _ 2d : ndarray
 The 2D array that is resized .
 new _ shape : ( int , int )
 The ( y , x ) new pixel dimension of the trimmed array .
 origin : ( int , int )
 The oigin of the resized array , e . g . the central pixel around which the array is extracted .
 Returns
 ndarray
 The resized 2D array from the input 2D array .
 Examples
 array _ 2d = np . ones ( ( 5,5 ) )
 resize _ array = resize _ array _ 2d ( array _ 2d = array _ 2d , new _ shape = ( 2,2 ) , origin = ( 2 , 2 ) )"""

implementation:
padded_array_2d = pad_2d_array_for_binning_up_with_bin_up_factor ( array_2d = array_2d , bin_up_factor = bin_up_factor )
binned_array_2d = np . zeros ( shape = ( padded_array_2d . shape [ 0 ] // bin_up_factor , padded_array_2d . shape [ 1 ] // bin_up_factor ) )
for y in range ( binned_array_2d . shape [ 0 ] ) :
    for x in range ( binned_array_2d . shape [ 1 ] ) :
        value = 0.0
        for y1 in range ( bin_up_factor ) :
            for x1 in range ( bin_up_factor ) :
                padded_y = y * bin_up_factor + y1
                padded_x = x * bin_up_factor + x1
                value += padded_array_2d [ padded_y , padded_x ]
        binned_array_2d [ y , x ] = value / ( bin_up_factor ** 2.0 )
return binned_array_2d


signature:
def numpy_array_2d_to_fits ( array_2d , file_path , overwrite = False ) :
    """Write a 2D NumPy array to a . fits file .
 Before outputting a NumPy array , the array is flipped upside - down using np . flipud . This is so that the arrays appear the same orientation as . fits files loaded in DS9.
 Parameters
 array _ 2d : ndarray
 The 2D array that is written to fits .
 file _ path : str
 The full path of the file that is output , including the file name and ' . fits ' extension .
 overwrite : bool
 If True and a file already exists with the input file _ path the . fits file is overwritten . If False , an error will be raised .
 Returns
 None
 Examples
 array _ 2d = np . ones ( ( 5,5 ) )
 numpy _ array _ to _ fits ( array = array _ 2d , file _ path = ' / path / to / file / filename . fits ' , overwrite = True )"""

implementation:
if overwrite and os . path . exists ( file_path ) :
    os . remove ( file_path )
new_hdr = fits . Header ( )
hdu = fits . PrimaryHDU ( np . flipud ( array_2d ) , new_hdr )
hdu . writeto ( file_path )


signature:
def numpy_array_2d_from_fits ( file_path , hdu ) :
    """Read a 2D NumPy array to a . fits file .
 After loading the NumPy array , the array is flipped upside - down using np . flipud . This is so that the arrays appear the same orientation as . fits files loaded in DS9.
 Parameters
 file _ path : str
 The full path of the file that is loaded , including the file name and ' . fits ' extension .
 hdu : int
 The HDU extension of the array that is loaded from the . fits file .
 Returns
 ndarray
 The NumPy array that is loaded from the . fits file .
 Examples
 array _ 2d = numpy _ array _ from _ fits ( file _ path = ' / path / to / file / filename . fits ' , hdu = 0)"""

implementation:
hdu_list = fits . open ( file_path )
return np . flipud ( np . array ( hdu_list [ hdu ] . data ) )


signature:
def plot_lens_subtracted_image ( fit , mask = None , extract_array_from_mask = False , zoom_around_mask = 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 = 'Fit Model Image' , titlesize = 16 , xlabelsize = 16 , ylabelsize = 16 , xyticksize = 16 , mask_pointsize = 10 , position_pointsize = 10 , output_path = None , output_format = 'show' , output_filename = 'fit_lens_subtracted_image' ) :
    """Plot the model image of a specific plane of a lens fit .
 Set * autolens . datas . array . plotters . array _ plotters * for a description of all input parameters not described below .
 Parameters
 fit : datas . fitting . fitting . AbstractFitter
 The fit to the datas , which includes a list of every model image , residual _ map , chi - squareds , etc .
 image _ index : int
 The index of the datas in the datas - set of which the model image is plotted .
 plane _ indexes : int
 The plane from which the model image is generated ."""

implementation:
if fit . tracer . total_planes == 2 :
    if fit . tracer . image_plane . has_light_profile :
        lens_subtracted_image = fit . image - fit . model_image_of_planes [ 0 ]
    else :
        lens_subtracted_image = fit . image
else :
    lens_subtracted_image = fit . image - sum ( fit . model_image_of_planes [ 0 : - 2 ] )
array_plotters . plot_array ( array = lens_subtracted_image , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , 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 , output_path = output_path , output_format = output_format , output_filename = output_filename )


signature:
def plot_model_image_of_planes ( fit , plot_foreground = False , plot_source = False , mask = None , extract_array_from_mask = False , zoom_around_mask = False , positions = None , plot_mass_profile_centres = True , 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 = 'Fit Model Image' , titlesize = 16 , xlabelsize = 16 , ylabelsize = 16 , xyticksize = 16 , mask_pointsize = 10 , position_pointsize = 10 , output_path = None , output_format = 'show' , output_filename = 'fit_model_image_of_plane' ) :
    """Plot the model image of a specific plane of a lens fit .
 Set * autolens . datas . array . plotters . array _ plotters * for a description of all input parameters not described below .
 Parameters
 fit : datas . fitting . fitting . AbstractFitter
 The fit to the datas , which includes a list of every model image , residual _ map , chi - squareds , etc .
 plane _ indexes : [ int ]
 The plane from which the model image is generated ."""

implementation:
centres = get_mass_profile_centes ( plot_mass_profile_centres = plot_mass_profile_centres , fit = fit )
if plot_foreground :
    if fit . tracer . total_planes == 2 :
        model_image = fit . model_image_of_planes [ 0 ]
    else :
        model_image = sum ( fit . model_image_of_planes [ 0 : - 2 ] )
elif plot_source :
    model_image = fit . model_image_of_planes [ - 1 ]
else :
    raise exc . PlottingException ( 'Both plot_foreground and plot_source were False, one must be True' )
array_plotters . plot_array ( array = model_image , mask = mask , extract_array_from_mask = extract_array_from_mask , zoom_around_mask = zoom_around_mask , positions = positions , centres = centres , 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 , output_path = output_path , output_format = output_format , output_filename = output_filename )


signature:
def grid_at_redshift_from_image_plane_grid_and_redshift ( self , image_plane_grid , redshift ) :
    """For an input grid of ( y , x ) arc - second image - plane coordinates , ray - trace the coordinates to any redshift in the strong lens configuration .
 This is performed using multi - plane ray - tracing and the existing redshifts and planes of the tracer . However , any redshift can be input even if a plane does not exist there , including redshifts before the first plane of the lensing system .
 Parameters
 image _ plane _ grid : ndsrray or grids . RegularGrid
 The image - plane grid which is traced to the redshift .
 redshift : float
 The redshift the image - plane grid is traced to ."""

implementation:
# TODO : We need to come up with a better abstraction for multi - plane lensing 0_0
image_plane_grid_stack = grids . GridStack ( regular = image_plane_grid , sub = np . array ( [ [ 0.0 , 0.0 ] ] ) , blurring = np . array ( [ [ 0.0 , 0.0 ] ] ) )
tracer = TracerMultiPlanes ( galaxies = self . galaxies , image_plane_grid_stack = image_plane_grid_stack , border = None , cosmology = self . cosmology )
for plane_index in range ( 0 , len ( self . plane_redshifts ) ) :
    new_grid_stack = image_plane_grid_stack
    if redshift <= tracer . plane_redshifts [ plane_index ] : # If redshift is between two planes , we need to map over all previous planes coordinates / deflections .
        if plane_index > 0 :
            for previous_plane_index in range ( plane_index ) :
                scaling_factor = cosmology_util . scaling_factor_between_redshifts_from_redshifts_and_cosmology ( redshift_0 = tracer . plane_redshifts [ previous_plane_index ] , redshift_1 = redshift , redshift_final = tracer . plane_redshifts [ - 1 ] , cosmology = tracer . cosmology )
                scaled_deflection_stack = lens_util . scaled_deflection_stack_from_plane_and_scaling_factor ( plane = tracer . planes [ previous_plane_index ] , scaling_factor = scaling_factor )
                new_grid_stack = lens_util . grid_stack_from_deflection_stack ( grid_stack = new_grid_stack , deflection_stack = scaled_deflection_stack )
        # If redshift is before the first plane , no change to image pllane coordinates .
        elif plane_index == 0 :
            return new_grid_stack . regular
        return new_grid_stack . regular


signature:
def convolve_mapping_matrix ( self , mapping_matrix ) :
    """For a given inversion mapping matrix , convolve every pixel ' s mapped regular with the PSF kernel .
 A mapping matrix provides non - zero entries in all elements which map two pixels to one another
 ( see * inversions . mappers * ) .
 For example , lets take an regular which is masked using a ' cross ' of 5 pixels :
 [ [ True , False , True ] ] ,
 [ [ False , False , False ] ] ,
 [ [ True , False , True ] ]
 As example mapping matrix of this cross is as follows ( 5 regular pixels x 3 source pixels ) :
 [1 , 0 , 0 ] [ 0 - > 0]
 [1 , 0 , 0 ] [ 1 - > 0]
 [0 , 1 , 0 ] [ 2 - > 1]
 [0 , 1 , 0 ] [ 3 - > 1]
 [0 , 0 , 1 ] [ 4 - > 2]
 For each source - pixel , we can create an regular of its unit - surface brightnesses by mapping the non - zero
 entries back to masks . For example , doing this for source pixel 1 gives :
 [ [ 0.0 , 1.0 , 0.0 ] ] ,
 [ [ 1.0 , 0.0 , 0.0 ] ]
 [ [ 0.0 , 0.0 , 0.0 ] ]
 And source pixel 2:
 [ [ 0.0 , 0.0 , 0.0 ] ] ,
 [ [ 0.0 , 1.0 , 1.0 ] ]
 [ [ 0.0 , 0.0 , 0.0 ] ]
 We then convolve each of these regular with our PSF kernel , in 2 dimensions , like we would a normal regular . For
 example , using the kernel below :
 kernel :
 [ [ 0.0 , 0.1 , 0.0 ] ]
 [ [ 0.1 , 0.6 , 0.1 ] ]
 [ [ 0.0 , 0.1 , 0.0 ] ]
 Blurred Source Pixel 1 ( we don ' t need to perform the convolution into masked pixels ) :
 [ [ 0.0 , 0.6 , 0.0 ] ] ,
 [ [ 0.6 , 0.0 , 0.0 ] ] ,
 [ [ 0.0 , 0.0 , 0.0 ] ]
 Blurred Source pixel 2:
 [ [ 0.0 , 0.0 , 0.0 ] ] ,
 [ [ 0.0 , 0.7 , 0.7 ] ] ,
 [ [ 0.0 , 0.0 , 0.0 ] ]
 Finally , we map each of these blurred regular back to a blurred mapping matrix , which is analogous to the
 mapping matrix .
 [0.6 , 0.0 , 0.0 ] [ 0 - > 0]
 [0.6 , 0.0 , 0.0 ] [ 1 - > 0]
 [0.0 , 0.7 , 0.0 ] [ 2 - > 1]
 [0.0 , 0.7 , 0.0 ] [ 3 - > 1]
 [0.0 , 0.0 , 0.6 ] [ 4 - > 2]
 If the mapping matrix is sub - gridded , we perform the convolution on the fractional surface brightnesses in an
 identical fashion to above .
 Parameters
 mapping _ matrix : ndarray
 The 2D mapping matix describing how every inversion pixel maps to an datas _ pixel ."""

implementation: return self . convolve_matrix_jit ( mapping_matrix , self . image_frame_indexes , self . image_frame_psfs , self . image_frame_lengths )


signature:
def mass_within_circle_in_units ( self , radius : dim . Length , unit_mass = 'angular' , kpc_per_arcsec = None , critical_surface_density = None ) :
    """Integrate the mass profiles ' s convergence profile to compute the total mass within a circle of specified radius . This is centred on the mass profile .
 The following units for mass can be specified and output :
 - Dimensionless angular units ( default ) - ' angular ' .
 - Solar masses - ' angular ' ( multiplies the angular mass by the critical surface mass density ) .
 Parameters
 radius : dim . Length
 The radius of the circle to compute the dimensionless mass within .
 unit _ mass : str
 The units the mass is returned in ( angular | angular ) .
 critical _ surface _ density : float or None
 The critical surface mass density of the strong lens configuration , which converts mass from angulalr units to phsical units ( e . g . solar masses ) ."""

implementation:
self . check_units_of_radius_and_critical_surface_density ( radius = radius , critical_surface_density = critical_surface_density )
profile = self . new_profile_with_units_converted ( unit_length = radius . unit_length , unit_mass = 'angular' , kpc_per_arcsec = kpc_per_arcsec , critical_surface_density = critical_surface_density )
mass_angular = dim . Mass ( value = quad ( profile . mass_integral , a = 0.0 , b = radius , args = ( 1.0 , ) ) [ 0 ] , unit_mass = 'angular' )
return mass_angular . convert ( unit_mass = unit_mass , critical_surface_density = critical_surface_density )


signature:
def mass_within_ellipse_in_units ( self , major_axis , unit_mass = 'angular' , kpc_per_arcsec = None , critical_surface_density = None ) :
    """Integrate the mass profiles ' s convergence profile to compute the total angular mass within an ellipse of specified major axis . This is centred on the mass profile .
 The following units for mass can be specified and output :
 - Dimensionless angular units ( default ) - ' angular ' .
 - Solar masses - ' angular ' ( multiplies the angular mass by the critical surface mass density )
 Parameters
 major _ axis : float
 The major - axis radius of the ellipse .
 unit _ mass : str
 The units the mass is returned in ( angular | angular ) .
 critical _ surface _ density : float or None
 The critical surface mass density of the strong lens configuration , which converts mass from angular units to phsical units ( e . g . solar masses ) ."""

implementation:
self . check_units_of_radius_and_critical_surface_density ( radius = major_axis , critical_surface_density = critical_surface_density )
profile = self . new_profile_with_units_converted ( unit_length = major_axis . unit_length , unit_mass = 'angular' , kpc_per_arcsec = kpc_per_arcsec , critical_surface_density = critical_surface_density )
mass_angular = dim . Mass ( value = quad ( profile . mass_integral , a = 0.0 , b = major_axis , args = ( self . axis_ratio , ) ) [ 0 ] , unit_mass = 'angular' )
return mass_angular . convert ( unit_mass = unit_mass , critical_surface_density = critical_surface_density )


signature:
def mass_integral ( self , x , axis_ratio ) :
    """Routine to integrate an elliptical light profiles - set axis ratio to 1 to compute the luminosity within a circle"""

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


signature:
def density_between_circular_annuli_in_angular_units ( self , inner_annuli_radius , outer_annuli_radius ) :
    """Calculate the mass between two circular annuli and compute the density by dividing by the annuli surface
 area .
 The value returned by the mass integral is dimensionless , therefore the density between annuli is returned in units of inverse radius squared . A conversion factor can be specified to convert this to a physical value ( e . g . the critical surface mass density ) .
 Parameters
 inner _ annuli _ radius : float
 The radius of the inner annulus outside of which the density are estimated .
 outer _ annuli _ radius : float
 The radius of the outer annulus inside of which the density is estimated ."""

implementation:
annuli_area = ( np . pi * outer_annuli_radius ** 2.0 ) - ( np . pi * inner_annuli_radius ** 2.0 )
return ( self . mass_within_circle_in_units ( radius = outer_annuli_radius ) - self . mass_within_circle_in_units ( radius = inner_annuli_radius ) ) / annuli_area


signature:
def average_convergence_of_1_radius_in_units ( self , unit_length = 'arcsec' , kpc_per_arcsec = None ) :
    """The radius a critical curve forms for this mass profile , e . g . where the mean convergence is equal to 1.0.
 In case of ellipitical mass profiles , the ' average ' critical curve is used , whereby the convergence is rescaled into a circle using the axis ratio .
 This radius corresponds to the Einstein radius of the mass profile , and is a property of a number of mass profiles below ."""

implementation:
def func ( radius ) :
    radius = dim . Length ( radius , unit_length = unit_length )
    return self . mass_within_circle_in_units ( radius = radius ) - np . pi * radius ** 2.0
radius = self . ellipticity_rescale * root_scalar ( func , bracket = [ 1e-4 , 1000.0 ] ) . root
radius = dim . Length ( radius , unit_length )
return radius . convert ( unit_length = unit_length , kpc_per_arcsec = kpc_per_arcsec )


signature:
def einstein_radius_rescaled ( self ) :
    """Rescale the einstein radius by slope and axis _ ratio , to reduce its degeneracy with other mass - profiles
 parameters"""

implementation: return ( ( 3 - self . slope ) / ( 1 + self . axis_ratio ) ) * self . einstein_radius ** ( self . slope - 1 )


signature:
def convergence_from_grid ( self , grid ) :
    """Calculate the projected convergence at a given set of arc - second gridded coordinates .
 Parameters
 grid : grids . RegularGrid
 The grid of ( y , x ) arc - second coordinates the surface density is computed on ."""

implementation:
surface_density_grid = np . zeros ( grid . shape [ 0 ] )
grid_eta = self . grid_to_elliptical_radii ( grid )
for i in range ( grid . shape [ 0 ] ) :
    surface_density_grid [ i ] = self . convergence_func ( grid_eta [ i ] )
return surface_density_grid


signature:
def potential_from_grid ( self , grid ) :
    """Calculate the potential at a given set of arc - second gridded coordinates .
 Parameters
 grid : grids . RegularGrid
 The grid of ( y , x ) arc - second coordinates the deflection angles are computed on ."""

implementation:
potential_grid = quad_grid ( self . potential_func , 0.0 , 1.0 , grid , args = ( self . axis_ratio , self . slope , self . core_radius ) ) [ 0 ]
return self . einstein_radius_rescaled * self . axis_ratio * potential_grid


signature:
def deflections_from_grid ( self , grid ) :
    """Calculate the deflection angles at a given set of arc - second gridded coordinates .
 Parameters
 grid : grids . RegularGrid
 The grid of ( y , x ) arc - second coordinates the deflection angles are computed on ."""

implementation:
def calculate_deflection_component ( npow , index ) :
    einstein_radius_rescaled = self . einstein_radius_rescaled
    deflection_grid = self . axis_ratio * grid [ : , index ]
    deflection_grid *= quad_grid ( self . deflection_func , 0.0 , 1.0 , grid , args = ( npow , self . axis_ratio , einstein_radius_rescaled , self . slope , self . core_radius ) ) [ 0 ]
    return deflection_grid
deflection_y = calculate_deflection_component ( 1.0 , 0 )
deflection_x = calculate_deflection_component ( 0.0 , 1 )
return self . rotate_grid_from_profile ( np . multiply ( 1.0 , np . vstack ( ( deflection_y , deflection_x ) ) . T ) )


implementation:
eta = self . grid_to_grid_radii ( grid = grid )
deflection = np . multiply ( 2. * self . einstein_radius_rescaled , np . divide ( np . add ( np . power ( np . add ( self . core_radius ** 2 , np . square ( eta ) ) , ( 3. - self . slope ) / 2. ) , - self . core_radius ** ( 3 - self . slope ) ) , np . multiply ( ( 3. - self . slope ) , eta ) ) )
return self . grid_to_grid_cartesian ( grid = grid , radius = deflection )


signature:
def deflections_from_grid ( self , grid ) :
    """Calculate the deflection angles at a given set of arc - second gridded coordinates .
 For coordinates ( 0.0 , 0.0 ) the analytic calculation of the deflection angle gives a NaN . Therefore , coordinates at ( 0.0 , 0.0 ) are shifted slightly to ( 1.0e - 8 , 1.0e - 8 ) .
 Parameters
 grid : grids . RegularGrid
 The grid of ( y , x ) arc - second coordinates the deflection angles are computed on ."""

implementation:
factor = 2.0 * self . einstein_radius_rescaled * self . axis_ratio / np . sqrt ( 1 - self . axis_ratio ** 2 )
psi = np . sqrt ( np . add ( np . multiply ( self . axis_ratio ** 2 , np . square ( grid [ : , 1 ] ) ) , np . square ( grid [ : , 0 ] ) ) )
deflection_y = np . arctanh ( np . divide ( np . multiply ( np . sqrt ( 1 - self . axis_ratio ** 2 ) , grid [ : , 0 ] ) , psi ) )
deflection_x = np . arctan ( np . divide ( np . multiply ( np . sqrt ( 1 - self . axis_ratio ** 2 ) , grid [ : , 1 ] ) , psi ) )
return self . rotate_grid_from_profile ( np . multiply ( factor , np . vstack ( ( deflection_y , deflection_x ) ) . T ) )


implementation:
eta = self . grid_to_elliptical_radii ( grid )
return 2.0 * self . einstein_radius_rescaled * eta


implementation: return self . grid_to_grid_cartesian ( grid = grid , radius = np . full ( grid . shape [ 0 ] , 2.0 * self . einstein_radius_rescaled ) )


signature:
def tabulate_integral ( self , grid , tabulate_bins ) :
    """Tabulate an integral over the surface density of deflection potential of a mass profile . This is used in the GeneralizedNFW profile classes to speed up the integration procedure .
 Parameters
 grid : grids . RegularGrid
 The grid of ( y , x ) arc - second coordinates the potential / deflection _ stacks are computed on .
 tabulate _ bins : int
 The number of bins to tabulate the inner integral of this profile ."""

implementation:
eta_min = 1.0e-4
eta_max = 1.05 * np . max ( self . grid_to_elliptical_radii ( grid ) )
minimum_log_eta = np . log10 ( eta_min )
maximum_log_eta = np . log10 ( eta_max )
bin_size = ( maximum_log_eta - minimum_log_eta ) / ( tabulate_bins - 1 )
return eta_min , eta_max , minimum_log_eta , maximum_log_eta , bin_size


signature:
def potential_from_grid ( self , grid , tabulate_bins = 1000 ) :
    """Calculate the potential at a given set of arc - second gridded coordinates .
 Parameters
 grid : grids . RegularGrid
 The grid of ( y , x ) arc - second coordinates the deflection angles are computed on .
 tabulate _ bins : int
 The number of bins to tabulate the inner integral of this profile ."""

implementation:
@ jit_integrand
def deflection_integrand ( x , kappa_radius , scale_radius , inner_slope ) :
    return ( x + kappa_radius / scale_radius ) ** ( inner_slope - 3 ) * ( ( 1 - np . sqrt ( 1 - x ** 2 ) ) / x )
eta_min , eta_max , minimum_log_eta , maximum_log_eta , bin_size = self . tabulate_integral ( grid , tabulate_bins )
potential_grid = np . zeros ( grid . shape [ 0 ] )
deflection_integral = np . zeros ( ( tabulate_bins , ) )
for i in range ( tabulate_bins ) :
    eta = 10. ** ( minimum_log_eta + ( i - 1 ) * bin_size )
    integral = quad ( deflection_integrand , a = 0.0 , b = 1.0 , args = ( eta , self . scale_radius , self . inner_slope ) , epsrel = EllipticalGeneralizedNFW . epsrel ) [ 0 ]
    deflection_integral [ i ] = ( ( eta / self . scale_radius ) ** ( 2 - self . inner_slope ) ) * ( ( 1.0 / ( 3 - self . inner_slope ) ) * special . hyp2f1 ( 3 - self . inner_slope , 3 - self . inner_slope , 4 - self . inner_slope , - ( eta / self . scale_radius ) ) + integral )
for i in range ( grid . shape [ 0 ] ) :
    potential_grid [ i ] = ( 2.0 * self . kappa_s * self . axis_ratio ) * quad ( self . potential_func , a = 0.0 , b = 1.0 , args = ( grid [ i , 0 ] , grid [ i , 1 ] , self . axis_ratio , minimum_log_eta , maximum_log_eta , tabulate_bins , deflection_integral ) , epsrel = EllipticalGeneralizedNFW . epsrel ) [ 0 ]
return potential_grid


signature:
def deflections_from_grid ( self , grid , tabulate_bins = 1000 ) :
    """Calculate the deflection angles at a given set of arc - second gridded coordinates .
 Parameters
 grid : grids . RegularGrid
 The grid of ( y , x ) arc - second coordinates the deflection angles are computed on .
 tabulate _ bins : int
 The number of bins to tabulate the inner integral of this profile ."""

implementation:
@ jit_integrand
def surface_density_integrand ( x , kappa_radius , scale_radius , inner_slope ) :
    return ( 3 - inner_slope ) * ( x + kappa_radius / scale_radius ) ** ( inner_slope - 4 ) * ( 1 - np . sqrt ( 1 - x * x ) )
def calculate_deflection_component ( npow , index ) :
    deflection_grid = 2.0 * self . kappa_s * self . axis_ratio * grid [ : , index ]
    deflection_grid *= quad_grid ( self . deflection_func , 0.0 , 1.0 , grid , args = ( npow , self . axis_ratio , minimum_log_eta , maximum_log_eta , tabulate_bins , surface_density_integral ) , epsrel = EllipticalGeneralizedNFW . epsrel ) [ 0 ]
    return deflection_grid
eta_min , eta_max , minimum_log_eta , maximum_log_eta , bin_size = self . tabulate_integral ( grid , tabulate_bins )
surface_density_integral = np . zeros ( ( tabulate_bins , ) )
for i in range ( tabulate_bins ) :
    eta = 10. ** ( minimum_log_eta + ( i - 1 ) * bin_size )
    integral = quad ( surface_density_integrand , a = 0.0 , b = 1.0 , args = ( eta , self . scale_radius , self . inner_slope ) , epsrel = EllipticalGeneralizedNFW . epsrel ) [ 0 ]
    surface_density_integral [ i ] = ( ( eta / self . scale_radius ) ** ( 1 - self . inner_slope ) ) * ( ( ( 1 + eta / self . scale_radius ) ** ( self . inner_slope - 3 ) ) + integral )
deflection_y = calculate_deflection_component ( 1.0 , 0 )
deflection_x = calculate_deflection_component ( 0.0 , 1 )
return self . rotate_grid_from_profile ( np . multiply ( 1.0 , np . vstack ( ( deflection_y , deflection_x ) ) . T ) )


signature:
def deflections_from_grid ( self , grid , ** kwargs ) :
    """Calculate the deflection angles at a given set of arc - second gridded coordinates .
 Parameters
 grid : grids . RegularGrid
 The grid of ( y , x ) arc - second coordinates the deflection angles are computed on ."""

implementation:
eta = np . multiply ( 1. / self . scale_radius , self . grid_to_grid_radii ( grid ) )
deflection_grid = np . zeros ( grid . shape [ 0 ] )
for i in range ( grid . shape [ 0 ] ) :
    deflection_grid [ i ] = np . multiply ( 4. * self . kappa_s * self . scale_radius , self . deflection_func_sph ( eta [ i ] ) )
return self . grid_to_grid_cartesian ( grid , deflection_grid )


implementation:
eta = np . multiply ( 1. / self . scale_radius , self . grid_to_grid_radii ( grid ) )
deflection_grid = np . multiply ( ( 4. * self . kappa_s * self . scale_radius / eta ) , self . deflection_func_sph ( eta ) )
return self . grid_to_grid_cartesian ( grid , deflection_grid )


implementation:
potential_grid = quad_grid ( self . potential_func , 0.0 , 1.0 , grid , args = ( self . axis_ratio , self . kappa_s , self . scale_radius ) , epsrel = 1.49e-5 ) [ 0 ]
return potential_grid


implementation:
def calculate_deflection_component ( npow , index ) :
    deflection_grid = self . axis_ratio * grid [ : , index ]
    deflection_grid *= quad_grid ( self . deflection_func , 0.0 , 1.0 , grid , args = ( npow , self . axis_ratio , self . kappa_s , self . scale_radius ) ) [ 0 ]
    return deflection_grid
deflection_y = calculate_deflection_component ( 1.0 , 0 )
deflection_x = calculate_deflection_component ( 0.0 , 1 )
return self . rotate_grid_from_profile ( np . multiply ( 1.0 , np . vstack ( ( deflection_y , deflection_x ) ) . T ) )


implementation:
eta = ( 1.0 / self . scale_radius ) * self . grid_to_grid_radii ( grid ) + 0j
return np . real ( 2.0 * self . scale_radius * self . kappa_s * self . potential_func_sph ( eta ) )


implementation:
eta = np . multiply ( 1. / self . scale_radius , self . grid_to_grid_radii ( grid = grid ) )
deflection_r = np . multiply ( 4. * self . kappa_s * self . scale_radius , self . deflection_func_sph ( eta ) )
return self . grid_to_grid_cartesian ( grid , deflection_r )


signature:
def intensity_at_radius ( self , radius ) :
    """Compute the intensity of the profile at a given radius .
 Parameters
 radius : float
 The distance from the centre of the profile ."""

implementation: return self . intensity * np . exp ( - self . sersic_constant * ( ( ( radius / self . effective_radius ) ** ( 1. / self . sersic_index ) ) - 1 ) )


signature:
def sersic_constant ( self ) :
    """A parameter derived from Sersic index which ensures that effective radius contains 50 % of the profile ' s
 total integrated light ."""


implementation:
def calculate_deflection_component ( npow , index ) :
    sersic_constant = self . sersic_constant
    deflection_grid = self . axis_ratio * grid [ : , index ]
    deflection_grid *= quad_grid ( self . deflection_func , 0.0 , 1.0 , grid , args = ( npow , self . axis_ratio , self . intensity , self . sersic_index , self . effective_radius , self . mass_to_light_ratio , self . mass_to_light_gradient , sersic_constant ) ) [ 0 ]
    return deflection_grid
deflection_y = calculate_deflection_component ( 1.0 , 0 )
deflection_x = calculate_deflection_component ( 0.0 , 1 )
return self . rotate_grid_from_profile ( np . multiply ( 1.0 , np . vstack ( ( deflection_y , deflection_x ) ) . T ) )


implementation:
deflection_y = - np . multiply ( self . magnitude , grid [ : , 0 ] )
deflection_x = np . multiply ( self . magnitude , grid [ : , 1 ] )
return self . rotate_grid_from_profile ( np . vstack ( ( deflection_y , deflection_x ) ) . T )


signature:
def intensities_from_grid ( self , grid ) :
    """Calculate the summed intensities of all of the galaxy ' s light profiles using a grid of Cartesian ( y , x ) coordinates .
 If the galaxy has no light profiles , a grid of zeros is returned .
 See * profiles . light _ profiles * for a description of how light profile intensities are computed .
 Parameters
 grid : ndarray
 The ( y , x ) coordinates in the original reference frame of the grid ."""

implementation:
if self . has_light_profile :
    return sum ( map ( lambda p : p . intensities_from_grid ( grid ) , self . light_profiles ) )
else :
    return np . zeros ( ( grid . shape [ 0 ] , ) )


signature:
def luminosity_within_circle_in_units ( self , radius : dim . Length , unit_luminosity = 'eps' , kpc_per_arcsec = None , exposure_time = None ) :
    """Compute the total luminosity of the galaxy ' s light profiles within a circle of specified radius .
 See * light _ profiles . luminosity _ within _ circle * for details of how this is performed .
 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
 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_circle_in_units ( radius = radius , unit_luminosity = unit_luminosity , kpc_per_arcsec = kpc_per_arcsec , exposure_time = exposure_time ) , self . light_profiles ) )
else :
    return None