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:
objectClass to perform aperture photometry on 2D data.
This class sums the (weighted) input
datavalues within the given aperture(s) and provides the aperture fluxes, uncertainties, unmasked overlap areas, and bitwise quality flags as lazily-computed attributes. Useto_tableto obtain the results as anQTable.Note that this class returns the sum of the (weighted) input
datavalues 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.
datashould be background-subtracted. Ifdatais aQuantityarray, thenerror(if input) must also be aQuantityarray with the same units. Nonfinitedatavalues (NaN and inf) are automatically masked. See the Notes section below for more information aboutNDDatainput.- apertures
Aperture, supportedregions.Region, list ofApertureorregions.Region The aperture(s) to use for the photometry. If
aperturesis a list ofApertureorregions.Region, then they all must have the same position(s). A tuple orndarrayof them is also accepted. The list must not be empty. Ifaperturescontains aSkyApertureorSkyRegionobject, then a WCS must be input using thewcskeyword. Region objects are converted to aperture objects.- errorarray_like or
Quantity, optional The pixel-wise Gaussian 1-sigma errors of the input
data.erroris assumed to include all sources of error, including the Poisson error of the sources (seecalc_total_error).errormust have the same shape as the inputdata. If aQuantityarray, thendatamust also be aQuantityarray with the same units.- maskarray_like (bool), optional
A boolean mask with the same shape as
datawhere aTruevalue indicates the corresponding element ofdatais masked. Masked data are excluded from all calculations. Nonfinite values (NaN and inf) in the inputdataare 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, thesky_centerattribute and the'sky_center'column ofto_tablewill contain the sky coordinates of the input aperture center(s). This keyword is required if the inputaperturescontains aSkyApertureorSkyRegion.- 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 thesubpixelsparameter. 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 ofsubpixels**2subpixels to approximate the overlap. This parameter is ignored for other methods.- segmentation_image
SegmentationImageorNone, 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 themask_methodkeyword. This keyword is required ifmask_methodis not'none'and is ignored ifmask_methodis'none'(the default). Thelabelskeyword 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_imageassociated with the aperture position(s).labelsis required ifsegmentation_imageis input andmask_methodis'mask','source_only', or'correct'. It is not used ifmask_methodis'none'or'background_only'.labelsmust have the same length as the number of aperture positions, and each nonzero label must be present in thesegmentation_image(unlessmask_methodis'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): Thesegmentation_imageis 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. Thelabelskeyword 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.
- dataarray_like,
See also
photutils.aperture.ApertureStatsPer-source statistics (e.g., centroid, min, max, median, standard deviation, and morphological properties) of the pixels within an aperture.
Notes
Regionobjects are converted toApertureobjects using theregion_to_aperture()function.If the input
datais aNDDataobject, then itsmask,wcs, unit, and uncertainty are used. Theerror,mask, andwcskeywords are then ignored, and anAstropyUserWarningis issued for each one that is input. The uncertainty is used aserroronly if it is aStdDevUncertainty. Any other uncertainty type is ignored.The measured
flux,flux_err,area, andflagsattributes (as well asid,x_center,y_center, andsky_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)orCircularAperture([(10, 20), (30, 40)], r=5)). If a list of apertures is input, theflux,flux_err,area, andflagsattributes gain a trailing aperture axis, giving shape(n_apertures,)for a single scalar position and(n_positions, n_apertures)otherwise.Nonfinite
datavalues (NaN and inf) are automatically masked. Such pixels are excluded from theflux,flux_err, andareacalculations and are indicated by thenon_finite_dataquality flag (seedecode_aperture_flags).This class should be treated as immutable after initialization (aside from the internal lazily-computed
functools.cached_propertycache), 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
Aperturesubclass that overridesto_mask). That path suppresses warnings usingwarnings.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
The total unmasked overlap area of the aperture(s) (in
pix**2).The bitwise quality flags for the aperture(s).
The sum of the (weighted) values within the aperture(s).
The uncertainty in the
fluxvalues.The aperture identification number(s).
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).The number of aperture positions.
The sky coordinates of the aperture center(s), or
Noneif nowcswas input.The
xpixel coordinate(s) of the aperture center(s).The
ypixel 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
QTableof 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 (
maskkeyword), 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_flagsfor decoding flag values.
- flux[source]#
The sum of the (weighted) values within the aperture(s).
The values are always float64, regardless of the input
datadtype (aQuantityifdatahas units).The value is NaN where the aperture does not overlap the data (the
'no_overlap'flag).
- flux_err[source]#
The uncertainty in the
fluxvalues.The values are always float64, regardless of the input
errordtype (aQuantityifdatahas units). If the inputerrorisNone, this is filled with NaN values.
- 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).
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_flagswith theflagsattribute.- 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
idto 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 (2Dflags), each value is a list with one entry per aperture, sodecoded[id][j]gives the active flags for positionidand aperturej. The entries follow the position order.
- to_table(*, columns=None)[source]#
Create a
QTableof 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'. IfcolumnsisNone, then a default list of columns will be used (thedefault_columnsattribute). 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'), whereiis the index of the aperture in the input list.
- columnsstr, list or tuple of str, or
- Returns:
- table
QTable A table of the aperture photometry results with one row per aperture position.
- table
- Raises:
- ValueError
If any name in
columnsis not a valid column name, or if'sky_center'is requested but no WCS was input.