diff --git a/.claude/skills/spherex-data-release/SKILL.md b/.claude/skills/spherex-data-release/SKILL.md new file mode 100644 index 00000000..7eedf1c8 --- /dev/null +++ b/.claude/skills/spherex-data-release/SKILL.md @@ -0,0 +1,115 @@ +--- +name: spherex-data-release +description: Update the SPHEREx tutorial notebooks in irsa-tutorials for a new SPHEREx data release (DR2, DR3, a new Quick Release, a reprocessing). Use this whenever someone mentions a new SPHEREx release, new SPHEREx collections or DOIs, a new SPHEREx Explanatory Supplement, new FLAGS bits, or asks to "update the SPHEREx notebooks", "test SPHEREx against irsatest", or prepare the SPHEREx release-day PR -- even if they only ask about one of those pieces. +--- + +# SPHEREx data-release update + +This skill repeats the work done for DR1 (issue #392, released 2026-11-12). +Find every place in the SPHEREx notebooks that depends on the release, test against pre-release IRSA hosts, collect the answers that only other people can give, and land everything in one PR on release day. + +Most of the time goes into waiting on other people, not editing code. +So the main job is to keep a written plan current, ask for missing information early, and do everything that does not depend on those answers right away. + +## Files in this skill + +- `references/touchpoints.md` -- every release-dependent spot in each notebook, as of the date at its top. + Read this first; it is the work list. + Notebooks merged after that date are not in it. +- `references/decisions.md` -- rules settled during DR1 and gotchas that cost time. + Read before asking the user anything; most questions were already answered once. +- `scripts/check_release.sh ` -- what is live for release `` (e.g. `dr2`) on the pre-release and production hosts, S3 buckets and docs. +- `scripts/run_release_test.py` -- executes notebooks against a pre-release host by changing only a copy of each, and reports any cell errors. + +## Workflow + +### 1. Start a plan file + +Create `SPHEREX__PLAN.md` at the repo root and add it (and any local test folder) to `.git/info/exclude` so it never gets committed. +Put a short "RESUME HERE" block at the top: branch, last commit, what is blocked and on whom, next actions. +Update it at the end of every work chunk. +The work spans weeks and many sessions, and this file is the only thing that carries over. + +Work on a branch named `spherex-` off `main`. +It must not merge before the release is public. + +### 2. Find out what exists + +Run `scripts/check_release.sh ` (needs IRSA VPN for the pre-release hosts). +It reports, for TAP, SIA, IBE, S3 and the supplement PDF, whether the new release is visible. +Record the results as a "data products needed" table in the plan (product, which notebook uses it, test location, available yes/no, date checked). +Re-run it whenever something might have changed. + +### 3. Ask early for what only people can provide + +Send these questions as soon as the release date is known. +Draft each as a paste-ready message in a fenced code block. +Keep each one short and specific. + +- **IRSA** (archive/backend staff): When will the new SIA collections be loaded on the pre-release hosts (irsadev, irsatest), so the notebooks can be tested? What will the collections be named? + Will `cloud_access` be filled in those rows? (The Source Discovery Tool reads its S3 paths from it. Check it in SIA results, e.g. with `scripts/check_release.sh`: TAP's `ivoa.obscore` leaves it blank even when SIA fills it.) + Will the data be on a staging S3 bucket, and when does it move to the public one? +- **IRSA** (DOIs): the DOI for the new release. + It is usually not available until close to release. +- **SSDC**: a copy of the new Explanatory Supplement, or confirmation that the online one is current. + Ask about any new FLAGS bits and which ones should count as bad for photometry. + +Decide with the user which releases the notebooks should show after this release (after DR1 they show DR1 and QR3). +Then decide what happens if the pre-release load does not come through (for DR1 the fallback was letting the tutorials go out a few days after release). +Set a date to follow up and write it in the plan. + +### 4. Make the changes + +Go through `references/touchpoints.md` notebook by notebook, plus any SPHEREx notebook merged after its date. +Write the notebooks with production URLs and the new release's names, as they should read on release day. +Never put test hosts or test switches in the notebooks; `scripts/run_release_test.py` points a copy at the pre-release host instead. +In order of how early they can be done: + +1. TAP notebooks (`spherex_cutouts.md`, `spherex_psf.md`, SDT sec. 12, the spectrophotometry tool): testable as soon as the release is in TAP on a pre-release host. +2. Header-driven code and text: open one new-release image and compare its extensions, FLAGS `MSKN*` keywords and `L2 N_*` counts with what the notebooks say and parse (see touchpoints). + New flags or renamed keywords break code silently: the DR1 photometry recorded no flags at all until the parser was fixed. +3. SIA notebooks (`spherex_intro.md`, SDT secs. 6-11): use the collection names IRSA gives, and confirm them on the pre-release host as soon as they are loaded (`check_release.sh` lists them). + If the names are not known yet, follow the previous release's pattern (`spherex_qr3`, `spherex_qr3_deep`, `spherex_qr3_cal` became `spherex_dr1`, `spherex_dr1_deep`, `spherex_dr1_cal`), and keep "confirm the collection names" open in the plan until they are. +4. Narrative: supplement link and table number, DOIs, release wording on the landing page. + +Commit in small, single-purpose commits and push to the fork. +Ask before committing, and say in the plan what each commit did. + +### 5. Test every notebook end to end + +Run whole notebooks, not selected cells. +A DR1 test that ran only some cells of the Source Discovery Tool, with a 2MASS star standing in for secs. 9-11, passed while sec. 6 was silently picking a D5 image instead of D4 (see decisions.md). + +`scripts/run_release_test.py` copies each notebook's folder, points the copy at the pre-release host (TAP, SIA, cutout and HiPS URLs, `s3://nasa-irsa-spherex/` reads through that host's IBE mirror, and Firefly through that host's viewer), executes every cell and lists the errors. +Run each notebook in a kernel made from its own conda env, so the test also checks that the env works. +For example, for the SDT (its env includes SExtractor): + +```bash +conda env create -f tutorials/spherex/spherex_source_discovery/conda-spherex_sdt.yml +conda run -n spherex_sdt python -m ipykernel install --user --name spherex_sdt +python .claude/skills/spherex-data-release/scripts/run_release_test.py \ + tutorials/spherex/spherex_source_discovery/spherex_source_discovery_tool_demo.md \ + --kernel spherex_sdt --out +``` + +Run it with any Python that has `jupytext` and `nbclient`. +Notebooks that share an env can be listed together. +It does not redirect S3 reads made through `s3fs` or `https://.s3.amazonaws.com` URLs (the spectrophotometry tool), so those notebooks can be tested only once the data is in the bucket they read. + +Then open the executed copies and check the results, not just the error count. +Ask the user to look at the Firefly tabs it opens. +For the SDT: sec. 6 must pick D2 and D4, the hard-coded `selected_ids` source must exist, and its spectrum should look like a real source. +For DR1 the SDT ran 33 code cells with 0 errors; SExtractor found 79 sources and #65 was 40th by flux; the spectrum had 276 points, 0.75-4.99 um, median S/N about 11, 50 points with a `bad_flags` pixel in the aperture. + +### 6. Release day + +Keep a release-day checklist in the plan from the start and refine it as answers arrive. +Its final shape for DR1 is in `references/decisions.md` under "Release-day checklist". +Open a draft PR well before release so it can be reviewed, with the checklist in the PR description. + +As the last checklist item, update this skill with what was learned (see below). + +## Keeping this skill current + +After each release, update `references/touchpoints.md` from `main` (new values, new notebooks, and the date at the top), add new decisions and gotchas to `references/decisions.md`, and fix anything in this file that was wrong. +Leave out people's names: say which group to ask (IRSA, SSDC), not who. diff --git a/.claude/skills/spherex-data-release/references/decisions.md b/.claude/skills/spherex-data-release/references/decisions.md new file mode 100644 index 00000000..68f146a9 --- /dev/null +++ b/.claude/skills/spherex-data-release/references/decisions.md @@ -0,0 +1,64 @@ +# Decisions and gotchas from DR1 + +## Rules (settled; don't re-ask unless something changed) + +- **Which releases to show:** decide case by case for each release. + After DR1 the notebooks show DR1 and QR3 (`spherex_intro.md` and the SDT search both, and the TAP notebooks have no release filter). +- **DOIs:** cite the DOI of each release the notebook actually loads. +- **`bad_flags` in the Source Discovery Tool:** use the flag list that sets the supplement's CONTAINS_BAD_PIXEL warning (supplement v2.1, sec. 3.3 "Photometric Measurements", p. 45). + This came from the SSDC developer who wrote the SDT. + Do not use the shorter "flags for masking pixels for photometry calculations" list just above it. + For DR1 the list was: TRANSIENT, OVERFLOW, SUR_ERROR, NONFUNC, DICHROIC, MISSING_DATA, HOT, COLD, NONLINEAR, CROSSTALK, GHOST, GHOST_FPA, GHOST_EXT, STREAK, PERSIST, BLOOM, SNOWBALL, HALO, SATELLITE_HALO. + FULLSAMPLE is informational and was removed. +- **Supplement:** link `SPHEREx_Expsupp.pdf` (the `_QR` suffix was dropped for DR1). + Only the current version is online, so cite sections and tables, not pages. + For flag definitions, the online supplement is the reference, not plans for a future release. + Cite the flag table by number (Table 16 in v2.1) and recheck the number when a new version appears. +- **No test code in the notebooks:** test against pre-release hosts with `scripts/run_release_test.py`, which changes only a copy. +- **`cloud_access`:** assume the new SIA collection fills it. + If a pre-release collection has it empty, build the S3 path from the URI for local testing only, and don't commit that. + +## Gotchas + +- irsatest/irsadev are reachable only on the IRSA network or VPN. + Cloud notebook servers get 403 or cannot resolve them. +- IRSA production TAP/SIA can return 502 for a while. + For non-SPHEREx lookups in tests (like 2MASS), irsatest works too. +- `spherex.plane.datarelease` is a date, not a release name. + To pick out one release in TAP, filter on the URI path (`a.uri LIKE 'ibe/data/spherex//%'`) or `obs_publisher_did`. +- Each release has a `_cal` SIA collection listing calibration files (ePSF, SAPM) per detector. + It is the quickest way to learn calibration version names. +- IBE mirrors the S3 paths, so `s3://nasa-irsa-spherex//...` reads can be pointed at `https:///ibe/data/spherex//...` for testing. +- For DR1, pre-release S3 data sat in a staging bucket (`nasa-irsa-spherex-dr1-staging`) that moved to the public `nasa-irsa-spherex` on release day. +- FLAGS keywords changed between releases (`MP_*` in QR2, `MSKN*`/`MSKD*` from QR3). + New flags can appear in the supplement before they appear in image headers (SATELLITE_HALO, bit 29, was in supplement v2.0 but not in DR1 v7.0.5 headers), so code must tolerate missing flag names. +- To look at a pre-release host by hand, set both `Irsa.sia_url = "https://irsadev.ipac.caltech.edu/SIA"` and `Irsa.tap_url = "https://irsadev.ipac.caltech.edu/TAP"`. + `Irsa.list_collections()` uses TAP, so it lists production collections unless `tap_url` is set too. + irsadev SIA `access_url`s point at a dev IBE host. + IRSA may load only part of the sky, so confirm the notebook positions are covered. +- Select detectors by name, never by position. + The SDT once took D4 as `results.group_by('energy_bandpassname').groups[3]`, which is D4 only if all six detectors have images at the position. + DR1 at the demo position had D1, D2, D4 and D5, so it silently used D5 with every label still saying D4. + Fixed for DR1 by matching `groups.keys` to `'SPHEREx-D4'`. +- The SDT's sec. 12.1 measures a hard-coded SExtractor source number (`selected_ids = [65]`). + The numbering changes whenever the images change, so check the number on every release, including release day. + For DR1 it was left as 65 (a real source, mid-brightness) with a release-day check. +- Production Firefly (irsa.ipac.caltech.edu/irsaviewer) can't load images from pre-release hosts: it shows "failed". + Use the same host's viewer (`https://irsatest.ipac.caltech.edu/irsaviewer`) when testing (`run_release_test.py` does this), and check production Firefly on release day. +- For DR1, MOST on the pre-release hosts didn't index the new release, so `MOST_queries.md` couldn't be tested end to end before release. + Check again for the next release. + Its SPHEREx cutout cell could still be tested: take the exposures production MOST returns, find the new-release file with the same observation ID (`level2___`) on the pre-release IBE, and run the cell on it. + +## Release-day checklist (DR1's final shape) + +1. Confirm the release is live: `scripts/check_release.sh `. + Check the SIA collection names in the intro and SDT, and confirm production SIA rows have `cloud_access`. +2. Put in the new DOI (SDT acknowledgements). +3. Bump `**Updated:**` in every notebook that changed. +4. Run each changed notebook against production with `jupytext --to notebook --execute` in its conda env (the SDT's is `conda-spherex_sdt.yml`, which includes SExtractor). + Check the Firefly tabs show images, and that the SDT's hard-coded `selected_ids` still gives a real spectrum. +5. `techniques-and-tools/MOST_queries.md` uses SPHEREx too. + It needed no changes for DR1; check whether MOST serves the new release and which release it returns. +6. Recheck the supplement's flag table number. +7. Mark the draft PR ready for review (it closes the release issue). +8. Update this skill with what was learned. diff --git a/.claude/skills/spherex-data-release/references/touchpoints.md b/.claude/skills/spherex-data-release/references/touchpoints.md new file mode 100644 index 00000000..e8bbf8a0 --- /dev/null +++ b/.claude/skills/spherex-data-release/references/touchpoints.md @@ -0,0 +1,88 @@ +# Release-dependent spots in the SPHEREx notebooks + +Checked against `main` on 2026-12-03, after DR1 (released 2026-11-12). +Any SPHEREx notebook merged after that date is not listed here: go through it the same way and add it. +Line numbers drift; search for the quoted text instead. +Paths are relative to `tutorials/spherex/`. + +## spherex_cutouts.md (TAP + IBE cutouts) + +- TAP query on `spherex.artifact`/`spherex.plane`, with no release filter, so it returns every release IRSA serves (DR1 and QR3 after DR1). + The text says "The SPHEREx metadata tables include DR1 and QR3 images." +- Cutout URL prefix `'https://irsa.ipac.caltech.edu/' || a.uri`. +- Comment listing extensions 1-6 (IMAGE, FLAGS, VARIANCE, ZODI, EPSF, WCS-WAVE); check against a new image. +- Supplement link (`SPHEREx_Expsupp.pdf`), `**Updated:**`. + +## spherex_psf.md (TAP + IBE cutouts + S3) + +- Same TAP query and cutout URL prefix as cutouts. +- Intro and sec. 5.2 text on which releases supersede which ("QR3 and DR1 supersede QR2"). +- "primary HDU plus 6 extensions (IMAGE, FLAGS, VARIANCE, ZODI, EPSF, WCS-WAVE)"; check against a new image. +- Sec. 5.1 reads the image's own `EPSF` extension (image version >= 7.0). + Sec. 5.2 is for QR2 images, which have no `EPSF` extension, and reads ePSF calibration files from S3 (`qr3/epsf/cal-epsf-v*-*`). + Every sec. 5.2 cell is guarded by `if not epsf_in_image:`, so it is skipped for new images. + The guard was added during the DR1 update, after the fallback was found overwriting a new image's own ePSF; keep it. +- Supplement link, `**Updated:**`. + +## spherex_intro.md (SIA) + +- Sec. 2: "This notebook uses data from SPHEREx Data Release 1 (DR1)." and the supersede sentence. +- Bullet list of collections (`spherex_dr1`, `spherex_dr1_deep`, `spherex_qr3`, `spherex_qr3_deep`) and `Irsa.query_sia(..., collection=['spherex_dr1', 'spherex_qr3'])`. +- Sec. 6 extension list and sec. 12 describe the `EPSF` bintable (DR1: 441 rows = 21x21 regions, 5x oversampled via `OVSMPX`/`OVSMPY`). +- Sec. 8d prints `spectral_image_header['L2 N_*']` and explains the `_NB` and `_NS` keywords. + It cites the supplement's flag table (Table 16 in supplement v2.1). +- Sec. 9 loops over FLAGS header `MSKNnnnn` (name) / `MSKDnnnn` (description). + QR2 used `MP_*`. +- Supplement link, `**Updated:**`. + +## spherex_source_discovery/spherex_source_discovery_tool_demo.md (SIA + S3 + TAP) + +- Sec. 5 "valid as of **SPHEREx Data Release 1 (DR1), November 2026**" note. +- Sec. 5 parameters: `data_release = "dr1"`, `sia_collection = [f"spherex_{data_release}", "spherex_qr3"]`, `sapm_collection = "cal-sapm-v3-2026-191"`. + `data_release` also builds the S3 path `nasa-irsa-spherex/{data_release}/solid_angle_pixel_map/{sapm_collection}/...` (folder is `solid_angle_pixel_map/`, not `sapm/`). +- "Note that we have used the collections `spherex_dr1` and `spherex_qr3`" sentence after the SIA query. +- Sec. 6 picks the D2 and D4 images by `energy_bandpassname` (D4 through `groups.keys`). + Check that the search still returns both detectors at the demo position. +- Sec. 7 `get_s3_fpath(cloud_access)`: needs `cloud_access` filled in SIA results. +- Sec. 12.1 TAP query (`pyvo.dal.TAPService("https://irsa.ipac.caltech.edu/TAP")`, no release filter) and cutout URL prefix. +- Sec. 12.1 `selected_ids = [65]`: a SExtractor source number from sec. 10, so it changes when the images do. + Check it still names a real source. +- Sec. 12.2 `bad_flags`: the supplement's CONTAINS_BAD_PIXEL list (see decisions.md), and the sentence citing the flag table (Table 16). +- Acknowledgements: DOI sentence. + As of 2026-12-03 it still cites only the QR2 DOI (`10.26131/IRSA629`), although the notebook loads DR1 and QR3. +- Supplement link, `**Updated:**`. +- Package `spherex_source_discovery_tool/aperture_photometry.py`: `build_phot_table` reads flag names from `MSKN*` (falls back to `MP_*`); `grab_star` skips `bad_flags` entries an image does not define. + Check both against new FLAGS headers. + +## spherex_spectrophotometry/spherex_spectrophotometry_tool.md (TAP + S3) + +- TAP query on `spherex.obscore` with no release filter; each image's release comes from its `obs_collection` (`_release_of`), and the S3 path from that release prefix. + Text and comments mention "DR1 (year 1) + QR3 (year 2)". +- Lists S3 folders with `s3fs` (L2 version folders, `/epsf`, other calibration products), so the release's files must be in the public bucket; `run_release_test.py` does not redirect these reads. +- Supplement link uses the versioned file `SPHEREx_Expsupp_v2.1.pdf`; only the current version stays online (v2.0 now returns 404). +- Link to the "SPHEREx Data Release 1 (DR1) Overview" page and its DOIs. +- `**Updated:**`. + +## spherex_hipscube.md (HiPS) + +- `hips_data_url = "https://irsa.ipac.caltech.edu/ibe/data/spherex/dr1/hips5_cube/hips_20261026"`: release and build date are in the path. + `hips_url` (`.../data/hips/SPHEREx/spherex_allsky_cube`) has neither. + +## spherex_mosaic.md + +- Supplement link. +- The static `M101_irsa.fits` demo cube was not regenerated for DR1. + +## spherex.md (landing page) + +- Wording about Quick Releases and Data Releases ("e.g., DR1") and the supersede sentence. + +## techniques-and-tools/MOST_queries.md + +- Uses SPHEREx but needed no changes for DR1. + Sec. 5 queries MOST with `catalog="spherex"` (Vesta, Aug 2025); `plot_path()` uses only MOST's output columns; the cutout cell reads `hdul[1]` and `PC1_1`/`PC1_2`. + No release-specific code, but which release MOST returns is known only after release (see decisions.md). + +## Repo files + +- `deploy_to_fornax_manifest.in` and `notebook_metadata.yml` list the SPHEREx files; update them if files are added, renamed or removed (a stale manifest entry fails CI). diff --git a/.claude/skills/spherex-data-release/scripts/check_release.sh b/.claude/skills/spherex-data-release/scripts/check_release.sh new file mode 100755 index 00000000..11676a59 --- /dev/null +++ b/.claude/skills/spherex-data-release/scripts/check_release.sh @@ -0,0 +1,64 @@ +#!/usr/bin/env bash +# Report what is live for a SPHEREx release on IRSA's pre-release and production hosts. +# Usage: check_release.sh e.g. check_release.sh dr2 +# The irsadev/irsatest checks need the IRSA network or VPN. +set -u +REL="${1:?usage: check_release.sh }" + +sia_collections() { + local q="SELECT DISTINCT obs_collection FROM ivoa.obscore WHERE obs_collection LIKE 'spherex%'" + curl -s -m 60 --data-urlencode "QUERY=$q" -d FORMAT=csv -d LANG=ADQL "$1/TAP/sync" \ + | tail -n +2 | tr '\n' ' ' +} + +tap_rows() { + local q="SELECT TOP 1 a.uri FROM spherex.artifact a WHERE a.uri LIKE 'ibe/data/spherex/$REL/%'" + curl -s -m 120 --data-urlencode "QUERY=$q" -d FORMAT=csv -d LANG=ADQL "$1/TAP/sync" | sed -n 2p +} + +# Ask SIA, not TAP: ivoa.obscore leaves cloud_access blank even where SIA (what the notebooks +# use) fills it. Search at the position of one of the release's own images. IRSA's SIA CSV +# doesn't quote the JSON, so grep it out instead of parsing columns. +cloud_access() { + local q="SELECT TOP 1 s_ra, s_dec FROM ivoa.obscore WHERE obs_collection = 'spherex_$REL'" + local pos ra dec row + pos=$(curl -s -m 60 --data-urlencode "QUERY=$q" -d FORMAT=csv -d LANG=ADQL "$1/TAP/sync" | sed -n 2p) + [ -z "$pos" ] && { echo "(no spherex_$REL rows)"; return; } + IFS=, read -r ra dec <<<"$pos" + row=$(curl -s -m 120 "$1/SIA?COLLECTION=spherex_$REL&POS=CIRCLE+$ra+$dec+0.0003&MAXREC=1&RESPONSEFORMAT=csv" | sed -n 2p) + [ -z "$row" ] && { echo "(no SIA rows)"; return; } + grep -o '{"aws": {[^}]*}}' <<<"$row" || echo "(blank)" +} + +# Subfolders under / in a bucket ("(empty)" if none, or the S3 error code). +s3_prefixes() { + local xml out + xml=$(curl -s -m 60 "https://$1.s3.us-east-1.amazonaws.com/?list-type=2&delimiter=/&prefix=$REL/") + if grep -q '' <<<"$xml"; then + grep -o '[^<]*' <<<"$xml" | sed 's/<[^>]*>//g' + return + fi + out=$(grep -o '[^<]*' <<<"$xml" | sed 's/<[^>]*>//g' | tr '\n' ' ') + echo "${out:-(empty)}" +} + +http_code() { curl -s -m 30 -o /dev/null -I -w '%{http_code}' "$1"; } + +for host in https://irsadev.ipac.caltech.edu https://irsatest.ipac.caltech.edu https://irsa.ipac.caltech.edu; do + echo "== $host" + echo " SIA collections: $(sia_collections "$host")" + uri=$(tap_rows "$host") + echo " $REL TAP row: ${uri:-(none)}" + echo " cloud_access (spherex_$REL): $(cloud_access "$host")" + # IBE has no directory listing, so check that the TAP row's file is served. + [ -n "$uri" ] && echo " IBE file for that row: HTTP $(http_code "$host/$uri")" +done + +echo "== S3" +echo " staging nasa-irsa-spherex-$REL-staging: $(s3_prefixes "nasa-irsa-spherex-$REL-staging")" +echo " public nasa-irsa-spherex: $(s3_prefixes nasa-irsa-spherex)" + +echo "== Docs" +for f in SPHEREx_Expsupp.pdf SPHEREx_Expsupp_QR.pdf; do + echo " $f: $(http_code "https://irsa.ipac.caltech.edu/data/SPHEREx/docs/$f")" +done diff --git a/.claude/skills/spherex-data-release/scripts/run_release_test.py b/.claude/skills/spherex-data-release/scripts/run_release_test.py new file mode 100644 index 00000000..10228307 --- /dev/null +++ b/.claude/skills/spherex-data-release/scripts/run_release_test.py @@ -0,0 +1,87 @@ +"""Execute SPHEREx notebooks against an IRSA pre-release host, without changing the notebooks. + +Usage (from the repo root, on the IRSA network or VPN): + python run_release_test.py [ ...] \ + [--host https://irsatest.ipac.caltech.edu] [--kernel ] [--out release_test_run] + +Run it with any Python that has jupytext and nbclient. +--kernel picks the Jupyter kernel that runs the notebook; use one built from the notebook's +conda env (e.g. `python -m ipykernel install --user --name spherex_sdt` inside that env). + +Each notebook's folder is copied into --out// and the copy is executed; +the tracked notebook is not changed. Test-only changes to the copy: +- `https://irsa.ipac.caltech.edu` in code cells -> --host (TAP, cutout URLs, HiPS, irsaviewer). +- astroquery's Irsa SIA and TAP -> --host. +- fits.open of s3://nasa-irsa-spherex/... -> the IBE mirror of the same path on --host + (the public bucket is empty before release). +- FireflyClient.make_lab_client() -> make_client() on --host's irsaviewer. A headless run has no + JupyterLab, and production Firefly can't load pre-release URLs. Browser tabs open; look at them. +Not redirected: S3 reads through s3fs or https://.s3.amazonaws.com URLs. +""" +import argparse +import os +import shutil + +import jupytext +import nbformat +from nbclient import NotebookClient + +PROD = "https://irsa.ipac.caltech.edu" + +ap = argparse.ArgumentParser() +ap.add_argument("notebooks", nargs="+") +ap.add_argument("--host", default="https://irsatest.ipac.caltech.edu") +ap.add_argument("--kernel", default="python3") +ap.add_argument("--out", default="release_test_run") +args = ap.parse_args() +host = args.host.rstrip("/") + +SETUP = f''' +# TEST HARNESS ONLY (run_release_test.py) +from astropy.io import fits +from astroquery.ipac.irsa import Irsa +Irsa.sia_url = "{host}/SIA" +Irsa.tap_url = "{host}/TAP" +_S3, _IBE = "s3://nasa-irsa-spherex/", "{host}/ibe/data/spherex/" +_real_open = fits.open +def _open_via_ibe(name, *args, **kwargs): + if isinstance(name, str) and name.startswith(_S3): + kwargs.pop("fsspec_kwargs", None) + name = _IBE + name[len(_S3):] + return _real_open(name, *args, **kwargs) +fits.open = _open_via_ibe +''' + +for path in args.notebooks: + name = os.path.basename(path) + out = os.path.abspath(os.path.join(args.out, name.removesuffix(".md"))) + if os.path.exists(out): + shutil.rmtree(out) + shutil.copytree(os.path.dirname(os.path.abspath(path)), out) + + nb = jupytext.read(os.path.join(out, name)) + code = [c for c in nb.cells if c.cell_type == "code"] + n_ff = 0 + for c in code: + c.source = c.source.replace(PROD, host) + while "FireflyClient.make_lab_client()" in c.source: + n_ff += 1 + c.source = c.source.replace( + "FireflyClient.make_lab_client()", + f'FireflyClient.make_client(url="{host}/irsaviewer", channel_override="release_test_{n_ff}")', + 1) + nb.cells.insert(0, nbformat.v4.new_code_cell(SETUP)) + + print(f"Executing {name} in {out} (may take several minutes) ...", flush=True) + NotebookClient(nb, timeout=1800, kernel_name=args.kernel, allow_errors=True, + resources={"metadata": {"path": out}}).execute() + executed = os.path.join(out, name.replace(".md", ".ipynb")) + nbformat.write(nb, executed) + + n_err = 0 + for c in code: + for o in c.get("outputs", []): + if o.get("output_type") == "error": + n_err += 1 + print("=" * 70, "\n" + c.source[:300], "\n--> ERROR", o["ename"], o["evalue"][:500]) + print(f"{name}: {len(code)} code cells, {n_err} errors. Executed copy: {executed}\n")