What’s New in Photutils 3.1?#

Here we highlight some of the new functionality of the 3.1 release. In addition to these changes, Photutils 3.1 includes several smaller improvements and bug fixes, which are described in the full Changelog.

Dependency Version Updates#

Photutils 3.1 bumps the minimum required versions of Python and several key dependencies to provide users with access to the latest features and performance improvements. The minimum required versions are now:

  • Python: 3.12

  • Astropy: 7.0

  • SciPy: 1.15

  • Matplotlib: 3.10

  • Regions: 0.10

  • gwcs: 0.22

  • Shapely: 2.1

  • tqdm: 4.67

ASDF Serialization Support#

Photutils 3.1 introduces initial support for serializing photutils objects to the Advanced Scientific Data Format (ASDF) file format. This requires installing the asdf package. Objects that store an Quantity or a SkyCoord also require the optional asdf-astropy package, which provides the converters for those Astropy types. That includes all of the PSF models, all of the sky apertures, and any pixel aperture whose rotation angle is given as an angular quantity.

>>> import asdf
>>> from photutils.aperture import CircularAperture
>>> aperture = CircularAperture((10, 20), r=5)
>>> with asdf.AsdfFile() as af:
...     af['aperture'] = aperture
...     af.write_to('aperture.asdf')
>>> with asdf.open('aperture.asdf') as af:
...     aperture = af['aperture']

The following classes can be serialized to and deserialized from ASDF files:

Apertures

PSF Models

See ASDF Serialization for more details.

Photutils Deprecation Warning Class#

All Photutils deprecation warnings are now emitted as PhotutilsDeprecationWarning, a subclass of astropy’s AstropyDeprecationWarning. The warning class name now identifies Photutils as the source of the warning, which makes it easier to find the deprecated code path when a warning is raised from within a larger pipeline. Because it is a subclass, existing warning filters and pytest.warns checks for AstropyDeprecationWarning continue to work unchanged.

Aperture Package#

ApertureStats has a new sky_orientation property (see Sky Orientation of Sources).

New AperturePhotometry Class#

Photutils 3.1 introduces a new AperturePhotometry class, which is now the recommended tool for aperture photometry. Like ApertureStats, the data, apertures, and options are supplied to the constructor, and the results are exposed as lazily computed attributes or as an Astropy QTable via the to_table method:

>>> import numpy as np
>>> from photutils.aperture import AperturePhotometry, CircularAperture
>>> data = np.ones((100, 100))
>>> aperture = CircularAperture([(30.0, 30.0), (40.0, 40.0)], r=5.0)
>>> phot = AperturePhotometry(data, aperture)
>>> fluxes = phot.flux  # lazily computed
>>> phot_table = phot.to_table()

The class reports the aperture flux, flux_err, unmasked overlap area, and bitwise quality flags as attributes, all of which are included in the default to_table() output. Compared to the legacy aperture_photometry() function, it adds the aperture areas and quality flags and supports segmentation-based neighbor masking (see below). The flux columns use the names 'flux' and 'flux_err' (rather than 'aperture_sum' and 'aperture_sum_err').

The class is immutable after construction (aside from the internal lazy-attribute cache), so a single instance is safe to share across threads, and independent images can be processed concurrently (see the thread-safety section below).

Like ApertureStats, the output attributes are scalars when a single scalar aperture position is input (e.g., CircularAperture((30.0, 30.0), r=5.0)) and arrays when multiple positions are input.

The legacy aperture_photometry() function remains available and is not deprecated, but it is now considered a legacy interface. New features are added only to the AperturePhotometry and ApertureStats classes.

Exact Rectangular Aperture Overlap#

Rectangular apertures used for aperture photometry and related statistical measurements now support the method='exact' option for computing pixel-aperture overlap fractions. Previously, requesting method='exact' for a RectangularAperture or RectangularAnnulus was silently translated to a 32x subpixel approximation. The new implementation computes the exact analytic overlap area using a Sutherland-Hodgman polygon-clipping algorithm.

Faster Aperture Photometry#

Aperture photometry is now significantly faster for all built-in aperture shapes. The photometry for all sources is now computed in a single call into compiled code, avoiding the per-source Python overhead of creating individual aperture masks and cutouts. Typical speedups range from ~2x to more than 25x, depending on the aperture shape and overlap method, with the largest gains for fields with many sources.

Faster Aperture Statistics#

ApertureStats is now significantly faster. The per-source statistics are computed in a single call into compiled code, reusing the same fast pixel-overlap machinery as the aperture photometry improvements above. Sigma-clipped statistics are also computed in compiled code for the common SigmaClip configurations. Typical speedups range from ~5x to ~15x, depending on which properties are requested.

Aperture Statistics Error Estimates#

ApertureStats now provides standard-error estimates for its location statistics via the new mean_err and median_err properties. The mean_err property returns the standard error of the mean, \(s / \sqrt{N}\), where \(s\) is the sample standard deviation of the unmasked aperture pixels and \(N\) is the number of those pixels. The median_err property returns the large-sample standard error of the median, \(\sqrt{\pi / 2} \, s / \sqrt{N} = \sqrt{\pi / (2 \, N)} \, s\), which assumes the pixel values are approximately normally distributed. Both properties are NaN for apertures with fewer than two unmasked pixels:

>>> import numpy as np
>>> from photutils.aperture import ApertureStats, CircularAperture
>>> rng = np.random.default_rng(seed=0)
>>> data = rng.normal(100.0, 5.0, (100, 100))
>>> aper = CircularAperture((50, 50), r=10)
>>> stats = ApertureStats(data, aper)
>>> stats.mean_err
np.float64(0.2744788180188647)

Corrected Flux Errors for Partial Pixels#

The propagated flux errors are now mathematically consistent with the reported fluxes. An aperture flux is the sum of the pixel values weighted by their aperture overlap fractions, \(F = \sum_i w_i f_i\), so its variance with independent pixel errors is \(\sum_i w_i^2 \sigma_i^2\). Previously, the pixel variances on the aperture boundary were weighted by the linear overlap fraction, which overestimates the flux error by a few percent for small and compact apertures (Monte Carlo simulations confirm that the new errors match the actual scatter of the measured fluxes).

The corrected error propagation applies everywhere fractional pixel weights are combined with an input error array, including AperturePhotometry, aperture_photometry(), ApertureStats (sum_err and error_sum_cutout), the SourceCatalog kron_flux_err and circular_photometry errors, and the profile_error values of the profile classes. The SourceCatalog segment_flux_err values are unchanged because source segments contain only whole pixels.

Sample Variance and Standard Deviation#

ApertureStats now accepts a ddof keyword that sets the delta degrees of freedom used when computing the var and std properties. The divisor used in the calculation is \(N - \mathrm{ddof}\), where \(N\) is the number of unmasked pixels within the aperture. The default is ddof=0, which gives the population variance and standard deviation (unchanged from previous versions). Use ddof=1 to obtain the sample (unbiased) variance and standard deviation:

>>> import numpy as np
>>> from photutils.aperture import ApertureStats, CircularAperture
>>> rng = np.random.default_rng(seed=0)
>>> data = rng.normal(100.0, 5.0, (100, 100))
>>> aper = CircularAperture((50, 50), r=10)
>>> stats = ApertureStats(data, aper, ddof=1)
>>> stats.std
np.float64(4.793566477062259)

