Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

IRSA Notebooks

SPHEREx Standalone Spectrophotometry Tool

Learning Goals

By the end of this tutorial, you will be able to:

Introduction

The SPHEREx Spectrophotometry Tool extracts a multi-band flux spectrum for a target of interest by performing forced photometry on SPHEREx Level 2 Linear Variable Filter (LVF) images. The tool is available as a web interface at IRSA, and this notebook reproduces the same result locally by calling the underlying Python functions directly and fetching data from IRSA’s cloud storage.

Photometry is performed using the Tractor image modeling framework, which fits all sources in a small image window simultaneously. This simultaneous fitting correctly accounts for flux contributions from neighboring sources, even when only the primary target’s photometry is of interest.

SPHEREx images are similar to narrow-band images. Each LVF image covers several small slices of wavelength, typically a few percent of a micron wide, along the image’s y-axis. A complete spectrum is built by combining measurements from many pixels (corresponding to different wavelength) of different images, each sampling a different wavelength slice across SPHEREx’s full 0.75–5 µm range. For a typical sky position, several hundred images contribute to the final spectrum. Because each image is processed independently, the photometry across images is straightforward to parallelize.

The code used here is equivalent to the IRSA SPHEREx Spectrophotometry online tool in multi-object mode: This mode fits a target together with its neighboring sources. For the online tool, those neighboring sources are uploaded by the user in a source table; for this tool, those neighboring sources are generated within the tool using a Gaia catalog of sources within ~0.8 arcmin of the target. Tractor then simultaneously fits all sources in each image window, which correctly deblends flux contributions from neighbors before measuring the target. This is not equivalent to requesting a single-source spectrum: running forced photometry on the target alone without neighbors would produce systematically different fluxes in crowded fields. The Gaia DR3 query in Section 5 automates the construction of this multi-object source table. _neighbor_radius sets how far from the target the catalog extends; it is fixed to Tractor’s fitting window — see Section 5 for details.

Input

Output

Documentation

The authoritative descriptions of the data and of the algorithm this notebook reproduces.

SPHEREx Explanatory Supplement (PDF, 30 MB) (SPHEREx Science Data Center (SSDC) document SSDC-DP-017, v2.1, 2026-11-10). The sections that bear directly on this notebook:

sectionwhy it matters here
§2 The SPHEREx Data ProductsLayers of an L2 LVF image, image anomalies and features, and the known limitations of the release
§3.2.2 Nonlinearity CorrectionDetector behaviour approaching saturation, and the NONLINEAR flag
§3.2.3 Variance MapThe per-pixel uncertainties the Tractor fit is weighted by, and from which flux_err derives
§3.3 Photometric MeasurementsThe forced-photometry algorithm this notebook reproduces. The supplement states it “is also used in the Spectrophotometry Tool hosted at IRSA”. Gives the twelve processing steps, the fit-quality metric of Eq. 20 (reported here as fit_ql), and the flag lists to mask for background estimation and for photometry
§4 CalibrationsEffective point spread function (ePSF) models (§4.1.2), absolute gain, and the spectral channel definitions behind lambda and lambda_width

IRSA documentation

Imports

1. Import SPHEREx Pipeline Packages

The SPHEREx task packages (spx_tasks, spx_data, spx_utils) should already be installed in the environment. See the build-spherex_spt-env.sh script described in the previous section.

2. Define the Target and Other Parameters

Edit the cell below to specify your target and to configure the run. Only RA and DEC are required parameters but you should review other parameters too to adjust the pipeline.

3. Discover SPHEREx Images at IRSA

We use the IRSA Table Access Protocol (TAP) service with the spherex.obscore table to find all L2 images that spatially overlap our target position. The access_url column returns a DataLink URL that we resolve to obtain the direct FITS download URL.

astroquery.ipac.irsa.Irsa can execute TAP queries (it is used for the Gaia lookup in Section 5), but it does not implement the IVOA DataLink protocol. The access_url column returned by spherex.obscore is a DataLink service endpoint, not a direct file URL; it must be dereferenced with a DataLink call to obtain the actual Amazon Simple Storage Service (S3) download URL. pyvo.dal.adhoc.DatalinkResults handles this step, so the helper functions here are still required even if the TAP queries themselves were handled by astroquery.irsa.

Each DataLink resolution is a network round-trip costing 4–14 s, so Section 3.3 makes exactly one — enough to learn the S3 bucket and release prefix — and constructs the remaining image URLs from columns the TAP query already returned.

Notebook Cell
Notebook Cell

3.2 Query IRSA for L2 Images

3.3 Get Image URLs for Cloud Access

Notebook Cell

4. Calibration Files

4.1 Discover Calibration Files in the Cloud

The solid_angle_pixel_map and spectral_wcs calibration products live in the same public S3 bucket as the L2 images, under well-known paths. We locate the latest version of each product per detector directly with s3fs, listing the bucket instead of querying IRSA for each file, which keeps this step to a couple of seconds.

The solid_angle_pixel_map converts each pixel’s recorded count rate to surface brightness (MJy/sr) by dividing by the pixel’s solid angle on the sky; it is loaded in Section 4.2 and passed to PerformForcedPhotometryTask in Section 6. The spectral_wcs maps each detector row to a central wavelength; it is passed to both EstimateDiffuseBackgroundTask and PerformForcedPhotometryTask in Section 6 so that each photometric measurement is assigned the correct wavelength.

Notebook Cell

4.2 Load Calibration Files

Calibration files are shared across all exposures for a given detector. We download once per detector and store them in dictionaries keyed by detector number.

4.3 ePSF, Flux Corrections and the He I Airglow Template

