diff --git a/deploy_to_fornax_manifest.in b/deploy_to_fornax_manifest.in index 9fd259b8..c37a7879 100644 --- a/deploy_to_fornax_manifest.in +++ b/deploy_to_fornax_manifest.in @@ -32,6 +32,9 @@ tutorials/spherex/spherex_source_discovery/spherex_source_discovery_tool/default tutorials/spherex/spherex_source_discovery/spherex_source_discovery_tool/firefly_viz.py tutorials/spherex/spherex_source_discovery/spherex_source_discovery_tool/sdt_utils.py tutorials/spherex/spherex_source_discovery/spherex_source_discovery_tool/source_extraction.py +tutorials/spherex/spherex_spectrophotometry/build-spherex_spt-env.sh +tutorials/spherex/spherex_spectrophotometry/conda-spherex_spt.yml +tutorials/spherex/spherex_spectrophotometry/spherex_spectrophotometry_tool.md tutorials/spherex/spherex_mosaic.md tutorials/spherex/spherex_hipscube.md tutorials/techniques-and-tools/cloud-access-intro.md diff --git a/ignore_tutorials/ignore_all_testing b/ignore_tutorials/ignore_all_testing index 29105c7b..4f742fef 100644 --- a/ignore_tutorials/ignore_all_testing +++ b/ignore_tutorials/ignore_all_testing @@ -1,2 +1,4 @@ # Requires source extractor, which requires a conda install tutorials/spherex/spherex_source_discovery/spherex_source_discovery_tool_demo.md +# Requires spherex-pipelines and tractor, which require a conda install +tutorials/spherex/spherex_spectrophotometry/spherex_spectrophotometry_tool.md diff --git a/ignore_tutorials/ignore_rendering_execution b/ignore_tutorials/ignore_rendering_execution index bd339c6a..b1355e5d 100644 --- a/ignore_tutorials/ignore_rendering_execution +++ b/ignore_tutorials/ignore_rendering_execution @@ -4,3 +4,5 @@ tutorials/techniques-and-tools/Parallelize_Convolution tutorials/wise/wise-allwise-catalog-demo # Requires source extractor, which requires a conda install tutorials/spherex/spherex_source_discovery/spherex_source_discovery_tool_demo +# Requires spherex-pipelines and tractor, which require a conda install +tutorials/spherex/spherex_spectrophotometry/spherex_spectrophotometry_tool diff --git a/notebook_metadata.yml b/notebook_metadata.yml index 08449c34..1918efb4 100644 --- a/notebook_metadata.yml +++ b/notebook_metadata.yml @@ -98,6 +98,10 @@ file: tutorials/spherex/spherex_source_discovery/spherex_source_discovery_tool_demo.md section: SPHEREx description: Discover, extract, and visualize sources from SPHEREx Spectral Images. +- title: Spectrophotometry Tool + file: tutorials/spherex/spherex_spectrophotometry/spherex_spectrophotometry_tool.md + section: SPHEREx + description: Extract a SPHEREx spectrum for any sky position by running the Spectrophotometry Tool's forced photometry in Python. - title: Spitzer IRS Spectra file: tutorials/spitzer/plot_Spitzer_IRS_spectra.md section: Spitzer diff --git a/toc.yml b/toc.yml index ddedd113..be61ef66 100644 --- a/toc.yml +++ b/toc.yml @@ -14,6 +14,8 @@ project: file: tutorials/spherex/spherex_psf.md - title: Source Discovery Tool file: tutorials/spherex/spherex_source_discovery/spherex_source_discovery_tool_demo.md + - title: Spectrophotometry Tool + file: tutorials/spherex/spherex_spectrophotometry/spherex_spectrophotometry_tool.md - title: Mosaic Cube file: tutorials/spherex/spherex_mosaic.md - title: HiPS All-Sky Cube diff --git a/tutorials/spherex/spherex.md b/tutorials/spherex/spherex.md index ff195ab7..2edb42f8 100644 --- a/tutorials/spherex/spherex.md +++ b/tutorials/spherex/spherex.md @@ -12,6 +12,7 @@ tutorials/spherex/spherex_intro.md tutorials/spherex/spherex_cutouts.md tutorials/spherex/spherex_psf.md tutorials/spherex/spherex_source_discovery/spherex_source_discovery_tool_demo.md +tutorials/spherex/spherex_spectrophotometry/spherex_spectrophotometry_tool.md tutorials/spherex/spherex_mosaic.md tutorials/spherex/spherex_hipscube.md ``` diff --git a/tutorials/spherex/spherex_spectrophotometry/build-spherex_spt-env.sh b/tutorials/spherex/spherex_spectrophotometry/build-spherex_spt-env.sh new file mode 100755 index 00000000..35e36460 --- /dev/null +++ b/tutorials/spherex/spherex_spectrophotometry/build-spherex_spt-env.sh @@ -0,0 +1,53 @@ +# Create a conda environment using conda-spherex_spt.yml, and an associated Jupyter kernel. +# Then install tractor-spherex and spherex-pipelines, which conda-spherex_spt.yml can't handle due to --no-build-isolation and --no-deps flags. +# +# Usage: ./build-spherex_spt-env.sh [args...] +# On Fornax, all arguments are passed through to setup-conda-env unchanged. +# +# If not running on Fornax, first create and activate the env, then run this script to install the rest. For example: +# conda env create -f conda-spherex_spt.yml +# conda activate spherex_spt +# python -m ipykernel install --name spherex_spt --user # optional: Jupyter kernel +# ./build-spherex_spt-env.sh + +# Exit immediately if any command encounters a problem. +set -euo pipefail + +# The Fornax command setup-conda-env (below) will name the env based on the filename syntax conda-{ENV_NAME}.yml. +# We expect conda-spherex_spt.yml, so the env name will be "spherex_spt". +ENV_NAME=spherex_spt + +# If the command 'setup-conda-env' exists, we're on Fornax. +if command -v setup-conda-env >/dev/null; then + # Fornax: create the env and kernel based on conda-spherex_spt.yml. + setup-conda-env "$@" || exit $? + + # Activate the env so we can use the numpy and swig libraries we've installed. + # setup-conda-env may have installed to $ENV_DIR or $USER_ENV_DIR, so check both. + env_path="$USER_ENV_DIR/$ENV_NAME" + [[ -d "$env_path" ]] || env_path="$ENV_DIR/$ENV_NAME" + eval "$(micromamba shell hook --shell bash)" + micromamba activate "$env_path" +else + # Elsewhere: expect the env from conda-spherex_spt.yml to already be active. + env_path="${CONDA_PREFIX:?activate the $ENV_NAME env first}" +fi + +# Use uv pip if available (Fornax), else pip. +if command -v uv >/dev/null; then + pip_install=(uv pip install --python "$env_path") +else + pip_install=("$env_path/bin/python" -m pip install) +fi + +# Install tractor-spherex (spherex-pipelines dependency). +# Use --no-build-isolation to use pre-installed numpy and swig (conda-spherex_spt.yml). +"${pip_install[@]}" --no-build-isolation git+https://github.com/Caltech-IPAC/tractor-spherex.git@066680f05b889c554f4dd30e8211ee957d66d56f + +# Install spherex-pipelines (public tag 7.1.1+public.1). +# Without --no-deps it would try to install lsst_daf_butler[postgres], which brings in psycopg2, which requires a compiler. +# Instead, conda-spherex_spt.yml installs psycopg2-binary (and other spherex-pipelines dependencies) and we skip here using --no-deps. +# SETUPTOOLS_SCM_PRETEND_VERSION works around a known spherex-pipelines issue: setuptools_scm cannot parse +# public tags such as 7.1.1+public.1, so building from them fails. Remove it once a fix is released. +SETUPTOOLS_SCM_PRETEND_VERSION=7.1.1+public.1 \ + "${pip_install[@]}" --no-deps git+https://github.com/Caltech-IPAC/spherex-pipelines.git@2cd6ca41e5c204a0e1b3ecf803c666fcd052f469 diff --git a/tutorials/spherex/spherex_spectrophotometry/conda-spherex_spt.yml b/tutorials/spherex/spherex_spectrophotometry/conda-spherex_spt.yml new file mode 100644 index 00000000..eed7ee0f --- /dev/null +++ b/tutorials/spherex/spherex_spectrophotometry/conda-spherex_spt.yml @@ -0,0 +1,49 @@ +# Environment for SPHEREx notebooks. +# Additional installs are needed for Spectrophotometry Tool notebook (see build-spherex_spt-env.sh). +name: spherex_spt +channels: + - conda-forge +dependencies: + - python>=3.11.0,<=3.13 # >=3.11.0 required by spherex-pipelines. kete doesn't provide wheels for >3.13. + - pip + # ---- spherex-pipelines dependencies + - astrometry # must install astrometry before spherex-pipelines. Not available on PyPI. + - alive-progress + - astropy + - click>8.3.0 # pin required by spherex-pipelines. + - gwcs + - healpy>=1.17.1 # pin required by spherex-pipelines + - ipywidgets + - joblib + - matplotlib + - numba + - numpy + - parsl + - photutils + - psycopg2-binary # lsst_daf_butler needs psycopg2 but that requires a compiler. Use psycopg2-binary instead. + - pyarrow + - pydantic>=2.3,<3 # pin required by spherex-pipelines + - regions + - reproject + - scikit-image + - scikit-learn + - scipy>=1.6 # pin required by spherex-pipelines + - sep + - sqlalchemy + - spiceypy + - swig==4.4.1 # swig==4.5.0 breaks tractor-spherex install + - tenacity + - tqdm + # ---- Additional libraries used in Spectrophotometry Tool notebook + - astroquery + - pyvo + - specutils + - s3fs + + - pip: + # ---- spherex-pipelines dependencies not available on conda-forge + - opencv-python-headless # required by tractor-spherex + - kete<2.0 # pin required by spherex-pipelines. + - lsst_ctrl_mpexec + - lsst_pipe_base + - lsst_daf_butler diff --git a/tutorials/spherex/spherex_spectrophotometry/spherex_spectrophotometry_tool.md b/tutorials/spherex/spherex_spectrophotometry/spherex_spectrophotometry_tool.md new file mode 100644 index 00000000..26b2c9ea --- /dev/null +++ b/tutorials/spherex/spherex_spectrophotometry/spherex_spectrophotometry_tool.md @@ -0,0 +1,1756 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.19.4 +kernelspec: + name: spherex_spt + display_name: spherex_spt + language: python +authors: + - name: Jessica Krick +--- + +# SPHEREx Standalone Spectrophotometry Tool + ++++ + +## Learning Goals + +By the end of this tutorial, you will be able to: + +- Query IRSA for SPHEREx images covering a sky position of interest. +- Build a source reference catalog from Gaia Data Release 3 (DR3). +- Run SPHEREx forced photometry directly in Python using SPHEREx pipeline code. +- Combine per-image measurements into a multi-band spectrum spanning 0.75–5 µm. + ++++ + +## Introduction + +The [SPHEREx Spectrophotometry Tool](https://irsa.ipac.caltech.edu/applications/spherex/tool-spectrophotometry) +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](https://github.com/dstndstn/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 + +- Right ascension and declination of a single target (degrees, ICRS). +- Optional: time range, detector filter. + +### Output + +- Table of per-band photometry measurements. +- Spectrum plot of flux versus central wavelength. + +### Documentation + +The authoritative descriptions of the data and of the algorithm this notebook reproduces. + +**[SPHEREx Explanatory Supplement (PDF, 30 MB)](https://irsa.ipac.caltech.edu/data/SPHEREx/docs/SPHEREx_Expsupp_v2.1.pdf)** +(SPHEREx Science Data Center (SSDC) document SSDC-DP-017, v2.1, 2026-11-10). The sections that bear directly on this notebook: + +| section | why it matters here | +|---|---| +| §2 The SPHEREx Data Products | Layers of an L2 LVF image, image anomalies and features, and the known limitations of the release | +| §3.2.2 Nonlinearity Correction | Detector behaviour approaching saturation, and the `NONLINEAR` flag | +| §3.2.3 Variance Map | The per-pixel uncertainties the Tractor fit is weighted by, and from which `flux_err` derives | +| **§3.3 Photometric Measurements** | **The 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 Calibrations | Effective point spread function (ePSF) models (§4.1.2), absolute gain, and the spectral channel definitions behind `lambda` and `lambda_width` | + +**IRSA documentation** + +- [SPHEREx Data Release 1 (DR1) Overview](https://irsa.ipac.caltech.edu/data/SPHEREx/docs/overview_dr1.html) — data + access routes, and the DOIs to cite when publishing. +- [SPHEREx Archive User Guide](https://irsa.ipac.caltech.edu/spherex-archive-documentation/) — how + the archive is organised and queried. +- [PSF Extension Header Error](https://irsa.ipac.caltech.edu/data/SPHEREx/docs/psfhdrerr.html) — an + erratum worth knowing about: QR1 and QR2 shipped a point spread function (PSF) header that indexed the PSF cube by the + wrong axis, which affected the PSF extension, the stand-alone PSF calibration product and results + from the Spectrophotometry Tool, by up to ±5% depending on where the source fell on the detector. + Corrected on 31 March 2026; corrected files carry a `+psffix1` suffix in the header `VERSION`, and + pipeline 6.5.6 onwards was never affected. +- Related IRSA tutorials: + [Introduction to SPHEREx Spectral Images](https://caltech-ipac.github.io/irsa-tutorials/spherex-intro/), + [SPHEREx Spectral Image Cutouts](https://caltech-ipac.github.io/irsa-tutorials/spherex-cutouts/), + [SPHEREx PSF in Spectral Image Cutouts](https://caltech-ipac.github.io/irsa-tutorials/spherex-psf/), + [SPHEREx Source Discovery Tool](https://caltech-ipac.github.io/irsa-tutorials/spherex-source-discovery-tool-demo/). + ++++ + +## Imports + +:::{important} Create conda environment first +Before running this notebook, you must create a conda environment and kernel using the provided files. + +If running on Fornax, open a terminal, `cd` into this directory, and run: + +```sh +# Create the environment and kernel. +# Remove --user to make the env temporary (not persistent across restarts). +./build-spherex_spt-env.sh --user +``` + +If not running on Fornax, read instructions in `build-spherex_spt-env.sh` first. + +Connect this notebook to the `spherex_spt` kernel after you've created the environment and kernel. +::: + +:::{note} Limited support for `spherex-pipelines` +Please be aware that the `spherex-pipelines` code is intended solely for use within the SPHEREx data processing environment. +The specific functions used in this notebook were carefully chosen and they should work anywhere you can install the Conda environment described above. +However, many other functions will not. +The `spherex-pipelines` code is not guaranteed to work for the typical user, and the SPHEREx team does not have the resources to support users who try. +For more information, see the README at . + +If you have trouble with the functions in this notebook, please contact the [IRSA Help Desk](https://irsa.ipac.caltech.edu/docs/help_desk.html). +::: + +```{code-cell} ipython3 +import json +import logging +import os +import sys +import contextlib +import io +import concurrent.futures +import warnings + +# Suppress numpy warning from estimate_abs_gain_matrix when flux_list contains masked scalars. +warnings.filterwarnings("ignore", message=".*converting a masked element.*", category=UserWarning) +# Suppress per-image provenance warning: our Gaia srccat has no refcat_run/refcat_version metadata. +logging.getLogger("spx_utils.utils").setLevel(logging.ERROR) + +import numpy as np +import matplotlib.pyplot as plt +from matplotlib.patches import Circle +import scipy.ndimage +from tqdm.auto import tqdm + +import astropy.units as u +import astropy.io.fits as fits +import astropy.coordinates as coord +from astropy.table import Table, vstack +from astropy.time import Time +from astropy.utils.data import download_file +from astropy.nddata import Cutout2D, StdDevUncertainty +from astropy.wcs import WCS + +import pyvo +import pyvo.dal.adhoc +import pyarrow.compute as pc +import s3fs + +from specutils import Spectrum +from astroquery.ipac.irsa import Irsa +import ipywidgets as widgets +from io import BytesIO as _BytesIO +from IPython.display import display as _ipy_display +from IPython.display import Image as _IPyImage +``` + +## 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. + +```{code-cell} ipython3 +from spx_tasks.l3a import L3aTask, validate_table +# Column list the production QueryReferenceCatalogTask requires before it will apply proper +# motions; reused in Section 5 so the notebook's check matches the pipeline's. +from spx_tasks.query_reference_catalog import PM_CORR_INPUTS +from spx_data import SPHERExImage +from spx_data.spx_param import get_pix_scale +from spx_tasks.create_all_sky_catalog import CreateAllSkyCatalogTask +``` + +## 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. + +```{code-cell} ipython3 +# --- Required --- +target_name = "2MASS 21282814-0559310" +RA = 322.117265 # degrees, ICRS +DEC = -5.991964 # degrees, ICRS + +# --- Optional filters --- +# Restrict to a time range. Set to None to use all available images. +# Example: TIME_RANGE = (Time("2024-01-01"), Time("2024-06-01")) +TIME_RANGE = None + +# Restrict to specific detectors. Set to None to use all six. +# Example: DETECTORS = ["D1", "D2"] +DETECTORS = None + +# Include the deep-field collections, matching the online tool's "include deep-field images" +# checkbox. IRSA serves deep-field images in their own `spherex__deep` collections +# alongside the all-sky ones, and this notebook has always included both. +# +# It matters far more than it looks at the ecliptic poles. A position in the NEP deep field has +# ~25,000 L2 images in total, 97% of them deep-field; even inside a 10-day TIME_RANGE it is 509-599 +# with them and ~40-56 without. Leaving them in is right for depth and is the default; turning them +# off is how to get a quick look, or to reproduce a run made with the checkbox cleared. +INCLUDE_DEEP_FIELD = True + +# --- Output format and path --- +# "ecsv" — astropy Enhanced CSV (default; preserves all columns and metadata) +# "votable" — IVOA VOTable (matches the IRSA online tool's output format) +# "fits_sdm" — FITS serialization following the IVOA Spectrum Data Model (for VO tool interoperability) +OUTPUT_FORMAT = "ecsv" +OUTPUT_DIR = "output" + +# --- Image viewer --- +# Number of LVF images to display in Section 9. Recommended: 1, 3, 5, or 7. +N_DISPLAY_IMAGES = 5 +# Radius (arcsec) of the target-position marker circle drawn on the displayed +# images and written to the DS9 region file. +MARKER_RADIUS_ARCSEC = 4.5 +# Set to True to show the Tractor data/model/residual panels in Section 10. +RETURN_RESIDUALS = False + +# --- Image panel output --- +# Set True and choose IMAGE_PANEL_FORMAT to save the Section 9 panel alongside the spectrum. +IMAGE_PANEL_SAVE = False +IMAGE_PANEL_FORMAT = "png" # "png": rendered panel | "fits": north-up cutout data | "region": DS9 circle + +# --- Parallelism --- +# Workers for parallel photometry. Each worker holds calibration files in memory +# (~600 MB for all 6 detectors); runtime more likely limited by CPU or bandwidth than RAM. +N_PHOT_CORES = os.cpu_count() + +# --- Logging --- +# The pipeline's background estimation emits many harmless +# "[WARN] Region N has no valid pixels, skipping." messages (most spectral bins +# are empty in any single image). Set True to filter them out of the Section 6 +# photometry output so the progress bar stays legible; set False to see them. +SUPPRESS_PIPELINE_WARNINGS = True + +# --- Image limit --- +# Set to an integer to process only the N earliest images (useful for quick tests). +# Set to None to process all available images (may take significantly longer). +MAX_IMAGES = 10 +``` + +## 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. + +### 3.1 DataLink Helper + +`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. + +```{code-cell} ipython3 +--- +jupyter: + source_hidden: true +tags: [hide-cell] +--- +def tap_search(adql, maxrec=None, retries=3, delay=5): + """Run a TAP query against ``tap_service`` with retry logic for transient errors. + + Parameters + ---------- + adql : str + ADQL query string. + maxrec : int, optional + Maximum number of rows to return (passed as TAP MAXREC). + retries : int, optional + Maximum number of attempts before re-raising the exception. + delay : float, optional + Seconds to wait between attempts. + + Returns + ------- + `~pyvo.dal.TAPResults` + Query result object; call ``.to_table()`` to get an Astropy Table. + + Raises + ------ + `~pyvo.dal.DALServiceError` + If the server returns an error on the final attempt. + """ + import time as _time + from pyvo.dal import DALServiceError + for attempt in range(retries): + try: + return tap_service.search(adql, maxrec=maxrec) + except DALServiceError as e: + if attempt < retries - 1: + print(f"TAP query failed ({e}); retrying in {delay}s… (attempt {attempt+1}/{retries})") + _time.sleep(delay) + else: + raise +``` + +```{code-cell} ipython3 +--- +jupyter: + source_hidden: true +tags: [hide-cell] +--- +def resolve_datalink(datalink_url: str, semantics: str = "#this", + retries: int = 4, delay: float = 2.0) -> str: + """Resolve an IRSA DataLink URL to a direct S3 HTTPS download URL. + + Uses PyVO's DataLink API to select the row matching ``semantics`` and + returns the S3 URL from the ``cloud_access`` column. + + Parameters + ---------- + datalink_url : str + URL returned in the ``access_url`` column of ``spherex.obscore``. + semantics : str, optional + DataLink semantics tag to select. Use ``"#this"`` for the primary + science file and ``"#calibration"`` for calibration products. + retries : int, optional + Maximum number of attempts before re-raising the exception. + delay : float, optional + Seconds to wait between attempts. + + Returns + ------- + str + Direct S3 HTTPS URL for the requested file. + + Raises + ------ + ValueError + If no DataLink entry with the requested semantics is found. + """ + import time as _time + # The IRSA DataLink service occasionally returns a non-VOTABLE response + # (e.g. a transient error page) when hit with many parallel requests, which + # makes PyVO's VOTable parse raise. Retry a few times before giving up. + for attempt in range(retries): + try: + dl = pyvo.dal.adhoc.DatalinkResults.from_result_url(datalink_url) + break + except Exception: + if attempt < retries - 1: + _time.sleep(delay) + else: + raise + rows = list(dl.bysemantics(semantics)) + if not rows: + raise ValueError( + f"No DataLink entry with semantics={semantics!r} found at {datalink_url}") + aws = json.loads(str(rows[0]["cloud_access"]))["aws"] + return f"https://{aws['bucket_name']}.s3.amazonaws.com/{aws['key']}" +``` + +### 3.2 Query IRSA for L2 Images + +```{code-cell} ipython3 +#Setup for IRSA TAP +IRSA_TAP_URL = "https://irsa.ipac.caltech.edu/TAP" +tap_service = pyvo.dal.TAPService(IRSA_TAP_URL) + +# Build optional time filter +time_clause = "" +if TIME_RANGE is not None: + t_start, t_end = TIME_RANGE + if t_start is not None: + time_clause += f" AND t_min >= {t_start.mjd}\n" + if t_end is not None: + time_clause += f" AND t_max <= {t_end.mjd}\n" + +# Build optional detector filter using energy_bandpassname (e.g. "SPHEREx-D1") +detector_clause = "" +if DETECTORS is not None: + det_conditions = " OR ".join(f"energy_bandpassname = 'SPHEREx-{d}'" for d in DETECTORS) + detector_clause = f" AND ({det_conditions})\n" + +# Build optional deep-field filter. Deep-field collections are `spherex__deep` +# (see `_release_of`), so excluding them is a suffix match on obs_collection. `_` is a +# single-character wildcard in ADQL LIKE, so the pattern deliberately matches on "deep" +# alone rather than trying to escape the underscore, which not every TAP service supports. +deep_clause = "" +if not INCLUDE_DEEP_FIELD: + deep_clause = " AND obs_collection NOT LIKE '%deep'\n" + +# NOTE: the spatial CONTAINS() predicate must be the first condition in the +# WHERE clause — the IRSA TAP service rejects queries with other filters first. +adql = f""" +SELECT + obs_id, energy_bandpassname, t_min, t_max, access_url, obs_collection +FROM spherex.obscore +WHERE CONTAINS(POINT('ICRS', {RA}, {DEC}), s_region) = 1 + AND obs_intent = 'science' +{time_clause}{detector_clause}{deep_clause} +""" + +# maxrec must exceed the image count of the densest field this notebook is pointed at, or +# the sample is silently truncated to whatever order TAP happened to return. 500 was ample +# for the all-sky survey (~180-270 images per position) but not for the deep fields at the +# ecliptic poles: a position in the NEP deep field has ~25,000 L2 images in total and 509-599 +# even within a 10-day TIME_RANGE, so every such target came back truncated at exactly 500. +print("Querying IRSA TAP for L2 images…") +lvf_result = tap_search(adql, maxrec=20000) +lvf_results = lvf_result.to_table() +_n_deep = sum(1 for r in lvf_results if str(r["obs_collection"]).strip().endswith("_deep")) +print(f"Found {len(lvf_results)} L2 images covering RA={RA}, Dec={DEC}" + f" ({_n_deep} deep-field, {len(lvf_results) - _n_deep} all-sky;" + f" INCLUDE_DEEP_FIELD={INCLUDE_DEEP_FIELD})") +if lvf_result.query_status == "OVERFLOW": + # Raised, not printed: a truncated image set produces a plausible-looking spectrum built + # from an arbitrary subset, which is worse than no spectrum. The warning this replaces + # went to the notebook's cell output, where a headless driver never saw it. + raise RuntimeError( + f"TAP returned the MAXREC limit ({len(lvf_results)}) — the image set is TRUNCATED " + f"and any spectrum built from it would use an arbitrary subset. Raise maxrec in the " + f"tap_search() call above, or narrow TIME_RANGE / DETECTORS.") + +#show just the top 5 entries in the table for a quicklook +lvf_results[:5] +``` + +### 3.3 Get Image URLs for Cloud Access + +```{code-cell} ipython3 +--- +jupyter: + source_hidden: true +tags: [hide-cell] +--- +from urllib.parse import urlparse as _urlparse + +_visit_dirs = {} # (release, visit) -> list of version directory names +_l2_versions = {} # (release, visit, detector) -> version dir, when there is only one +_l2_obs_versions = {} # (release, visit, detector) -> {obs_id: version dir}, when several + + +def _l2_version(visit, det, obs_id, bucket, release, fs): + """Return the ``l2b-*`` version directory holding one image. + + The version tag varies between visits and, within a visit, between detectors, so it + cannot be constructed from ``obs_id``. Usually every image of a given (visit, detector) + shares one version directory, and naming it costs nothing beyond listing the visit. + A partial reprocessing can split them, though: the version directories then hold + *disjoint* sets of obs_ids, so the version cannot be assumed uniform across a + (visit, detector). Only in that case do we list the directories to find which one + holds each image. + """ + base = f"{bucket}/{release}/level2/{visit}" + vkey = (release, visit) + if vkey not in _visit_dirs: + _visit_dirs[vkey] = [d.rsplit("/", 1)[-1] for d in fs.ls(base)] + + key = (release, visit, det) + if key not in _l2_versions and key not in _l2_obs_versions: + candidates = sorted(v for v in _visit_dirs[vkey] if fs.exists(f"{base}/{v}/{det}")) + if not candidates: + raise RuntimeError( + f"No level2 version directory for visit {visit} detector D{det} " + f"under s3://{bucket}/{release}") + if len(candidates) == 1: + _l2_versions[key] = candidates[0] + else: + _l2_obs_versions[key] = { + f.rsplit("/", 1)[-1].partition("level2_")[2].partition(f"D{det}_spx_")[0]: v + for v in candidates + for f in fs.ls(f"{base}/{v}/{det}") + } + + if key in _l2_versions: + return _l2_versions[key] + try: + return _l2_obs_versions[key][obs_id] + except KeyError: + raise RuntimeError( + f"No level2 file for {obs_id} D{det} in any of " + f"{sorted(set(_l2_obs_versions[key].values()))} under " + f"s3://{bucket}/{release}") from None + + +def get_lvf_url(row, bucket, release, fs) -> tuple[str, int]: + """Build the direct S3 URL and detector number for one ObsCore row. + + Parameters + ---------- + row : `~astropy.table.Row` + One row from the ``spherex.obscore`` TAP result table. + bucket, release : str + Bucket name and release prefix, derived once from a DataLink resolution. + fs : `~s3fs.S3FileSystem` + Anonymous S3 filesystem used to look up version directories. + + Returns + ------- + tuple[str, int] + ``(fits_url, det_num)`` where ``fits_url`` is the direct S3 HTTPS URL + and ``det_num`` is the integer detector number (1–6). + """ + obs_id = str(row["obs_id"]) + det = str(row["energy_bandpassname"]).split("-D")[1] + visit = obs_id.rsplit("_", 2)[0] # "2025W19_1B_0186_1" -> "2025W19_1B" + version = _l2_version(visit, det, obs_id, bucket, release, fs) + key = (f"{release}/level2/{visit}/{version}/{det}/" + f"level2_{obs_id}D{det}_spx_{version}.fits") + return f"https://{bucket}.s3.amazonaws.com/{key}", int(det) +``` + +```{code-cell} ipython3 +# TAP returns rows in no guaranteed order, so sort before slicing: MAX_IMAGES then always takes +# the earliest observations, which new data (always later in time) cannot displace. +# obs_id and detector break ties between the detectors of one exposure. +lvf_results.sort(["t_min", "obs_id", "energy_bandpassname"]) +# Slice BEFORE building URLs so only the images we will actually process are looked up. +lvf_results_to_process = lvf_results[:MAX_IMAGES] if MAX_IMAGES else lvf_results +print(f"{len(lvf_results_to_process)} images (of {len(lvf_results)} available)") +if len(lvf_results_to_process) == 0: + # Name the actual cause: an empty result is just as often an over-tight filter as it is a + # genuinely uncovered position, and the two need very different fixes. + _active = [] + if TIME_RANGE is not None: + _t0, _t1 = TIME_RANGE + _active.append(f"TIME_RANGE = {_t0.mjd if _t0 else '-inf'} to {_t1.mjd if _t1 else '+inf'} MJD") + if DETECTORS is not None: + _active.append(f"DETECTORS = {DETECTORS}") + _hint = (" No optional filters are set, so this position is probably not covered by the " + "images currently in the archive." + if not _active else + f" Optional filters in effect ({'; '.join(_active)}) may be excluding every image; " + "try widening or removing them before concluding the position is uncovered.") + raise RuntimeError(f"No L2 images to process for RA={RA}, Dec={DEC}.{_hint}") + +# A single DataLink call establishes the S3 bucket; every image URL is then built from +# obs_id, detector and the image's own release, which the TAP query already returned, plus +# one S3 listing per (release, visit, detector) to find the version directory. Resolving a +# DataLink URL is a 4–14 s network round-trip, so making one call rather than one per image +# keeps a large field (~270 images) down to seconds instead of minutes. +_first_url = resolve_datalink(str(lvf_results_to_process[0]["access_url"]), semantics="#this") +_p = _urlparse(_first_url) # https://.s3.amazonaws.com/ +_bucket = _p.netloc.replace(".s3.amazonaws.com", "") +_fs = s3fs.S3FileSystem(anon=True) + + +def _release_of(row) -> str: + """S3 release prefix for one ObsCore row, from its own ``obs_collection``. + + IRSA serves more than one release at once: DR1 (year 1) + QR3 (year 2). A single field + whose images straddle a release boundary therefore comes back as a *mix*, so the release + has to be taken per image rather than assumed from the first one. + + ``obs_collection`` is ``spherex_`` with an optional ``_deep`` or ``_cal`` + suffix, and every collection lives under a matching ``/`` prefix in the + bucket (confirmed with IRSA, 2026-08-18). + + No de-duplication is needed: IRSA confirmed the search interfaces never return two + releases for the same observation, so each observation appears exactly once. + + Superseded by the ``cloud_access`` column once ``spherex.obscore`` exposes it — each + row will then carry its own S3 location and neither this function nor the path + construction in ``get_lvf_url`` will be needed. Not available as of 2026-08-18. + """ + coll = str(row["obs_collection"]).strip() + rel = coll[len("spherex_"):] if coll.startswith("spherex_") else coll + for suffix in ("_deep", "_cal"): + if rel.endswith(suffix): + rel = rel[: -len(suffix)] + if not rel: + raise RuntimeError(f"Cannot derive a release prefix from obs_collection={coll!r}") + return rel + + +# Silent unless something is unexpected. IRSA supersede a release in place rather than +# serving two versions of one observation, so a field spanning more than one release is +# possible (year 1 in DR1, year 2 in QR3) but worth flagging if it happens. +_releases = sorted({_release_of(row) for row in lvf_results_to_process}) +if len(_releases) > 1: + print(f"NOTE: this field spans {len(_releases)} data releases " + f"({', '.join(_releases)}); each image is read from its own release.") + +# Calibration products live under a release prefix too, but `find_calib_urls` in Section 4.1 +# returns one file per *detector*, not one per (release, detector), so it needs a single +# release rather than a per-image one. Take the sample's, and say so when the sample spans +# more than one -- that is precisely the case the cal-file lookup cannot yet express. +_cal_release = _releases[0] +if len(_releases) > 1: + print(f"NOTE: calibration files will be taken from '{_cal_release}' for all images; " + f"the cal lookup is keyed by detector only and has no release dimension.") + +lvf_url_det_pairs = [get_lvf_url(row, _bucket, _release_of(row), _fs) + for row in lvf_results_to_process] +lvf_urls = [url for url, _ in lvf_url_det_pairs] +print(f"Example URL: {lvf_urls[0] if lvf_urls else 'none'}") +``` + +## 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. + +```{code-cell} ipython3 +--- +jupyter: + source_hidden: true +tags: [hide-cell] +--- +# Calibration files share the bucket + release prefix of the L2 images and are laid out as: +# {release}/{product}/cal--v-//.fits +# `_bucket`, `_cal_release` and `_fs` were established in Section 3.3; use s3fs to select the +# newest version of each product, one detector at a time. + + +def _calib_version_key(version_dir): + """Sort key ordering ``cal--v--`` directories oldest to newest. + + Comparing these names as plain strings works only while the version number keeps a + fixed digit width — ``"v10"`` sorts below ``"v2"`` — so compare it as an integer. + """ + parts = version_dir.rsplit("/", 1)[-1].split("-") + version = next((int(p[1:]) for p in parts if p[:1] == "v" and p[1:].isdigit()), -1) + return version, tuple(int(p) for p in parts[-2:] if p.isdigit()) + + +def find_calib_urls(product, required=True): + """Return ``{detector_int: https_url}`` for the newest version of ``product`` per detector. + + ``product`` is an S3 calibration directory name: ``"solid_angle_pixel_map"``, + ``"spectral_wcs"``, ``"epsf"``, ``"l3_flux_corrections"`` or ``"he_template"``. The + single FITS file found for each detector is returned as a download-friendly HTTPS URL + (Section 4.2 and 4.3 cache these with ``download_file``). + + The version is resolved **per detector**, not once for the product, because that is what + the pipeline itself does: in ``spx_tasks`` every calibration is a ``PrerequisiteInput`` + with ``dimensions=["instrument", "detector"]`` and ``isCalibration=True``, so the butler + resolves one certified dataset per (product, detector) and a delivery that respins a + single detector leaves the others on their previous version. ``dr1/epsf`` is exactly + that case: ``cal-epsf-v2-2026-191`` holds D3 alone and D1, D2, D4, D5, D6 stay at + ``cal-epsf-v1-2026-191``, so taking one newest directory for all six would return D3 and + silently drop the rest. + + The bucket carries no validity timespans, so "newest" here is the highest version + directory that has a file for that detector, where the butler would additionally match + the exposure's time against the certified validity range. + """ + product_dir = f"{_bucket}/{_cal_release}/{product}" + version_dirs = _fs.ls(product_dir) if _fs.exists(product_dir) else [] + if not version_dirs: + if not required: # he_template is a `minimum=0` input; the pipeline runs without it + return {} + raise RuntimeError(f"No {product} calibration found in s3://{_bucket}/{_cal_release}") + urls = {} + # Oldest version first, so a newer one simply overwrites the detectors it supersedes. + for version_dir in sorted(version_dirs, key=_calib_version_key): + for path in _fs.glob(f"{version_dir}/*/*.fits"): + det = int(path.rsplit("/", 2)[-2]) # ...///.fits + key = path.split("/", 1)[1] # strip bucket from the path + urls[det] = f"https://{_bucket}.s3.amazonaws.com/{key}" + return urls +``` + +```{code-cell} ipython3 +# SSDC certify their calibration products as one set (the `IRSA-r7-tools` chained collection +# holds epsf, l3_flux_corrections, solid_angle_pixel_map, spectral_wcs and he_template +# together), so all five come from one release prefix, `_cal_release` (Section 3.3). Mixing +# products from different releases would run a calibration that matches neither the online +# tool nor the SSDC benchmark. +sapm_urls = find_calib_urls("solid_angle_pixel_map") +wcs_urls = find_calib_urls("spectral_wcs") +epsf_urls = find_calib_urls("epsf") +flux_corr_urls = find_calib_urls("l3_flux_corrections") +he_urls = find_calib_urls("he_template", required=False) + +for product, urls in [("solid_angle_pixel_map", sapm_urls), ("spectral_wcs", wcs_urls), + ("epsf", epsf_urls), ("l3_flux_corrections", flux_corr_urls), + ("he_template", he_urls)]: + if not urls: + continue + print(f"{product} per detector:") + for det in sorted(urls): + print(f" D{det}: {urls[det]}") +``` + +### 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. + +```{code-cell} ipython3 +solid_angle_maps = {} # {detector_int: SPHERExImage} +spectral_wcs_hduls = {} # {detector_int: astropy.io.fits.HDUList} +sapm_cache_paths = {} # local cache file paths passed to worker processes +wcs_cache_paths = {} + +unique_detectors = {det for _, det in lvf_url_det_pairs} + +for det in sorted(unique_detectors): + if det not in sapm_urls: + print(f"WARNING: no solid_angle_pixel_map for detector {det}, skipping") + continue + if det not in wcs_urls: + print(f"WARNING: no spectral_wcs for detector {det}, skipping") + continue + + sapm_path = download_file(sapm_urls[det], cache=True, show_progress=False) + wcs_path = download_file(wcs_urls[det], cache=True, show_progress=False) + + solid_angle_maps[det] = SPHERExImage.read(sapm_path) + spectral_wcs_hduls[det] = fits.open(wcs_path) + sapm_cache_paths[det] = sapm_path + wcs_cache_paths[det] = wcs_path + print(f"Loaded calibrations for detector {det}") +``` + +### 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. + +```{code-cell} ipython3 +def _cal_paths(urls): + """Return ``{detector_int: local path}`` for one product, downloaded from S3.""" + return {det: download_file(url, cache=True, show_progress=False) + for det, url in sorted(urls.items())} + + +epsf_cache_paths = _cal_paths(epsf_urls) +flux_corr_paths = _cal_paths(flux_corr_urls) +# He I airglow template. Published for D1-2 only, and that is the complete set: the He I +# line is at 1.083 um, which falls on D1 (0.735-1.127) and the edge of D2 (1.085-1.668) +# and on no other detector. EstimateDiffuseBackgroundTask takes it as an optional input +# (minimum=0), so passing it for D1-2 and None elsewhere is what the butler would supply. +he_template_paths = _cal_paths(he_urls) + +_cal_source = f"s3://{_bucket}/{_cal_release}" +if not epsf_cache_paths: + raise RuntimeError(f"No ePSF files found in {_cal_source}") +if not flux_corr_paths: + raise RuntimeError(f"No flux-correction files found in {_cal_source}") +print(f"Calibration source: {_cal_source}") +print(f"ePSF files (detectors): {sorted(epsf_cache_paths)}") +print(f"Flux-correction files (detectors): {sorted(flux_corr_paths)}") +print(f"He airglow template files (detectors): {sorted(he_template_paths) or 'none'}" + " [D1-2 only by design: He I 1.083 um falls on no other detector]") +``` + +## 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. + ++++ + +```{tip} + **Using a custom source catalog:** To use your own catalog instead of Gaia DR3, + skip the query cell below and construct an astropy ``Table`` directly. + Required columns and units: ``SPHERExRefID`` (unique int64), ``ra``/``dec`` + (degrees, with ``u.deg``), ``ra_error``/``dec_error`` (degrees), + ``ref_ra``/``ref_dec`` (degrees; typically equal to ``ra``/``dec``), + ``sersic``, ``shape_r`` (**arcseconds**), + ``ab_ratio``, ``phi``, ``do_phot`` (bool). + SPHEREx guidance is to model every source as a point source, so set the + morphology columns to point-source defaults (``sersic=0``, ``shape_r=0``, + ``ab_ratio=1``, ``phi=0``); extended source types are not recommended with this tool. + The catalog will be trimmed to ``_neighbor_radius`` automatically. + The primary target is identified as the source closest to (``RA``, ``DEC``), + so make sure your target is included. + ``validate_table()`` will catch column format errors before photometry begins. + + +``` + +```{code-cell} ipython3 +# The Tractor fitting window is (_pfp.cut_side_length + 2×_pfp.frame_width) px square. +# The corner-to-center distance (√2 × half-side) is the maximum radius at which a neighbor +# could contribute flux to the target window; use that as the neighbor search radius. +_pfp = L3aTask.ConfigClass().perform_forced_photometry +_window_side = _pfp.cut_side_length + 2 * _pfp.frame_width +_neighbor_radius = (np.sqrt(2) * _window_side / 2 * get_pix_scale()).to(u.arcmin) + +GAIA_CATALOG = "gaia_dr3_source" + +# Only these columns are used downstream: `build_srccat_from_gaia` reads ra/dec and their errors, +# and PM_CORR_INPUTS needs pmra/pmdec/parallax/ref_epoch to propagate positions to the observation +# epoch. Nothing reads phot_g_mean_mag, and the Gaia source_id is not used either -- SPHERExRefID is +# generated locally. Asking for the whole table instead means IRSA serialising ~157 columns to +# deliver eight, which is slow and is the first thing to fail when the service is under load. +GAIA_COLUMNS = "ra,dec,ra_error,dec_error,pmra,pmdec,parallax,ref_epoch" + +target_coord = coord.SkyCoord(ra=RA * u.deg, dec=DEC * u.deg) + +print(f"Querying Gaia DR3 within {_neighbor_radius} of RA={RA}, Dec={DEC}…") +gaia_raw = Irsa.query_region( + target_coord, + catalog=GAIA_CATALOG, + radius=_neighbor_radius, + columns=GAIA_COLUMNS, +) +print(f"Retrieved {len(gaia_raw)} Gaia sources ({len(gaia_raw.colnames)} columns)") +``` + +```{code-cell} ipython3 +--- +jupyter: + source_hidden: true +tags: [hide-cell] +--- +def build_srccat_from_gaia(gaia_table: Table, target_ra: float, target_dec: float, + obs_epoch_mjd: float | None = None) -> Table: + """Map Gaia DR3 columns to the srccat format expected by PerformForcedPhotometryTask. + + Column units match what validate_table() (from spx_tasks.l3a) requires: + ra/dec in degrees, shape_r in arcseconds. All sources — the target and its + neighbors — are modeled as point sources. SPHEREx guidance is to use point + sources with this tool; extended (Sérsic) source fitting is not recommended, + so the morphology columns are always set to point-source defaults. + + Parameters + ---------- + gaia_table : `~astropy.table.Table` + Gaia DR3 sources returned by ``Irsa.query_region``. + target_ra : float + Right ascension of the primary target in degrees (ICRS). + target_dec : float + Declination of the primary target in degrees (ICRS). + obs_epoch_mjd : float, optional + Mean MJD of the images being fitted. When given, Gaia positions are propagated + from the catalog reference epoch (J2016.0 for DR3) to this epoch using the Gaia + proper motions, following the same convention as the production pipeline's + ``QueryReferenceCatalogTask``: ``ref_ra``/``ref_dec`` keep the catalog + reference-epoch positions while ``ra``/``dec`` carry the propagated ones. + If omitted, positions are used as catalogued. + + Returns + ------- + `~astropy.table.Table` + Source catalog with columns required by ``PerformForcedPhotometryTask``. + """ + n = len(gaia_table) + + if n == 0: + # No Gaia DR3 source anywhere in the search radius — a legitimate case for targets Gaia + # does not carry (transients, very red objects below its limit, moving objects). Fit the + # target alone at the supplied coordinates rather than failing. + print(f"WARNING: no Gaia DR3 sources within the search radius of " + f"(RA={target_ra}, Dec={target_dec}). Fitting the target alone at the supplied " + "coordinates; no neighbors will be deblended.") + return Table({ + "SPHERExRefID": np.array([1], dtype=np.int64), + "ra": [target_ra] * u.deg, + "dec": [target_dec] * u.deg, + "ra_error": [0.0] * u.deg, + "dec_error": [0.0] * u.deg, + "ref_ra": [target_ra] * u.deg, + "ref_dec": [target_dec] * u.deg, + "sersic": np.zeros(1, dtype=np.float32), + "shape_r": np.zeros(1, dtype=np.float32) * u.arcsecond, + "ab_ratio": np.ones(1, dtype=np.float32), + "phi": np.zeros(1, dtype=np.float32), + "do_phot": np.ones(1, dtype=bool), + }) + + srccat = Table() + srccat["SPHERExRefID"] = np.arange(1, n + 1, dtype=np.int64) + srccat["ra"] = np.array(gaia_table["ra"], dtype=np.float64) * u.deg + srccat["dec"] = np.array(gaia_table["dec"], dtype=np.float64) * u.deg + # Gaia position errors are in mas; convert to degrees + srccat["ra_error"] = (np.array(gaia_table["ra_error"], dtype=np.float64) * u.mas).to(u.deg) + srccat["dec_error"] = (np.array(gaia_table["dec_error"], dtype=np.float64) * u.mas).to(u.deg) + # ref_ra/ref_dec keep the catalog reference-epoch positions; ra/dec are propagated to the + # observation epoch just below. This is QueryReferenceCatalogTask's convention. + srccat["ref_ra"] = srccat["ra"].copy() + srccat["ref_dec"] = srccat["dec"].copy() + + # Apply proper motion corrections. QueryReferenceCatalogTask cannot be called directly here + # because it requires the Butler-backed reference-catalog infrastructure this notebook exists + # to avoid, so we reuse its required-column list (PM_CORR_INPUTS), its -9999.0 sentinel + # convention, and the same astropy space-motion call it uses. + if obs_epoch_mjd is not None and all(c in gaia_table.colnames for c in PM_CORR_INPUTS): + ref_epoch = np.array(gaia_table["ref_epoch"], dtype=np.float64) + pmra = np.array(gaia_table["pmra"], dtype=np.float64) + pmdec = np.array(gaia_table["pmdec"], dtype=np.float64) + valid = ((ref_epoch != -9999.0) & (pmra != -9999.0) & (pmdec != -9999.0) + & np.isfinite(ref_epoch) & np.isfinite(pmra) & np.isfinite(pmdec)) + pm_idx = np.nonzero(valid)[0] + if len(pm_idx) > 0: + gaia_star_coords = coord.SkyCoord( + ra=np.asarray(srccat["ref_ra"][pm_idx]) * u.deg, + dec=np.asarray(srccat["ref_dec"][pm_idx]) * u.deg, + pm_ra_cosdec=pmra[pm_idx] * u.mas / u.yr, + pm_dec=pmdec[pm_idx] * u.mas / u.yr, + frame="icrs", + obstime=Time(ref_epoch[pm_idx], format="jyear"), + ) + updated_coords = gaia_star_coords.apply_space_motion( + new_obstime=Time(obs_epoch_mjd, format="mjd")) + srccat["ra"][pm_idx] = updated_coords.ra.deg + srccat["dec"][pm_idx] = updated_coords.dec.deg + _shift = updated_coords.separation(gaia_star_coords).to(u.arcsec) + print(f"Proper motion applied to {len(pm_idx)}/{n} sources at MJD {obs_epoch_mjd:.3f}: " + f"median shift {np.median(_shift.value):.3f}\", max {np.max(_shift.value):.3f}\"") + else: + print("No sources have usable Gaia proper motions; positions used as catalogued.") + elif obs_epoch_mjd is None: + print("No observation epoch given; Gaia positions used as catalogued (no PM correction).") + # All sources are modeled as point sources (SPHEREx guidance: do not use + # extended source types with this tool); shape_r in arcseconds as required. + srccat["sersic"] = np.zeros(n, dtype=np.float32) + srccat["shape_r"] = np.zeros(n, dtype=np.float32) * u.arcsecond + srccat["ab_ratio"] = np.ones(n, dtype=np.float32) + srccat["phi"] = np.zeros(n, dtype=np.float32) + srccat["do_phot"] = np.ones(n, dtype=bool) + + # Identify the target as the closest Gaia source to (target_ra, target_dec). + # If no Gaia source is within GAIA_MATCH_RADIUS, fall back to the user's + # coordinates directly so that the target position is not silently wrong. + GAIA_MATCH_RADIUS = 15 * u.arcsec + target_coord = coord.SkyCoord(ra=target_ra * u.deg, dec=target_dec * u.deg) + separations = coord.SkyCoord(ra=srccat["ra"], dec=srccat["dec"]).separation(target_coord) + target_idx = int(np.argmin(separations)) + + if separations[target_idx] > GAIA_MATCH_RADIUS: + print(f"WARNING: nearest Gaia source is {separations[target_idx].to(u.arcsec):.1f} from " + f"(RA={target_ra}, Dec={target_dec}) — beyond {GAIA_MATCH_RADIUS}. " + "Using user coordinates as the target.") + user_row = {col: srccat[col][[0]] for col in srccat.colnames} + user_row["ra"] = [target_ra] * u.deg + user_row["dec"] = [target_dec] * u.deg + user_row["ref_ra"] = [target_ra] * u.deg + user_row["ref_dec"] = [target_dec] * u.deg + srccat = vstack([Table(user_row), srccat]) + # user_row was copied from row 0, so it carried that row's SPHERExRefID. Renumber so the + # IDs stay unique — a duplicate would make the downstream target lookup match two sources. + srccat["SPHERExRefID"] = np.arange(1, len(srccat) + 1, dtype=np.int64) + + return srccat +``` + +```{code-cell} ipython3 +# Mean epoch of the images being fitted, used to propagate Gaia positions forward. The +# production pipeline corrects per slew group; the standalone tool fits one source list across +# the whole image set, so a single mean epoch is used. Over a typical few-month span the +# residual is well under a milliarcsecond for all but the highest proper-motion stars. +_obs_epoch_mjd = float(np.mean(0.5 * (np.asarray(lvf_results_to_process["t_min"], dtype=np.float64) + + np.asarray(lvf_results_to_process["t_max"], dtype=np.float64)))) + +srccat = build_srccat_from_gaia(gaia_raw, RA, DEC, obs_epoch_mjd=_obs_epoch_mjd) +# Validate column names, types, and units against the production pipeline's expectations +validate_table(srccat) +print(f"Source catalog: {len(srccat)} sources (validated)") + +# Trim to sources within _neighbor_radius of the target. +neighbor_seps = target_coord.separation(coord.SkyCoord(ra=srccat["ra"], dec=srccat["dec"])) +srccat_trimmed = srccat[neighbor_seps < _neighbor_radius] +print(f"Trimmed: {len(srccat)} → {len(srccat_trimmed)} sources within {_neighbor_radius}") + +# Identify the primary target now, while the per-source separations are available. +trimmed_seps = neighbor_seps[neighbor_seps < _neighbor_radius] +target_source_id = int(srccat_trimmed["SPHERExRefID"][int(np.argmin(trimmed_seps))]) +print(f"Primary target source_id: {target_source_id}") +srccat_trimmed[:8] +``` + +## 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. + +```{code-cell} ipython3 +--- +jupyter: + source_hidden: true +tags: [hide-cell] +--- +# Per-process state; populated by the initializer in each worker, never shared. +_phot_worker_state: dict = {} + + +class _DropLines(io.TextIOBase): + """Text stream wrapper that drops whole lines containing ``drop_substr``.""" + + def __init__(self, target, drop_substr): + self._target = target + self._drop = drop_substr + self._buf = "" + + def write(self, s): + self._buf += s + while "\n" in self._buf: + line, self._buf = self._buf.split("\n", 1) + if self._drop not in line: + self._target.write(line + "\n") + return len(s) + + def flush(self): + self._target.flush() + + +@contextlib.contextmanager +def _filter_pipeline_warnings(drop_substr="no valid pixels"): + """Drop stdout/stderr lines containing ``drop_substr`` (harmless pipeline warnings).""" + with contextlib.redirect_stdout(_DropLines(sys.stdout, drop_substr)), \ + contextlib.redirect_stderr(_DropLines(sys.stderr, drop_substr)): + yield + + +def _init_phot_worker(sapm_paths: dict, wcs_paths: dict, srccat, + return_residuals: bool = False, + target_ra: float = None, target_dec: float = None, + suppress_warnings: bool = True, + epsf_paths: dict = None, he_paths: dict = None) -> None: + """Initialize per-worker process state for parallel photometry. + + Called once per worker process at startup by ``ProcessPoolExecutor``. + Loads calibration files and creates an ``L3aTask`` instance in the + worker's private memory so they are not shared across processes. + + Parameters + ---------- + sapm_paths : dict + Mapping of detector number to local cache path for the + ``solid_angle_pixel_map`` calibration file. + wcs_paths : dict + Mapping of detector number to local cache path for the + ``spectral_wcs`` calibration file. + srccat : `~astropy.table.Table` + Trimmed source catalog passed to ``PerformForcedPhotometryTask``. + return_residuals : bool + If True, configure the task to return per-window Tractor fit data. + target_ra, target_dec : float + Sky coordinates of the primary target (degrees, ICRS), used to + identify the target's Tractor window when ``return_residuals=True``. + suppress_warnings : bool + If True, filter the pipeline's harmless "no valid pixels" warnings + out of the worker's stdout/stderr. + epsf_paths : dict + Mapping of detector number to local path for the SPHEREx-provided ePSF + calibration file, used in place of the legacy PSF. + """ + config = L3aTask.ConfigClass() + config.perform_forced_photometry.combinedOutput = True + # Use the SPHEREx-provided ePSF (supplied per image as the `epsf` input) instead of the legacy + # PSF. override_epsf=True makes the pipeline read the ePSF from that input rather than an image + # extension — the public L2 images carry only a legacy PSF layer. + config.perform_forced_photometry.psf_extension = "EPSF" + config.perform_forced_photometry.override_epsf = True + # This notebook does forced photometry on a fixed source list; disable solar-system-object + # fitting (R7 defaults it on and then requires an `ssocat` input we don't provide). + config.perform_forced_photometry.fit_sso = False + # Tag each measurement with its data release (qr2, qr3 or dr1) in a `data_collection` column, + # as the online tool does; Section 7 uses it to apply the flux corrections to QR2 only. + config.perform_forced_photometry.phot_tool_mode = True + config.perform_forced_photometry.return_fit = return_residuals + _phot_worker_state["task"] = L3aTask(config=config) + _phot_worker_state["sapm"] = {d: SPHERExImage.read(p) for d, p in sapm_paths.items()} + _phot_worker_state["epsf"] = {d: SPHERExImage.read(p) for d, p in epsf_paths.items()} + _phot_worker_state["wcs"] = {d: fits.open(p) for d, p in wcs_paths.items()} + # He I airglow template, D1-2 only; absent for the rest, which is correct rather than + # missing -- the He I line at 1.083 um falls on no other detector. + _phot_worker_state["he"] = {d: SPHERExImage.read(p) + for d, p in (he_paths or {}).items()} + _phot_worker_state["srccat"] = srccat + _phot_worker_state["return_residuals"] = return_residuals + _phot_worker_state["target_ra"] = target_ra + _phot_worker_state["target_dec"] = target_dec + _phot_worker_state["suppress_warnings"] = suppress_warnings + + +def _phot_worker(url_det_pair: tuple[str, int]): + """Download and run forced photometry on one LVF image. + + Runs ``EstimateDiffuseBackgroundTask`` then ``PerformForcedPhotometryTask`` + on the downloaded image using the per-process state loaded by + ``_init_phot_worker``. Images that failed fine astrometry (``FINAST != 0``) + are skipped. + + Parameters + ---------- + url_det_pair : tuple[str, int] + ``(fits_url, det_num)`` identifying the LVF image to process. + + Returns + ------- + `~astropy.table.Table` or None + Combined photometry table, or ``None`` if skipped. + When ``return_residuals=True``, returns a ``(table, hdul, col, row)`` tuple + where ``hdul`` is the Tractor window HDUList and ``col``, ``row`` are the + target's pixel position within the cutout array. + """ + url, det = url_det_pair + _return_residuals = _phot_worker_state.get("return_residuals", False) + _null = (None, None, None, None) if _return_residuals else None + if det not in _phot_worker_state.get("sapm", {}): + return _null + local_path = download_file(url, cache=True, show_progress=False) + img = SPHERExImage.read(local_path, hdu_layers=["PSF", "CATALOG"]) + # Skip images that failed fine astrometry — same guard as L3aTask.run() + if ("FINAST" not in img.header) or (img.header["FINAST"] != 0): + return _null + wcs_hdul = _phot_worker_state["wcs"][det] + _filter = (_filter_pipeline_warnings() if _phot_worker_state.get("suppress_warnings") + else contextlib.nullcontext()) + with _filter: + # he_template is optional: without it EstimateDiffuseBackgroundTask estimates no + # airglow component at all, whereas R7 defaults est_he_airglow=True. Pass it where + # one exists so the standalone matches the pipeline. + bkg_result = _phot_worker_state["task"].estimate_diffuse_background.run( + spximg=img, spectral_wcs=wcs_hdul, + he_template=_phot_worker_state["he"].get(det)) + phot_result = _phot_worker_state["task"].perform_forced_photometry.run( + spximg=img, + srccat=_phot_worker_state["srccat"], + global_bkgd=bkg_result.global_bkgd, + solid_angle_pixel_map=_phot_worker_state["sapm"][det], + spectral_wcs=wcs_hdul, + epsf=_phot_worker_state["epsf"].get(det), + ) + if not _return_residuals: + return phot_result.phot_meas_combined + # Find the window centered on the target using sky WCS from the image file + _target_sky = coord.SkyCoord( + _phot_worker_state["target_ra"] * u.deg, + _phot_worker_state["target_dec"] * u.deg) + with fits.open(local_path, memmap=True) as _hf: + _sky_wcs = WCS(_hf["IMAGE"].header) + _tx, _ty = _sky_wcs.world_to_pixel(_target_sky) + _best_hdul, _best_dist, _best_ox, _best_oy = None, np.inf, 0, 0 + for _pos_str, _hdul in (phot_result.tractor_fits or {}).items(): + _ox, _oy = map(int, _pos_str.split(",")) + _ch, _cw = _hdul["CUTOUT"].data.shape + _d = np.hypot(_ox + _cw / 2.0 - _tx, _oy + _ch / 2.0 - _ty) + if _d < _best_dist: + _best_dist, _best_hdul = _d, _hdul + _best_ox, _best_oy = _ox, _oy + return (phot_result.phot_meas_combined, _best_hdul, + float(_tx - _best_ox), float(_ty - _best_oy)) + + +def run_photometry(url_det_pairs, srccat, sapm_paths, wcs_paths, n_workers, + target_ra, target_dec, return_residuals=False, + suppress_warnings=True, epsf_paths=None, he_paths=None): + """Run forced photometry on every LVF image and collect the per-image results. + + Each image is processed in its own worker process: ``EstimateDiffuseBackgroundTask`` + followed by ``PerformForcedPhotometryTask``. Images that were skipped, or that + produced no measurements, are dropped from the returned tables. + + Parameters + ---------- + url_det_pairs : list of tuple[str, int] + ``(fits_url, det_num)`` pairs built in Section 3.3. + srccat : `~astropy.table.Table` + Trimmed Gaia source catalog from Section 5. + sapm_paths, wcs_paths : dict + Detector number to local calibration file path, from Section 4. + n_workers : int + Number of parallel worker processes. + target_ra, target_dec : float + Primary target position (degrees, ICRS). + return_residuals : bool, optional + If True, also collect the target's Tractor window from each image so that + Section 10 can plot fit residuals. + suppress_warnings : bool, optional + If True, filter the pipeline's harmless "no valid pixels" warnings. + epsf_paths : dict + Detector number to local path for the SPHEREx-provided ePSF calibration + file, from Section 4.3, used in place of the legacy PSF. + + Returns + ------- + tables : list of `~astropy.table.Table` + One combined photometry table per image that yielded measurements. + lvf_id_to_url : dict + ``lvf_id`` to image URL, used by Section 9 to re-fetch images for display. + tractor_fits_by_url : dict + Image URL to ``(HDUList, target_col, target_row)``. Empty unless + ``return_residuals=True``. + """ + # Don't start more workers than there are images. + n_workers = min(n_workers, len(url_det_pairs)) + print(f"Running photometry on {len(url_det_pairs)} images ({n_workers} workers)…") + with concurrent.futures.ProcessPoolExecutor( + max_workers=n_workers, + initializer=_init_phot_worker, + initargs=(sapm_paths, wcs_paths, srccat, + return_residuals, target_ra, target_dec, suppress_warnings, + epsf_paths, he_paths), + ) as pool: + raw_results = list(tqdm( + pool.map(_phot_worker, url_det_pairs), + total=len(url_det_pairs), + desc="Photometry", + )) + + # Workers return (table, hdul, col, row) tuples when return_residuals=True. + tractor_fits_by_url = {} + if return_residuals: + tables = [r[0] for r in raw_results] + tractor_fits_by_url = { + url: (hdul, tc, tr) + for (url, _det), (t, hdul, tc, tr) in zip(url_det_pairs, raw_results) + if hdul is not None + } + print(f"Collected {len(tractor_fits_by_url)} target-window HDULists for residuals.") + else: + tables = raw_results + + # Build lvf_id → URL before filtering so Section 9 can retrieve images by lvf_id. + lvf_id_to_url = { + int(t["lvf_id"][0]): url + for (url, _det), t in zip(url_det_pairs, tables) + if t is not None and len(t) > 0 + } + + tables = [t for t in tables if t is not None and len(t) > 0] + print(f"Successful measurements from {len(tables)} images") + return tables, lvf_id_to_url, tractor_fits_by_url +``` + +```{code-cell} ipython3 +per_image_tables, _lvf_id_to_url, _tractor_fits_by_url = run_photometry( + lvf_url_det_pairs, + srccat_trimmed, + sapm_cache_paths, + wcs_cache_paths, + n_workers=N_PHOT_CORES, + target_ra=RA, + target_dec=DEC, + return_residuals=RETURN_RESIDUALS, + suppress_warnings=SUPPRESS_PIPELINE_WARNINGS, + epsf_paths=epsf_cache_paths, + he_paths=he_template_paths, +) +``` + +## 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. + +```{code-cell} ipython3 +if not per_image_tables: + raise RuntimeError("No photometry measurements were produced. " + "Check that the target is covered by the retrieved L2 images.") + +# CreateAllSkyCatalogTask is "level3b" in L3ToolPipeline.yaml — despite its name, +# it is the correct pipeline step for spectral combining: it groups per-image +# measurements by source, sorts by wavelength, and applies calibrations including +# the catalog-level variance boost (flux_err = sqrt(flux_err_tractor^2 + (0.03*flux)^2)). +class _TableHandle: + """Minimal mock of lsst.daf.butler.DeferredDatasetHandle.""" + def __init__(self, table): self._table = table + def get(self, **kwargs): return self._table + +handles = [] +for t in per_image_tables: + t2 = t.copy() + if "hips6" in t2.colnames: + t2.remove_column("hips6") + handles.append(_TableHandle(t2)) + +cat_config = CreateAllSkyCatalogTask.ConfigClass() +cat_config.merge_refcat = False +cat_config.apply_flux_corrections = True +# As in the online tool: apply the flux corrections to QR2 measurements only. DR1 and QR3 +# measurements are left unchanged. +cat_config.phot_tool_mode = True +cat_config.apply_variance_boost = True +cat_config.list_items = [ + "x_image", "y_image", "mjd", "lambda", "lambda_width", + "flux", "flux_err", "flux_err_tractor", "flux_bkg", "flags", "fit_ql", "deep_flg", "lvf_id", "det_id", + "data_collection", +] +# Supply the SPHEREx-provided per-detector flux corrections. CreateAllSkyCatalogTask expects a +# list of deferred handles whose .get() returns a SPHERExImage (keyed by detector internally via +# getArrayId()); reuse the _TableHandle passthrough. flux_corr_run is just a cache-key string. +flux_corr_handles = [_TableHandle(SPHERExImage.read(p)) + for _det, p in sorted(flux_corr_paths.items())] +cat_result = CreateAllSkyCatalogTask(config=cat_config).run( + meas_table_list=handles, + l3_flux_corrections=flux_corr_handles, + flux_corr_run="spherex_cal_override", +) +allsky_pa = cat_result.allsky_cat + +target_pa = allsky_pa.filter(pc.equal(allsky_pa["source_id"], target_source_id)) +if len(target_pa) == 0: + raise RuntimeError(f"source_id={target_source_id} not found in combined catalog.") +list_cols = set(cat_config.list_items) +n = len(target_pa["flux"][0].as_py()) +data = {col: (target_pa[col][0].as_py() if col in list_cols + else [target_pa[col][0].as_py()] * n) + for col in target_pa.schema.names} +spectrum = Table(data) +spectrum.sort("lambda") + +# Wrap in a specutils Spectrum object for compatibility with the specutils/astropy ecosystem. +# The underlying Table is preserved for saving; spec is for in-memory analysis and plotting. +spec = Spectrum( + spectral_axis=np.array(spectrum["lambda"]) * u.um, + flux=np.array(spectrum["flux"]) * u.uJy, + uncertainty=StdDevUncertainty(np.array(spectrum["flux_err"]) * u.uJy), +) + +print(f"Spectrum: {len(spectrum)} measurements for source_id={target_source_id}") +spectrum[:5] +``` + +## 8. Display and Save the Spectrum +Now that we have a spectrum, let's take a look! + +```{code-cell} ipython3 +fig, ax = plt.subplots(figsize=(10, 5)) + +ax.errorbar(spec.spectral_axis.value, spec.flux.value, + yerr=spec.uncertainty.quantity.value, + fmt="o", markersize=3, linewidth=0.8, + label=f"RA={RA:.4f}, Dec={DEC:.4f}") + +# Scale the y-axis to the fluxes, not the error bars, so a single failed fit +# with a huge uncertainty doesn't flatten the spectrum. No points are hidden. +flux = spec.flux.value +pad = 0.1 * (np.nanmax(flux) - np.nanmin(flux)) +ax.set_ylim(np.nanmin(flux) - pad, np.nanmax(flux) + pad) + +ax.set_xlabel(f"Central Wavelength ({spec.spectral_axis.unit})") +ax.set_ylabel(f"Flux ({spec.flux.unit})") +ax.set_title("SPHEREx Forced-Photometry Spectrum") +ax.legend() +plt.tight_layout() +plt.show() +``` + +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). + +```{code-cell} ipython3 +os.makedirs(OUTPUT_DIR, exist_ok=True) +output_stem = os.path.join(OUTPUT_DIR, f"spherex_spectrum_ra{RA:.4f}_dec{DEC:.4f}") + +if OUTPUT_FORMAT == "ecsv": + output_path = f"{output_stem}.ecsv" + spectrum.write(output_path, format="ascii.ecsv", overwrite=True) + +elif OUTPUT_FORMAT == "votable": + output_path = f"{output_stem}.vot" + spectrum.write(output_path, format="votable", overwrite=True) + +elif OUTPUT_FORMAT == "fits_sdm": + # Write a FITS file following the IVOA Spectrum Data Model. Building an + # astropy Table with the standard SpectrumDM column names/units and header + # keywords in .meta lets Table.write() emit the bintable so VO tools + # (TOPCAT, Aladin, etc.) can read it without configuration. + output_path = f"{output_stem}_sdm.fits" + sdm = Table() + sdm["WAVELENGTH"] = np.array(spectrum["lambda"], dtype=np.float64) * u.um + sdm["FLUX"] = np.array(spectrum["flux"], dtype=np.float64) * u.uJy + sdm["ERROR"] = np.array(spectrum["flux_err"], dtype=np.float64) * u.uJy + sdm["QUALITY"] = np.array(spectrum["flags"], dtype=np.int32) + sdm.meta.update({ + "EXTNAME": "SPECTRUM", + "VOCLASS": "Spectrum-1.0", + "TELESCOP": "SPHEREx", + "INSTRUME": "SPHEREx", + "RA_TARG": RA, + "DEC_TARG": DEC, + }) + sdm.write(output_path, format="fits", overwrite=True) + +else: + raise ValueError(f"Unknown OUTPUT_FORMAT={OUTPUT_FORMAT!r}. " + "Choose 'ecsv', 'votable', or 'fits_sdm'.") + +print(f"Spectrum saved to {output_path} (format={OUTPUT_FORMAT})") +``` + +## 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). + +```{code-cell} ipython3 +--- +jupyter: + source_hidden: true +tags: [hide-cell] +--- +def _north_up_cutout(url, hdu_name): + """Download one LVF image and return a north-up cutout centred on the target. + + Parameters + ---------- + url : str + Direct S3 HTTPS URL for the LVF FITS file. + hdu_name : str + Name of the image extension to read (e.g. ``"IMAGE"``, ``"FLAGS"``). + + Returns + ------- + rotated : `~numpy.ndarray` + 2-D float array of the cutout, rotated so north is up and east is left. + circle_radius_px : float + Radius in pixels of the target-position marker circle + (``MARKER_RADIUS_ARCSEC`` converted to pixels). + """ + local_path = download_file(url, cache=True) + with fits.open(local_path, memmap=True) as hdul: + data = hdul[hdu_name].data.astype(np.float64) + wcs_img = WCS(hdul[hdu_name].header) + cutout = Cutout2D(data, _target_coord, + size=(FOV_ARCMIN * u.arcmin, FOV_ARCMIN * u.arcmin), + wcs=wcs_img, mode="partial", fill_value=np.nan) + # Measure PA of the +y axis from north using the cutout WCS + cx, cy = np.array(cutout.data.shape[::-1]) / 2.0 - 0.5 # cutout center + sky_c = cutout.wcs.pixel_to_world(cx, cy) + sky_n = cutout.wcs.pixel_to_world(cx, cy + 1.0) + pa = sky_c.position_angle(sky_n).to(u.deg).value + pix_scale = sky_c.separation(sky_n).to(u.arcsec).value # arcsec/px + rotated = scipy.ndimage.rotate(cutout.data, pa, reshape=False, + cval=np.nan, order=1) + circle_radius_px = MARKER_RADIUS_ARCSEC / pix_scale # marker radius in pixels + return rotated, circle_radius_px + + +def _show_images(hdu_name="IMAGE", save_path=None): + """Display a panel of north-up LVF cutouts at the selected wavelengths. + + Parameters + ---------- + hdu_name : str, optional + FITS extension to display. One of ``"IMAGE"``, ``"FLAGS"``, + ``"VARIANCE"``, or ``"ZODI"``. + save_path : str or None, optional + If provided, save the panel as a PNG file at this path. + """ + plt.close("all") + n = len(_display_items) + fig, axes = plt.subplots(1, n, figsize=(3 * n, 3.3)) + if n == 1: + axes = [axes] + for ax, (lam, url) in zip(axes, _display_items): + try: + img, r_px = _north_up_cutout(url, hdu_name) + except OSError as exc: + ax.text(0.5, 0.5, str(exc)[:40], ha="center", va="center", + transform=ax.transAxes, fontsize=9, color="red") + ax.set_axis_off() + continue + h, w = img.shape + # FLAGS: integer bitmap — all-zero means no flags set on any pixel + if hdu_name == "FLAGS": + _flag_max = np.nanmax(img) + if _flag_max == 0: + ax.text(0.5, 0.5, "No flags set", ha="center", va="center", + transform=ax.transAxes, fontsize=10, color="gray") + ax.set_facecolor("black") + ax.set_title(f"λ={lam:.4f} µm", fontsize=16) + ax.set_xticks([]); ax.set_yticks([]) + continue + vmin, vmax = 0, _flag_max + else: + # Stretch around background: clip the bright source to reveal background texture + vmin, vmax = np.nanpercentile(img, [10, 90]) + ax.imshow(img, origin="lower", cmap="gray_r", vmin=vmin, vmax=vmax, + interpolation="nearest") + ax.add_patch(Circle((w / 2 - 0.5, h / 2 - 0.5), radius=r_px, + edgecolor="yellow", facecolor="none", linewidth=1.5)) + ax.set_title(f"λ={lam:.4f} µm", fontsize=16) + ax.set_xticks([]); ax.set_yticks([]) + # North/East compass on first panel: arrows from junction, labels at tips + _cx, _cy, _arm = 0.12, 0.78, 0.13 + _lbl = dict(boxstyle="round,pad=0.1", fc="white", ec="none", alpha=0.7) + axes[0].annotate("", xy=(_cx, _cy + _arm), xytext=(_cx, _cy), + xycoords="axes fraction", + arrowprops=dict(arrowstyle="->", color="black", lw=1.5)) + axes[0].text(_cx, _cy + _arm + 0.04, "N", transform=axes[0].transAxes, + color="black", fontsize=12, ha="center", va="bottom", + fontweight="bold", bbox=_lbl) + axes[0].annotate("", xy=(_cx + _arm, _cy), xytext=(_cx, _cy), + xycoords="axes fraction", + arrowprops=dict(arrowstyle="->", color="black", lw=1.5)) + axes[0].text(_cx + _arm + 0.03, _cy, "E", transform=axes[0].transAxes, + color="black", fontsize=12, ha="left", va="center", + fontweight="bold", bbox=_lbl) + fig.suptitle( + f"{hdu_name} | FOV {FOV_ARCMIN}′ | Target: RA={RA:.4f}, Dec={DEC:.4f}", + fontsize=16) + plt.tight_layout() + if save_path is not None: + fig.savefig(save_path, dpi=150, bbox_inches="tight") + print(f"Saved {save_path}") + # Render to PNG buffer so the figure displays at full size regardless of backend. + _buf = _BytesIO() + fig.savefig(_buf, format="png", dpi=150, bbox_inches="tight") + _buf.seek(0) + _ipy_display(_IPyImage(data=_buf.read())) + plt.close(fig) +``` + +```{code-cell} ipython3 +FOV_ARCMIN = 1.3 # field of view matching the online tool (arcmin) +_target_coord = coord.SkyCoord(RA * u.deg, DEC * u.deg) +_DISPLAY_HDUS = ["IMAGE", "FLAGS", "VARIANCE", "ZODI"] + +# Build the list of (lambda_um, s3_url) pairs for the N display images. +# Fast path: photometry already ran — use _lvf_id_to_url built in Section 6. +# Slow path: query TAP directly (~15 s) so this section works standalone. +if "_lvf_id_to_url" in dir(): + _lam_arr = np.array(spectrum["lambda"]) + _display_items = [] + _seen = set() + for _tgt in np.linspace(_lam_arr.min(), _lam_arr.max(), N_DISPLAY_IMAGES): + _idx = int(np.argmin(np.abs(_lam_arr - _tgt))) + if _idx not in _seen: + _seen.add(_idx) + _row = spectrum[_idx] + _url = _lvf_id_to_url.get(int(_row["lvf_id"])) + if _url: + _display_items.append((float(_row["lambda"]), _url)) +else: + # Standalone path: query TAP for images at evenly spaced wavelengths + print("Photometry results not in memory — querying TAP for display images…") + _all_imgs = tap_search(f""" + SELECT obs_id, access_url, (em_min + em_max) / 2.0 AS lam_m + FROM spherex.obscore + WHERE CONTAINS(POINT('ICRS', {RA}, {DEC}), s_region) = 1 + AND obs_intent = 'science' + """, maxrec=500).to_table() + _all_lam_um = (np.array(_all_imgs["lam_m"]) * u.m).to(u.um).value + _display_items, _seen = [], set() + for _tgt in np.linspace(_all_lam_um.min(), _all_lam_um.max(), N_DISPLAY_IMAGES): + _idx = int(np.argmin(np.abs(_all_lam_um - _tgt))) + if _idx not in _seen: + _seen.add(_idx) + _url = resolve_datalink(str(_all_imgs[_idx]["access_url"])) + _display_items.append((float(_all_lam_um[_idx]), _url)) + print(f"Found {len(_display_items)} images to display.") + + + +widgets.interact(_show_images, + hdu_name=widgets.Dropdown(options=_DISPLAY_HDUS, description="HDU:"), + save_path=widgets.fixed(None)) +``` + +```{code-cell} ipython3 +# Optionally save the image panel displayed above +if IMAGE_PANEL_SAVE: + _out_stem = f"spherex_imagepanel_ra{RA:.4f}_dec{DEC:.4f}" + if IMAGE_PANEL_FORMAT == "png": + _show_images("IMAGE", save_path=f"{_out_stem}.png") + elif IMAGE_PANEL_FORMAT == "fits": + _out_hdus = [fits.PrimaryHDU()] + for _i, (_lam, _url) in enumerate(_display_items): + _img, _ = _north_up_cutout(_url, "IMAGE") + _ext = fits.ImageHDU(_img.astype(np.float32), name=f"LAM{_i + 1}") + _ext.header["LAMBDA"] = (_lam, "Central wavelength (µm)") + _ext.header["RA_TARG"] = (RA, "Target RA (deg)") + _ext.header["DEC_TARG"] = (DEC, "Target Dec (deg)") + _out_hdus.append(_ext) + _fits_path = f"{_out_stem}.fits" + fits.HDUList(_out_hdus).writeto(_fits_path, overwrite=True) + print(f"Saved {_fits_path} ({len(_out_hdus) - 1} image extensions)") + elif IMAGE_PANEL_FORMAT == "region": + _reg_path = f"{_out_stem}.reg" + with open(_reg_path, "w") as _f: + _f.write("# Region file format: DS9 version 4.1\n") + _f.write("global color=yellow width=2\n") + _f.write("fk5\n") + _f.write(f'circle({RA:.6f},{DEC:.6f},{MARKER_RADIUS_ARCSEC}")\n') + print(f"Saved {_reg_path}") + else: + print(f"Unknown IMAGE_PANEL_FORMAT {IMAGE_PANEL_FORMAT!r}. Use 'png', 'fits', or 'region'.") +``` + +## 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. + +```{code-cell} ipython3 +if RETURN_RESIDUALS: + if "_display_items" not in dir(): + raise RuntimeError("Run Sections 6–9 first.") + if not _tractor_fits_by_url: + raise RuntimeError("No Tractor windows were collected. " + "Re-run Section 6 with RETURN_RESIDUALS = True.") + _residual_panels = [] + for _lam, _url in _display_items: + _val = _tractor_fits_by_url.get(_url) + if _val is None: + print(f" λ={_lam:.4f} µm: no tractor window (image may have been skipped)") + continue + _hdul, _tc, _tr = _val + _data = np.array(_hdul["CUTOUT"].data, dtype=float) + _model = np.array(_hdul[0].data, dtype=float) + _chi = np.array(_hdul["CHI"].data, dtype=float) + _ch, _cw = _data.shape + # Shift each array so the target pixel lands at the array center + _shift = ((_ch - 1) / 2.0 - _tr, (_cw - 1) / 2.0 - _tc) + _residual_panels.append(( + _lam, + scipy.ndimage.shift(_data, _shift, cval=np.nan, order=1), + scipy.ndimage.shift(_model, _shift, cval=np.nan, order=1), + scipy.ndimage.shift(_chi, _shift, cval=np.nan, order=1), + )) + print(f"{len(_residual_panels)} residual panels ready.") + + plt.close("all") + _n = len(_residual_panels) + # Shared scales per row so colorbars are meaningful across wavelengths + _data_all = np.concatenate([r[1].ravel() for r in _residual_panels]) + _model_all = np.concatenate([r[2].ravel() for r in _residual_panels]) + _chi_all = np.concatenate([r[3].ravel() for r in _residual_panels]) + _dlo, _dhi = np.nanpercentile(_data_all, [5, 95]) + _mlo, _mhi = np.nanpercentile(_model_all, [5, 95]) + _chi_vmax = max(float(np.nanpercentile(np.abs(_chi_all), 99)), 0.1) + _row_cfg = [ + ("Data", "gray_r", _dlo, _dhi, "Flux (MJy/sr)"), + ("Model", "gray_r", _mlo, _mhi, "Flux (MJy/sr)"), + ("χ = (data−model) / noise", "RdBu_r", -_chi_vmax, _chi_vmax, "σ"), + ] + _fig, _axes = plt.subplots(3, _n, figsize=(3.5 * _n, 8), + constrained_layout=True) + if _n == 1: + _axes = _axes.reshape(3, 1) + for _row, (_label, _cmap, _vlo, _vhi, _cb_label) in enumerate(_row_cfg): + for _col, (_lam, _data_arr, _model_arr, _chi_arr) in enumerate(_residual_panels): + _arr = [_data_arr, _model_arr, _chi_arr][_row] + _ax = _axes[_row, _col] + _im = _ax.imshow(_arr, origin="lower", cmap=_cmap, + vmin=_vlo, vmax=_vhi, interpolation="nearest", + aspect="auto") + if _row == 0: + _ax.set_title(f"λ={_lam:.4f} µm", fontsize=14) + if _col == 0: + _ax.set_ylabel(_label, fontsize=12) + _ax.set_xticks([]); _ax.set_yticks([]) + _fig.colorbar(_im, ax=_axes[_row, :], label=_cb_label, shrink=0.8) + _fig.suptitle( + f"Tractor fit | Target: RA={RA:.4f}, Dec={DEC:.4f}", + fontsize=16) + # Render to PNG buffer so the figure displays at full size regardless of backend. + _buf = _BytesIO() + _fig.savefig(_buf, format="png", dpi=100, bbox_inches="tight") + _buf.seek(0) + _ipy_display(_IPyImage(data=_buf.read())) + plt.close(_fig) +``` + +## Acknowledgements + +- [Caltech/IPAC-IRSA](https://irsa.ipac.caltech.edu/) +- [SPHEREx Mission](https://spherex.caltech.edu/) +- [Gaia DR3](https://www.cosmos.esa.int/web/gaia/dr3) via IRSA + +## About this Notebook + +**Updated:** 30 November 2026 + +**Contact:** [IRSA Helpdesk](https://irsa.ipac.caltech.edu/docs/help_desk.html) 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.