The ddof keyword affects only the var and std properties. All other properties are unaffected, including the mean_err and median_err standard errors, which are always computed using the sample standard deviation regardless of the value of ddof.

Thread-Safe and Free-Threading-Compatible Aperture Photometry#

The new aperture photometry implementation releases the Python global interpreter lock (GIL) during the computation and uses no global state, making it safe to call concurrently from multiple threads. The compiled extensions are also declared compatible with free-threaded CPython builds, so threads can run the computation truly in parallel.

The simplest way to use multiple threads is the new n_threads keyword of AperturePhotometry and ApertureStats. The aperture positions are divided into chunks and processed concurrently, producing results identical to the single-threaded computation:

>>> import numpy as np
>>> from photutils.aperture import (AperturePhotometry,
...                                 ApertureStats, CircularAperture)
>>> rng = np.random.default_rng(seed=0)
>>> data = rng.random((4096, 4096))
>>> positions = rng.uniform(0, 4096, (100_000, 2))
>>> aperture = CircularAperture(positions, r=5.0)
>>> phot = AperturePhotometry(data, aperture, n_threads=8)
>>> stats = ApertureStats(data, aperture, n_threads=8)

The aperture sums, sigma clipping, and per-source statistic reductions (e.g., the sorts, order statistics, robust estimators, and moments) all run in the threads, so both classes scale nearly linearly with the thread count for large numbers of positions. For the example above, measured speedups are ~2x with 2 threads and ~8-10x with 12 threads, for the aperture fluxes and sums as well as for statistics such as the median, MAD standard deviation, and the biweight estimators.

SourceCatalog also accepts an n_threads keyword. Its compiled per-source measurements (the isophotal moments, segment pixel statistics, windowed and quadratic centroids, perimeter, Kron and circular photometry, and flux radii) are computed in chunks of sources processed concurrently, with results identical to the single-threaded computation, so the default to_table output of a large catalog is several times faster with several threads:

>>> from photutils.datasets import make_100gaussians_image
>>> from photutils.segmentation import SourceCatalog, detect_sources
>>> image = make_100gaussians_image() - 5.0  # subtract background
>>> segm = detect_sources(image, 9.0, n_pixels=5)
>>> cat = SourceCatalog(image, segm, n_threads=8)
>>> table = cat.to_table()

For more advanced workflows, independent images can also be processed concurrently with a thread pool, one instance per image:

>>> from concurrent.futures import ThreadPoolExecutor
>>> images = [rng.random((1024, 1024)) for _ in range(8)]
>>> aperture = CircularAperture(rng.uniform(0, 1024, (1000, 2)),
...                             r=5.0)
>>> with ThreadPoolExecutor(max_workers=8) as executor:
...     results = list(executor.map(
...         lambda image: AperturePhotometry(image, aperture),
...         images))
>>> tables = [result.to_table() for result in results]

Because executor.map returns results in input order, the tables are in the same order as the input images.

Polygon Apertures#

Two new aperture classes have been added: PolygonAperture and SkyPolygonAperture. Like the other aperture types, they have a single fixed shape (parameterized by vertex_offsets) that can be applied at one or more positions:

>>> import numpy as np
>>> from photutils.aperture import PolygonAperture
>>> positions = [(10.0, 20.0), (30.0, 40.0)]
>>> # A regular hexagon centered on each position
>>> outer_radius = 5.0
>>> theta = np.linspace(0.0, 2 * np.pi, 6, endpoint=False)
>>> offsets = np.column_stack([outer_radius * np.cos(theta),
...                            outer_radius * np.sin(theta)])
>>> aper = PolygonAperture(positions, offsets)

The polygon must be simple (non-self-intersecting), but it does not need to be convex. Nonconvex shapes such as L-shapes or stars are fully supported.

Regular polygons can be constructed by specifying a center, the number of vertices, the circumradius (outer radius), and an optional rotation angle via the from_regular_polygon classmethod. The is_regular property reports whether a polygon is regular, and the outer_radius, inner_radius, side_length, interior_angle, exterior_angle, and theta properties expose the geometric parameters of regular polygons (they raise ValueError for nonregular polygons):

>>> hexagon = PolygonAperture.from_regular_polygon((10.0, 20.0),
...                                                n_vertices=6,
...                                                radius=5.0)
>>> hexagon.is_regular
True
>>> hexagon.outer_radius
5.0
>>> hexagon.interior_angle
<Quantity 120. deg>

A from_vertices classmethod is also provided as a convenience for building a single polygon directly from absolute pixel or sky vertex coordinates:

>>> verts = [(0.0, 0.0), (4.0, 0.0), (4.0, 3.0)]
>>> aper = PolygonAperture.from_vertices(verts)

Both polygon aperture classes also expose a vertices attribute returning the absolute vertex coordinates at every aperture position.

Conversions between PolygonAperture and SkyPolygonAperture use wcs.pixel_to_world and wcs.world_to_pixel directly on the absolute vertex coordinates, so the conversion captures the actual finite-displacement WCS transformation of the polygon corners.

aperture_to_region and region_to_aperture also now support PolygonPixelRegion and PolygonSkyRegion.

Converting Apertures to Polygons#

The circular, elliptical, and rectangular apertures (both their pixel and sky variants) now have a to_polygon method that converts them to an equivalent PolygonAperture or SkyPolygonAperture. The circular and elliptical apertures are approximated by a polygon with a configurable number of vertices (n_vertices, default 100), while the rectangular aperture is converted exactly to a four-vertex polygon:

>>> from photutils.aperture import CircularAperture
>>> aper = CircularAperture((10.0, 20.0), r=5.0)
>>> poly = aper.to_polygon(n_vertices=100)

Segmentation-Based Masking in Aperture Photometry#

AperturePhotometry and ApertureStats now accept segmentation_image, labels, and mask_method keywords to mask or correct the flux from neighboring sources that overlap an aperture. The segmentation_image must be a SegmentationImage (see Image Segmentation) that labels each source with a positive integer, and the mask_method keyword selects how neighboring sources are handled:

  • 'none' (default): the segmentation image is ignored.

  • 'mask': pixels belonging to neighboring sources are excluded.

  • 'source_only': only pixels belonging to the target source are included.

  • 'background_only': pixels belonging to any source are excluded, e.g., to estimate the local background within an annulus aperture.

  • 'correct': neighboring-source pixels are replaced by the values mirrored across the aperture center (excluded if the mirror pixel is unavailable).

It is required to explicitly provide the source labels for each aperture when a segmentation_image is input and mask_method is 'mask', 'source_only', or 'correct' (the 'background_only' method does not use the labels). The labels keyword must have the same length as the number of aperture positions and identifies the target source for each aperture. Requiring explicit labels ensures the correct target source is used for each aperture, which is especially important for irregularly shaped source segmentation footprints or for apertures that are not centered on a source.

Example of using the new segmentation-based masking:

>>> import numpy as np
>>> from photutils.aperture import AperturePhotometry, CircularAperture
>>> from photutils.segmentation import SegmentationImage
>>> data = np.ones((11, 11))
>>> data[4:7, 4:7] = 10.0  # target source
>>> data[4:7, 7:10] = 50.0  # bright neighbor
>>> segm = np.zeros((11, 11), dtype=int)
>>> segm[4:7, 4:7] = 1
>>> segm[4:7, 7:10] = 2
>>> segm = SegmentationImage(segm)
>>> aperture = CircularAperture((5, 5), r=4)
>>> phot = AperturePhotometry(data, aperture, segmentation_image=segm,
...                           labels=1, mask_method='mask')

