Skip to content

Read FITS regions directly into xFit forced photometry - #223

Merged
tpn merged 5 commits into
mainfrom
codex/xfit-direct-fits-photometry
Nov 26, 2026
Merged

tpn merged 5 commits into
mainfrom
codex/xfit-direct-fits-photometry

Conversation

@tpn

@tpn tpn commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator

This PR builds on #221. Callers with FITS images and target pixel coordinates can feed the same science, variance, mask and subpixel offsets to the PSF and aperture estimators. Previously they had to build the stamps and admission mask themselves.

cuphoton.xfit.read_forced_photometry_stamps reads the smallest rectangle covering the requested stamps from each of three co-registered HDUs. It preserves input order, repeated positions and pixel dtypes. The caller chooses rejected FITS mask bits. With reader="xdr", device=True, the gather and mask construction operate on CuPy arrays. The default Astropy path returns NumPy arrays. The xFit component documentation includes a worked example for both estimators.

Validation

  • Compared all five device arrays from both readers to the Astropy host result on synthetic GZIP_2 images, including the sign bit of an int16 mask, NaN science, zero variance, repeated targets and fractional positions.
  • Checked that a mismatched full-HDU shape raises even when each HDU contains the requested crop.
  • Verified in a fresh interpreter that importing the new xFit API leaves Astropy FITS and CuPy unloaded.
  • The GPU FITS and cold-import run passed all 38 tests on an RTX PRO 6000. The CPU run of tests/xfit, tests/core/test_fits_io.py and tests/test_public_api.py passed 470 tests with 216 skips. Repository-wide Ruff, formatting, mypy and the lockfile check passed.

@tpn
tpn requested a review from melo-gonzo as a code owner November 24, 2026 01:53
@coderabbitai

coderabbitai Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are limited based on label configuration.

🏷️ Required labels (at least one): 1

  • ai-review

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review

@melo-gonzo melo-gonzo left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving. The stamp gather matches its docstring. I checked the covering rectangle, the floor(p + 0.5) centers and their offsets against the (x, y) convention both estimators use, input order and repeats, dtypes, and the mask bits, including the int16 sign bit. I reviewed by reading the code and ran the edge cases below with the Astropy reader.

Notes for a follow-up:

  • One target near an edge rejects the whole batch, and the message does not say which target. A stamp that crosses an edge reaches the core check, "FITS section must lie within every image". A position below -0.5 raises "positions exceed the supported pixel index range" instead. Forced photometry at catalog positions often has a few targets within half a stamp of an edge. To filter them, callers have to repeat the rounding and the image-shape lookup. Checking positions against the header shape before the read, and naming the rows, would fix the message. Padding with good=False would instead let the aperture report the lost pixels as MASKED, and the PSF fit would use the pixels inside the image.
  • Memory follows how far apart the targets are, not how many stamps there are. That is host memory by default and device memory with device=True. Two targets in opposite corners of a 4096 x 4096 exposure read the whole image. With float32 science and variance and an int32 mask, that is about 200 MB to return two 41 x 41 stamps. With reader="astropy", device=True, the whole rectangle is also copied to the GPU before the gather. The guide could say this, and the Astropy path could gather on the host and copy only the stamps.
  • The shape, integer-mask and mask-width checks (src/cuphoton/xfit/fits_input.py:399-408) run after the read decodes the pixels. All three use header facts, so they could run on inspect_fits_image results before decoding.
  • test_forced_photometry_device_read_matches_host (tests/xfit/test_fits_input.py:153) skips on CPU jobs and is not in the GPU job's list (.github/workflows/ci.yml:350-366), so CI never runs it.
  • The guide says the default reader returns NumPy arrays and the example returns CuPy arrays (docs/components/xfit.md:634-636). device decides that, not reader. reader="astropy", device=True also returns CuPy arrays.
  • This reader rounds half up. forced_flux_at and window_stamps use rint, which rounds half to even, so x = 10.5 gets a stamp centered at 11 here and at 10 there. Each offset is consistent with its stamp, but the same target lands on different pixels in the two paths.
Reproducer (Astropy reader, a5656b9)
import numpy as np
from astropy.io import fits
from cuphoton.xfit import read_forced_photometry_stamps as read