Download the ePSF and flux-correction files (one per detector) from the URLs resolved in Section 4.1. These are the calibrations the SPHEREx online tool applies. The PSF products are described in Explanatory Supplement §4.1.2, Effective Point Spread Function (ePSF) models: the ePSF replaces the legacy PSF in the forced-photometry step (Section 6), and the flux corrections are applied when combining (Section 7). As in the online tool, the flux corrections apply to QR2 measurements only; IRSA no longer serves QR2, so they leave DR1 and QR3 results unchanged and are kept only so this notebook’s configuration mirrors the online tool.

5. Build the Reference Catalog from Gaia DR3

The SPHEREx photometry task requires a source catalog so that neighbors can be simultaneously modeled and deblended. We query Gaia DR3 from IRSA and map its columns to the format expected by the SPHEREx pipeline: PerformForcedPhotometryTask. Gaia positions are catalogued at the DR3 reference epoch (J2016.0), so they are propagated to the mean epoch of the images being fitted using the Gaia proper motions, following the same convention as the pipeline’s QueryReferenceCatalogTask: ref_ra/ref_dec hold the reference-epoch positions and ra/dec hold the propagated ones. This matters most for high proper-motion stars — a source moving 400 mas/yr drifts about 4 arcsec over a decade, comparable to the SPHEREx PSF.

_neighbor_radius is fixed, not a user parameter: it is the corner-to-center distance of Tractor’s fitting window — a square cutout ~11 px (~68 arcsec) per side centered on the target — so ~0.8 arcmin. That is the farthest a source can sit and still fall inside the cutout, so we query Gaia within _neighbor_radius rather than the full image footprint. Sources beyond _neighbor_radius are never used as neighbors regardless of how large the catalog is.

Notebook Cell

6. Run Forced Photometry

See Explanatory Supplement §3.3, Photometric Measurements, for details of this process.

run_photometry() runs EstimateDiffuseBackgroundTask followed by PerformForcedPhotometryTask on each L2 image, using N_PHOT_CORES parallel worker processes. Its definition, along with the per-worker setup it relies on, is in the hidden cell above the call; expand that cell if you want to see or adapt the pipeline configuration. Tractor’s C extensions are not thread-safe but are process-safe: each worker has its own isolated memory and never shares state with other workers. The per-image results are collected and combined in Section 7.

The pipeline’s background estimation emits many [WARN] Region N has no valid pixels, skipping. messages — these come from harmlessly skipping empty spectral bins (most bins are empty in any single image) and are not a cause for concern. They are filtered out by default via SUPPRESS_PIPELINE_WARNINGS (Section 2); set it to False to see them. A tqdm progress bar reports how many images have completed.

Notebook Cell

7. Combine Per-Image Results

We combine the per-image photometry tables into a single spectrum using CreateAllSkyCatalogTask, which groups measurements by source, sorts by wavelength, and applies the catalog-level variance boost: a 3% systematic floor is added in quadrature to each flux uncertainty, flux_err = sqrt(flux_err_tractor² + (0.03 × flux)²). This floor accounts for calibration uncertainties not captured by the Tractor per-pixel noise model and matches the uncertainty floor applied by the SPHEREx production pipeline and online tool.

8. Display and Save the Spectrum

Now that we have a spectrum, let’s take a look!

The plot shows the SPHEREx flux measurements across all six detectors (0.75–5 µm). Each point is one spectral band from one LVF exposure; scatter between overlapping bands reflects different roll angles and detector systematics. Gaps correspond to wavelengths not covered by the retrieved images.

Finally, save the spectrum to disk in the format chosen by OUTPUT_FORMAT (Section 2).

9. Display SPHEREx Images

A panel of N_DISPLAY_IMAGES LVF images is shown at wavelengths evenly spaced across the full spectrum. Each image is rotated so that north is up and east is to the left. The yellow circle marks the target position. Use the HDU dropdown to switch between the science image, flags, variance, and zodiacal light estimate.

This section can be run standalone (after Section 2) without running the full photometry pipeline. If the photometry results are available in memory it uses them directly; otherwise it queries IRSA TAP for images at the selected wavelengths (~15 seconds).

Notebook Cell

10. Tractor Fit Residuals - Optional

This section is optional and only runs when RETURN_RESIDUALS = True (Section 2). When enabled, the Section 6 photometry worker collects the Tractor window HDUList for the target source during the main photometry run.

To obtain the Tractor residuals, set RETURN_RESIDUALS = True in Section 2 and rerun Section 6 before running the cell below. The Tractor windows are produced during the photometry run itself, so changing the flag afterwards is not enough on its own. This section displays the Tractor data, model, and χ = (data − model) / noise for N_DISPLAY_IMAGES wavelengths. A good fit has χ values near zero across the window; large residuals indicate deblending errors, cosmic rays, centroid offsets, or other image artifacts.

Acknowledgements

About this Notebook

Updated: 30 November 2026

Contact: IRSA Helpdesk with questions or problems.

Runtime: Runtime scales with the number of L2 images covering the target and is dominated by image downloads and photometry. On a Fornax Large instance (16 CPU, 64 GB) running close to IRSA’s S3 storage, a full run for a typical bright source (~290 images) takes about 9 minutes on the first run. Subsequent runs complete in less time because calibration files and images are cached locally by astropy. Running off-cloud (e.g., a personal laptop) will be significantly slower due to download times. This runtime is heavily dependent on archive servers, which means runtime will vary for users. Set MAX_IMAGES = 10 for a quick test run (~1–2 minutes).

AI Acknowledgement: This tutorial was developed with the assistance of AI tools.