Aperture Photometry Quality Flags#

Aperture photometry and statistics now provide per-source bitwise quality flags, unified across the AperturePhotometry and ApertureStats classes (e.g., a new flags property, included in the default to_table() columns). In ApertureStats, flags reports conditions from both the 'center'-method footprint used by the value statistics and the sum_method footprint used by the sum properties. A flag value of 0 means that no issues were detected. The flags indicate conditions such as:

  • the aperture is partially ('partial_overlap') or fully ('no_overlap') outside the data

  • the aperture contains no pixels with nonzero weight ('no_pixels')

  • input-masked pixels within the aperture ('masked_pixels')

  • nonfinite data or error values within the aperture ('non_finite_data', 'non_finite_error')

  • pixels excluded or corrected due to neighboring sources in a segmentation image ('neighbor_pixels', 'uncorrected_pixels')

  • no valid pixels at all, because every pixel is masked, nonfinite, or excluded ('all_masked')

  • sigma-clipped pixels within the aperture ('sigma_clipped', 'all_clipped') and too few pixels to compute a statistic ('too_few_pixels') in ApertureStats

  • sources whose net flux is not positive or whose second-order moments are not positive semidefinite ('undefined_shape'), whose covariance matrix is singular or nearly singular ('singular_covariance'), or whose centroid lies outside the aperture bounding box ('centroid_outside_bbox'), so that the centroid and shape properties are undefined or unreliable, in ApertureStats

The overlap flags are precise. They are based on the pixels with nonzero aperture weight, not simply the aperture bounding box. The new decode_aperture_flags() function and the photutils.aperture.AperturePhotometry.decode_flags() and photutils.aperture.ApertureStats.decode_flags() methods (which return a dictionary keyed by aperture position ID) decode flag values into human-readable names:

>>> import numpy as np
>>> from photutils.aperture import (AperturePhotometry,
...                                 CircularAperture,
...                                 decode_aperture_flags)
>>> data = np.ones((25, 25))
>>> mask = np.zeros(data.shape, dtype=bool)
>>> mask[12, 12] = True  # bad pixel inside the first aperture
>>> positions = [(12.0, 12.0), (0.0, 12.0), (-50.0, 12.0)]
>>> aperture = CircularAperture(positions, r=3.0)
>>> phot = AperturePhotometry(data, aperture, mask=mask)
>>> decoded = decode_aperture_flags(phot.flags)
>>> for source_id, names in zip(phot.id, decoded):
...     print(source_id, names)
1 ['masked_pixels']
2 ['partial_overlap']
3 ['no_overlap', 'no_pixels']

See Aperture Quality Flags for more details.

Circular Apertures as Ellipses#

A circle on the sky maps to an ellipse in pixel coordinates whenever the pixels are not square or the WCS is sheared, and likewise a pixel circle maps to an ellipse on the sky. The to_pixel and to_sky methods of CircularAperture, CircularAnnulus, SkyCircularAperture, and SkyCircularAnnulus now accept an as_ellipse keyword. If True, the image of the circle under the local linear WCS at the reference position is returned as an ellipse instead of a circle scaled by the mean pixel scale. The default remains a circle, so existing results are unchanged:

>>> import astropy.units as u
>>> from astropy.coordinates import SkyCoord
>>> from astropy.wcs import WCS
>>> from photutils.aperture import SkyCircularAperture
>>> wcs = WCS(naxis=2)
>>> wcs.wcs.ctype = ['RA---TAN', 'DEC--TAN']
>>> wcs.wcs.crval = [150.0, 20.0]
>>> wcs.wcs.crpix = [50.0, 50.0]
>>> wcs.wcs.cdelt = [-0.05 / 3600, 0.03 / 3600]  # nonsquare pixels
>>> aperture = SkyCircularAperture(SkyCoord(150.0, 20.0, unit='deg'),
...                                r=1 * u.arcsec)
>>> ellipse = aperture.to_pixel(wcs, as_ellipse=True)
>>> ellipse
<EllipticalAperture([49., 49.], a=33.33333336112715, b=20.000000013646787, theta=90.00000000582446 deg)>

For most imagers the pixel anisotropy is a percent or less, and the flux difference between the ellipse and the mean-scale circle is negligible. The ellipse matters for strongly rectangular pixels or a strongly sheared WCS, and whenever the footprint of the aperture must follow the WCS rather than the mean pixel scale.

Faster Aperture WCS Conversions#

The to_sky and to_pixel methods of all apertures are now two to five times faster. The to_pixel methods of the sky apertures invert the WCS only once, for the aperture positions, and reuse that pixel position for the shape conversion.

Background Package#

Multithreaded 2D Background Estimation#

Background2D now accepts an n_threads keyword to compute the box statistics using multiple threads. The boxes are divided into chunks and processed concurrently, producing results identical to the single-threaded computation. The underlying sigma-clipping and statistics kernels release the Python global interpreter lock (GIL), so the threads run in parallel:

>>> import numpy as np
>>> from photutils.background import Background2D
>>> rng = np.random.default_rng(seed=0)
>>> data = rng.normal(100.0, 5.0, (4096, 4096))
>>> bkg = Background2D(data, (64, 64), n_threads=8)

The n_threads keyword also multithreads the interpolation of the low-resolution meshes to the full-size background and background_rms maps (for the 'reflect' and 'mirror' interpolation boundary modes, with SciPy 1.16 or later).

Background2D is also significantly faster when the sigma_clip, bkg_estimator, and bkg_rms_estimator inputs are among the standard photutils options. The sigma clipping and the box statistics are then computed in a single combined pass in compiled code. Custom estimator callables use the previous implementation and give the same results as before.

In addition, Background2D instances are now immutable after construction (aside from internal lazy-attribute caches), so a single instance is safe to share across threads and independent images can be processed concurrently.

Faster Local Backgrounds#

LocalBackground is now significantly faster when the bkg_estimator is a standard photutils estimator class. The local backgrounds for all positions are computed with the batched ApertureStats kernels instead of a Python loop over the apertures. A new n_threads keyword measures the local backgrounds using multiple threads, with results identical to the single-threaded computation. Quantity input data is now also supported, and the result has the same unit as the input data.

Centroids Package#

Symmetry Centroid#

The new centroid_symmetry function calculates the center of a source as the point about which its core is most symmetric under a rotation by 180 degrees. This is the definition of the center of an ePSF of Anderson 2016 (WFC3 ISR 2016-12). Unlike the center of mass, it is insensitive to asymmetric structure around the core.

It is now the default recentering_func of EPSFBuilder (see New EPSFBuilder Default Recentering).

Profiles Package#

The profile_error values of the profile classes are now corrected for partial pixels (see Corrected Flux Errors for Partial Pixels).

Faster and Thread-Safe Profiles#

The radial profile and curve-of-growth classes are now about 3x faster. The aperture photometry and unmasked areas for all radii are computed in a single batched AperturePhotometry call instead of one calculation per radius. The profile classes are now also thread-safe.

PSF Package#

Faster PSF Fitting via Analytic Jacobians#