image = np.arange(128, dtype=np.float32).reshape(8, 16)
variance = np.full(image.shape, 2.0)
mask = np.zeros(image.shape, dtype=np.int16)
planes = (image, variance, mask)
fits.HDUList([fits.PrimaryHDU(), *(fits.CompImageHDU(p, compression_type="GZIP_2", quantize_level=0) for p in planes)]).writeto("visit.fits", overwrite=True)
args = dict(science_hdu=1, variance_hdu=2, mask_hdu=3, bad_mask_bits=32768, stamp_shape=(3, 5))
print("ok", read("visit.fits", [[8.75, 4.25]], **args).offsets)
for pos in ([[8.75, 4.25], [1.0, 4.0]], [[8.75, 4.25], [14.6, 4.0]], [[8.75, 4.25], [-0.6, 4.0]]):
    try:
        read("visit.fits", pos, **args)
        print(pos, "no error")
    except ValueError as e:
        print(pos, "ValueError:", e)
# ok [[-0.25  0.25]]
# [[8.75, 4.25], [1.0, 4.0]] ValueError: FITS section must lie within every image
# [[8.75, 4.25], [14.6, 4.0]] ValueError: FITS section must lie within every image
# [[8.75, 4.25], [-0.6, 4.0]] ValueError: positions exceed the supported pixel index range

@tpn
tpn force-pushed the codex/dp1-batched-photometry branch from 9dc3fad to 16e9409 Compare November 26, 2026 03:08
@tpn
tpn force-pushed the codex/xfit-direct-fits-photometry branch from a5656b9 to c44be04 Compare November 26, 2026 03:24
tpn added 4 commits November 25, 2026 20:16
Gather science, variance and mask stamps from one exposure region so
PSF and aperture measurements can share device-resident pixels and
subpixel positions. Preserve the input mask bits and expose the reader
provenance for callers that require GPU decoding.

Signed-off-by: Trent Nelson <trentn@nvidia.com>
Check target coordinates before converting them to real values so a
missing coordinate or imaginary component cannot become a valid
measurement at a different position.

Signed-off-by: Trent Nelson <trentn@nvidia.com>
Load the shared FITS layer when a caller starts a FITS operation so
importing the xFit API stays light. Exercise both device readers on
compressed data with a signed mask and verify co-registration for
the full planes even when the requested section fits each HDU.

Signed-off-by: Trent Nelson <trentn@nvidia.com>
Identify out-of-bounds target rows and match the xPois half-pixel
rounding convention. Gather Astropy stamps before copying to CUDA and
exercise both device readers in the native xDR coverage job.

Signed-off-by: Trent Nelson <trentn@nvidia.com>
@tpn
tpn changed the base branch from codex/dp1-batched-photometry to main November 26, 2026 04:16
@tpn
tpn force-pushed the codex/xfit-direct-fits-photometry branch from c44be04 to 68efd74 Compare November 26, 2026 04:16
@tpn

tpn commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks for checking the reader against the Astropy reproducer, Carmelo. I addressed the six points from your review in 68efd747.

  1. Image edges. The reader checks every footprint against the header dimensions before decoding. It still requires a complete stamp and now reports the zero-based rows of all offending targets, including negative positions. Callers can filter those rows and retry without reproducing the rounding rules.
  2. Memory and transfers. The guide explains that memory scales with the bounding rectangle. A full 4096 × 4096 rectangle needs 192 MiB for float32 science and variance plus an int32 mask, before temporaries. With reader="astropy", device=True, the host now gathers the stamps before copying them to the GPU. The transfer regression sees only the three stamp arrays and their offsets. xDR still decodes the rectangle on the GPU.
  3. Header validation. Co-registered shapes, integer mask dtype and the width of bad_mask_bits are checked before the pixel read. Regression tests fail if invalid headers reach the decoder.
  4. GPU CI. Both the Astropy and xDR versions of the device-versus-host test now run in the native xDR coverage job on an L40G. That job builds the CFITSIO-backed extension and rejects skipped tests. Both reader variants also passed on a local CUDA device.
  5. Return type. The guide now separates the decoder from the destination. device=False returns NumPy arrays and device=True returns CuPy arrays with either reader.
  6. Half-pixel ties. The new reader now uses the xPois ties-to-even convention. Both 9.5 and 10.5 center on pixel 10, with offsets −0.5 and +0.5. A regression compares the actual windows and offsets. The existing xPois rounding behavior is unchanged.

Inspect nested rows and object arrays before conversion to real values.
A missing coordinate or an imaginary component can otherwise select a
plausible but incorrect target pixel.

Signed-off-by: Trent Nelson <trentn@nvidia.com>
@tpn
tpn merged commit 7757397 into main Nov 26, 2026
60 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants