Search is not available for this dataset
text
stringlengths 75
104k
|
---|
def load_ccd_data_from_fits(image_path, pixel_scale, image_hdu=0,
resized_ccd_shape=None, resized_ccd_origin_pixels=None,
resized_ccd_origin_arcsec=None,
psf_path=None, psf_hdu=0, resized_psf_shape=None, renormalize_psf=True,
noise_map_path=None, noise_map_hdu=0,
noise_map_from_image_and_background_noise_map=False,
convert_noise_map_from_weight_map=False,
convert_noise_map_from_inverse_noise_map=False,
background_noise_map_path=None, background_noise_map_hdu=0,
convert_background_noise_map_from_weight_map=False,
convert_background_noise_map_from_inverse_noise_map=False,
poisson_noise_map_path=None, poisson_noise_map_hdu=0,
poisson_noise_map_from_image=False,
convert_poisson_noise_map_from_weight_map=False,
convert_poisson_noise_map_from_inverse_noise_map=False,
exposure_time_map_path=None, exposure_time_map_hdu=0,
exposure_time_map_from_single_value=None,
exposure_time_map_from_inverse_noise_map=False,
background_sky_map_path=None, background_sky_map_hdu=0,
convert_from_electrons=False,
gain=None, convert_from_adus=False, lens_name=None):
"""Factory for loading the ccd data from .fits files, as well as computing properties like the noise-map,
exposure-time map, etc. from the ccd-data.
This factory also includes a number of routines for converting the ccd-data from units not supported by PyAutoLens \
(e.g. adus, electrons) to electrons per second.
Parameters
----------
lens_name
image_path : str
The path to the image .fits file containing the image (e.g. '/path/to/image.fits')
pixel_scale : float
The size of each pixel in arc seconds.
image_hdu : int
The hdu the image is contained in the .fits file specified by *image_path*.
image_hdu : int
The hdu the image is contained in the .fits file that *image_path* points too.
resized_ccd_shape : (int, int) | None
If input, the ccd arrays that are image sized, e.g. the image, noise-maps) are resized to these dimensions.
resized_ccd_origin_pixels : (int, int) | None
If the ccd arrays are resized, this defines a new origin (in pixels) around which recentering occurs.
resized_ccd_origin_arcsec : (float, float) | None
If the ccd arrays are resized, this defines a new origin (in arc-seconds) around which recentering occurs.
psf_path : str
The path to the psf .fits file containing the psf (e.g. '/path/to/psf.fits')
psf_hdu : int
The hdu the psf is contained in the .fits file specified by *psf_path*.
resized_psf_shape : (int, int) | None
If input, the psf is resized to these dimensions.
renormalize_psf : bool
If True, the PSF is renoralized such that all elements sum to 1.0.
noise_map_path : str
The path to the noise_map .fits file containing the noise_map (e.g. '/path/to/noise_map.fits')
noise_map_hdu : int
The hdu the noise_map is contained in the .fits file specified by *noise_map_path*.
noise_map_from_image_and_background_noise_map : bool
If True, the noise-map is computed from the observed image and background noise-map \
(see NoiseMap.from_image_and_background_noise_map).
convert_noise_map_from_weight_map : bool
If True, the noise-map loaded from the .fits file is converted from a weight-map to a noise-map (see \
*NoiseMap.from_weight_map).
convert_noise_map_from_inverse_noise_map : bool
If True, the noise-map loaded from the .fits file is converted from an inverse noise-map to a noise-map (see \
*NoiseMap.from_inverse_noise_map).
background_noise_map_path : str
The path to the background_noise_map .fits file containing the background noise-map \
(e.g. '/path/to/background_noise_map.fits')
background_noise_map_hdu : int
The hdu the background_noise_map is contained in the .fits file specified by *background_noise_map_path*.
convert_background_noise_map_from_weight_map : bool
If True, the bacground noise-map loaded from the .fits file is converted from a weight-map to a noise-map (see \
*NoiseMap.from_weight_map).
convert_background_noise_map_from_inverse_noise_map : bool
If True, the background noise-map loaded from the .fits file is converted from an inverse noise-map to a \
noise-map (see *NoiseMap.from_inverse_noise_map).
poisson_noise_map_path : str
The path to the poisson_noise_map .fits file containing the Poisson noise-map \
(e.g. '/path/to/poisson_noise_map.fits')
poisson_noise_map_hdu : int
The hdu the poisson_noise_map is contained in the .fits file specified by *poisson_noise_map_path*.
poisson_noise_map_from_image : bool
If True, the Poisson noise-map is estimated using the image.
convert_poisson_noise_map_from_weight_map : bool
If True, the Poisson noise-map loaded from the .fits file is converted from a weight-map to a noise-map (see \
*NoiseMap.from_weight_map).
convert_poisson_noise_map_from_inverse_noise_map : bool
If True, the Poisson noise-map loaded from the .fits file is converted from an inverse noise-map to a \
noise-map (see *NoiseMap.from_inverse_noise_map).
exposure_time_map_path : str
The path to the exposure_time_map .fits file containing the exposure time map \
(e.g. '/path/to/exposure_time_map.fits')
exposure_time_map_hdu : int
The hdu the exposure_time_map is contained in the .fits file specified by *exposure_time_map_path*.
exposure_time_map_from_single_value : float
The exposure time of the ccd imaging, which is used to compute the exposure-time map as a single value \
(see *ExposureTimeMap.from_single_value*).
exposure_time_map_from_inverse_noise_map : bool
If True, the exposure-time map is computed from the background noise_map map \
(see *ExposureTimeMap.from_background_noise_map*)
background_sky_map_path : str
The path to the background_sky_map .fits file containing the background sky map \
(e.g. '/path/to/background_sky_map.fits').
background_sky_map_hdu : int
The hdu the background_sky_map is contained in the .fits file specified by *background_sky_map_path*.
convert_from_electrons : bool
If True, the input unblurred_image_1d are in units of electrons and all converted to electrons / second using the exposure \
time map.
gain : float
The image gain, used for convert from ADUs.
convert_from_adus : bool
If True, the input unblurred_image_1d are in units of adus and all converted to electrons / second using the exposure \
time map and gain.
"""
image = load_image(image_path=image_path, image_hdu=image_hdu, pixel_scale=pixel_scale)
background_noise_map = load_background_noise_map(background_noise_map_path=background_noise_map_path,
background_noise_map_hdu=background_noise_map_hdu,
pixel_scale=pixel_scale,
convert_background_noise_map_from_weight_map=convert_background_noise_map_from_weight_map,
convert_background_noise_map_from_inverse_noise_map=convert_background_noise_map_from_inverse_noise_map)
if background_noise_map is not None:
inverse_noise_map = 1.0 / background_noise_map
else:
inverse_noise_map = None
exposure_time_map = load_exposure_time_map(exposure_time_map_path=exposure_time_map_path,
exposure_time_map_hdu=exposure_time_map_hdu,
pixel_scale=pixel_scale, shape=image.shape,
exposure_time=exposure_time_map_from_single_value,
exposure_time_map_from_inverse_noise_map=exposure_time_map_from_inverse_noise_map,
inverse_noise_map=inverse_noise_map)
poisson_noise_map = load_poisson_noise_map(poisson_noise_map_path=poisson_noise_map_path,
poisson_noise_map_hdu=poisson_noise_map_hdu,
pixel_scale=pixel_scale,
convert_poisson_noise_map_from_weight_map=convert_poisson_noise_map_from_weight_map,
convert_poisson_noise_map_from_inverse_noise_map=convert_poisson_noise_map_from_inverse_noise_map,
image=image, exposure_time_map=exposure_time_map,
poisson_noise_map_from_image=poisson_noise_map_from_image,
convert_from_electrons=convert_from_electrons, gain=gain,
convert_from_adus=convert_from_adus)
noise_map = load_noise_map(noise_map_path=noise_map_path, noise_map_hdu=noise_map_hdu, pixel_scale=pixel_scale,
image=image, background_noise_map=background_noise_map,
exposure_time_map=exposure_time_map,
convert_noise_map_from_weight_map=convert_noise_map_from_weight_map,
convert_noise_map_from_inverse_noise_map=convert_noise_map_from_inverse_noise_map,
noise_map_from_image_and_background_noise_map=noise_map_from_image_and_background_noise_map,
convert_from_electrons=convert_from_electrons, gain=gain,
convert_from_adus=convert_from_adus)
psf = load_psf(psf_path=psf_path, psf_hdu=psf_hdu, pixel_scale=pixel_scale, renormalize=renormalize_psf)
background_sky_map = load_background_sky_map(background_sky_map_path=background_sky_map_path,
background_sky_map_hdu=background_sky_map_hdu,
pixel_scale=pixel_scale)
image = CCDData(image=image, pixel_scale=pixel_scale, psf=psf, noise_map=noise_map,
background_noise_map=background_noise_map, poisson_noise_map=poisson_noise_map,
exposure_time_map=exposure_time_map, background_sky_map=background_sky_map, gain=gain,
name=lens_name)
if resized_ccd_shape is not None:
image = image.new_ccd_data_with_resized_arrays(new_shape=resized_ccd_shape,
new_centre_pixels=resized_ccd_origin_pixels,
new_centre_arcsec=resized_ccd_origin_arcsec)
if resized_psf_shape is not None:
image = image.new_ccd_data_with_resized_psf(new_shape=resized_psf_shape)
if convert_from_electrons:
image = image.new_ccd_data_converted_from_electrons()
elif convert_from_adus:
image = image.new_ccd_data_converted_from_adus(gain=gain)
return image
|
def load_image(image_path, image_hdu, pixel_scale):
"""Factory for loading the image from a .fits file
Parameters
----------
image_path : str
The path to the image .fits file containing the image (e.g. '/path/to/image.fits')
image_hdu : int
The hdu the image is contained in the .fits file specified by *image_path*.
pixel_scale : float
The size of each pixel in arc seconds..
"""
return ScaledSquarePixelArray.from_fits_with_pixel_scale(file_path=image_path, hdu=image_hdu,
pixel_scale=pixel_scale)
|
def load_noise_map(noise_map_path, noise_map_hdu, pixel_scale, image, background_noise_map, exposure_time_map,
convert_noise_map_from_weight_map, convert_noise_map_from_inverse_noise_map,
noise_map_from_image_and_background_noise_map, convert_from_electrons, gain, convert_from_adus):
"""Factory for loading the noise-map from a .fits file.
This factory also includes a number of routines for converting the noise-map from from other units (e.g. \
a weight map) or computing the noise-map from other unblurred_image_1d (e.g. the ccd image and background noise-map).
Parameters
----------
noise_map_path : str
The path to the noise_map .fits file containing the noise_map (e.g. '/path/to/noise_map.fits')
noise_map_hdu : int
The hdu the noise_map is contained in the .fits file specified by *noise_map_path*.
pixel_scale : float
The size of each pixel in arc seconds.
image : ndarray
The image-image, which the noise-map can be calculated using.
background_noise_map : ndarray
The background noise-map, which the noise-map can be calculated using.
exposure_time_map : ndarray
The exposure-time map, which the noise-map can be calculated using.
convert_noise_map_from_weight_map : bool
If True, the noise-map loaded from the .fits file is converted from a weight-map to a noise-map (see \
*NoiseMap.from_weight_map).
convert_noise_map_from_inverse_noise_map : bool
If True, the noise-map loaded from the .fits file is converted from an inverse noise-map to a noise-map (see \
*NoiseMap.from_inverse_noise_map).
background_noise_map_path : str
The path and filename of the .fits image containing the background noise-map.
background_noise_map_hdu : int
The hdu the background noise-map is contained in the .fits file that *background_noise_map_path* points too.
convert_background_noise_map_from_weight_map : bool
If True, the bacground noise-map loaded from the .fits file is converted from a weight-map to a noise-map (see \
*NoiseMap.from_weight_map).
convert_background_noise_map_from_inverse_noise_map : bool
If True, the background noise-map loaded from the .fits file is converted from an inverse noise-map to a \
noise-map (see *NoiseMap.from_inverse_noise_map).
noise_map_from_image_and_background_noise_map : bool
If True, the noise-map is computed from the observed image and background noise-map \
(see NoiseMap.from_image_and_background_noise_map).
convert_from_electrons : bool
If True, the input unblurred_image_1d are in units of electrons and all converted to electrons / second using the exposure \
time map.
gain : float
The image gain, used for convert from ADUs.
convert_from_adus : bool
If True, the input unblurred_image_1d are in units of adus and all converted to electrons / second using the exposure \
time map and gain.
"""
noise_map_options = sum([convert_noise_map_from_weight_map,
convert_noise_map_from_inverse_noise_map,
noise_map_from_image_and_background_noise_map])
if noise_map_options > 1:
raise exc.DataException('You have specified more than one method to load the noise_map map, e.g.:'
'convert_noise_map_from_weight_map | '
'convert_noise_map_from_inverse_noise_map |'
'noise_map_from_image_and_background_noise_map')
if noise_map_options == 0 and noise_map_path is not None:
return NoiseMap.from_fits_with_pixel_scale(file_path=noise_map_path, hdu=noise_map_hdu, pixel_scale=pixel_scale)
elif convert_noise_map_from_weight_map and noise_map_path is not None:
weight_map = Array.from_fits(file_path=noise_map_path, hdu=noise_map_hdu)
return NoiseMap.from_weight_map(weight_map=weight_map, pixel_scale=pixel_scale)
elif convert_noise_map_from_inverse_noise_map and noise_map_path is not None:
inverse_noise_map = Array.from_fits(file_path=noise_map_path, hdu=noise_map_hdu)
return NoiseMap.from_inverse_noise_map(inverse_noise_map=inverse_noise_map, pixel_scale=pixel_scale)
elif noise_map_from_image_and_background_noise_map:
if background_noise_map is None:
raise exc.DataException('Cannot compute the noise-map from the image and background noise_map map if a '
'background noise_map map is not supplied.')
if not (convert_from_electrons or convert_from_adus) and exposure_time_map is None:
raise exc.DataException('Cannot compute the noise-map from the image and background noise_map map if an '
'exposure-time (or exposure time map) is not supplied to convert to adus')
if convert_from_adus and gain is None:
raise exc.DataException('Cannot compute the noise-map from the image and background noise_map map if a'
'gain is not supplied to convert from adus')
return NoiseMap.from_image_and_background_noise_map(pixel_scale=pixel_scale, image=image,
background_noise_map=background_noise_map,
exposure_time_map=exposure_time_map,
convert_from_electrons=convert_from_electrons,
gain=gain, convert_from_adus=convert_from_adus)
else:
raise exc.DataException(
'A noise_map map was not loaded, specify a noise_map_path or option to compute a noise_map map.')
|
def load_background_noise_map(background_noise_map_path, background_noise_map_hdu, pixel_scale,
convert_background_noise_map_from_weight_map,
convert_background_noise_map_from_inverse_noise_map):
"""Factory for loading the background noise-map from a .fits file.
This factory also includes a number of routines for converting the background noise-map from from other units (e.g. \
a weight map).
Parameters
----------
background_noise_map_path : str
The path to the background_noise_map .fits file containing the background noise-map \
(e.g. '/path/to/background_noise_map.fits')
background_noise_map_hdu : int
The hdu the background_noise_map is contained in the .fits file specified by *background_noise_map_path*.
pixel_scale : float
The size of each pixel in arc seconds.
convert_background_noise_map_from_weight_map : bool
If True, the bacground noise-map loaded from the .fits file is converted from a weight-map to a noise-map (see \
*NoiseMap.from_weight_map).
convert_background_noise_map_from_inverse_noise_map : bool
If True, the background noise-map loaded from the .fits file is converted from an inverse noise-map to a \
noise-map (see *NoiseMap.from_inverse_noise_map).
"""
background_noise_map_options = sum([convert_background_noise_map_from_weight_map,
convert_background_noise_map_from_inverse_noise_map])
if background_noise_map_options == 0 and background_noise_map_path is not None:
return NoiseMap.from_fits_with_pixel_scale(file_path=background_noise_map_path, hdu=background_noise_map_hdu,
pixel_scale=pixel_scale)
elif convert_background_noise_map_from_weight_map and background_noise_map_path is not None:
weight_map = Array.from_fits(file_path=background_noise_map_path, hdu=background_noise_map_hdu)
return NoiseMap.from_weight_map(weight_map=weight_map, pixel_scale=pixel_scale)
elif convert_background_noise_map_from_inverse_noise_map and background_noise_map_path is not None:
inverse_noise_map = Array.from_fits(file_path=background_noise_map_path, hdu=background_noise_map_hdu)
return NoiseMap.from_inverse_noise_map(inverse_noise_map=inverse_noise_map, pixel_scale=pixel_scale)
else:
return None
|
def load_poisson_noise_map(poisson_noise_map_path, poisson_noise_map_hdu, pixel_scale,
convert_poisson_noise_map_from_weight_map,
convert_poisson_noise_map_from_inverse_noise_map,
poisson_noise_map_from_image,
image, exposure_time_map, convert_from_electrons, gain, convert_from_adus):
"""Factory for loading the Poisson noise-map from a .fits file.
This factory also includes a number of routines for converting the Poisson noise-map from from other units (e.g. \
a weight map) or computing the Poisson noise_map from other unblurred_image_1d (e.g. the ccd image).
Parameters
----------
poisson_noise_map_path : str
The path to the poisson_noise_map .fits file containing the Poisson noise-map \
(e.g. '/path/to/poisson_noise_map.fits')
poisson_noise_map_hdu : int
The hdu the poisson_noise_map is contained in the .fits file specified by *poisson_noise_map_path*.
pixel_scale : float
The size of each pixel in arc seconds.
convert_poisson_noise_map_from_weight_map : bool
If True, the Poisson noise-map loaded from the .fits file is converted from a weight-map to a noise-map (see \
*NoiseMap.from_weight_map).
convert_poisson_noise_map_from_inverse_noise_map : bool
If True, the Poisson noise-map loaded from the .fits file is converted from an inverse noise-map to a \
noise-map (see *NoiseMap.from_inverse_noise_map).
poisson_noise_map_from_image : bool
If True, the Poisson noise-map is estimated using the image.
image : ndarray
The image, which the Poisson noise-map can be calculated using.
background_noise_map : ndarray
The background noise-map, which the Poisson noise-map can be calculated using.
exposure_time_map : ndarray
The exposure-time map, which the Poisson noise-map can be calculated using.
convert_from_electrons : bool
If True, the input unblurred_image_1d are in units of electrons and all converted to electrons / second using the exposure \
time map.
gain : float
The image gain, used for convert from ADUs.
convert_from_adus : bool
If True, the input unblurred_image_1d are in units of adus and all converted to electrons / second using the exposure \
time map and gain.
"""
poisson_noise_map_options = sum([convert_poisson_noise_map_from_weight_map,
convert_poisson_noise_map_from_inverse_noise_map,
poisson_noise_map_from_image])
if poisson_noise_map_options == 0 and poisson_noise_map_path is not None:
return PoissonNoiseMap.from_fits_with_pixel_scale(file_path=poisson_noise_map_path, hdu=poisson_noise_map_hdu,
pixel_scale=pixel_scale)
elif poisson_noise_map_from_image:
if not (convert_from_electrons or convert_from_adus) and exposure_time_map is None:
raise exc.DataException('Cannot compute the Poisson noise-map from the image if an '
'exposure-time (or exposure time map) is not supplied to convert to adus')
if convert_from_adus and gain is None:
raise exc.DataException('Cannot compute the Poisson noise-map from the image if a'
'gain is not supplied to convert from adus')
return PoissonNoiseMap.from_image_and_exposure_time_map(pixel_scale=pixel_scale, image=image,
exposure_time_map=exposure_time_map,
convert_from_electrons=convert_from_electrons,
gain=gain,
convert_from_adus=convert_from_adus)
elif convert_poisson_noise_map_from_weight_map and poisson_noise_map_path is not None:
weight_map = Array.from_fits(file_path=poisson_noise_map_path, hdu=poisson_noise_map_hdu)
return PoissonNoiseMap.from_weight_map(weight_map=weight_map, pixel_scale=pixel_scale)
elif convert_poisson_noise_map_from_inverse_noise_map and poisson_noise_map_path is not None:
inverse_noise_map = Array.from_fits(file_path=poisson_noise_map_path, hdu=poisson_noise_map_hdu)
return PoissonNoiseMap.from_inverse_noise_map(inverse_noise_map=inverse_noise_map, pixel_scale=pixel_scale)
else:
return None
|
def load_psf(psf_path, psf_hdu, pixel_scale, renormalize=False):
"""Factory for loading the psf from a .fits file.
Parameters
----------
psf_path : str
The path to the psf .fits file containing the psf (e.g. '/path/to/psf.fits')
psf_hdu : int
The hdu the psf is contained in the .fits file specified by *psf_path*.
pixel_scale : float
The size of each pixel in arc seconds.
renormalize : bool
If True, the PSF is renoralized such that all elements sum to 1.0.
"""
if renormalize:
return PSF.from_fits_renormalized(file_path=psf_path, hdu=psf_hdu, pixel_scale=pixel_scale)
if not renormalize:
return PSF.from_fits_with_scale(file_path=psf_path, hdu=psf_hdu, pixel_scale=pixel_scale)
|
def load_exposure_time_map(exposure_time_map_path, exposure_time_map_hdu, pixel_scale, shape, exposure_time,
exposure_time_map_from_inverse_noise_map, inverse_noise_map):
"""Factory for loading the exposure time map from a .fits file.
This factory also includes a number of routines for computing the exposure-time map from other unblurred_image_1d \
(e.g. the background noise-map).
Parameters
----------
exposure_time_map_path : str
The path to the exposure_time_map .fits file containing the exposure time map \
(e.g. '/path/to/exposure_time_map.fits')
exposure_time_map_hdu : int
The hdu the exposure_time_map is contained in the .fits file specified by *exposure_time_map_path*.
pixel_scale : float
The size of each pixel in arc seconds.
shape : (int, int)
The shape of the image, required if a single value is used to calculate the exposure time map.
exposure_time : float
The exposure-time used to compute the expsure-time map if only a single value is used.
exposure_time_map_from_inverse_noise_map : bool
If True, the exposure-time map is computed from the background noise_map map \
(see *ExposureTimeMap.from_background_noise_map*)
inverse_noise_map : ndarray
The background noise-map, which the Poisson noise-map can be calculated using.
"""
exposure_time_map_options = sum([exposure_time_map_from_inverse_noise_map])
if exposure_time is not None and exposure_time_map_path is not None:
raise exc.DataException(
'You have supplied both a exposure_time_map_path to an exposure time map and an exposure time. Only'
'one quantity should be supplied.')
if exposure_time_map_options == 0:
if exposure_time is not None and exposure_time_map_path is None:
return ExposureTimeMap.single_value(value=exposure_time, pixel_scale=pixel_scale, shape=shape)
elif exposure_time is None and exposure_time_map_path is not None:
return ExposureTimeMap.from_fits_with_pixel_scale(file_path=exposure_time_map_path,
hdu=exposure_time_map_hdu, pixel_scale=pixel_scale)
else:
if exposure_time_map_from_inverse_noise_map:
return ExposureTimeMap.from_exposure_time_and_inverse_noise_map(pixel_scale=pixel_scale,
exposure_time=exposure_time,
inverse_noise_map=inverse_noise_map)
|
def load_background_sky_map(background_sky_map_path, background_sky_map_hdu, pixel_scale):
"""Factory for loading the background sky from a .fits file.
Parameters
----------
background_sky_map_path : str
The path to the background_sky_map .fits file containing the background sky map \
(e.g. '/path/to/background_sky_map.fits').
background_sky_map_hdu : int
The hdu the background_sky_map is contained in the .fits file specified by *background_sky_map_path*.
pixel_scale : float
The size of each pixel in arc seconds.
"""
if background_sky_map_path is not None:
return ScaledSquarePixelArray.from_fits_with_pixel_scale(file_path=background_sky_map_path,
hdu=background_sky_map_hdu, pixel_scale=pixel_scale)
else:
return None
|
def load_positions(positions_path):
"""Load the positions of an image.
Positions correspond to a set of pixels in the lensed source galaxy that are anticipated to come from the same \
multiply-imaged region of the source-plane. Mass models which do not trace the pixels within a threshold value of \
one another are resampled during the non-linear search.
Positions are stored in a .dat file, where each line of the file gives a list of list of (y,x) positions which \
correspond to the same region of the source-plane. Thus, multiple source-plane regions can be input over multiple \
lines of the same positions file.
Parameters
----------
positions_path : str
The path to the positions .dat file containing the positions (e.g. '/path/to/positions.dat')
"""
with open(positions_path) as f:
position_string = f.readlines()
positions = []
for line in position_string:
position_list = ast.literal_eval(line)
positions.append(position_list)
return positions
|
def output_positions(positions, positions_path):
"""Output the positions of an image to a positions.dat file.
Positions correspond to a set of pixels in the lensed source galaxy that are anticipated to come from the same \
multiply-imaged region of the source-plane. Mass models which do not trace the pixels within a threshold value of \
one another are resampled during the non-linear search.
Positions are stored in a .dat file, where each line of the file gives a list of list of (y,x) positions which \
correspond to the same region of the source-plane. Thus, multiple source-plane regions can be input over multiple \
lines of the same positions file.
Parameters
----------
positions : [[[]]]
The lists of positions (e.g. [[[1.0, 1.0], [2.0, 2.0]], [[3.0, 3.0], [4.0, 4.0]]])
positions_path : str
The path to the positions .dat file containing the positions (e.g. '/path/to/positions.dat')
"""
with open(positions_path, 'w') as f:
for position in positions:
f.write("%s\n" % position)
|
def simulate_variable_arrays(cls, array, pixel_scale, exposure_time_map, psf=None, background_sky_map=None,
add_noise=True, noise_if_add_noise_false=0.1, noise_seed=-1, name=None):
"""
Create a realistic simulated image by applying effects to a plain simulated image.
Parameters
----------
name
array : ndarray
The image before simulating (e.g. the lens and source galaxies before optics blurring and CCD read-out).
pixel_scale: float
The scale of each pixel in arc seconds
exposure_time_map : ndarray
An array representing the effective exposure time of each pixel.
psf: PSF
An array describing the PSF the simulated image is blurred with.
background_sky_map : ndarray
The value of background sky in every image pixel (electrons per second).
add_noise: Bool
If True poisson noise_maps is simulated and added to the image, based on the total counts in each image
pixel
noise_seed: int
A seed for random noise_maps generation
"""
if background_sky_map is not None:
array += background_sky_map
if psf is not None:
array = psf.convolve(array)
array = cls.trim_psf_edges(array, psf)
exposure_time_map = cls.trim_psf_edges(exposure_time_map, psf)
if background_sky_map is not None:
background_sky_map = cls.trim_psf_edges(background_sky_map, psf)
if add_noise is True:
array += generate_poisson_noise(array, exposure_time_map, noise_seed)
array_counts = np.multiply(array, exposure_time_map)
noise_map = np.divide(np.sqrt(array_counts), exposure_time_map)
else:
noise_map = noise_if_add_noise_false * np.ones(array.shape)
if np.isnan(noise_map).any():
raise exc.DataException('The noise-map has NaN values in it. This suggests your exposure time and / or'
'background sky levels are too low, create signal counts at or close to 0.0.')
if background_sky_map is not None:
array -= background_sky_map
# ESTIMATE THE BACKGROUND NOISE MAP FROM THE IMAGE
if background_sky_map is not None:
background_noise_map_counts = np.sqrt(np.multiply(background_sky_map, exposure_time_map))
background_noise_map = np.divide(background_noise_map_counts, exposure_time_map)
else:
background_noise_map = None
# ESTIMATE THE POISSON NOISE MAP FROM THE IMAGE
array_counts = np.multiply(array, exposure_time_map)
poisson_noise_map = np.divide(np.sqrt(np.abs(array_counts)), exposure_time_map)
array = ScaledSquarePixelArray(array=array, pixel_scale=pixel_scale)
noise_map = NoiseMap(array=noise_map, pixel_scale=pixel_scale)
if background_noise_map is not None:
background_noise_map = NoiseMap(array=background_noise_map, pixel_scale=pixel_scale)
if poisson_noise_map is not None:
poisson_noise_map = PoissonNoiseMap(array=poisson_noise_map, pixel_scale=pixel_scale)
return CCDData(array, pixel_scale=pixel_scale, psf=psf, noise_map=noise_map,
background_noise_map=background_noise_map, poisson_noise_map=poisson_noise_map,
exposure_time_map=exposure_time_map, background_sky_map=background_sky_map, name=name)
|
def simulate_to_target_signal_to_noise(cls, array, pixel_scale, target_signal_to_noise, exposure_time_map,
psf=None, background_sky_map=None, seed=-1):
"""
Create a realistic simulated image by applying effects to a plain simulated image.
Parameters
----------
target_signal_to_noise
array : ndarray
The image before simulating (e.g. the lens and source galaxies before optics blurring and CCD read-out).
pixel_scale: float
The scale of each pixel in arc seconds
exposure_time_map : ndarray
An array representing the effective exposure time of each pixel.
psf: PSF
An array describing the PSF the simulated image is blurred with.
background_sky_map : ndarray
The value of background sky in every image pixel (electrons per second).
seed: int
A seed for random noise_maps generation
"""
max_index = np.unravel_index(array.argmax(), array.shape)
max_image = array[max_index]
max_effective_exposure_time = exposure_time_map[max_index]
max_array_counts = np.multiply(max_image, max_effective_exposure_time)
if background_sky_map is not None:
max_background_sky_map = background_sky_map[max_index]
max_background_sky_map_counts = np.multiply(max_background_sky_map, max_effective_exposure_time)
else:
max_background_sky_map_counts = None
scale_factor = 1.
if background_sky_map is None:
scale_factor = target_signal_to_noise ** 2.0 / max_array_counts
elif background_sky_map is not None:
scale_factor = (max_array_counts + max_background_sky_map_counts) * target_signal_to_noise ** 2.0 \
/ max_array_counts ** 2.0
scaled_effective_exposure_time = np.multiply(scale_factor, exposure_time_map)
return cls.simulate_variable_arrays(array=array, pixel_scale=pixel_scale,
exposure_time_map=scaled_effective_exposure_time,
psf=psf, background_sky_map=background_sky_map,
add_noise=True, noise_seed=seed)
|
def signal_to_noise_map(self):
"""The estimated signal-to-noise_maps mappers of the image."""
signal_to_noise_map = np.divide(self.image, self.noise_map)
signal_to_noise_map[signal_to_noise_map < 0] = 0
return signal_to_noise_map
|
def absolute_signal_to_noise_map(self):
"""The estimated absolute_signal-to-noise_maps mappers of the image."""
return np.divide(np.abs(self.image), self.noise_map)
|
def array_from_adus_to_electrons_per_second(self, array, gain):
"""
For an array (in counts) and an exposure time mappers, convert the array to units electrons per second
Parameters
----------
array : ndarray
The array the values are to be converted from counts to electrons per second.
"""
if array is not None:
return np.divide(gain * array, self.exposure_time_map)
else:
return None
|
def estimated_noise_map_counts(self):
""" The estimated noise_maps mappers of the image (using its background noise_maps mappers and image values
in counts) in counts.
"""
return np.sqrt((np.abs(self.image_counts) + np.square(self.background_noise_map_counts)))
|
def background_noise_from_edges(self, no_edges):
"""Estimate the background signal_to_noise_ratio by binning data_to_image located at the edge(s) of an image
into a histogram and fitting a Gaussian profiles to this histogram. The standard deviation (sigma) of this
Gaussian gives a signal_to_noise_ratio estimate.
Parameters
----------
no_edges : int
Number of edges used to estimate the background signal_to_noise_ratio.
"""
edges = []
for edge_no in range(no_edges):
top_edge = self.image[edge_no, edge_no:self.image.shape[1] - edge_no]
bottom_edge = self.image[self.image.shape[0] - 1 - edge_no, edge_no:self.image.shape[1] - edge_no]
left_edge = self.image[edge_no + 1:self.image.shape[0] - 1 - edge_no, edge_no]
right_edge = self.image[edge_no + 1:self.image.shape[0] - 1 - edge_no, self.image.shape[1] - 1 - edge_no]
edges = np.concatenate((edges, top_edge, bottom_edge, right_edge, left_edge))
return norm.fit(edges)[1]
|
def from_weight_map(cls, pixel_scale, weight_map):
"""Setup the noise-map from a weight map, which is a form of noise-map that comes via HST image-reduction and \
the software package MultiDrizzle.
The variance in each pixel is computed as:
Variance = 1.0 / sqrt(weight_map).
The weight map may contain zeros, in which cause the variances are converted to large values to omit them from \
the analysis.
Parameters
-----------
pixel_scale : float
The size of each pixel in arc seconds.
weight_map : ndarray
The weight-value of each pixel which is converted to a variance.
"""
np.seterr(divide='ignore')
noise_map = 1.0 / np.sqrt(weight_map)
noise_map[noise_map == np.inf] = 1.0e8
return NoiseMap(array=noise_map, pixel_scale=pixel_scale)
|
def from_inverse_noise_map(cls, pixel_scale, inverse_noise_map):
"""Setup the noise-map from an root-mean square standard deviation map, which is a form of noise-map that \
comes via HST image-reduction and the software package MultiDrizzle.
The variance in each pixel is computed as:
Variance = 1.0 / inverse_std_map.
The weight map may contain zeros, in which cause the variances are converted to large values to omit them from \
the analysis.
Parameters
-----------
pixel_scale : float
The size of each pixel in arc seconds.
inverse_noise_map : ndarray
The inverse noise_map value of each pixel which is converted to a variance.
"""
noise_map = 1.0 / inverse_noise_map
return NoiseMap(array=noise_map, pixel_scale=pixel_scale)
|
def simulate_as_gaussian(cls, shape, pixel_scale, sigma, centre=(0.0, 0.0), axis_ratio=1.0, phi=0.0):
"""Simulate the PSF as an elliptical Gaussian profile."""
from autolens.model.profiles.light_profiles import EllipticalGaussian
gaussian = EllipticalGaussian(centre=centre, axis_ratio=axis_ratio, phi=phi, intensity=1.0, sigma=sigma)
grid_1d = grid_util.regular_grid_1d_masked_from_mask_pixel_scales_and_origin(mask=np.full(shape, False),
pixel_scales=(
pixel_scale, pixel_scale))
gaussian_1d = gaussian.intensities_from_grid(grid=grid_1d)
gaussian_2d = mapping_util.map_unmasked_1d_array_to_2d_array_from_array_1d_and_shape(array_1d=gaussian_1d,
shape=shape)
return PSF(array=gaussian_2d, pixel_scale=pixel_scale, renormalize=True)
|
def from_fits_renormalized(cls, file_path, hdu, pixel_scale):
"""Loads a PSF from fits and renormalizes it
Parameters
----------
pixel_scale
file_path: String
The path to the file containing the PSF
hdu : int
The HDU the PSF is stored in the .fits file.
Returns
-------
psf: PSF
A renormalized PSF instance
"""
psf = PSF.from_fits_with_scale(file_path, hdu, pixel_scale)
psf[:, :] = np.divide(psf, np.sum(psf))
return psf
|
def from_fits_with_scale(cls, file_path, hdu, pixel_scale):
"""
Loads the PSF from a .fits file.
Parameters
----------
pixel_scale
file_path: String
The path to the file containing the PSF
hdu : int
The HDU the PSF is stored in the .fits file.
"""
return cls(array=array_util.numpy_array_2d_from_fits(file_path, hdu), pixel_scale=pixel_scale)
|
def new_psf_with_renormalized_array(self):
"""Renormalize the PSF such that its data_vector values sum to unity."""
return PSF(array=self, pixel_scale=self.pixel_scale, renormalize=True)
|
def convolve(self, array):
"""
Convolve an array with this PSF
Parameters
----------
image : ndarray
An array representing the image the PSF is convolved with.
Returns
-------
convolved_image : ndarray
An array representing the image after convolution.
Raises
------
KernelException if either PSF psf dimension is odd
"""
if self.shape[0] % 2 == 0 or self.shape[1] % 2 == 0:
raise exc.KernelException("PSF Kernel must be odd")
return scipy.signal.convolve2d(array, self, mode='same')
|
def setup_image_plane_pixelization_grid_from_galaxies_and_grid_stack(galaxies, grid_stack):
"""An image-plane pixelization is one where its pixel centres are computed by tracing a sparse grid of pixels from \
the image's regular grid to other planes (e.g. the source-plane).
Provided a galaxy has an image-plane pixelization, this function returns a new *GridStack* instance where the \
image-plane pixelization's sparse grid is added to it as an attibute.
Thus, when the *GridStack* are are passed to the *ray_tracing* module this sparse grid is also traced and the \
traced coordinates represent the centre of each pixelization pixel.
Parameters
-----------
galaxies : [model.galaxy.galaxy.Galaxy]
A list of galaxies, which may contain pixelizations and an *ImagePlanePixelization*.
grid_stacks : image.array.grid_stacks.GridStack
The collection of grid_stacks (regular, sub, etc.) which the image-plane pixelization grid (referred to as pix) \
may be added to.
"""
if not isinstance(grid_stack.regular, grids.PaddedRegularGrid):
for galaxy in galaxies:
if hasattr(galaxy, 'pixelization'):
if isinstance(galaxy.pixelization, ImagePlanePixelization):
image_plane_pix_grid = galaxy.pixelization.image_plane_pix_grid_from_regular_grid(
regular_grid=grid_stack.regular)
return grid_stack.new_grid_stack_with_pix_grid_added(pix_grid=image_plane_pix_grid.sparse_grid,
regular_to_nearest_pix=image_plane_pix_grid.regular_to_sparse)
return grid_stack
|
def image_plane_pix_grid_from_regular_grid(self, regular_grid):
"""Calculate the image-plane pixelization from a regular-grid of coordinates (and its mask).
See *grid_stacks.SparseToRegularGrid* for details on how this grid is calculated.
Parameters
-----------
regular_grid : grids.RegularGrid
The grid of (y,x) arc-second coordinates at the centre of every image value (e.g. image-pixels).
"""
pixel_scale = regular_grid.mask.pixel_scale
pixel_scales = ((regular_grid.masked_shape_arcsec[0] + pixel_scale) / (self.shape[0]),
(regular_grid.masked_shape_arcsec[1] + pixel_scale) / (self.shape[1]))
return grids.SparseToRegularGrid(unmasked_sparse_grid_shape=self.shape, pixel_scales=pixel_scales,
regular_grid=regular_grid, origin=regular_grid.mask.centre)
|
def geometry_from_grid(self, grid, buffer=1e-8):
"""Determine the geometry of the rectangular grid, by overlaying it over a grid of coordinates such that its \
outer-most pixels align with the grid's outer most coordinates plus a small buffer.
Parameters
-----------
grid : ndarray
The (y,x) grid of coordinates over which the rectangular pixelization is placed to determine its geometry.
buffer : float
The size the pixelization is buffered relative to the grid.
"""
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
pixel_scales = (float((y_max - y_min) / self.shape[0]), float((x_max - x_min) / self.shape[1]))
origin = ((y_max + y_min) / 2.0, (x_max + x_min) / 2.0)
pixel_neighbors, pixel_neighbors_size = self.neighbors_from_pixelization()
return self.Geometry(shape=self.shape, pixel_scales=pixel_scales, origin=origin,
pixel_neighbors=pixel_neighbors, pixel_neighbors_size=pixel_neighbors_size)
|
def mapper_from_grid_stack_and_border(self, grid_stack, border):
"""Setup a rectangular mapper from a rectangular pixelization, as follows:
1) If a border is supplied, relocate all of the grid-stack's regular and sub grid pixels beyond the border.
2) Determine the rectangular pixelization's geometry, by laying the pixelization over the sub-grid.
3) Setup the rectangular mapper from the relocated grid-stack and rectangular pixelization.
Parameters
----------
grid_stack : grids.GridStack
A stack of grid describing the observed image's pixel coordinates (e.g. an image-grid, sub-grid, etc.).
border : grids.RegularGridBorder | None
The border of the grid-stack's regular-grid.
"""
if border is not None:
relocated_grid_stack = border.relocated_grid_stack_from_grid_stack(grid_stack)
else:
relocated_grid_stack = grid_stack
geometry = self.geometry_from_grid(grid=relocated_grid_stack.sub)
return mappers.RectangularMapper(pixels=self.pixels, grid_stack=relocated_grid_stack, border=border,
shape=self.shape, geometry=geometry)
|
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.
"""
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)
|
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.
"""
return scipy.spatial.Voronoi(np.asarray([pixel_centers[:, 1], pixel_centers[:, 0]]).T,
qhull_options='Qbb Qc Qx Qm')
|
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).
"""
return pixelization_util.voronoi_neighbors_from_pixels_and_ridge_points(pixels=pixels,
ridge_points=np.asarray(ridge_points))
|
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).
"""
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)
|
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.
"""
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)
|
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.
"""
if units in 'arcsec' or kpc_per_arcsec is None:
return grid_arcsec
elif units in 'kpc':
return grid_arcsec * kpc_per_arcsec
|
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.
"""
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)
|
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.
"""
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)
|
def sub_to_image_grid(func):
"""
Wrap the function in a function that, if the grid is a sub-grid (grids.SubGrid), rebins the computed \
values to the sub-grids corresponding regular-grid by taking the mean of each set of sub-gridded values.
Parameters
----------
func : (profiles, *args, **kwargs) -> Object
A function that requires the sub-grid and galaxies.
"""
@wraps(func)
def wrapper(grid, galaxies, *args, **kwargs):
"""
Parameters
----------
grid : RegularGrid
The (y,x) coordinates of the grid, in an array of shape (total_coordinates, 2).
galaxies : [Galaxy]
The list of galaxies a profile quantity (e.g. intensities) is computed for which is rebinned if it \
is a sub-grid.
Returns
-------
ndarray
If a RegularGrid is input, the profile quantity of the galaxy (e.g. intensities) evaluated using this grid.
If a SubGrid is input, the profile quantity of the galaxy (e.g. intensities) evaluated using the sub-grid \
and rebinned to the regular-grids array dimensions.
Examples
---------
@grids.sub_to_image_grid
def intensities_of_galaxies_from_grid(grid, galaxies):
return sum(map(lambda g: g.intensities_from_grid(grid), galaxies))
galaxy_util.intensities_of_galaxies_from_grid(grid=grid_stack.sub, galaxies=galaxies)
"""
result = func(grid, galaxies, *args, *kwargs)
if isinstance(grid, SubGrid):
return grid.regular_data_1d_from_sub_data_1d(result)
else:
return result
return wrapper
|
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
"""
@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
|
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.
"""
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)
|
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.
"""
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)
|
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).
"""
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)
|
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.
"""
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]]))
|
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).
"""
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)
|
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.
"""
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)
|
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."""
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)
|
def map_function(self, func, *arg_lists):
"""Map a function to all grid_stack in a grid-stack"""
return GridStack(*[func(*args) for args in zip(self, *arg_lists)])
|
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.
"""
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))
|
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.
"""
array = grid_util.regular_grid_1d_masked_from_mask_pixel_scales_and_origin(mask=mask,
pixel_scales=mask.pixel_scales)
return cls(array, mask)
|
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.
"""
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)
|
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|
"""
blurring_mask = mask.blurring_mask_for_psf_shape(psf_shape)
return RegularGrid.from_mask(blurring_mask)
|
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.
"""
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)
|
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.
"""
return scaled_array.ScaledSquarePixelArray(array=self.array_2d_from_array_1d(array_1d),
pixel_scale=self.mask.pixel_scale,
origin=self.mask.origin)
|
def yticks(self):
"""Compute the yticks labels of this grid, used for plotting the y-axis ticks when visualizing a regular"""
return np.linspace(np.min(self[:, 0]), np.max(self[:, 0]), 4)
|
def xticks(self):
"""Compute the xticks labels of this grid, used for plotting the x-axis ticks when visualizing a regular"""
return np.linspace(np.min(self[:, 1]), np.max(self[:, 1]), 4)
|
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.
"""
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)
|
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.
"""
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)
|
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.
"""
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)
|
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.
"""
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)
|
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.
"""
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)
|
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.
"""
return np.multiply(self.sub_grid_fraction, sub_array_1d.reshape(-1, self.sub_grid_length).sum(axis=1))
|
def unmasked_sparse_to_sparse(self):
"""The 1D index mappings between the unmasked sparse-grid and masked sparse grid."""
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')
|
def sparse_to_unmasked_sparse(self):
"""The 1D index mappings between the masked sparse-grid and unmasked sparse grid."""
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')
|
def regular_to_sparse(self):
"""The 1D index mappings between the regular-grid and masked sparse-grid."""
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')
|
def sparse_grid(self):
"""The (y,x) arc-second coordinates of the masked sparse-grid."""
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)
|
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
"""
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)
|
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.
"""
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)
|
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*.
"""
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])
|
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*.
"""
return mapping_util.map_unmasked_1d_array_to_2d_array_from_array_1d_and_shape(array_1d=padded_array_1d,
shape=self.mask.shape)
|
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.
"""
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)
|
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.
"""
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))
|
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).
"""
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
|
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
"""
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
|
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.
"""
analysis = self.make_analysis(positions=positions, pixel_scale=pixel_scale, results=results)
result = self.run_analysis(analysis)
return self.make_result(result, analysis)
|
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
"""
self.pass_priors(results)
analysis = self.__class__.Analysis(positions=positions, pixel_scale=pixel_scale, cosmology=self.cosmology,
results=results)
return analysis
|
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.
"""
analysis = self.make_analysis(data=data, results=results, mask=mask, positions=positions)
result = self.run_analysis(analysis)
return self.make_result(result, analysis)
|
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
"""
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
|
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.
"""
analysis = self.make_analysis(galaxy_data=galaxy_data, results=results, mask=mask)
result = self.run_analysis(analysis)
return self.make_result(result, analysis)
|
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
"""
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)
|
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
"""
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
|
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))
"""
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
|
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))
"""
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
|
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)
"""
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
|
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)
"""
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
|
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)
"""
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
|
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)
"""
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
|
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.
"""
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
|
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.
"""
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
|
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.
"""
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
|
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.
"""
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
|
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)
"""
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
|
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))
"""
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
|
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))
"""
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
|
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)
"""
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)
|
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)
"""
hdu_list = fits.open(file_path)
return np.flipud(np.array(hdu_list[hdu].data))
|
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.
"""
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)
|
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.
"""
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)
|
def check_tracer_for_light_profile(func):
"""If none of the tracer's galaxies have a light profile, it image-plane image cannot be computed. This wrapper \
makes this property return *None*.
Parameters
----------
func : (self) -> Object
A property function that requires galaxies to have a mass profile.
"""
@wraps(func)
def wrapper(self):
"""
Parameters
----------
self
Returns
-------
A value or coordinate in the same coordinate system as those passed in.
"""
if self.has_light_profile is True:
return func(self)
else:
return None
return wrapper
|
def check_tracer_for_mass_profile(func):
"""If none of the tracer's galaxies have a mass profile, it surface density, potential and deflections cannot \
be computed. This wrapper makes these properties return *None*.
Parameters
----------
func : (self) -> Object
A property function that requires galaxies to have a mass profile.
"""
@wraps(func)
def wrapper(self):
"""
Parameters
----------
self
Returns
-------
A value or coordinate in the same coordinate system as those passed in.
"""
if self.has_mass_profile is True:
return func(self)
else:
return None
return wrapper
|
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.
"""
# 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
|
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.
"""
return self.convolve_matrix_jit(mapping_matrix, self.image_frame_indexes,
self.image_frame_psfs, self.image_frame_lengths)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.