The image-based PSF models ImagePSF and GriddedPSFModel now provide analytic Jacobians through their fit_deriv methods, computed from the derivatives of their interpolating splines. Astropy fitters use the Jacobian automatically during PSF photometry, removing the need for finite-difference approximations of the parameter derivatives. This eliminates roughly 60% of the model evaluations performed during fitting, speeding up PSF photometry with these models with no change in the fitted results.

The pixel-integrated Gaussian models GaussianPRF, CircularGaussianPRF, and CircularGaussianSigmaPRF, and the MoffatPSF and AiryDiskPSF models, also provide analytic Jacobians. All of the PSF models in photutils.psf now have one, so the fitted positions and fluxes no longer depend on the step size of a finite-difference approximation.

GriddedPSFModel and ImagePSF Performance Improvements#

GriddedPSFModel and ImagePSF evaluations are now significantly faster. Both models evaluate their interpolating splines, and the spline derivatives of their analytic Jacobians, with a compiled kernel instead of separate spline calls. For fit regions of 5x5 to 25x25 pixels, GriddedPSFModel evaluations are about 3 to 8 times faster and its Jacobian evaluations about 6 to 14 times faster. ImagePSF evaluations are about 1.2 to 3 times faster and its Jacobian evaluations about 2 to 5 times faster. This improves the runtime of PSF photometry workflows.

The models also use less memory. They cache a single set of spline coefficients, which is about a third of the memory that the cached splines used when the Jacobian is evaluated.

Defining a custom interpolator for ImagePSF, by overriding its interpolator attribute in a subclass or by assigning an interpolator to it, is now deprecated and will be removed in version 4.0. A model with a custom interpolator calls it as before and does not use the compiled kernel.

Scalable Source Grouping#

SourceGrouper now computes groups using a KD-tree connected-components algorithm instead of building a dense pairwise distance matrix. The resulting groups are identical to the previous single-linkage clustering, but grouping now scales to very large source lists in both runtime and memory.

Multithreaded PSF Photometry#

PSFPhotometry and IterativePSFPhotometry now accept an n_threads keyword to fit the source groups using multiple threads. The groups are divided into chunks that are fitted concurrently, each thread with its own copy of the PSF model and the fitter, producing results identical to the single-threaded computation:

>>> from photutils.psf import CircularGaussianPRF, PSFPhotometry
>>> psf_model = CircularGaussianPRF(fwhm=2.7)
>>> psfphot = PSFPhotometry(psf_model, (5, 5), n_threads=8)

Unlike the compiled aperture and background code, the PSF fitting runs mostly in Python code that holds the Python global interpreter lock (GIL). The threads therefore run in parallel only on a free-threaded CPython build, where measured speedups are ~1.8x with 2 threads and ~5x with 8 threads. When the GIL is enabled, threads would be slower than a single thread, so a warning is issued and the sources are fitted in a single thread.

PSF Photometry Fit Region Flag#

PSFPhotometry and IterativePSFPhotometry have a new bitwise flag (bit 4096, position_outside_fit_region) that is set when the fitted source position is outside the region of fitted data. The region is the fit_shape box around the initial position, trimmed to the input image. Such a fit is constrained only by the PSF wings, often because it moved toward a neighboring source. Unlike the position_outside_image flag (bit 2), which is set only for positions outside the input image, this flag also catches fits that move away from their data within the image. For grouped fits, the region is the box of each source, not the union of the boxes of the group.

Making an ePSF from a Sampled PSF#

The new make_epsf_from_psf function makes an effective PSF (ePSF) image from an oversampled PSF image whose values are samples of the PSF, such as the output of an optical model. The image-based PSF models ImagePSF and GriddedPSFModel interpolate their input images and do not integrate them over the detector pixels. They therefore require ePSF images, in which each value is the flux in a whole detector pixel centered at that position. A model made from a sampled PSF is sharper than the sources in the data. If the PSF is also undersampled by the detector pixels, the total flux of the evaluated model changes with the subpixel position of the source. The new function integrates the image over the area of a detector pixel centered at each grid point, which gives a model that conserves flux:

>>> from photutils.psf import ImagePSF, make_epsf_from_psf
>>> epsf = make_epsf_from_psf(psf, oversampling=4)
>>> model = ImagePSF(epsf, oversampling=4)

An optical model with an even oversampling factor typically returns an image with an even number of points, with the PSF centered between the four central grid points. The midpoints=True option makes the ePSF at the points midway between the input grid points. The result has an odd number of points with the PSF center on its central grid point, like the ePSFs made by EPSFBuilder.

Pixel-Integrated Moffat and Airy Disk Models#

The new MoffatPRF and AiryDiskPRF models are the Moffat and Airy disk profiles integrated over the detector pixels. They have the same parameters as MoffatPSF and AiryDiskPSF, which are evaluated at the pixel centers. A model that is evaluated at the pixel centers is sharper than the image of a source, so it gives biased fluxes and positions when it is fit to the pixel values of an image. The bias is a few percent for a FWHM of 2 to 3 pixels and tens of percent for an undersampled PSF, where it also depends on the subpixel position of the source. The new models remove that bias and their shape parameters can be fit. Every analytic PSF model in photutils.psf now has a pixel-integrated counterpart, which should be used for PSF photometry.

The integral over each pixel is computed with Gauss-Legendre quadrature. The number of nodes along each axis of a pixel is set by the n_nodes keyword. With the default of 9 nodes, the new models are about 10 times slower to evaluate than MoffatPSF and AiryDiskPSF on the small cutouts used for PSF fitting.

More Robust ePSF Building#

EPSFBuilder no longer produces a checkerboard pattern in the ePSF when the input stars are heterogeneous. This includes stars from exposures with different PSFs, saturated or contaminated cutouts, spurious detections, and low signal-to-noise stars. The issue occurred when the oversampling factor was greater than one.

Previously, each star-pixel residual was assigned to the nearest oversampled grid point. As a result, neighboring grid points were estimated from different subsets of stars. These subsets were selected based on the stars’ subpixel phases. Noise in the grid biased the fitted star centers toward particular subpixel phases. This prevented alternate grid points from being sampled evenly. The effect grew with each iteration and produced a checkerboard, or alias, pattern.

Now, each star-pixel residual is deposited on the oversampled grid points within 0.375 pixel (and at least one grid spacing) of the pixel center along each axis. This ensures that every star contributes to both parities of the grid, regardless of its subpixel phase. In each iteration, power near and above one cycle per input pixel is also removed from the ePSF with a low-pass filter (unit gain up to 0.8 cycles per input pixel, or 0.7 for an oversampling factor of 2). Here a spatial frequency of one cycle per pixel describes structure that repeats with a period of one input pixel, and a frequency of 0.5 cycles per pixel describes structure that repeats every two pixels. A pixel-integrated PSF has essentially no signal at one cycle per input pixel. However, that is the frequency at which the star-pixel sampling lattice aliases onto the oversampled grid. The new alias_passband keyword sets the passband of this filter. The ePSF of a strongly undersampled detector (e.g., HST WFC3/IR F110W, JWST NIRCam F070W, or Roman WFI F062) has real signal just below one cycle per pixel, and a value of 0.85 or 0.9 with more iterations recovers the peak of such an ePSF more accurately than the default. See the ePSF building user guide for how to choose the value.

After the building iterations, the ePSF is now refined (refinement_iters, 5 by default) for an oversampling factor of 4 or larger. Each refinement iteration updates the ePSF with the star centers and fluxes held fixed and then refits the stars. These updates use a low-pass filter that does not remove signal near one cycle per pixel, so they restore the real signal of an undersampled ePSF that the filter of the building iterations removes. Without the refinement, that missing signal shows as a ripple pattern along the row and the column through the center of the ePSF. The convergence attributes of EPSFBuildResults then describe the last refinement iteration, so that they match the returned stars.

The EPSFBuildResults now keep the ePSF image of every iteration (iteration_epsfs) and a table of the convergence statistics of each iteration (iteration_info), as well as the image of the input ePSF, if any (initial_epsf). The new plot_iterations method plots the ePSF after each iteration and its change from the previous iteration, which shows whether the build has stopped changing and where it is still changing.

The new center_asymmetry attribute of the results is the offset of the center of mass of the built ePSF from its symmetry center (see centroid_symmetry). The center of an asymmetric ePSF is a convention, and this offset is the amount by which the star positions measured with the ePSF depend on that convention.

The wings of the final ePSF are now smoothed more strongly than its core (wing_smoothing, True by default). Beyond 3.5 FWHM from the center, where the ePSF is faint and varies slowly, each value is replaced by a least-squares quadratic fit to the values in a box 1.25 to 1.75 FWHM wide. This lowers the noise of the wings, by up to about 50% for undersampled ePSFs built from a few hundred stars. The core changes only by the renormalization of the smoothed ePSF (less than 0.03% in tests). The smoothing also removes real structure in the wings that is finer than about two FWHM, such as diffraction rings and spikes, so set wing_smoothing=False for large star samples of high signal-to-noise. With an oversampling factor of 1 it can make the wings of a strongly undersampled ePSF less accurate (see the ePSF building user guide).

On clean data, the ePSF is at least as accurate as before and is often better. Star centers are recovered more accurately, and the build converges in fewer iterations. A warning is now emitted if the fitted star centers have strongly nonuniform subpixel phases at the end of the build. This indicates that the star centers may be biased.

The ePSF building user guide now includes guidelines for choosing the oversampling factor and the star sample, e.g., using at least about four grid points per FWHM, not using an oversampling factor larger than the data require, and providing enough stars to sample every subpixel cell.

The fluxes of linked stars (the same star observed in multiple dithered images) are now constrained to their mean value after each fitting iteration, in addition to their centers. This breaks the degeneracy between the flux of a star and its subpixel position caused by intra-pixel sensitivity variations, which would otherwise be absorbed into the ePSF. Set constrain_fluxes=False if the linked images have different flux scales. The constraint is also available as the new constrain_fluxes() method.

The default smoothing kernel and fitting box now scale with the FWHM of the ePSF (smoothing_kernel='auto' and fit_shape='auto'). The previous fixed 5x5 'quartic' kernel (in oversampled grid points) and 5-pixel fitting box (in detector pixels) were designed for HST images with an oversampling factor of 4, where they correspond to about 0.7 and 2.5 FWHM, respectively. A fixed kernel oversmooths heavily undersampled ePSFs, and a fixed 5-pixel fitting box applied to a well-sampled star uses only its flat core, which biases the fitted centers and can prevent the build from converging. The automatic kernel is a least-squares quartic polynomial kernel at most 0.7 FWHM wide in oversampled grid points (no smoothing below 5 grid points, i.e., for fewer than about 7 grid points per FWHM), and the automatic fitting box is 2 FWHM wide in detector pixels (at least 5 pixels and at most the star cutout size). The choices made in the final iteration are reported in the new smoothing_kernel and fit_shape attributes of EPSFBuildResults, and they can be input as fixed values to reproduce the build. The previous behavior is available with smoothing_kernel='quartic' and fit_shape=5.

ePSF building is also faster. The build now converges when at least a converged_fraction (default 0.95) of the successfully fitted stars have settled to the requested center_accuracy, instead of requiring every star. A few spurious detections or contaminated cutouts whose centers never settle previously forced the build to run to maxiters. On a real sample of about 2000 stars with 30% spurious detections, the build now stops after 6 iterations instead of 100, in 21 seconds instead of about 5 minutes. The fraction achieved is reported in the new final_converged_fraction attribute of the results, and converged_fraction=1.0 restores the previous behavior. Each iteration is also about 20% faster (25% at an oversampling of 4) because the ePSF spline interpolators are built once per iteration instead of once per star and the star residuals are stacked in a single vectorized operation.

New EPSFBuilder Default Recentering#

The new centroid_symmetry function is now the default recentering_func of EPSFBuilder, which previously centered the ePSF on its center of mass in a 5x5 pixel box. The center of an asymmetric PSF is a convention, and the star positions that are fit with an ePSF follow the convention of that ePSF. The center of mass is pulled toward asymmetric structure around the core, such as an uneven first diffraction ring. In tests with simulated JWST and Roman PSFs, the positions fit with a center-of-mass ePSF were offset from the position of the source in the optical model by up to 0.1 pixel, and by 0.05 pixel or less with a symmetry-centered ePSF. The offset is the same for every star, so it does not affect relative positions measured with one ePSF, but it differs from filter to filter. The accuracy of the built ePSF and of the fitted fluxes is unchanged. Positions fit with a newly built ePSF therefore differ from those of earlier versions by a constant offset for an asymmetric PSF. Use recentering_func=centroid_com to restore the previous centering.

The convergence of a build is now measured from the changes of the star centers relative to their median change. A change that is common to all the stars is a shift of the center of the ePSF, which changes neither its shape nor the relative positions of the stars. The median change must itself be less than center_accuracy, and it is reported in the new common_center_shift column of iteration_info. With this criterion the converged flag depends much less on the recentering function.

Extracting Stars from Plain Arrays#

The extract_stars function now accepts a plain 2D array, or a list of 2D arrays, as the input data. The image no longer needs to be wrapped in an NDData object:

>>> from photutils.psf import extract_stars
>>> stars = extract_stars(data, catalog, size=25)

The stars extracted from a plain array are given uniform weights, and the star positions must be input in pixel coordinates. The masked pixels of a MaskedArray are given zero weight. An NDData object is still needed to input an uncertainty, a mask, or a WCS along with the image.

Segmentation Package#

Some changes in the aperture package also apply to the segmentation package:

Centroid Position Errors#

SourceCatalog now provides 1-sigma errors on the isophotal, windowed, and quadratic centroid positions, propagated from the input error array. The new properties are centroid_err, x_centroid_err, and y_centroid_err for the isophotal centroid, centroid_win_err, x_centroid_win_err, and y_centroid_win_err for the “windowed” centroid (centroid_win), and centroid_quad_err, x_centroid_quad_err, and y_centroid_quad_err for the quadratic-fit centroid (centroid_quad):

