diff --git a/deploy_to_fornax_manifest.in b/deploy_to_fornax_manifest.in index 9fd259b8..2ddde093 100644 --- a/deploy_to_fornax_manifest.in +++ b/deploy_to_fornax_manifest.in @@ -7,6 +7,8 @@ tutorials/euclid/5_Euclid_intro_SPE_catalog.md tutorials/euclid/Euclid_ERO.md tutorials/euclid/euclid-cloud-access.md tutorials/euclid/hats-catalogs/1-euclid-dr1-hats-intro.md +tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md +tutorials/euclid/hats-catalogs/requirements-euclid-dr1-hats.txt tutorials/euclid/hats-catalogs/1-euclid-q1-hats-intro.md tutorials/euclid/hats-catalogs/4-euclid-q1-hats-magnitudes.md tutorials/simulated-data/OpenUniverse2024/openuniverse2024_firefly_visualization.md diff --git a/ignore_tutorials/ignore_circleci_testing b/ignore_tutorials/ignore_circleci_testing index 036d747f..22178406 100644 --- a/ignore_tutorials/ignore_circleci_testing +++ b/ignore_tutorials/ignore_circleci_testing @@ -7,4 +7,5 @@ tutorials/euclid/euclid-cloud-access tutorials/techniques-and-tools/cloud-access-intro tutorials/euclid/euclid_clusters_tutorial.md # There are fsps install issues on circleCI, remove once https://github.com/Caltech-IPAC/irsa-tutorials/issues/315 is resolved -tutorials/simulated-data/OpenUniverse2024/openuniverse2024_SED_fit.md \ No newline at end of file +tutorials/simulated-data/OpenUniverse2024/openuniverse2024_SED_fit.md +tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra \ No newline at end of file diff --git a/ignore_tutorials/ignore_gha_testing b/ignore_tutorials/ignore_gha_testing index 19828652..449c6649 100644 --- a/ignore_tutorials/ignore_gha_testing +++ b/ignore_tutorials/ignore_gha_testing @@ -1,3 +1,4 @@ # Both NEOWISE parquet notebooks work with large data that doesn't work within CircleCI or GHA resource limits tutorials/wise/neowise-source-table-lightcurves tutorials/wise/neowise-source-table-strategies +tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra diff --git a/notebook_metadata.yml b/notebook_metadata.yml index 08449c34..87c501ae 100644 --- a/notebook_metadata.yml +++ b/notebook_metadata.yml @@ -38,6 +38,10 @@ file: tutorials/euclid/hats-catalogs/1-euclid-dr1-hats-intro.md section: Euclid description: Learn which Euclid DR1 catalogs are available in HATS format and how they are organized, then perform a basic query and a cone search. +- title: 'DR1 HATS Catalogs: Bulk Access to 1D Spectra' + file: tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md + section: Euclid + description: Get the spectra of thousands of Euclid DR1 objects in one query, from a region of the sky, a list of positions or object IDs, or properties in other DR1 catalogs; compare the time with spectrumDM, and stack the spectra to reveal faint emission lines. - title: 'Merged Objects Catalog: Introduction' file: tutorials/euclid/hats-catalogs/1-euclid-q1-hats-intro.md section: Euclid diff --git a/toc.yml b/toc.yml index ddedd113..8a0bac96 100644 --- a/toc.yml +++ b/toc.yml @@ -37,6 +37,8 @@ project: children: - title: DR1 Introduction file: tutorials/euclid/hats-catalogs/1-euclid-dr1-hats-intro.md + - title: DR1 Bulk Spectra + file: tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md - title: Q1 Introduction file: tutorials/euclid/hats-catalogs/1-euclid-q1-hats-intro.md - title: Q1 Magnitudes diff --git a/tutorials/euclid/euclid.md b/tutorials/euclid/euclid.md index cda1168b..1501364d 100644 --- a/tutorials/euclid/euclid.md +++ b/tutorials/euclid/euclid.md @@ -23,6 +23,7 @@ tutorials/euclid/2_Euclid_intro_MER_catalog.md tutorials/euclid/4_Euclid_intro_PHZ_catalog.md tutorials/euclid/5_Euclid_intro_SPE_catalog.md tutorials/euclid/hats-catalogs/1-euclid-dr1-hats-intro.md +tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md tutorials/euclid/hats-catalogs/1-euclid-q1-hats-intro.md tutorials/euclid/hats-catalogs/4-euclid-q1-hats-magnitudes.md tutorials/euclid/euclid-cloud-access.md diff --git a/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md b/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md new file mode 100644 index 00000000..31f5098a --- /dev/null +++ b/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md @@ -0,0 +1,799 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.18.1 +kernelspec: + display_name: euclid-dr1-hats + language: python + name: python3 +authors: + - name: Deeksha Mohanty, Troy Raen, Jessica Krick, Vandana Desai +--- + +# Euclid DR1 HATS Catalogs: Bulk Access to 1D Spectra + ++++ + +This tutorial shows how to get the spectra of thousands of Euclid DR1 objects at once from the HATS catalog of combined 1D spectra, and how long this takes. + ++++ + +## Learning Goals + +In this tutorial, we will: + +- Compare the time to get many spectra from the HATS catalog with the time to get them from IRSA's spectrumDM service, one request per spectrum, and see when each is faster. +- Get the spectra of all objects in a region of the sky, and save them to disk. +- Get the spectra of a list of objects, from their positions or from their Euclid object IDs. +- Get the spectra of objects selected by their properties in other DR1 catalogs, such as redshift and emission-line flux. +- Stack thousands of spectra to reveal faint emission lines. +- See how long each of these queries takes, and estimate how long larger ones would take. + ++++ + +## 1. Introduction + +Euclid Data Release 1 (DR1) provides more than 170 million validated 1D spectra from the Near-Infrared Spectrometer and Photometer (NISP), taken with its red grism and its blue grism ([Euclid Collaboration: Fumana et al. 2026](https://arxiv.org/abs/2611.17305)). +Many science cases need the spectra of a large number of objects at once, for example to stack them, to train machine-learning models, or to study a published list of objects. + +Getting many spectra from the original data products is difficult: +the spectra are packed into FITS (Flexible Image Transport System) files with one spectrum per extension and many spectra per file. +IRSA's spectrumDM service, used in the [Euclid DR1 SIR 1D spectra tutorial](../3_Euclid_intro_1D_spectra.md), reads one spectrum from these files per request, so getting many spectra means making many requests. + +IRSA provides the Euclid DR1 combined 1D spectra as a HATS catalog, `sir_combined_spectra`, with one spectrum per row. +[HATS](https://hats.readthedocs.io/) (Hierarchical Adaptive Tiling Scheme) is a format that splits a catalog into Parquet files by position on the sky. +The Euclid DR1 HATS catalogs are stored in the cloud, on Amazon Web Services (AWS) S3, and can be read in parallel with the Python library [LSDB](https://docs.lsdb.io/) (Large Survey DataBase). +Getting many spectra is therefore a catalog query, and the spectra can be joined to the other DR1 catalogs on `object_id`. +LSDB reads the files directly from AWS S3, so there is no limit on the number of spectra that a query can return; the limits are the time to read the files, and the memory and disk space for the result. +For an introduction to the catalogs and the `spectrum` column, see the [Euclid DR1 HATS Catalogs introduction](1-euclid-dr1-hats-intro.md). +All the Euclid data in this notebook come from IRSA, the NASA archive for Euclid. + +How we select the spectra depends on what we start from. +This notebook covers four starting points: + +| Case | Starting point | Example | Section | +|---|---|---|---| +| 1 | A region of the sky | All spectra around the planetary nebula NGC 6543 | 5 | +| 2 | A list of positions | The strong lens candidates of Euclid Collaboration: Lines et al. (2026) | 6 | +| 3 | A list of object IDs | The same lens candidates, by their Euclid object ID | 7 | +| 4 | Properties of the objects, from other DR1 catalogs | Galaxies with a bright H$\alpha$ line, selected like the sample of Euclid Collaboration: Le Brun et al. (2026) | 8 | + +Section 4 compares the HATS catalog with spectrumDM on the same spectra, and Section 10 compares their times for every case. +In Section 9, we use the spectra from Section 8 to make a stacked spectrum like Figure 4 of Euclid Collaboration: Le Brun et al. (2026). + ++++ + +### 1.1 Duplicate object IDs + +As described in Section 1.1 of the introduction tutorial, an object can have more than one spectrum in `sir_combined_spectra`: for example, a red grism spectrum (`lrange` = `RGS`) and a blue grism spectrum (`BGS`). +Every query in this notebook returns all the spectra of each object it selects, one spectrum per row. + ++++ + +### 1.2 Runtime + +This notebook takes about 15 minutes to run on Fornax, using Server Type: 'Large' (64 GB RAM, 16 CPUs) and the `euclid-dr1-hats` environment (Section 2). +The text above each slow cell gives roughly how long it takes. +On a server with less memory, the Dask workers can run out of memory. + +Most of the time goes into reading the files of the spectra catalog. +Each file holds tens of thousands of spectra and is read whole, so the time depends mostly on how many files a query reads, rather than on how many spectra it returns. + +This notebook saves a catalog of spectra to local disk (about 0.1 GB, in Section 5). + ++++ + +## 2. Imports + ++++ + +This notebook needs the libraries listed in `requirements-euclid-dr1-hats.txt`, in the same directory as this notebook. +On Fornax, create an environment with them. +Open a separate terminal, `cd` into this directory, and run the following: + +``` +setup-pip-env --user +``` + +You should see this at the bottom of the output: + +``` +Found 1 files: + requirements-euclid-dr1-hats.txt +Continue? [y/N] +``` + +Press "y" to continue. +That will create a new environment called `euclid-dr1-hats`, store the necessary files in `$USER_ENV_DIR` (which is in your home directory), and create an associated Jupyter kernel. +Those will persist across sessions, so you should only have to do that once. + +It may take a minute or so after `setup-pip-env` finishes before the kernel is available. +Once it's ready, connect this notebook to the `euclid-dr1-hats` kernel. + +Elsewhere, you can install the libraries with the commented line below. + +```{code-cell} ipython3 +# Uncomment the next line to install dependencies if needed. +# %pip install -r requirements-euclid-dr1-hats.txt +``` + +```{code-cell} ipython3 +import contextlib # Hide the list of IDs that id_search prints +import io # Read the lens catalog from Zenodo +import logging +import os # Number of CPUs for the Dask workers +import time # Time the spectrumDM requests +import urllib.request # Download the lens catalog from Zenodo +import warnings +import zipfile # Read the lens catalog from Zenodo +from concurrent.futures import ThreadPoolExecutor # Send spectrumDM requests in parallel +from pathlib import Path # Size of the saved catalogs + +import lsdb # Query HATS catalogs +import matplotlib.pyplot as plt # Plot spectra +import numpy as np # Stack spectra +import pandas as pd # Read the lens catalog +from astropy.table import QTable # Read spectra from spectrumDM +from astropy.units import UnitsWarning +from astropy.utils.data import conf # Timeout of the spectrumDM requests +from astroquery.ipac.irsa import Irsa # Find the spectrum files with TAP +from dask.distributed import Client # Run LSDB queries in parallel +from distributed.system import MEMORY_LIMIT # Memory available to the Dask workers +from IPython.display import HTML, display +``` + +## 3. Catalog Paths and Helper Functions + ++++ + +Each Euclid DR1 HATS catalog is stored in its own collection on AWS S3. +The function below returns the path of a collection, and we open the spectra catalog with only the columns we need. + +```{code-cell} ipython3 +s3_bucket = "nasa-irsa-euclid-dr1" +collections_prefix = "contributed/dr1/hats/reformatted_catalogs" + + +def collection_uri(catalog): + """S3 URI of the HATS collection for a Euclid DR1 catalog.""" + return f"s3://{s3_bucket}/{collections_prefix}/{catalog}" + + +spectra_catalog = lsdb.open_catalog( + collection_uri("sir_combined_spectra"), columns=["object_id", "lrange", "spectrum"] +) +``` + +The helper functions below: + +- Join two catalogs on `object_id` (Section 8). + Both catalogs have the columns `object_id`, `ra_from_object_id`, and `dec_from_object_id`, and LSDB needs the two copies to have different names, so we add a suffix, such as `_quality`, to those of the second catalog. +- Keep one row per object, for a join that returns the same object more than once (Section 8.3). +- Load a query result into memory, or save it to disk as a HATS catalog, with a Dask client that runs the work on up to 4 workers, which share the memory of the machine. The client prints a link to the Dask dashboard, where you can follow the progress. +- Find the usable wavelength bins of a spectrum: as in the [Euclid DR1 SIR 1D spectra tutorial](../3_Euclid_intro_1D_spectra.md), a bin is unusable if its `mask` value is odd (flag `NOT_USE`: invalid flux) or 64 or more (flag `ABS_FLUX`: suspicious flux calibration). +- Report the size of a saved catalog on disk. +- Time spectrumDM requests, and estimate how long spectrumDM would take for a number of spectra (Section 4). + +Click on the cell to expand it. + +```{code-cell} ipython3 +--- +jupyter: + source_hidden: true +tags: [hide-cell] +--- +# Hide the harmless error that the Dask dashboard prints when it closes while open in a browser. +logging.getLogger("tornado.application").setLevel(logging.CRITICAL) + + +def join_on_object_id(left, right, suffix): + """Join two catalogs on object_id, adding `suffix` to overlapping right-catalog columns.""" + # LSDB joins the catalogs partition by partition, keeping the rows with the same object_id. + # With suffix_method="overlapping_columns", only the columns that are in both catalogs get a suffix. + return left.join( + right, + left_on="object_id", + right_on="object_id", + suffixes=("", suffix), + suffix_method="overlapping_columns", + ) + + +def one_row_per_object(catalog): + """Keep the first row of each object_id. All rows of an object_id are in the same partition.""" + # Run drop_duplicates on each partition separately; no partition needs data from another. + return catalog.map_partitions(lambda partition: partition.drop_duplicates("object_id")) + + +def dask_client(catalog, max_workers=4): + """A Dask client with up to 4 single-threaded workers, sharing the memory equally.""" + # No more workers than CPUs, or than partitions to work on. + n_workers = min(max_workers, os.cpu_count(), catalog.npartitions + 1) + # Split all the available memory between the workers. With memory_limit="auto", each worker + # would only get the share of the memory that matches its share of the CPUs. + memory_limit = MEMORY_LIMIT // n_workers + client = Client(n_workers=n_workers, threads_per_worker=1, memory_limit=memory_limit) + # On Fornax the link is relative to the Fornax address; as an HTML link, the browser completes it. + link = f'Dask dashboard' + display(HTML(f"Monitor progress in the {link}.")) + return client + + +def load(catalog): + """Load a catalog query into memory.""" + # The client is closed at the end of the `with` block, which frees the workers' memory. + with dask_client(catalog): + return catalog.compute() + + +def save(catalog, path): + """Save a catalog query to a local HATS catalog.""" + # Each worker writes the partitions it computes, so the result never has to fit in memory at once. + # as_collection=False: save only the spectra, without the margin cache, which only cross matches use. + with dask_client(catalog): + catalog.write_catalog(path, as_collection=False, overwrite=True) + + +def good_bins(spectrum): + """True for usable bins: flags NOT_USE (odd mask) and ABS_FLUX (mask >= 64) not set.""" + return (spectrum["mask"] % 2 == 0) & (spectrum["mask"] < 64) + + +def disk_size_gb(path): + """Total size of the files in a directory, in GB.""" + return sum(file.stat().st_size for file in Path(path).rglob("*") if file.is_file()) / 1e9 + + +SPECTRUMDM_URL = "https://irsacloud.ipac.caltech.edu/api/spectrumdm/convert/" + + +def spectrumdm_seconds(files, n_parallel): + """Average seconds per spectrum to read `files` (columns path, hdu) with spectrumDM, n_parallel requests at a time.""" + urls = [f"{SPECTRUMDM_URL}{path}?dataset_id=euclid_combspec_dr1&hdu={hdu}" for path, hdu in zip(files["path"], files["hdu"])] + start = time.perf_counter() + # The files use deprecated unit names, and a request can take longer than astropy's default timeout. + with warnings.catch_warnings(), conf.set_temp("remote_timeout", 120), ThreadPoolExecutor(n_parallel) as pool: + warnings.simplefilter("ignore", UnitsWarning) + list(pool.map(QTable.read, urls)) + return (time.perf_counter() - start) / len(urls) + + +def duration(seconds): + """A duration as text, in seconds, minutes, hours, or days.""" + for unit, size in (("days", 86400), ("hours", 3600), ("minutes", 60)): + if seconds >= size: + return f"{seconds / size:.1f} {unit}" + return f"{seconds:.0f} seconds" + + +def spectrumdm_estimate(n_spectra): + """Print how long spectrumDM would take for n_spectra spectra, from the times per spectrum measured in Section 4.""" + print(f"spectrumDM, {n_spectra:,} spectra: about {duration(n_spectra * seconds_one)} one request at a time, or {duration(n_spectra * seconds_parallel)} with 16 requests at a time") +``` + +## 4. HATS Compared with spectrumDM + ++++ + +How much faster is it to get many spectra from the HATS catalog than from spectrumDM? +The two work differently: spectrumDM returns one spectrum per request, while LSDB reads a whole file of the HATS catalog, with tens of thousands of spectra, at once. +So we compare them on the same spectra. + +First, LSDB loads all the spectra of one file of the catalog. + +```{code-cell} ipython3 +pixel = spectra_catalog.get_healpix_pixels()[1000] # One file of the catalog +start = time.perf_counter() +file_ids = load(spectra_catalog.pixel_search(pixel))["object_id"] # Keep only the IDs, to free the memory +lsdb_seconds = time.perf_counter() - start +``` + +Then spectrumDM gets 90 of the same spectra, the way the [Euclid DR1 SIR 1D spectra tutorial](../3_Euclid_intro_1D_spectra.md) does: we find the file and HDU of each spectrum in IRSA's association table with TAP, and read each spectrum with one request. +We read 10 spectra one request at a time and 80 with 16 requests at a time, and scale the times to the whole file. + +```{code-cell} ipython3 +ids = ", ".join(str(object_id) for object_id in file_ids.unique()[:90]) +query = f"SELECT path, hdu FROM euclid.objectid_spectrafile_association_dr1 WHERE objectid IN ({ids})" +spectrum_files = Irsa.query_tap(query).to_table()[:90] +seconds_one = spectrumdm_seconds(spectrum_files[:10], n_parallel=1) +seconds_parallel = spectrumdm_seconds(spectrum_files[10:], n_parallel=16) + +print(f"LSDB, {len(file_ids):,} spectra: {duration(lsdb_seconds)}") +spectrumdm_estimate(len(file_ids)) +``` + +When we ran this notebook, LSDB loaded the 111,262 spectra of this file in about 30 seconds; with spectrumDM, they would take about 11 hours one request at a time, or about 1 hour with 16 requests at a time. +In an earlier test with other spectra, spectrumDM took about 4 times longer per spectrum, so its times vary. +So LSDB is much faster when we want many spectra from each file it reads. +For a few hundred spectra spread over many files, as in Cases 2 and 3, spectrumDM with parallel requests can be faster (Section 10). + +## 5. Case 1: Spectra in a Region of the Sky + ++++ + +When we start from a position on the sky and want the spectra of all the objects around it, we use a cone search. +Here we take every spectrum within 0.1 degrees of the planetary nebula NGC 6543, in the Euclid Deep Field North (EDF-N), and save them to disk. + +```{code-cell} ipython3 +ngc6543_ra, ngc6543_dec = 269.6394799, 66.6329765 # degrees +region_spectra = spectra_catalog.cone_search( + ra=ngc6543_ra, dec=ngc6543_dec, radius_arcsec=0.1 * 3600 +) +``` + +This cell takes about 1 minute to run. + +```{code-cell} ipython3 +%%time +save(region_spectra, "euclid_dr1_ngc6543_spectra") +``` + +The saved catalog is a HATS catalog like the ones on AWS S3, so we open it with `lsdb.open_catalog`. +Each row is one spectrum, and the `spectrum` column holds the spectrum itself as a nested table (see the introduction tutorial). + +```{code-cell} ipython3 +saved_region = lsdb.open_catalog("euclid_dr1_ngc6543_spectra") +saved_region.head() +``` + +We count the spectra, reading only the `object_id` column. + +```{code-cell} ipython3 +saved_region_ids = lsdb.open_catalog("euclid_dr1_ngc6543_spectra", columns=["object_id"]) +region_ids = saved_region_ids.compute()["object_id"] +print(f"{len(region_ids):,} spectra, {disk_size_gb('euclid_dr1_ngc6543_spectra'):.1f} GB on disk") +``` + +The region contains 32,890 spectra, which take 0.1 GB on disk. +Our `save` helper writes only the spectra; to cross match a saved catalog with another catalog later, call `write_catalog` with `as_collection=True` (its default), which also writes the margin cache that cross matches use: a copy of the spectra just outside each file's area of the sky. + +This query is fast because the spectra of a small region are in only a few files of the catalog (2 here), so LSDB keeps many spectra from each file it reads. + +The same code works for a larger radius; the time grows with the number of files that the cone covers, which LSDB knows before reading any data: + +```{code-cell} ipython3 +for radius_deg in (0.1, 1, 3): + cone = spectra_catalog.cone_search(ra=ngc6543_ra, dec=ngc6543_dec, radius_arcsec=radius_deg * 3600) + print(f"Radius of {radius_deg} degrees: {cone.npartitions} files") +``` + +Multiplying the number of files by the time per file that we measured (about 3.5 to 5.5 seconds, Section 10.1) gives a rough estimate: for example, about 25 to 40 minutes for a radius of 3 degrees (414 files). +For a large region, use `save` as above rather than `load`: the workers write the spectra to disk file by file, so the result never has to fit in memory. + ++++ + +## 6. Case 2: Spectra for a List of Positions + ++++ + +When we start from a list of positions, for example a published catalog of objects, we cross match the list with the spectra catalog. + +Our example is the catalog of strong gravitational lens candidates in Euclid DR1 of [Euclid Collaboration: Lines et al. (2026)](https://arxiv.org/abs/2611.15883): massive galaxies whose gravity bends the light of a more distant galaxy into arcs or multiple images, typically within about 1 arcsecond (the paper gives a typical Einstein radius of 0.85 arcseconds). +Experts graded each candidate A (sure lens), B (probable lens), C (possible lens), or X (not a lens). +We download the catalog from Zenodo (about 4 MB) and keep the grade A and B candidates. + +```{code-cell} ipython3 +lens_url = "https://zenodo.org/api/records/19654904/files/ECLIPSE_object_catalogue.zip/content" +with urllib.request.urlopen(lens_url) as response: + with zipfile.ZipFile(io.BytesIO(response.read())) as lens_zip: + # Read MER_object_id as integers that can be missing ("Int64"); as floating-point numbers, + # the 19-digit IDs would lose their last digits. + lenses = pd.read_csv( + lens_zip.open("ECLIPSE_object_catalogue/ECLIPSE_object_catalogue.csv"), + dtype={"MER_object_id": "Int64"}, + ) + +lenses = lenses[lenses["Expert_Grade"].isin(["A", "B"])] +print(f"{len(lenses):,} grade A and B lens candidates") +lenses[["Unique_Identifier", "RA_obj", "DEC_obj", "Expert_Grade", "MER_object_id"]].head() +``` + +The 15,072 candidates are spread over the whole DR1 area, so a cross match with all of them would read many more files of the spectra catalog. +To keep this notebook short, we use only the candidates within 3 degrees of one position in the Wide Survey; the same code can be used for the whole list, and Section 10.1 discusses much longer lists. + +We cross match the positions of the lens galaxies with `sir_combined_spectra` within 2 arcseconds, larger than the Einstein radius of most lenses, and allow up to 10 spectra per lens. +So the match can also return the spectra of lensed images, where they were detected as separate objects in the MER catalog. + +```{code-cell} ipython3 +lens_positions = lsdb.from_dataframe( + lenses[["Unique_Identifier", "RA_obj", "DEC_obj", "Expert_Grade", "MER_object_id"]], + ra_column="RA_obj", + dec_column="DEC_obj", +) +lens_region = lens_positions.cone_search(ra=40.37, dec=-59.83, radius_arcsec=3 * 3600) +lens_region_table = lens_region.compute() # The positions only; this does not read the spectra. +lens_spectra = lens_region.crossmatch( + spectra_catalog, + radius_arcsec=2, + n_neighbors=10, + suffixes=("_lens", ""), + suffix_method="overlapping_columns", +) +``` + +This cell takes about 3 minutes to run. + +```{code-cell} ipython3 +%%time +lens_spectra_table = load(lens_spectra) +n_lenses_found = lens_spectra_table["Unique_Identifier"].nunique() +print( + f"{len(lens_spectra_table):,} spectra within 2 arcsec of" + f" {n_lenses_found:,} of the {len(lens_region_table):,} lens candidates in the region" +) +``` + +We find 317 spectra within 2 arcseconds of 275 of the 276 lens candidates in the region. +Each row is one spectrum, with the lens candidate it was matched to (`Unique_Identifier`) and its distance from the candidate's position, in arcseconds (`_dist_arcsec`). + +```{code-cell} ipython3 +lens_spectra_table[["Unique_Identifier", "object_id", "lrange", "_dist_arcsec", "spectrum"]].head() +``` + +In Section 7.1, we look at the spectrum of one of these lens candidates that was studied in detail in a Euclid DR1 paper. + ++++ + +## 7. Case 3: Spectra for a List of Object IDs + ++++ + +When we start from a list of Euclid object IDs, we can look them up directly with `id_search`, without a cross match. +Each catalog collection comes with an index table on `object_id` (see Section 3.5 of the introduction tutorial), which records which file of the catalog holds each `object_id`, so `id_search` reads only those files. + +The lens catalog of Section 6 also gives the Euclid MER `object_id` of most candidates (column `MER_object_id`; according to the catalog's README, it is missing where the lens position was refined after the inspection). + +We look up the candidates in the same region as in Section 6. + +```{code-cell} ipython3 +lens_object_ids = lens_region_table["MER_object_id"].dropna().astype("int64").to_list() +print(f"{len(lens_object_ids):,} lens candidates in the region with a MER object_id") +``` + +This cell takes about 4 minutes to run. +`id_search` prints the list of IDs it searches for, which we hide. +LSDB also prints a warning about the estimated size of the files it reads; the result itself is small. + +```{code-cell} ipython3 +%%time +with contextlib.redirect_stdout(io.StringIO()): + lens_id_search = spectra_catalog.id_search(values={"object_id": lens_object_ids}) +id_spectra_table = load(lens_id_search) +n_ids_found = id_spectra_table["object_id"].nunique() +print(f"{len(id_spectra_table):,} spectra of {n_ids_found:,} of the {len(lens_object_ids):,} lens candidates") +print(f"LSDB read {lens_id_search.npartitions} files of the spectra catalog") +``` + +Of the 260 lens candidates with a MER `object_id`, 259 have a spectrum, one each. + +```{code-cell} ipython3 +id_spectra_table[["object_id", "lrange", "spectrum"]].head() +``` + +Sections 6 and 7 find the spectra of the same lens candidates in two ways. +The cross match finds them by position, so it also returns the spectra of neighbors; `id_search` returns only the spectra of the objects with the given IDs. +`id_search` is not faster here than the cross match, because it also reads whole files (39 here, to keep 259 spectra), after looking up the IDs in the index table. + +### 7.1 A known lens: PS1J1821+7130 + +[Euclid Collaboration: Bergamini et al. (2026)](https://arxiv.org/abs/2611.15891) studied four strong lenses in detail with the Euclid NISP spectra. +One of them, PS1J1821+7130 (their Sect. 2.4), is a galaxy at redshift 0.235 surrounded by an Einstein ring: the image of a more distant galaxy, stretched into a ring by the lens. +In the Euclid spectra, they detect the H$\alpha$ emission line of the ring at an observed wavelength of about 15,531 Å, which gives the ring a redshift of 1.366 (their Table 1 and Figure 4). + +This lens is also in the lens catalog of Section 6, as `EUCL-DR1-L015763`, with its Euclid `object_id`. + +```{code-cell} ipython3 +known_lens = lenses[lenses["Unique_Identifier"] == "EUCL-DR1-L015763"] +known_lens[["Unique_Identifier", "RA_obj", "DEC_obj", "Expert_Grade", "MER_object_id", "desi_deflector_specz"]] +``` + +The column `desi_deflector_specz` is the redshift of the lens galaxy measured by the DESI survey, 0.235, the same as in Bergamini et al. (2026). +We look up the spectra of the lens galaxy by its `object_id`. + +```{code-cell} ipython3 +known_lens_id = int(known_lens["MER_object_id"].iloc[0]) +with contextlib.redirect_stdout(io.StringIO()): # Hide the ID that id_search prints + known_lens_spectra = spectra_catalog.id_search(values={"object_id": [known_lens_id]}) +known_lens_spectra = known_lens_spectra.compute() +known_lens_spectra[["object_id", "lrange"]] +``` + +We plot the spectra, with the flux multiplied by the scale factor $10^{-16}$ (FITS keyword `FSCALE`), which the catalog's unit metadata omits, and mark the wavelength at which Bergamini et al. (2026) detect the H$\alpha$ line of the ring. + +```{code-cell} ipython3 +FSCALE = 1e-16 +ring_halpha = 15531 # Angstrom, observed wavelength (Bergamini et al. 2026, Figure 4) + +fig, ax = plt.subplots(figsize=(10, 4)) +for _, row in known_lens_spectra.iterrows(): + spectrum = row["spectrum"] + flux = (spectrum["signal"] * FSCALE).where(good_bins(spectrum)) + ax.plot(spectrum["wavelength"], flux, lw=0.7, label=row["lrange"]) +ax.axvline(ring_halpha, color="gray", ls="--", label=r"Ring H$\alpha$ (Bergamini et al. 2026)") +ax.set_xlabel("Wavelength (Angstrom)") +ax.set_ylabel("Flux (erg s$^{-1}$ cm$^{-2}$ Å$^{-1}$)") +ax.set_title("PS1J1821+7130 (EUCL-DR1-L015763)") +ax.legend() +plt.show() +``` + +The lens galaxy has a red grism spectrum only: PS1J1821+7130 is in the Wide Survey area (Bergamini et al. 2026, Sect. 3), where DR1 provides only red grism spectra (Euclid Collaboration: Le Brun et al. 2026, Sect. 2.3). +The gaps in the spectrum are wavelength bins that `good_bins` marks as unusable (odd `mask` value, or 64 or more), which we do not plot. + ++++ + +## 8. Case 4: Spectra of Objects Selected by Their Properties + ++++ + +When we don't start with positions or object IDs, but only know what kind of objects we want, we filter the DR1 catalogs on their columns and then join the objects that pass to their spectra. + +As an example, we select galaxies with good spectra and a bright H$\alpha$ line in EDF-N, with the criteria of the high-quality sample of [Euclid Collaboration: Le Brun et al. (2026)](https://arxiv.org/abs/2611.17960), Sect. 4.3. +EDF-N has the most complete spectral coverage of the three Euclid Deep Fields (Sects. 1 and 4.3 of the paper). + +### 8.1 The selection criteria + +Each criterion is a filter on a column of one of the DR1 catalogs: the MER catalog of objects, and the SPE catalogs of redshifts and emission lines. +The two criteria marked "this notebook" are not stated in Sect. 4.3 of the paper; they are how we implement its selection. + +| Catalog | Criterion | Reason | +|---|---|---| +| `spectro_z_spe_quality_deep` | `spe_n_dith_med >= 15`, `spe_npix >= 800` | Complete spectra, built from enough visits | +| `mer_catalogue_deep_survey` | `point_like_prob < 0.05`, `spurious_prob < 0.5`, `kron_radius < 50` | Exclude point-like objects (mainly stars), objects that may not be real, and large objects (`kron_radius` in pixels), which are unlikely to be at redshift above 0.85 | +| `spectro_z_spe_galaxy_candidates_deep` | `spe_rank == 0` (this notebook) | The best redshift solution for each galaxy, as in the paper's example query (Appendix C) | +| | `0.85 <= spe_z <= 1.85` | The H$\alpha$ line falls in the red grism spectrum | +| | `spe_z_prob > 0.94`, `spe_z_rel > 0.05` | Exclude unreliable redshifts | +| `spectro_line_features_spe_line_features_deep` | H$\alpha$ line, `spe_rank == 0` (this notebook) | The H$\alpha$ measurement for the same (best) redshift solution | +| | `spe_line_flux_gf > 1.5e-16` | A bright H$\alpha$ line, above $1.5 \times 10^{-16}$ erg s$^{-1}$ cm$^{-2}$ | +| | `spe_line_snr_gf > 0` | Exclude low-quality flux measurements | +| | Last digit of `spe_line_qual_gf` is 2 or 3 | Measured in the red grism, or in both grisms combined | + +The last digit of the quality flag `spe_line_qual_gf` gives the grism (1: blue, 2: red, 3: both combined; Appendix D of the paper); see the [Euclid DR1 SPE tutorial](../5_Euclid_intro_SPE_catalog.md) for more on this flag. + ++++ + +### 8.2 Open the catalogs with the criteria + +We pass the criteria to `lsdb.open_catalog` as `filters`, a list of `[column, operator, value]` conditions that must all be true, which LSDB applies while it reads the Parquet files. +We also read only the sky within 3 degrees of the center of EDF-N, from Table 1 of the [Euclid archive user guide at IRSA (PDF)](https://irsa.ipac.caltech.edu/data/Euclid/docs/euclid_archive_at_irsa_user_guide.pdf). + +```{code-cell} ipython3 +# EDF-N: center 17h58m55.9s +66d01m03.7s, and a radius of 3 degrees. +edfn_ra, edfn_dec = 269.732917, 66.017694 # degrees +edfn = lsdb.ConeSearch(ra=edfn_ra, dec=edfn_dec, radius_arcsec=3 * 3600) + +# Spectrum quality: many exposures, few missing pixels. +quality = lsdb.open_catalog( + collection_uri("spectro_z_spe_quality_deep"), + columns=["object_id"], + search_filter=edfn, + filters=[["spe_n_dith_med", ">=", 15], ["spe_npix", ">=", 800]], +) + +# Object properties: extended, real, and not very large. +mer = lsdb.open_catalog( + collection_uri("mer_catalogue_deep_survey"), + columns=["object_id"], + search_filter=edfn, + filters=[["point_like_prob", "<", 0.05], ["spurious_prob", "<", 0.5], ["kron_radius", "<", 50]], +) + +# Redshift: the best solution, in the H-alpha range, with high probability and reliability. +galaxies = lsdb.open_catalog( + collection_uri("spectro_z_spe_galaxy_candidates_deep"), + columns=["object_id", "spe_z"], + search_filter=edfn, + filters=[ + ["spe_rank", "==", 0], + ["spe_z", ">=", 0.85], + ["spe_z", "<=", 1.85], + ["spe_z_prob", ">", 0.94], + ["spe_z_rel", ">", 0.05], + ], +) + +# H-alpha line: bright, detected, and measured in the red grism (last flag digit 2) +# or in both grisms combined (last flag digit 3). +red_or_combined_flags = [flag for flag in range(100, 400) if flag % 10 in (2, 3)] +halpha = lsdb.open_catalog( + collection_uri("spectro_line_features_spe_line_features_deep"), + columns=["object_id"], + search_filter=edfn, + filters=[ + ["spe_rank", "==", 0], + ["spe_line_name", "==", "Halpha"], + ["spe_line_flux_gf", ">", 1.5e-16], + ["spe_line_snr_gf", ">", 0], + ["spe_line_qual_gf", "in", red_or_combined_flags], + ], +) +``` + +These cells run quickly, because LSDB does not read any data yet: it only records the queries. + ++++ + +### 8.3 Combine the criteria + +Every Euclid DR1 HATS catalog is partitioned using coordinates calculated from `object_id`, so LSDB can join the catalogs partition by partition. +The lines catalog can have more than one H$\alpha$ row for the same galaxy (for example, red grism alone and both grisms combined), so after joining them we keep one row per galaxy, and then join the galaxies to their spectra. + +```{code-cell} ipython3 +deep_sample = join_on_object_id(galaxies, quality, "_quality") +deep_sample = join_on_object_id(deep_sample, mer, "_mer") +deep_sample = one_row_per_object(join_on_object_id(deep_sample, halpha, "_halpha")) +deep_spectra = join_on_object_id(deep_sample, spectra_catalog, "_spectra") +``` + +For each join, LSDB prints a table of the columns it renamed because they are in both catalogs (`object_id` and the two position columns); this is expected. + +### 8.4 Count the galaxies + +First we load only the sample itself, without the spectra. +This reads only small catalog columns, so it is much faster than loading the spectra: it takes about 1.5 minutes. + +```{code-cell} ipython3 +%%time +deep_sample_table = load(deep_sample) +print(f"{len(deep_sample_table):,} galaxies") +``` + +These galaxies have 159,720 spectra (about two per galaxy: red grism and blue grism), in 440 files of the spectra catalog. +In a test run with 2 Dask workers, saving all of them to disk took about 40 minutes, and they took 0.7 GB. +In Section 9 we therefore load the spectra of only part of the sample. + ++++ + +## 9. Stack Thousands of Spectra + ++++ + +A single spectrum is noisy, so faint emission lines are hidden in the noise. +Averaging many spectra of similar galaxies (stacking) reduces the noise and reveals lines that are hard to see in a single spectrum. + +Like Figure 4 of Euclid Collaboration: Le Brun et al. (2026), we stack the spectra of 4,000 randomly chosen galaxies of the sample. +A stack does not need galaxies from the whole field, so we take them from a small part of EDF-N, whose spectra are in far fewer files of the spectra catalog. + +First we load the spectra of the sample galaxies within 0.6 degrees of the center of EDF-N: 4,399 galaxies, whose spectra are in 33 files (compared with 440 files for the whole sample). +This cell takes about 3 minutes to run. + +```{code-cell} ipython3 +%%time +stack_region = deep_spectra.cone_search(ra=edfn_ra, dec=edfn_dec, radius_arcsec=0.6 * 3600) +stack_region_table = load(stack_region) +print(f"{stack_region_table['object_id'].nunique():,} galaxies in the region") +``` + +Each row is one spectrum, with the redshift `spe_z` of its galaxy. +Then we choose 4,000 of these galaxies at random, and keep their spectra. + +```{code-cell} ipython3 +rng = np.random.default_rng(seed=0) +stack_region_ids = stack_region_table["object_id"].unique() +stack_ids = rng.choice(stack_region_ids, size=min(4000, len(stack_region_ids)), replace=False) +stack_spectra = stack_region_table[stack_region_table["object_id"].isin(stack_ids)] +print(f"{len(stack_spectra):,} spectra of {stack_spectra['object_id'].nunique():,} galaxies") +``` + +We follow the paper's recipe, treating the red and blue grism spectra as separate spectra: we shift each spectrum to the rest frame by dividing its wavelengths by $1 + z$, divide it by its median flux so that bright galaxies do not dominate, resample it onto a common grid with 5 Å pixels, and take the median of all spectra at each wavelength. + +```{code-cell} ipython3 +rest_grid = np.arange(3000, 10500, 5.0) # Angstrom +resampled = np.full((len(stack_spectra), rest_grid.size), np.nan, dtype=np.float32) +for i, (_, row) in enumerate(stack_spectra.iterrows()): + good = good_bins(row["spectrum"]) + wavelength = row["spectrum"]["wavelength"][good].to_numpy() / (1 + row["spe_z"]) + flux = row["spectrum"]["signal"][good].to_numpy() + median = np.median(flux) if flux.size else 0 + if median > 0: # Skip spectra without usable bins, or with a median flux that is not positive + # NaN outside the spectrum's wavelength range, so those bins don't count in the median. + resampled[i] = np.interp(rest_grid, wavelength, flux / median, left=np.nan, right=np.nan) + +# Take the median only at wavelengths covered by at least one spectrum. +n_contributing = np.sum(~np.isnan(resampled), axis=0) +covered = n_contributing > 0 +stack = np.full(rest_grid.size, np.nan) +stack[covered] = np.nanmedian(resampled[:, covered], axis=0) +``` + +As in the paper's figure, the top panel shows how many spectra contribute at each wavelength, and the bottom panel shows the stack, with some of the emission lines that the paper identifies. + +```{code-cell} ipython3 +# Approximate rest-frame vacuum wavelengths, in Angstrom, as labeled in Figure 4 of the paper. +lines = { + "[O II]": 3727, + "[Ne III]": 3870, + r"H$\beta$": 4863, + "[O III]": 5008, + "He I": 5877, + "[O I]": 6302, + r"H$\alpha$+[N II]": 6565, + "[S III]": 9533, +} + +fig, (ax_n, ax_stack) = plt.subplots( + 2, 1, figsize=(12, 7), sharex=True, gridspec_kw={"height_ratios": [1, 3]} +) +ax_n.plot(rest_grid, n_contributing) +ax_n.set_ylabel("Number of spectra") +ax_stack.plot(rest_grid, stack, lw=0.8) +for name, line_wavelength in lines.items(): + ax_stack.axvline(line_wavelength, color="gray", ls=":", lw=0.8) + ax_stack.text( + line_wavelength, 1.01, name, transform=ax_stack.get_xaxis_transform(), + ha="center", va="bottom", fontsize=8, rotation=90, + ) +ax_stack.set_xlabel("Rest-frame wavelength (Angstrom)") +ax_stack.set_ylabel("Normalized flux") +plt.tight_layout() +plt.show() +``` + +H$\alpha$+[N II] is the strongest line, as expected for a sample selected for its bright H$\alpha$ line, and weaker lines such as [Ne III], He I, and [O I], which are hard to see in a single spectrum, are also visible. +Near the edges, few spectra contribute (top panel), so the stack is noisy there. + ++++ + +## 10. Summary + ++++ + +The table below summarizes the queries of this notebook, with their approximate run times with LSDB, and the times that spectrumDM would take for the same spectra, estimated from the times per spectrum that we measured with spectrumDM (in Section 4 and in an earlier test). + +| Case | Starting point | Result | LSDB (4 Dask workers) | spectrumDM: 1 request at a time / 16 at a time | +|---|---|---|---|---| +| 1 | Region of 0.1 degrees in radius (Section 5) | 32,890 spectra, saved to disk (0.1 GB) | about 1 minute | 3 to 13 hours / 20 to 90 minutes | +| 2 | List of 276 positions (Section 6) | 317 spectra | about 3 minutes | 2 to 8 minutes / 10 seconds to 1 minute | +| 3 | List of 260 object IDs (Section 7) | 259 spectra | about 4 minutes | 1.5 to 6 minutes / 10 to 45 seconds | +| 4 | Object properties, Deep Survey (Section 8) | 80,432 galaxies, without their spectra | about 1.5 minutes | | +| | Stack (Section 9) | 8,002 spectra of 4,000 galaxies | about 3 minutes | 45 minutes to 3 hours / 5 to 20 minutes | + +As explained in Section 1.2, the LSDB time depends mostly on how many files of the spectra catalog a query reads, rather than on how many spectra it returns. +For a few hundred spectra spread over many files (Cases 2 and 3), spectrumDM with parallel requests is faster. +The HATS catalog has these advantages: + +- It is faster when a query keeps many spectra from each file it reads: much faster for the spectra of a region of the sky (Case 1), and faster for a sample in one field (the stack). +- It can select objects by their properties in other DR1 catalogs and get their spectra in the same query (Case 4); spectrumDM needs the object IDs first. +- It runs in your own session, and more Dask workers make it faster, as long as each worker has enough memory. + +### 10.1 Larger queries + +We can use the times of this notebook to estimate roughly how long larger queries would take. +When we ran this notebook with its 4 Dask workers, the queries that load spectra (Sections 6, 7, and 9) took about 3.5 to 5.5 seconds for each file of the spectra catalog that they read. +The time per file depends on the server, the number of Dask workers, and what the query does with each file, so these numbers are only a guide. + +A query whose objects are spread over the whole DR1 area, such as a list of a million positions, could need to read every file of the catalog. +For a result this large, use `save` (Section 5) rather than `load`, so that the spectra are written to disk file by file and never have to fit in memory; at the size of Section 5 (0.1 GB for 32,890 spectra), a million spectra would take a few GB on disk. +The number of files is known without reading any data: + +```{code-cell} ipython3 +n_files = spectra_catalog.npartitions +print(f"{n_files:,} files in the spectra catalog") +for seconds_per_file in (3.5, 5.5): + hours = n_files * seconds_per_file / 3600 + print(f"At {seconds_per_file} seconds per file, reading all of them would take about {hours:.0f} hours") +``` + +These are rough estimates from the times of this notebook, not measurements. + ++++ + +## References + +- Euclid Collaboration: Fumana et al. 2026, *Euclid Data Release 1 (DR1): SIR spectroscopic calibration*, [arXiv:2611.17305](https://arxiv.org/abs/2611.17305) +- Euclid Collaboration: Le Brun et al. 2026, *Euclid Data Release 1 (DR1): Performance of the redshift measurement and spectroscopic analysis*, [arXiv:2611.17960](https://arxiv.org/abs/2611.17960) +- Euclid Collaboration: Lines et al. 2026, *Euclid Data Release 1 (DR1). Euclid Lens Identification Pipeline and Scientific Exploration (ECLIPSE) A: Strong lens catalogue overview*, [arXiv:2611.15883](https://arxiv.org/abs/2611.15883); catalog on [Zenodo](https://doi.org/10.5281/zenodo.19654904) +- Euclid Collaboration: Bergamini et al. 2026, *Euclid Data Release 1 (DR1). NISP spectroscopy of gravitational arcs and multiple images*, [arXiv:2611.15891](https://arxiv.org/abs/2611.15891) + +## About this notebook + +**Updated:** 2026-12-03 + +**Contact:** [IRSA Helpdesk](https://irsa.ipac.caltech.edu/docs/help_desk.html) + +**Runtime:** As of the date above, this notebook takes about 15 minutes to run to completion on Fornax using Server Type: 'Large' (64 GB RAM, 16 CPUs) and the `euclid-dr1-hats` environment (Section 2). + +**AI Acknowledgement:** This tutorial was developed with the assistance of AI tools. diff --git a/tutorials/euclid/hats-catalogs/requirements-euclid-dr1-hats.txt b/tutorials/euclid/hats-catalogs/requirements-euclid-dr1-hats.txt new file mode 100644 index 00000000..574da0e5 --- /dev/null +++ b/tutorials/euclid/hats-catalogs/requirements-euclid-dr1-hats.txt @@ -0,0 +1,9 @@ +# Libraries for the Euclid DR1 HATS catalogs notebooks. +astropy +astroquery>=0.4.11 +dask[distributed] +lsdb>=0.8.1 +matplotlib +numpy +pandas +s3fs