AperturePhotometry#

class photutils.aperture.AperturePhotometry(data, apertures, *, error=None, mask=None, wcs=None, method='exact', subpixels=5, segmentation_image=None, labels=None, mask_method='none', n_threads=1)[source]#

Bases: object

Class to perform aperture photometry on 2D data.

This class sums the (weighted) input data values within the given aperture(s) and provides the aperture fluxes, uncertainties, unmasked overlap areas, and bitwise quality flags as lazily-computed attributes. Use to_table to obtain the results as an QTable.

Note that this class returns the sum of the (weighted) input data values within the aperture. It does not convert data in surface brightness units to flux or counts. Conversion from surface-brightness units should be performed before using this class.

Parameters:
dataarray_like, Quantity, NDData

The 2D array on which to perform photometry. data should be background-subtracted. If data is a Quantity array, then error (if input) must also be a Quantity array with the same units. Nonfinite data values (NaN and inf) are automatically masked. See the Notes section below for more information about NDData input.

aperturesAperture, supported regions.Region, list of Aperture or regions.Region

The aperture(s) to use for the photometry. If apertures is a list of Aperture or regions.Region, then they all must have the same position(s). A tuple or ndarray of them is also accepted. The list must not be empty. If apertures contains a SkyAperture or SkyRegion object, then a WCS must be input using the wcs keyword. Region objects are converted to aperture objects.

errorarray_like or Quantity, optional

The pixel-wise Gaussian 1-sigma errors of the input data. error is assumed to include all sources of error, including the Poisson error of the sources (see calc_total_error). error must have the same shape as the input data. If a Quantity array, then data must also be a Quantity array with the same units.

maskarray_like (bool), optional

A boolean mask with the same shape as data where a True value indicates the corresponding element of data is masked. Masked data are excluded from all calculations. Nonfinite values (NaN and inf) in the input data are automatically masked.

wcsWCS object, optional

A world coordinate system (WCS) transformation that supports the astropy shared interface for WCS (e.g., astropy.wcs.WCS, gwcs.wcs.WCS). If provided, the sky_center attribute and the 'sky_center' column of to_table will contain the sky coordinates of the input aperture center(s). This keyword is required if the input apertures contains a SkyAperture or SkyRegion.

method{‘exact’, ‘center’, ‘subpixel’}, optional

The method used to determine the pixel weights (the fraction of the pixel area covered by the aperture):

  • 'exact' (default): Calculates the exact geometric overlap area. Weights are continuous in the range [0, 1].

  • 'center': Binary weighting based on the pixel center. Weights are either 0 or 1. A pixel is included only if its center lies strictly inside the aperture. Pixel centers lying exactly on the outer aperture boundary are excluded (weight 0). For an annulus, pixel centers lying exactly on the inner boundary are included (weight 1).

  • 'subpixel': Approximates the overlap by averaging binary samples on a subgrid. The number of samples is set by the subpixels parameter. Weights are discrete in the range [0, 1]. A subpixel is included only if its center lies strictly inside the aperture. Subpixel centers lying exactly on the outer aperture boundary are excluded (weight 0). For an annulus, subpixel centers lying exactly on the inner boundary are included.

subpixelsint, optional

The subsampling factor per axis used with the 'subpixel' method. Each pixel is divided into a grid of subpixels**2 subpixels to approximate the overlap. This parameter is ignored for other methods.

segmentation_imageSegmentationImage or None, optional

A segmentation image with the same shape as data, where background pixels have a value of 0 and sources are labeled with positive integers. It is used to mask or correct neighboring sources within each aperture according to the mask_method keyword. This keyword is required if mask_method is not 'none' and is ignored if mask_method is 'none' (the default). The labels keyword must also be input for the 'mask', 'source_only', and 'correct' methods so that the correct target source is used for each aperture.

labelsint, 1D array_like, or None, optional

The source label(s) in segmentation_image associated with the aperture position(s). labels is required if segmentation_image is input and mask_method is 'mask', 'source_only', or 'correct'. It is not used if mask_method is 'none' or 'background_only'. labels must have the same length as the number of aperture positions, and each nonzero label must be present in the segmentation_image (unless mask_method is 'none' or 'background_only'). A label of 0 disables the segmentation masking for that aperture.

mask_method{‘none’, ‘mask’, ‘source_only’, ‘background_only’, ‘correct’}, optional

The method used to handle neighboring sources within each aperture using the segmentation_image:

  • 'none' (default): The segmentation_image is ignored and all pixels within the aperture are included.

  • 'mask': Pixels belonging to neighboring sources (i.e., labeled but not the target source) are excluded.

  • 'source_only': Only pixels belonging to the target source are included. Both neighboring sources and background pixels are excluded.

  • 'background_only': Only background pixels are included. Pixels belonging to any source are excluded, including the source at the aperture position (if any). This method is intended for estimating the local background, e.g., within an annulus aperture. The labels keyword is not used.

  • 'correct': Pixels belonging to neighboring sources are replaced by the values of the pixels mirrored across the aperture center. If a mirror pixel is unavailable, the pixel is excluded.

n_threadsint, optional

The number of threads to use to compute the aperture sums. The default is 1 (no multithreading). When n_threads > 1, the aperture positions are divided into chunks and processed concurrently. The per-position results are independent, so they are identical to the single-threaded computation. The underlying kernels release the Python global interpreter lock (GIL), so multithreading can significantly speed up the photometry for many aperture positions. Multithreading is used only for apertures and input arrays supported by the fast batch code path. Otherwise, the computation is serial.

See also

photutils.aperture.ApertureStats

Per-source statistics (e.g., centroid, min, max, median, standard deviation, and morphological properties) of the pixels within an aperture.

Notes

Region objects are converted to Aperture objects using the region_to_aperture() function.

If the input data is a NDData object, then its mask, wcs, unit, and uncertainty are used. The error, mask, and wcs keywords are then ignored, and an AstropyUserWarning is issued for each one that is input. The uncertainty is used as error only if it is a StdDevUncertainty. Any other uncertainty type is ignored.

The measured flux, flux_err, area, and flags attributes (as well as id, x_center, y_center, and sky_center) are scalars if a single scalar aperture position is input (e.g., CircularAperture((10, 20), r=5)). They are 1D arrays with one element per position if multiple positions are input (e.g., CircularAperture([(10, 20)], r=5) or CircularAperture([(10, 20), (30, 40)], r=5)). If a list of apertures is input, the flux, flux_err, area, and flags attributes gain a trailing aperture axis, giving shape (n_apertures,) for a single scalar position and (n_positions, n_apertures) otherwise.

Nonfinite data values (NaN and inf) are automatically masked. Such pixels are excluded from the flux, flux_err, and area calculations and are indicated by the non_finite_data quality flag (see decode_aperture_flags).

This class should be treated as immutable after initialization (aside from the internal lazily-computed functools.cached_property cache), so a single instance can be safely shared across threads. Do not reassign its attributes after construction.

One caveat applies to apertures that are not supported by the compiled batch code path (e.g., a Aperture subclass that overrides to_mask). That path suppresses warnings using warnings.catch_warnings, which mutates process-global warning-filter state, so concurrent calls can transiently affect the warning filters seen by other threads. On free-threaded Python builds the warning filters are context-aware, so this does not apply.

Examples

>>> import numpy as np
>>> from photutils.datasets import make_4gaussians_image
>>> from photutils.aperture import AperturePhotometry, CircularAperture
>>> data = make_4gaussians_image()
>>> error = 0.1 * np.ones(data.shape)  # simple background-only error
>>> aper = CircularAperture([(25, 40), (90, 60), (150, 25)], r=8)
>>> phot = AperturePhotometry(data, aper, error=error)
>>> print(phot.flux)
[ 5853.59627292 28440.27461471  9286.70920641]
>>> print(phot.flux_err)
[1.38553058 1.38553058 1.38553058]
>>> print(phot.to_table(columns=['id', 'flux', 'flux_err']))
 id        flux             flux_err