>>> import numpy as np
>>> from astropy.convolution import convolve
>>> from photutils.datasets import make_100gaussians_image
>>> from photutils.segmentation import (SourceCatalog, SourceFinder,
...                                     make_2dgaussian_kernel)
>>> data = make_100gaussians_image() - 5.0  # subtract background
>>> error = np.full(data.shape, 2.0)
>>> kernel = make_2dgaussian_kernel(3.0, size=5)
>>> convolved_data = convolve(data, kernel)
>>> finder = SourceFinder(n_pixels=10)
>>> segment_map = finder(convolved_data, 4.5)
>>> cat = SourceCatalog(data, segment_map,
...                     convolved_data=convolved_data, error=error)
>>> columns = ['label', 'x_centroid_err', 'y_centroid_err',
...            'x_centroid_win_err', 'y_centroid_win_err']
>>> tbl = cat.to_table(columns=columns)[:5]
>>> for col in tbl.colnames[1:]:
...     tbl[col].info.format = '%.6f'
>>> print(tbl)
label x_centroid_err y_centroid_err x_centroid_win_err y_centroid_win_err
----- -------------- -------------- ------------------ ------------------
    1       0.107193       0.040633           0.096188           0.081614
    2       0.115570       0.069543           0.145871           0.146489
    3       0.083684       0.087086           0.144631           0.144630
    4       0.078204       0.104136           0.158468           0.158468
    5       0.081175       0.098188           0.181951           0.181947

When a wcs is also input, the corresponding 1-sigma sky position errors are available in arcsec via the sky_centroid_err, sky_centroid_ra_err, and sky_centroid_dec_err properties (and their _win and _quad variants), computed by transporting the pixel centroid error covariance through the local WCS Jacobian. The RA errors are expressed as great-circle angles along the East direction (i.e., they include the cos(dec) factor).

Sky Orientation of Sources#

SourceCatalog and ApertureStats have new sky_orientation and sky_orientation properties giving the position angle on the sky of the major axis of each source, measured from North toward East in the range (-90, 90] degrees. It is computed by transporting the pixel covariance matrix to the local tangent plane with the WCS Jacobian at each source centroid, so it accounts for the WCS rotation, parity, and local distortion:

>>> import numpy as np
>>> from astropy.modeling.models import Gaussian2D
>>> from photutils.datasets import make_wcs
>>> from photutils.segmentation import SourceCatalog, detect_sources
>>> yy, xx = np.mgrid[0:31, 0:31]
>>> theta = np.deg2rad(70.0)
>>> data = Gaussian2D(500.0, 15.0, 15.0, 3.0, 1.5, theta)(xx, yy)
>>> segm = detect_sources(data, 10.0, n_pixels=10)
>>> wcs = make_wcs(data.shape)
>>> cat = SourceCatalog(data, segm, wcs=wcs)
>>> print(cat.orientation.to_value('deg').round(2))
[70.49]
>>> print(cat.sky_orientation.to_value('deg').round(2))
[40.49]

Segmentation Quality Flags#

The segmentation package now provides bitwise quality flags. SourceCatalog has a new flags attribute and default table column that records, per source, deblending provenance (deblended, deblending-mode fallbacks) and measurement conditions (source touches an image boundary, masked or nonfinite pixels within the segment, undefined or degenerate shape properties, Kron-aperture issues, and a local background with too few usable annulus pixels).

SegmentationImage exposes the per-label provenance flags via a new flags attribute, and a new decode_segmentation_flags() function decodes flag values into names. The flag definitions are available in the new public SEGMENTATION_FLAGS registry.

decode_flags() is a convenience method that decodes the catalog’s own flag values into a dictionary keyed by source label. Flags describing the same condition as an aperture flag share the aperture flag’s name. However, the bit values are package-specific, so always decode a flag column with the decoder of the package that produced it. The new centroid_win_fallback and centroid_quad_fallback properties report where the windowed or quadratic centroid was replaced by the isophotal centroid or the peak pixel position.

The kron_minimum_radius flag marks sources whose kron_radius was set to the minimum Kron radius or replaced by the minimum circular aperture. This is common for compact sources because the unscaled Kron radius of a Gaussian source is about 1.25, which is below the default minimum of 1.4. The new kron_radius_measured property returns the measured Kron radius before the kron_params minimum values are applied.

Faster Source Catalog Measurements#

SourceCatalog is now significantly faster. The windowed and quadratic centroids, Kron radii and photometry, flux_radius, circular_photometry, image moments, perimeter, gini, the segment pixel statistics (e.g., segment_flux, area, and min_value), and the positions of the minimum and maximum pixel values are each computed for all sources in a single call into compiled code, replacing the per-source Python loops and cutouts. Typical speedups range from ~3x to ~20x depending on the property, and the flags attribute and the default to_table() output are about 5x faster for large catalogs. The results are unchanged to within floating-point rounding. Because no property loops over the sources in Python anymore, no progress bar is displayed and the progress_bar keyword is deprecated (see New Deprecations).

The compiled code reads the input arrays directly when they share a common float32 or float64 dtype. Otherwise, it makes full-image working copies that are cached for the lifetime of the catalog. The new release_cache() method frees that memory after the desired properties have been calculated.

Faster Segmentation Images#

Creating a SegmentationImage and getting its labels, areas, and slices attributes is now typically ~3x to ~15x faster, depending on the number of labels and the fraction of labeled pixels. They are measured by compiled code in a single pass over the segmentation array, producing identical results.

Mapping Labels Between Segmentation Images#

The new get_label_mapping() method finds the mapping of labels between two segmentation images defined on the same pixel grid. For each label, it returns the labels in the other segmentation image that cover any of the same pixels. A typical use is mapping the original (parent) labels to the deblended (child) labels for segmentation images made before and after deblending, e.g., images read from files.

Source Deblending Performance Improvements#

Source deblending with deblend_sources() and SourceFinder is now typically 7 to 30 times faster, producing identical results. The whole watershed step now runs in compiled code.

The compiled watershed kernel produces results identical to skimage.segmentation.watershed, so scikit-image is no longer an optional dependency.

A new n_threads keyword in deblend_sources() and SourceFinder deblends the sources using multiple threads. The sources are divided into chunks and processed concurrently, producing results identical to the single-threaded computation. Each chunk of sources is deblended by a few compiled calls that release the GIL, so multithreading also speeds up fields of many small sources.

A new contrast_method keyword selects the flux used by the deblending contrast criterion. The 'basin' method preserves the existing behavior where the contrast fraction is the total flux in the source’s watershed basin, and below-contrast basins are removed iteratively. The new 'saddle' method instead measures the flux a source holds above the saddle level where it separates from its neighbors. It measures the significance of the peak itself, independently of how much envelope territory the source would inherit from the watershed, and requires only a single watershed pass, so it is never slower and is substantially faster when many below-contrast basins would otherwise be removed iteratively. The default of None currently resolves to 'basin'. The default may change to 'saddle' in version 4.0.

Utils Package#

Per-Pixel Sky Areas from a WCS#

The new compute_pixel_areas() and compute_pixel_area_map() functions compute the on-sky area of image pixels directly from a WCS, either at an array of positions or for every pixel in an image. The area of each pixel is the absolute determinant of the local WCS Jacobian, evaluated with central finite differences, so it follows the distortion across the field and is well defined at the celestial poles and across the RA wraparound. Both functions accept any WCS that supports the astropy shared WCS interface, including gwcs objects.

The pixel area of a distorted image typically varies by a few percent across the field. Converting a surface-brightness image (e.g., in MJy/sr) to fluxes with a single nominal pixel area therefore leaves a position-dependent error. Multiplying by the pixel-area map removes it:

>>> import astropy.units as u
>>> from photutils.datasets import make_wcs
>>> from photutils.utils import compute_pixel_area_map
>>> shape = (100, 100)
>>> wcs = make_wcs(shape)
>>> areas = compute_pixel_area_map(wcs, shape) * u.arcsec**2
>>> areas[50, 50]
<Quantity 0.01 arcsec2>
>>> pixel_area_sr = areas.to(u.sr)  # multiply a MJy/sr image by this

