Source code for synthesizer.imaging.image

"""A module containing the definition of an image.

This module contains the definition of an image.

An image can be generated from particle based data with or without smoothing,
and from parametric data with smoothing defined by a morphology derived
density grid.

Example Usage:
        # Particle based case
        img = Image(resolution=0.1 * kpc, fov=1.0 * kpc)
        img.get_img(signal, coordinates * kpc, smoothing_lengths * kpc, kernel)

        # Parametric case
        img = Image(resolution=0.1 * kpc, fov=1.0 * kpc)
        img.get_img(signal, density_grid)
"""

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import Normalize
from scipy.ndimage import zoom
from unyt import arcsecond, kpc, unyt_array, unyt_quantity

from synthesizer import exceptions
from synthesizer.imaging.base_imaging import ImagingBase
from synthesizer.imaging.image_generators import (
    _generate_image_parametric_smoothed,
    _generate_image_particle_hist,
    _generate_image_particle_smoothed,
)
from synthesizer.synth_warnings import deprecated, warn
from synthesizer.units import accepts, unit_is_compatible
from synthesizer.utils import TableFormatter
from synthesizer.utils.operation_timers import timed


[docs] class Image(ImagingBase): """A class for generating images. This class is used to generate images from particle based data with or without smoothing, and from parametric data with smoothing defined by a morphology derived density grid. This can be used in isolation to generate singular images or generated by an ImageCollection to generate a collection of images in various filters. Attributes: resolution (unyt_quantity of float): The resolution of the image. fov (unyt_quantity of float): The field of view of the image. npix (tuple): The number of pixels in the image. arr (array_like, float): The array containing the image. units (unyt.Units): The units of the image. noise_arr (array_like, float): The noise array added to the image. weight_map (array_like, float): The weight map derived from the noise array. """ @timed("Image.__init__") def __init__( self, resolution, fov, img=None, ): """Create an image with the images metadata. Args: resolution (unyt_quantity of float): The resolution of the image. fov (unyt_quantity of float): The field of view of the image. If a single value is passed then the FOV is assumed to be square. img (unyt_array/array_like, float): The image array. Only used to attach an existing image array to an image instance. Mostly used internally when methods make a new image instance for self. """ # Instantiate the base class holding the geometry ImagingBase.__init__(self, resolution, fov) # Attribute to hold the image array itself self.arr = None # Attributes to hold the image units self.units = None # Attach an image if handed one if img is not None: self.arr = img.ndview if isinstance(img, unyt_array) else img self.units = img.units if isinstance(img, unyt_array) else None # Set up the noise array and weight map self.noise_arr = None self.weight_map = None
[docs] def cast(self, dtype): """Cast the image arrays to a new floating-point dtype in place. Casts the image array and, when present, the noise array and weight map. Arrays already at the requested dtype are left untouched. Args: dtype (np.dtype/type): The dtype to cast to. Returns: Image: This image (to allow chaining). """ dtype = np.dtype(dtype) if self.arr is not None and self.arr.dtype != dtype: self.arr = self.arr.astype(dtype) if self.noise_arr is not None and self.noise_arr.dtype != dtype: self.noise_arr = self.noise_arr.astype(dtype) if self.weight_map is not None and self.weight_map.dtype != dtype: self.weight_map = self.weight_map.astype(dtype) return self
@property def img(self): """The image array with units.""" if self.arr is None: raise exceptions.MissingImage( "The image array hasn't been generated yet. Please run " "generate_img_hist() or generate_img_smoothed() before " "accessing the " "image." ) return self.arr * self.units if self.units is not None else self.arr @img.setter def img(self, value): """Set the image array and units.""" if isinstance(value, unyt_array): self.arr = value.value self.units = value.units else: self.arr = value self.units = None @property def shape(self): """Return the shape of the image. Returns: tuple The shape of the image. """ return self.npix
[docs] def resample(self, factor): """Resample the image by factor. If factor, or 1/factor for downsampling, is an integer, use flux-conserving integer resampling: downsampling is performed by summing pixel blocks, and supersampling is performed by uniformly splitting each pixel into subpixels. This preserves the total flux. Otherwise, for non-integer factors use a spline interpolation. Args: factor (float): The factor by which to resample the image, >1 increases resolution, <1 decreases resolution. """ # Resample the image. # NOTE: skimage.transform.pyramid_gaussian is more efficient but adds # another dependency. if self.arr is None: raise exceptions.MissingImage( "The image array hasn't been generated yet. Please run " "generate_img_hist() or generate_img_smoothed() before " "resampling." ) elif factor == 1: warn( "Resampling is unnecessary for resampling factor = 1. " "Ignoring resample request." ) return elif factor > 0 and np.isfinite(factor): # Resample the resoltion, this will also update the npix and fov # (if necessary) int_factor = int(round(factor)) inv_factor = int(round(1.0 / factor)) if np.isclose(factor, int_factor): # Replace each pixel with an int_factor x int_factor # block whose subpixels each contain 1 / int_factor**2 # of the original pixel value, preserving total flux. self.arr = ( np.repeat( np.repeat(self.arr, int_factor, axis=0), int_factor, axis=1, ) / int_factor**2 ) elif np.isclose(1.0 / factor, inv_factor): ny, nx = self.arr.shape if ny % inv_factor != 0 or nx % inv_factor != 0: # Image shape is not divisible by downsampling factor, # so use spline interpolation self.arr = zoom(self.arr, (factor, factor), order=3) else: # Group the image into non-overlapping # inv_factor x inv_factor blocks and sum each block into # one pixel, preserving total flux. self.arr = self.arr.reshape( ny // inv_factor, inv_factor, nx // inv_factor, inv_factor, ).sum(axis=(1, 3)) else: # Resample via spline interpolation self.arr = zoom(self.arr, (factor, factor), order=3) new_shape = self.arr.shape else: raise ValueError(f"Factor {factor} is not positive finite.") # Update pixel metadata self._resample_resolution(factor) # Handle the edge case where the conversion between resolutions has # messed with the FOV. if self.npix[0] != new_shape[0] or self.npix[1] != new_shape[1]: self.set_npix(new_shape)
[docs] def downsample(self, factor): """Downsample the image by a factor. Useful when returning from a temporarily supersampled image. Args: factor (float): The factor by which to resample the image. Values smaller than 1 reduce the image resolution. Raises: ValueError: If ``factor`` is greater than 1. """ # Keep the directional convenience API explicit so callers do not use # the downsampling helper to accidentally supersample images. if factor > 1: raise ValueError("Using downsample method to supersample!") # Delegate the actual image resampling to the canonical helper. self.resample(factor)
def __add__(self, other_img): """Add 2 Images together. Args: other_img (Image): The other image to be added. Returns: Image: The new image containing the added arrays. Raises: InconsistentArguments: If the images have different resolutions or fovs, or if the combination of units is incompatible an error is raised. """ # Ensure the images have the same resolution if not np.isclose(self.resolution, other_img.resolution): raise exceptions.InconsistentAddition( "The images must have the same resolution to be added " f"({self.resolution}, {other_img.resolution})." ) # Ensure the images have the same fov if np.any(self.fov != other_img.fov): raise exceptions.InconsistentAddition( "The images must have the same fov to be added " f"({self.fov}, {other_img.fov})." ) # Hanlde if units are involved or not if self.units is None and other_img.units is None: return Image( self.resolution, self.fov, img=self.arr + other_img.arr, ) elif self.units is not None and other_img.units is not None: return Image( self.resolution, self.fov, img=self.arr * self.units + other_img.arr * other_img.units, ) else: s = "dimensionless" raise exceptions.InconsistentArguments( "Cannot add inconsistent units " f"({self.units if self.units is not None else s}, " f"{other_img.units if other_img.units is not None else s})." ) def __sub__(self, other_img): """Subtract 2 Images. Args: other_img (Image): The other image to be subtracted. Returns: Image: The new image containing the subtracted arrays. Raises: InconsistentArguments: If the images have different resolutions or fovs, or if the combination of units is incompatible an error is raised. """ # Ensure the images have the same resolution if not np.isclose(self.resolution, other_img.resolution): raise exceptions.InconsistentAddition( "The images must have the same resolution to be subtracted " f"({self.resolution}, {other_img.resolution})." ) # Ensure the images have the same fov if np.any(self.fov != other_img.fov): raise exceptions.InconsistentAddition( "The images must have the same fov to be subtracted " f"({self.fov}, {other_img.fov})." ) # Hanlde if units are involved or not if self.units is None and other_img.units is None: return Image( self.resolution, self.fov, img=self.arr - other_img.arr, ) elif self.units is not None and other_img.units is not None: return Image( self.resolution, self.fov, img=self.arr * self.units - other_img.arr * other_img.units, ) else: s = "dimensionless" raise exceptions.InconsistentArguments( "Cannot subtract inconsistent units " f"({self.units if self.units is not None else s}, " f"{other_img.units if other_img.units is not None else s})." ) def __str__(self): """Return a string representation of the Image object. Returns: table (str) A string representation of the Image object. """ # Intialise the table formatter formatter = TableFormatter(self) return formatter.get_table("Image") def __mul__(self, mult): """Multiply the image by a multiplier. Args: mult (int/float/array-like): The number to multiply the image array by. Returns: Image: The new image containing the multipled array. """ # Create the new image new_img = Image( self.resolution, self.fov, ) # Associate the image array and units new_img.arr = self.arr.copy() new_img.units = self.units # Multiply the image array new_img.arr *= mult return new_img
[docs] def generate_img_hist( self, signal, coordinates, normalisation=None, ): """Calculate an image with no smoothing. This is only applicable to particle based images and is just a wrapper for numpy.histogram2d. Args: signal (array_like, float): The signal to be sorted into the image. coordinates (unyt_array, float): The coordinates of the particles. normalisation (array_like, float): The normalisation property. This is multiplied by the signal before sorting, then normalised out. Returns: img (array_like, float): A 2D array containing the pixel values sorted into the image. (npix, npix) """ return _generate_image_particle_hist( self, signal, coordinates, normalisation=normalisation, )
[docs] @deprecated( "is deprecated and will be removed in version 1.3.0. " "Use generate_img_hist(...) instead." ) def get_img_hist( self, signal, coordinates, normalisation=None, ): """Deprecated wrapper for generate_img_hist.""" # Delegate to the renamed low-level histogram image entry point. return self.generate_img_hist( signal=signal, coordinates=coordinates, normalisation=normalisation, )
[docs] def generate_img_smoothed( self, signal, coordinates=None, smoothing_lengths=None, kernel=None, kernel_threshold=1, density_grid=None, normalisation=None, nthreads=1, ): """Calculate a smoothed image. In the particle case this smooths each particle's signal over the SPH kernel defined by their smoothing length. This uses C extensions to calculate the image for each particle efficiently. Images can optionally be normalised by a secondary property. In the parametric case the signal is smoothed over a density grid. This density grid is an array defining the weight in each pixel. Args: signal (array_like, float): The signal to be sorted into the image. coordinates (unyt_array, float): The coordinates of the particles. (particle case only) smoothing_lengths (unyt_array, float): The smoothing lengths of the particles. (particle case only) kernel (np.ndarray or Kernel): The kernel lookup table, or a ``Kernel`` instance to extract the lookup table from. (particle case only) kernel_threshold (float): The threshold for the kernel. (particle case only) density_grid (array_like, float): The density grid to smooth over. (parametric case only) normalisation (array_like, float): The normalisation property to be used for the signal. This is multiplied by the signal before smoothing, then normalised out. (particle case only). nthreads (int): The number of threads to use for the C extension. (particle case only) Returns: img : array_like (float): A 2D array containing particles sorted into an image. (npix[0], npix[1]) Raises: InconsistentArguments If conflicting particle and parametric arguments are passed or any arguments are missing an error is raised. """ # Call the correct image generation function (particle or parametric) if density_grid is not None and signal is not None: # Generate the images for the parametric case return _generate_image_parametric_smoothed( self, density_grid=density_grid, signal=signal, normalisation=normalisation, ) elif ( coordinates is not None and smoothing_lengths is not None and kernel is not None and kernel_threshold is not None and signal is not None ): # Generate the images for the particle case return _generate_image_particle_smoothed( self, signal, cent_coords=coordinates, smoothing_lengths=smoothing_lengths, kernel=kernel, kernel_threshold=kernel_threshold, nthreads=nthreads, normalisation=normalisation, ) else: raise exceptions.InconsistentArguments( "Didn't find a valid set of arguments to generate images. " "Please provide either a density grid and a signal for " f"parametric imaging (found density_grid={type(density_grid)} " f"signal={type(signal)}) or coordinates, smoothing " f"lengths, kernel, and kernel_threshold for particle imaging " f"(found coordinates={type(coordinates)}, " f"smoothing_lengths={type(smoothing_lengths)}, " f"kernel={type(kernel)}, " f"kernel_threshold={type(kernel_threshold)}, " f"signal={type(signal)})" )
[docs] @deprecated( "is deprecated and will be removed in version 1.3.0. " "Use generate_img_smoothed(...) instead." ) def get_img_smoothed( self, signal, coordinates=None, smoothing_lengths=None, kernel=None, kernel_threshold=1, density_grid=None, normalisation=None, nthreads=1, ): """Deprecated wrapper for generate_img_smoothed.""" # Delegate to the renamed low-level image-generation entry point. return self.generate_img_smoothed( signal=signal, coordinates=coordinates, smoothing_lengths=smoothing_lengths, kernel=kernel, kernel_threshold=kernel_threshold, density_grid=density_grid, normalisation=normalisation, nthreads=nthreads, )
[docs] def apply_noise_array(self, noise_arr): """Apply a noise array. Args: noise_arr (np.ndarray of float): The noise array to add to the image. Returns: Image The image including the noise array np.ndarray The weight map, derived from 1 / std^2 """ # Make sure the noise has units if we have them if self.units is not None and not isinstance(noise_arr, unyt_array): raise exceptions.InconsistentArguments( "If the Image has units then the noise array must also be " f"passed with units. (image.units = {self.units})" ) # Add the noise array to the image if self.units is not None: noisy_img = self.arr * self.units + noise_arr.to(self.units) else: noisy_img = self.arr + noise_arr # Make the new image new_img = Image( resolution=self.resolution, fov=self.fov, img=noisy_img, ) # Store the noise array on the new image new_img.noise_arr = noise_arr # Calculate and store the weight map (if called from # apply_noise_from_std this will be overwritten with the # true standard deviation) new_img.weight_map = 1 / np.std(noise_arr) ** 2 return new_img
[docs] def apply_noise_from_std(self, noise_std): """Apply noise derived from a standard deviation. This creates noise with a normal distribution centred on 0 with the passed standard deviation. Args: noise_std (float): The standard deviation of the noise to add to the image. Returns: Image The image including the noise array np.ndarray The weight map. """ # Strip off units if necessary if isinstance(noise_std, unyt_quantity): units = noise_std.units noise_std = noise_std.value else: units = None # Get the noise array noise_arr = np.random.normal( loc=0, scale=noise_std, size=self.npix, ) # Reapply units if we have them if units is not None: noise_arr *= units # Add the noise to the image new_img = self.apply_noise_array(noise_arr) # Calculate the weight map new_img.weight_map = 1 / noise_std**2 return new_img
[docs] @accepts(aperture_radius=(kpc, arcsecond)) def apply_noise_from_snr(self, snr, depth, aperture_radius=None): """Apply noise derived from a SNR and depth. This can either be for a point source or an aperture if aperture_radius is passed. This assumes the SNR is defined as SNR = S / noise_std Args: snr (float): The signal to noise ratio of the image. depth (unyt_quantity of float): The depth of the image, i.e. the minimum signal strength detectable at the given SNR. aperture_radius (unyt_quantity): The radius of the aperture. If None then a point source is assumed. Returns: Image The image including the noise array np.ndarray The noise array. np.ndarray The weight map. """ # Convert aperture radius to consistent units if we have it if aperture_radius is not None: # Check the aperture is compatible with the resolution if not unit_is_compatible(aperture_radius, self.resolution.units): raise exceptions.InconsistentArguments( "The aperture radius must be compatible with the " f"resolution units. (aperture_radius = {aperture_radius}, " f"resolution = {self.resolution})" ) aperture_radius = aperture_radius.to(self.resolution.units).value # Ensure we have units if we need them if self.units is not None and not isinstance(depth, unyt_quantity): raise exceptions.InconsistentArguments( "If the Image has units then the depth must also be passed " f"with units. (image.units = {self.units})" ) # Strip off units from the depth if we have them if isinstance(depth, unyt_quantity): units = depth.units depth = depth.value else: units = None # Calculate the noise array from an aperture or point source if aperture_radius is not None: # Calculate the total noise in the aperture # NOTE: this assumes SNR = S / app_noise app_noise = depth / snr # Calculate the aperture area in image coordinates app_area_coordinates = np.pi * aperture_radius**2 # Convert the aperture area to per pixel app_area_pix = app_area_coordinates / self._resolution**2 # Get the noise per pixel noise_std = app_noise / np.sqrt(app_area_pix) # Calculate the noise from the depth and snr for a point source. else: # Calculate noise in a pixel noise_std = depth / snr # Reapply units if we have them if units is not None: noise_std *= units return self.apply_noise_from_std(noise_std)
[docs] def apply_correlated_noise( self, instrument, filter_code, correct_periodicity=True, rng_seed=None, inplace=False, ): """Apply correlated noise modelled from an instrument noise map. This requires an instrument with a correlated noise model for the requested filter. The noise template defined by this model will then be used to generate a new noise array with the same spatial correlations as the template, which is then added to the image. Args: instrument (Instrument): The instrument whose correlated-noise model for ``filter_code`` provides the observed noise template used to model the spatial correlations. filter_code (str): The key identifying the noise model to use. correct_periodicity (bool): If True a correction factor is applied to compensate for the assumption of periodicity in the DFT. Default is True. rng_seed (int, optional): Seed for the random number generator. Providing the same seed reproduces an identical noise realisation. inplace (bool): If True, update this image in place and return it. Otherwise return a new Image. Default is False. Returns: Image: A new Image with the correlated noise added. The ``noise_arr`` and ``weight_map`` attributes are populated on the returned object unless ``inplace=True``, in which case the current image is updated and returned. Raises: MissingArgument: If the instrument has no correlated-noise model for the requested filter. InconsistentArguments: If the noise model is dimensionless but the image has units. """ # Get the noise model for the requested filter noise_model = instrument.get_correlated_noise_model(filter_code) # Undo it and return the new image (or this image if inplace) return noise_model.apply_noise( self, correct_periodicity=correct_periodicity, rng_seed=rng_seed, inplace=inplace, )
[docs] def plot_img( self, show=False, cmap="Greys_r", norm=None, fig=None, ax=None, ): """Plot an image. Args: show (bool): Whether to show the plot or not (Default False). cmap (str): The name of the matplotlib colormap for image plotting. Can be any valid string that can be passed to the cmap argument of imshow. Defaults to "Greys_r". norm (function): A normalisation function. This can be custom made or one of matplotlib's normalisation functions. It must take an array and return the same array after normalisation. tick_formatter (matplotlib.ticker.FuncFormatter): An instance of the tick formatter for formatting the colorbar ticks. fig (matplotlib.pyplot.figure): The figure object to plot on. If None a new figure is created. ax (matplotlib.pyplot.figure.axis): The axis object to plot on. If None a new axis is created. Returns: matplotlib.pyplot.figure The figure object containing the plot matplotlib.pyplot.figure.axis The axis object containing the image. """ # Get the image img = self.arr # Set up the figure if fig is None: fig = plt.figure(figsize=(3.5, 3.5)) # Create the axis and turn off the ticks and frame if ax is None: ax = fig.add_subplot(111) ax.axis("off") # Plot the image and remove the surrounding axis ax.imshow( img, cmap=cmap, norm=norm, ) if show: plt.show() return fig, ax
[docs] def plot_map( self, show=False, extent=None, cmap="Greys_r", cbar_label=None, norm=None, tick_formatter=None, fig=None, ax=None, ): """Plot a map. Unlike an image we want a colorbar and axes for a map. Args: show (bool): Whether to show the plot or not (Default False). extent (list): The extent of the x and y axes. cmap (str): The name of the matplotlib colormap for image plotting. Can be any valid string that can be passed to the cmap argument of imshow. Defaults to "Greys_r". cbar_label (str): The label for the colorbar. norm (function): A normalisation function. This can be custom made or one of matplotlib's normalisation functions. It must take an array and return the same array after normalisation. tick_formatter (matplotlib.ticker.FuncFormatter): An instance of the tick formatter for formatting the colorbar ticks. fig (matplotlib.pyplot.figure): The figure object to plot on. If None a new figure is created. ax (matplotlib.pyplot.figure.axis): The axis object to plot on. If None a new axis is created. Returns: matplotlib.pyplot.figure The figure object containing the plot matplotlib.pyplot.figure.axis The axis object containing the image. """ # Get the image img = self.arr # Set up the figure if fig is None: fig = plt.figure(figsize=(3.5, 3.5)) # Create the axis if ax is None: ax = fig.add_subplot(111) # If no extent has been passed, calculate it if extent is None: extent = [ -self._fov[0] / 2, self._fov[0] / 2, -self._fov[1] / 2, self._fov[1] / 2, ] # Plot the image and remove the surrounding axis im = ax.imshow( img, extent=extent, origin="lower", interpolation="nearest", cmap=cmap, norm=norm, ) # Make the colorbar with the format if provided cbar = fig.colorbar(im, format=tick_formatter) if cbar_label is not None: cbar.set_label(cbar_label) if show: plt.show() return fig, ax
[docs] def print_ascii(self): """Print an ASCII representation of an image.""" # Define the possible ASCII symbols in density order scale = ( "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft|()1{}[]?-_+~<>" "i!lI;:,\"^`'. "[::-1] ) # Define the number of symbols nscale = len(scale) # Map the image onto a range of 0 -> nscale - 1 img = (nscale - 1) * self.arr / np.max(self.arr) # Convert to integers for indexing img = img.astype(int) # Create the ASCII string image ascii_img = "" for i in range(img.shape[0]): for j in range(img.shape[1]): ascii_img += 2 * scale[img[i, j]] ascii_img += "\n" print(ascii_img)
[docs] def plot_unknown_pleasures( self, contrast=100, target_lines=50, figsize=(8, 8), title="SYNTHESIZER", ): """Plot the image in the style of Unknown Pleasures. Creates a representation of an image similar in style to Joy Division's seminal 1979 album Unknown Pleasures. Borrows some code from this matplotlib examples: https://matplotlib.org/stable/gallery/animation/unchained.html Arguments: contrast (float): The contrast, i.e. the maximum value in the image. target_lines (int): The target number of individual lines to use. figsize (tuple): The size of the figure to create. title (str): The title to add to the image. If None no title is added. """ # Extract data data = self.arr # Normalise to the maximum and take the log10 data /= np.max(data) data = np.log10(data) # Set any -np.inf values to zero (once renormalised) data[data == -np.inf] = -np.log10(contrast) # Define normalising function norm = Normalize(vmin=-np.log10(contrast), vmax=0.0) # Normalise data data = norm(data) * 5 # Set any data <0.0 to zero data[data < 0.0] = 0.0 # Unknown Pleasures works best with about 50 lines so reshape the data # to have approximately 50 lines. # Calcualate the eventual number of lines. nlines = int(data.shape[0] / (data.shape[0] // target_lines)) # Resample the data to have the same x resolution but nlines y # resolution. data = zoom( data, (nlines / data.shape[0], 1), order=3, ) # Create new Figure with black background fig = plt.figure(figsize=figsize, facecolor="black") # Add a subplot with no frame ax = plt.subplot(111, frameon=False) X = np.linspace(-1, 1, data.shape[-1]) # Generate line plots lines = [] for i in range(data.shape[0]): # Small reduction of the X extents to get a cheap perspective # effect. xscale = 1 - i / 100.0 # Same for linewidth (thicker strokes on bottom) lw = 1.5 - i / 100.0 (line,) = ax.plot(xscale * X, i + data[i], color="w", lw=lw) lines.append(line) # Set y limit (or first line is cropped because of thickness) ax.set_ylim(-20, nlines + 20) # No ticks ax.set_xticks([]) ax.set_yticks([]) # Add title if title: ax.text( 0.5, 0.8, title, transform=ax.transAxes, ha="center", va="bottom", color="w", family="sans-serif", fontweight="light", fontsize=16, ) return fig, ax
[docs] def get_signal_in_aperture( self, aperture_radius, aperture_cent=None, nthreads=1, ): """Return the sum of the image within an aperture. This uses fractional pixel coverage to calculate the overlap between the aperture and each pixel. Args: aperture_radius (unyt_quantity of float): The radius of the aperture. aperture_cent (unyt_array, float): The centre of the aperture (in pixel coordinates, i.e. the centre is [npix/2, npix/2], top left is [0, 0], and bottom right is [npix, npix]). If None then the centre is assumed to be the maximum pixel. nthreads (int): The number of threads to use for the calculation. Default is 1. Returns: float The sum of the image within the aperture. """ # Convert the aperture radius to the correct units aperture_radius = aperture_radius.to(self.resolution.units).value # If the aperture centre isn't passed, assume it's the maximum # pixel if aperture_cent is None: max_pixel = np.unravel_index(self.arr.argmax(), self.arr.shape) aperture_cent = np.array(max_pixel) + 0.5 from synthesizer.imaging.extensions.circular_aperture import ( calculate_circular_overlap, ) return ( calculate_circular_overlap( self._resolution, self.npix[0], self.npix[1], aperture_radius, self.arr, aperture_cent, nthreads, ) * self.units )