--- ------------------ ------------------
  1  5853.596272924398 1.3855305772442865
  2 28440.274614708058 1.3855305772442865
  3  9286.709206410273 1.3855305772442865

Attributes Summary

area

The total unmasked overlap area of the aperture(s) (in pix**2).

flags

The bitwise quality flags for the aperture(s).

flux

The sum of the (weighted) values within the aperture(s).

flux_err

The uncertainty in the flux values.

id

The aperture identification number(s).

isscalar

Whether the instance is scalar (i.e., a single scalar aperture position such as CircularAperture((10, 20), r=5), not a length-1 list of positions).

n_positions

The number of aperture positions.

sky_center

The sky coordinates of the aperture center(s), or None if no wcs was input.

x_center

The x pixel coordinate(s) of the aperture center(s).

y_center

The y pixel coordinate(s) of the aperture center(s).

Methods Summary

decode_flags(*[, return_bit_values])

Decode the aperture quality flags into individual components.

to_table(*[, columns])

Create a QTable of the aperture photometry results.

Attributes Documentation

area[source]#

The total unmasked overlap area of the aperture(s) (in pix**2).

This takes into account the aperture mask method, masked data pixels (mask keyword), segmentation masking, and partial/no overlap of the aperture with the data. The value is NaN where the aperture does not overlap the data (the 'no_overlap' flag).

flags[source]#

The bitwise quality flags for the aperture(s).

See decode_aperture_flags for decoding flag values.

flux[source]#

The sum of the (weighted) values within the aperture(s).

The values are always float64, regardless of the input data dtype (a Quantity if data has units).

The value is NaN where the aperture does not overlap the data (the 'no_overlap' flag).

flux_err[source]#

The uncertainty in the flux values.

The values are always float64, regardless of the input error dtype (a Quantity if data has units). If the input error is None, this is filled with NaN values.

id[source]#

The aperture identification number(s).

isscalar[source]#

Whether the instance is scalar (i.e., a single scalar aperture position such as CircularAperture((10, 20), r=5), not a length-1 list of positions).

n_positions[source]#

The number of aperture positions.

sky_center[source]#

The sky coordinates of the aperture center(s), or None if no wcs was input.

x_center[source]#

The x pixel coordinate(s) of the aperture center(s).

y_center[source]#

The y pixel coordinate(s) of the aperture center(s).

Methods Documentation

decode_flags(*, return_bit_values=False)[source]#

Decode the aperture quality flags into individual components.

This is a convenience method that calls decode_aperture_flags with the flags attribute.

Parameters:
return_bit_valuesbool, optional

If True, return the decoded bit flags (integers) instead of the flag names (strings).

Returns:
decodeddict

A dictionary mapping each aperture position id to its decoded flags. For a single input aperture, each value is the list of active flag names (or bit values) for that position. If a list of apertures was input (2D flags), each value is a list with one entry per aperture, so decoded[id][j] gives the active flags for position id and aperture j. The entries follow the position order.

to_table(*, columns=None)[source]#

Create a QTable of the aperture photometry results.

Parameters:
columnsstr, list or tuple of str, or None, optional

Names of columns, in order, to include in the output QTable. The allowed column names are 'id', 'x_center', 'y_center', 'sky_center', 'flux', 'flux_err', 'area', and 'flags'. If columns is None, then a default list of columns will be used (the default_columns attribute). If a list of apertures was input, then the 'flux', 'flux_err', 'area', and 'flags' columns will have a '_i' suffix (e.g., 'flux_0'), where i is the index of the aperture in the input list.

Returns:
tableQTable

A table of the aperture photometry results with one row per aperture position.

Raises:
ValueError

If any name in columns is not a valid column name, or if 'sky_center' is requested but no WCS was input.