The map is interpolated from a coarse grid of positions by default, which is accurate to better than a part per million for typical distortions. Pass interpolate=False to evaluate the area exactly at every pixel instead.

API Changes#

New Deprecations#

PixelAperture.do_photometry Deprecated#

The PixelAperture.do_photometry method is now deprecated and will be removed in version 4.0. Use the new AperturePhotometry class instead.

ApertureStats.ids Renamed#

The ApertureStats ids attribute has been renamed to id. The old ids name is deprecated and will be removed in version 4.0.

ApertureStats.n_apertures Renamed#

The ApertureStats n_apertures attribute has been renamed to n_positions, matching the AperturePhotometry attribute of the same name (both count the aperture positions). The old n_apertures name is deprecated and will be removed in version 4.0.

DEFAULT_COLUMNS Constants Deprecated#

The DEFAULT_COLUMNS constants in the photutils.aperture.stats and photutils.segmentation.catalog modules were removed in version 3.1.0 without a deprecation period. Version 3.1.1 restores them as deprecated names that will be removed in version 4.0. They contain the 3.0 default columns, which do not include the flags column. Use the default_columns attribute of ApertureStats or SourceCatalog instead.

Dataset Loading Functions Deprecated#

The load_irac_psf() and load_simulated_hst_star_image() functions are deprecated and will be removed in version 4.0. The Spitzer/IRAC PSF images and the simulated HST star image remain available in the photutils-datasets repository and can be loaded directly with astropy.io.fits.getdata(), as shown in the PSF matching and ePSF building user guides.

make_psf_model Deprecated#

The make_psf_model() function is deprecated and will be removed in version 4.0. The PSF models provided by photutils.psf now cover the Gaussian, Moffat, and Airy disk profiles that it was mostly used to wrap, and they are faster to fit. The models that it returns are also not integrated over the detector pixels, and their flux is not the total flux if a shape parameter is fit. For other PSF profiles, make an ImagePSF from the output of make_epsf_from_psf(), or define a custom Fittable2DModel with x_0, y_0, and flux parameters (see Custom PSF Models).

EPSFBuildResult Renamed to EPSFBuildResults#

The EPSFBuildResult class returned by EPSFBuilder has been renamed to EPSFBuildResults. The old EPSFBuildResult name is deprecated and will be removed in version 4.0.

PSF Flags Renamed#

Several flags of PSFPhotometry and IterativePSFPhotometry have been renamed so that each name states what it describes:

  • outside_bounds (bit 2) is now position_outside_image. The new name states what is outside the image and avoids confusion with parameter_near_bound.

  • negative_flux (bit 4) is now non_positive_flux, because the flag is also set for a zero fitted flux.

  • near_bound (bit 32) is now parameter_near_bound, stating that a fitted parameter is near its bound.

  • non_finite_localbkg (bit 2048) is now non_finite_local_bkg, matching the local_bkg column name.

The flag constants have been renamed in the same way (e.g., OUTSIDE_BOUNDS is now POSITION_OUTSIDE_IMAGE). The old names are deprecated and will be removed in version 4.0. The bit values are unchanged, but decode_psf_flags() now returns the new names, so code that compares decoded names with the old names must be updated.

EPSFBuilder.coord_transformer Deprecated#

The EPSFBuilder coord_transformer attribute is deprecated and will be removed in a future version. It is an internal helper object that was never intended to be public.

Custom ImagePSF Interpolators Deprecated#

Defining a custom interpolator for ImagePSF, by overriding its interpolator attribute in a subclass or by assigning an interpolator to it, is deprecated and will be removed in version 4.0.

Deblending progress_bar and n_processes Deprecated#

The progress_bar and n_processes keywords of deblend_sources() and SourceFinder are deprecated and will be removed in version 4.0, and both keywords no longer have any effect. Deblending is now dominated by compiled code, so no progress bar is displayed, and the multiprocessing implementation has been removed because its process startup and data-pickling overheads made it slower than the serial implementation. Use the new n_threads keyword for multithreaded deblending instead.

inertia_tensor Deprecated#

The inertia_tensor property of SourceCatalog and ApertureStats is deprecated and will be removed in version 4.0. The inertia tensor carries no information beyond the covariance matrix. It has the same eigenvectors, and it is equal to the total flux times the difference between the trace of the covariance matrix times the identity matrix and the covariance matrix, with its rows and columns in the reverse (y, x) order. Use the covariance property and the shape properties that are derived from it instead.

SourceCatalog.progress_bar Deprecated#

The SourceCatalog progress_bar keyword is deprecated and will be removed in version 4.0. All property calculations are now computed for all sources at once in compiled code, so no progress bar is displayed and the keyword has no effect.

ShepardIDWInterpolator.ncoords Renamed#

The ShepardIDWInterpolator ncoords attribute has been renamed to n_coords for naming consistency within photutils. The old ncoords name is deprecated and will be removed in version 4.0.

Breaking Changes#

Pixel Scale of Circular Aperture Conversions#

The to_pixel and to_sky methods of the circular apertures and annuli now use the geometric mean of the two singular values of the local WCS Jacobian as the isotropic pixel scale for every WCS. This scale preserves the area of the mapped circle and inverts exactly, so a conversion to pixels and back returns the original radius. Previously, a distorted WCS or a gwcs used the arithmetic mean of the singular values. The radii are unchanged for an undistorted WCS with orthogonal pixel axes.

Aperture Photometry Masks Must Be Boolean#

The mask input to aperture photometry and to the aperture area_overlap method must now be a boolean array (or None).

StarFinderCatalogBase Representation#

The repr and str output of StarFinderCatalogBase now labels the number of sources as n_sources instead of nsources for naming consistency within photutils.

find_peaks min_separation Enforcement#

The min_separation keyword of find_peaks() now strictly enforces the minimum separation between all returned peaks. Previously, the result was equivalent to passing a circular footprint of the given radius to maximum_filter(), which returns every pixel that is tied for the maximum. Pixels with identical values could therefore all be returned as peaks, even when they were adjacent (e.g., the pixels of a saturated star or peaks in integer-valued data).

Pixels with identical values are now handled in two steps. First, each group of connected peak pixels is replaced by its pixel nearest to the centroid of the group. A saturated star therefore gives one peak near its center, even if its saturated core is larger than min_separation. Second, for any remaining equal-valued peaks that are separated by min_separation or less, only one is kept. The peak of the largest group of connected pixels is preferred, so that a saturated star is kept instead of a nearby isolated saturated pixel.

The returned peaks are a subset of the peaks previously found. Use a circular footprint to return every pixel that is tied for the maximum, as before. The star finder classes (DAOStarFinder, IRAFStarFinder, and StarFinder), which use min_separation internally, may now return fewer sources if the convolved image has pixels with identical values. Such pixels are uncommon for floating-point data.

Note that the star finders apply min_separation to the integer peak-pixel positions. The subpixel centroids computed afterwards may shift sources slightly, so the centroid-based separations in the output tables can be slightly smaller than min_separation.

IRAFStarFinder Minimum Number of Pixels#

IRAFStarFinder now rejects sources with fewer than 5 positive sky-subtracted pixels within the kernel footprint by default. This matches the default (and minimum) value of the npixmin parameter in IRAF’s starfind. Previously, only 2 such pixels were required, so fewer faint sources may now be returned.

The threshold is set by the new min_n_pixels keyword. Set min_n_pixels=2 to recover the previous behavior.

Exact Pixel Integration of a Rotated GaussianPRF#

GaussianPRF is now integrated exactly over the detector pixels for any rotation angle. Previously, the integration was performed along the rotated principal axes of the Gaussian, which is the integral over a rotated pixel and was exact only for theta = 0. The model values for a rotated Gaussian with different x and y widths change by up to about 1% of the peak for a FWHM of 1 pixel and by less than 0.1% for a FWHM of 2 pixels or more. The model now conserves flux for any subpixel position of the source. A rotated Gaussian is evaluated with Owen’s T function, which is about four times slower than the product of error functions that is still used when the Gaussian is not rotated (roughly 0.2 ms instead of 0.05 ms for a 25x25 pixel stamp). The slower evaluation applies only when theta is not a multiple of 90 degrees and the x and y widths differ. Positions that are not on a grid with a spacing of one pixel are about ten times slower, because their pixels share no corners.

PSF Photometry mask and error with NDData Input#

The mask and error keywords of PSFPhotometry and IterativePSFPhotometry now raise a ValueError when the input data is an NDData instance. Previously, they were silently ignored in favor of the NDData attributes.

PSF decode_flags Methods Return a Dictionary#

The photutils.psf.PSFPhotometry.decode_flags() and photutils.psf.IterativePSFPhotometry.decode_flags() methods now return a dictionary mapping each source ID from the results table to its list of active flag names (or bit values), instead of a positional list of lists. Decoded flags can now be looked up directly by source ID, which may not be sequential when custom IDs are input via init_params, and the result is consistent with the new aperture and segmentation decode_flags methods. Code that iterated over the previous list should iterate over the dictionary’s .values() (or .items() to also get the source IDs). The module-level decode_psf_flags() function is unchanged and still returns lists.

WebbPSF ePSF Grid Positions#

Reading a WebbPSF gridded-ePSF FITS file with webbpsf_reader() (or GriddedPSFModel.read(..., format='webbpsf')) now assigns the reference ePSFs to the correct detector positions. The DET_YX{i} header keywords record each position as (y, x), but the values were previously stored as (x, y), which transposed the ePSF grid. Grids whose x and y fiducial positions are identical (such as the square NIRCam short-wavelength grids) are unaffected.

STDPSFGrid Metadata#

The grid_xypos, oversampling, and grid_shape keys have been removed from the STDPSFGrid meta dictionary. The meta dictionary now contains only the metadata parsed from the filename (e.g., STDPSF, detector, and filter). The grid positions, oversampling factors, and grid shape are available as the grid_xypos and oversampling attributes and the new grid_shape property, which are now the single source of truth for this information:

>>> from photutils.psf import STDPSFGrid
>>> psfgrid = STDPSFGrid('STDPSF_ACSWFC_F814W.fits')
>>> psfgrid.grid_xypos  # instead of psfgrid.meta['grid_xypos']
>>> psfgrid.oversampling  # instead of psfgrid.meta['oversampling']

The grid_xypos attribute is now a ndarray instead of a list, matching the GriddedPSFModel attribute of the same name, and oversampling is now a read-only property.

Relatedly, the GriddedPSFModel meta dictionary now always stores 'grid_xypos' as the sorted array of grid positions and 'oversampling' as a normalized (y, x) tuple, so that both always match the attributes of the same name.

GriddedPSFModel 'grid_shape' Metadata Key#

The 'grid_shape' key has been removed from the GriddedPSFModel meta dictionary. Use the new grid_shape attribute instead, i.e., psfmodel.grid_shape instead of psfmodel.meta['grid_shape']. The redundant nxpsfs and nypsfs metadata keys of a GriddedPSFModel read from a STDPSF file have also been removed.

resize_psf Output Size#

resize_psf() now returns a PSF with exactly the requested pixel scale. Previously, the output pixel scale was off by a factor of (n_in - 1) / (n_out - 1), where n_in and n_out are the input and output sizes, which made the resized PSF too broad or too narrow by up to several percent. The output size is now the largest odd size for which the output grid lies within the outermost pixel centers of the input PSF, which can be smaller than before.

Deblending Fallback for Nonpositive Minima Changed to sinh#

When deblending with mode='exponential' (the default), sources with nonpositive minimum data values cannot use the exponential threshold spacing and fall back to another mode. The fallback mode has changed from “linear” to “sinh”. Like the linear spacing, the sinh spacing is well defined for any data values, but it keeps the threshold levels concentrated near the source minimum, recovering faint companions of bright sources that the linear spacing misses. Deblending results can therefore change for the affected sources, which continue to be recorded under the 'non_positive_min_labels' key of the info attribute and flagged with deblend_non_positive_min. To reproduce the previous spacing for such sources, pass mode='linear'. Note that this applies the linear spacing to every source, which is the only way to obtain the previous behavior.

Covariance Regularization of Unresolved Sources#

The covariance matrix of SourceCatalog and ApertureStats is regularized for unresolved sources, because a source cannot have a second moment smaller than 1/12 pixel**2, the variance of a uniform distribution across a single pixel. Previously, 1/12 was added to both diagonal elements when the covariance determinant was below (1/12)**2. That approach missed a thin source that is unresolved along only its minor axis if its major axis is long, inflated the variance along a resolved axis, and was discontinuous.

The variance along each principal axis (each eigenvalue of the covariance matrix) is now raised to at least 1/12 while the orientation is kept. A resolved axis is not modified, and the result is a continuous function of the image moments. The sources that are regularized are exactly those with the singular_covariance flag. Sources whose second-order moments are not positive semidefinite have NaN shape properties and the undefined_shape flag instead. A source that is unresolved along both axes becomes isotropic with an orientation of zero. An exactly thin tilted source, whose covariance determinant is zero apart from rounding, is now regularized instead of having NaN shape properties.

Orientation Range#

The orientation values returned by SourceCatalog, DAOStarFinder, and IRAFStarFinder are now in the range (-90, 90] degrees, consistent with ApertureStats. Previously, they were incorrectly wrapped to [0, 360) degrees.

Windowed Centroid Fallback Conditions#

The conditions for the SourceCatalog centroid_win fallback to the isophotal centroid have been expanded. The windowed centroid is now also reset when the total weighted flux is nonpositive, the windowed second-order moments are negative, or the windowed covariance determinant is negative. Previously, it was reset only when it had diverged far from the isophotal centroid and was outside the 1-sigma ellipse.

Segmentation Input Validation#

detect_sources() now emits an AstropyUserWarning if the threshold is negative or, for a threshold array, has any negative values. SegmentationImage now raises a TypeError for masked array input.

Deblending Warning Information#

deblend_sources() now emits a DeblendWarning (a subclass of astropy’s AstropyUserWarning) when the deblending mode is changed to a fallback mode for one or more sources. The affected input labels are now stored as arrays directly under 'non_positive_min_labels' and 'too_many_markers_labels' keys in the returned SegmentationImage info dictionary, replacing the nested info['warnings'] dictionary.

calc_total_error Output Dtype#

calc_total_error() now returns an array whose dtype follows the NumPy type promotion of its floating-point inputs, with a minimum of float32. For example, float32 inputs now give a float32 total error. Previously, the result was always float64. Integer inputs still give a float64 result.