From 6ffb2ae7a01a58326f7edb8f21eb3c80cd636aaf Mon Sep 17 00:00:00 2001 From: DeekshaMohanty Date: Mon, 30 Nov 2026 22:19:36 -0500 Subject: [PATCH 01/19] Draft Euclid DR1 bulk spectra notebook --- .../2-euclid-dr1-hats-bulk-spectra.md | 384 ++++++++++++++++++ 1 file changed, 384 insertions(+) create mode 100644 tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.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..770ca46a --- /dev/null +++ b/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md @@ -0,0 +1,384 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.18.1 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +authors: + - name: Deeksha Mohanty +--- + +# Euclid DR1 HATS Catalogs: Bulk Access to 1D Spectra + ++++ + +This tutorial shows how to select a large number of Euclid DR1 objects and load their combined 1D spectra in bulk from the Euclid DR1 HATS catalogs. + ++++ + +## Learning Goals + +In this tutorial, we will: + +- Load the spectra of many objects at once, starting from catalog values, a list of `object_id`s, a list of positions, or a region of the sky. +- Decide whether to load a result into memory or save it to disk. +- Show tens of thousands of spectra at once, and combine them into one stacked spectrum. + ++++ + +## 1. Introduction + +The combined 1D NISP spectra are stored in the HATS catalog `sir_combined_spectra`, with one spectrum per row in the nested column `spectrum`. +Because the spectra are in the catalog itself, loading many spectra is a catalog query: there is no limit on the number of spectra, and no need to download the original FITS files, each of which holds many spectra. + +For an introduction to the catalogs, their paths, and the `spectrum` column, see the [Euclid DR1 HATS Catalogs introduction](1-euclid-dr1-hats-intro.md). + +How we select the spectra depends on what we start from: + +| Case | Starting point | Section | +|---|---|---| +| 1 | Catalog values only, no positions or IDs (e.g., high-quality galaxy spectra) | 4 | +| 2 | A list of `object_id`s | 5 | +| 3 | A list of positions (RA, Dec) | 6 | +| 4 | A region of the sky | 7 | + +`sir_combined_spectra` contains only the spectra and a few identifying columns (`object_id`, `tileid`, `lrange`, `n_dith`). +Values such as redshifts and quality measurements are in the other DR1 catalogs, so Case 1 selects objects in those catalogs and then joins the selection to the spectra on `object_id`. + ++++ + +### 1.1 Duplicate object IDs + +As described in the introduction tutorial, `object_id` alone usually does not identify a unique row. +In `sir_combined_spectra`, an object can have a red grism spectrum (`lrange` = `RGS`), a blue grism spectrum (`BGS`), or both, and can have more than one spectrum with the same `lrange`. +Every method below therefore returns every spectrum of each selected object. + ++++ + +## 2. Imports + +```{code-cell} ipython3 +# # Uncomment the next line to install dependencies if needed. +# %pip install astropy "lsdb>=0.8.1" matplotlib numpy pandas pyarrow s3fs +``` + +```{code-cell} ipython3 +import time # Time the queries + +import lsdb # Query HATS catalogs +import matplotlib.pyplot as plt # Plot spectra +import numpy as np # Stack spectra +import pandas as pd # Stack spectra +``` + +## 3. Catalog Paths + +```{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_columns = ["object_id", "tileid", "lrange", "n_dith", "spectrum"] +spectra_catalog = lsdb.open_catalog(collection_uri("sir_combined_spectra"), columns=spectra_columns) +spectra_catalog +``` + +## 4. Case 1: Select by Catalog Values + ++++ + +Here we start without positions or object IDs and select high-quality galaxy spectra from the Deep Survey, following the sample of [Euclid Collaboration: Le Brun et al. 2026](https://arxiv.org/abs/2611.17960) (Sect. 4.3), who used it to check the Euclid redshifts against the DESI survey and by visual inspection. +Their criteria are spread over three catalogs: + +| Catalog | Criterion | Meaning | +|---|---|---| +| `spectro_z_spe_quality_deep` | `spe_n_dith_med >= 15`, `spe_npix >= 800` | The spectrum is complete and combines many exposures | +| `mer_catalogue_deep_survey` | `point_like_prob < 0.05`, `spurious_prob < 0.5`, `kron_radius < 50` | The object is an extended galaxy (not a star), not very large, and not a spurious detection | +| `spectro_z_spe_galaxy_candidates_deep` | `spe_rank == 0`, `0.85 < spe_z < 1.85`, `spe_z_prob > 0.94`, `spe_z_rel > 0.05` | The best redshift solution, in the range where the H$\alpha$ line is in the red grism, and reliable | + +The paper also requires an H$\alpha$ flux above $1.5 \times 10^{-16}$ erg s$^{-1}$ cm$^{-2}$, from `spectro_line_features_spe_line_features_deep`. +We leave out that criterion, because that catalog is large (about 944 million rows), so our sample is larger than the paper's. + +[TODO] Check whether the paper's sample also requires `spe_class == 'GALAXY'`, and whether the Deep tables cover only the Euclid Deep Field North (the paper's sample). + +```{code-cell} ipython3 +quality = lsdb.open_catalog( + collection_uri("spectro_z_spe_quality_deep"), columns=["object_id", "spe_n_dith_med", "spe_npix"] +).query("spe_n_dith_med >= 15 and spe_npix >= 800") + +mer = lsdb.open_catalog( + collection_uri("mer_catalogue_deep_survey"), columns=["object_id", "point_like_prob", "spurious_prob", "kron_radius"] +).query("point_like_prob < 0.05 and spurious_prob < 0.5 and kron_radius < 50") + +galaxies = lsdb.open_catalog( + collection_uri("spectro_z_spe_galaxy_candidates_deep"), columns=["object_id", "spe_rank", "spe_z", "spe_z_prob", "spe_z_rel"] +).query("spe_rank == 0 and spe_z > 0.85 and spe_z < 1.85 and spe_z_prob > 0.94 and spe_z_rel > 0.05") +``` + +Every Euclid DR1 HATS catalog is partitioned on coordinates calculated from `object_id` (`ra_from_object_id`, `dec_from_object_id`), so the same `object_id` falls in the same HEALPix pixel in every catalog. +We can therefore join the catalogs on `object_id`, and LSDB joins them pixel by pixel. +We keep only the red grism spectra, which contain H$\alpha$ for this redshift range. + +```{code-cell} ipython3 +sample = galaxies.join(quality, left_on="object_id", right_on="object_id", suffixes=("", "_quality")) +sample = sample.join(mer, left_on="object_id", right_on="object_id", suffixes=("", "_mer")) + +red_spectra = spectra_catalog.query("lrange == 'RGS'") +sample_spectra = sample.join(red_spectra, left_on="object_id", right_on="object_id", suffixes=("", "_spectra")) +sample_spectra +``` + +[TODO] Check for duplicate `object_id`s in each catalog before joining (Section 1.1), and count the rows of `sample_spectra`. + ++++ + +## 5. Case 2: A List of Object IDs + ++++ + +When we start from a list of `object_id`s (for example, from a table in a paper), we use `id_search`, which looks up the IDs in the catalog's index table on `object_id`. + +[TODO] Replace this stand-in list (taken from the Case 1 sample) with a realistic example. + +```{code-cell} ipython3 +object_ids = galaxies.head(100)["object_id"].to_list() +id_spectra = spectra_catalog.id_search(values={"object_id": object_ids}) +id_spectra +``` + +## 6. Case 3: A List of Positions + ++++ + +When we start from a list of positions, we load the list into LSDB and cross match it against `sir_combined_spectra`. +The list can contain many positions (for example, a million); LSDB matches it pixel by pixel. +We use a match radius of 0.2 arcseconds, as Euclid Collaboration: Le Brun et al. (2026) did when matching Euclid to DESI (Sect. 4.1). + +[TODO] Replace this stand-in table (positions from the Case 1 sample) with an external list, such as DESI DR1 positions. + +```{code-cell} ipython3 +positions = galaxies.head(100)[["ra_from_object_id", "dec_from_object_id"]].rename( + columns={"ra_from_object_id": "ra", "dec_from_object_id": "dec"} +) +positions_catalog = lsdb.from_dataframe(positions, ra_column="ra", dec_column="dec") +position_spectra = positions_catalog.crossmatch(spectra_catalog, radius_arcsec=0.2, n_neighbors=10, suffixes=("_input", "")) +position_spectra +``` + +## 7. Case 4: A Region of the Sky + ++++ + +For all spectra around a single position, we use a cone search. +Here we use a 30 arcminute radius around NGC 6543, in the Euclid Deep Field North. + +```{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=30 * 60) +region_spectra +``` + +## 8. Load or Save the Results + ++++ + +Every result above is lazy: nothing is read until we ask for it. + +- **Small results** (up to tens of thousands of spectra): load them into memory with `compute()`. +- **Large results**: each spectrum takes a few kilobytes, so a million spectra take several gigabytes. Save them to a local HATS catalog with `to_hats`, which processes one partition at a time, and open it later with `lsdb.open_catalog`. + +[TODO] Measure the size and run time for each case, and replace "a few kilobytes" and "several gigabytes" with the measured values. + +```{code-cell} ipython3 +id_spectra_loaded = id_spectra.compute() +id_spectra_loaded[["object_id", "tileid", "lrange", "n_dith"]] +``` + +```{code-cell} ipython3 +region_spectra.to_hats("euclid_dr1_ngc6543_spectra") +``` + +## 9. What Many Spectra Make Possible + ++++ + +Here we use the Case 1 sample to show what loading tens of thousands of spectra at once makes possible. + ++++ + +### 9.1 How many spectra, and where they come from + ++++ + +In the original Euclid data products, the spectra are packed into FITS files with one spectrum per extension, and each Euclid tile has many such files. +Collecting these spectra from the original files would mean finding which tiles they are in, downloading those files, and reading out each spectrum. +Here we count the spectra and the tiles they come from, loading only small columns. + +```{code-cell} ipython3 +spectra_light = lsdb.open_catalog(collection_uri("sir_combined_spectra"), columns=["object_id", "tileid", "lrange"]) +sample_light = sample.join( + spectra_light.query("lrange == 'RGS'"), left_on="object_id", right_on="object_id", suffixes=("", "_spectra") +).compute() + +print(f"{len(sample_light):,} red grism spectra of {sample_light['object_id'].nunique():,} galaxies, from {sample_light['tileid'].nunique():,} Euclid tiles") +``` + +[TODO] Add the number of original FITS files (about 150 per tile in the COMBSPEC checks) once the count is confirmed for this sample. + ++++ + +### 9.2 A wall of spectra + ++++ + +Redshift stretches every wavelength of a galaxy's light by a factor of $1 + z$. +For example, hydrogen emits the H$\alpha$ line at 6563 Å, which we observe at 13,126 Å for a galaxy at $z = 1$ and at 16,408 Å for a galaxy at $z = 1.5$. +Dividing the observed wavelengths by $1 + z$ returns them to the wavelengths the galaxy emitted (the rest frame). + +Here we load a few thousand spectra, sort them by redshift, and draw each one as a row of an image, first at the observed wavelengths and then in the rest frame. + +```{code-cell} ipython3 +wall = sample_spectra.head(2000).sort_values("spe_z") + +observed_grid = np.arange(12000, 19000, 10.0) # Angstrom +rest_grid = np.arange(4000, 10500, 5.0) # Angstrom + + +def normalized_spectrum(row): + """Observed wavelengths and median-normalized flux of the good bins of one spectrum.""" + spectrum = row["spectrum"] + good = (spectrum["mask"] % 2 == 0) & (spectrum["mask"] < 64) + wavelength = spectrum["wavelength"][good].to_numpy() + flux = spectrum["signal"][good].to_numpy() + if flux.size == 0 or np.median(flux) <= 0: + return None, None + return wavelength, flux / np.median(flux) + + +def resample(wavelength, flux, grid): + """Flux on a wavelength grid, NaN outside the spectrum's range.""" + return np.interp(grid, wavelength, flux, left=np.nan, right=np.nan) + + +observed_image, rest_image, wall_z = [], [], [] +for _, row in wall.iterrows(): + wavelength, flux = normalized_spectrum(row) + if wavelength is None: + continue + observed_image.append(resample(wavelength, flux, observed_grid)) + rest_image.append(resample(wavelength / (1 + row["spe_z"]), flux, rest_grid)) + wall_z.append(row["spe_z"]) +``` + +```{code-cell} ipython3 +fig, axes = plt.subplots(1, 2, figsize=(12, 6)) +for ax, image, grid, title in [ + (axes[0], observed_image, observed_grid, "Observed wavelength"), + (axes[1], rest_image, rest_grid, "Rest-frame wavelength"), +]: + ax.imshow( + np.array(image), aspect="auto", origin="lower", vmin=0, vmax=3, cmap="gray_r", + extent=[grid[0], grid[-1], 0, len(image)], + ) + ax.set_xlabel(f"{title} (Angstrom)") + ax.set_title(title) +axes[0].set_ylabel(f"Spectra sorted by redshift ({wall_z[0]:.2f} to {wall_z[-1]:.2f})") +plt.show() +``` + +At the observed wavelengths (left), H$\alpha$ is a bright streak that moves to longer wavelengths as the redshift increases. +In the rest frame (right), it lines up at 6563 Å in every spectrum, so the spectra can be averaged. + ++++ + +### 9.3 Stacking: one spectrum versus the whole sample + ++++ + +A single spectrum is noisy, so faint emission lines are hidden in the noise. +Averaging many rest-frame spectra (stacking) reduces the noise and reveals lines that no single spectrum shows ([Dobos et al. 2012](https://arxiv.org/abs/1111.1215); [Euclid Collaboration 2025](https://arxiv.org/abs/2509.16120)). + +We stack every red grism spectrum of the sample: each spectrum is divided by its median flux (so that bright galaxies do not dominate), shifted to the rest frame, resampled onto a common grid, and averaged. +LSDB runs this on one partition at a time with `map_partitions`, so the spectra are never all in memory at once. + +```{code-cell} ipython3 +def stack_partition(partition): + """Sum of normalized rest-frame spectra in one partition, and the number of spectra at each wavelength.""" + flux_sum = np.zeros(rest_grid.size) + n_spectra = np.zeros(rest_grid.size) + for _, row in partition.iterrows(): + wavelength, flux = normalized_spectrum(row) + if wavelength is None: + continue + rest_flux = resample(wavelength / (1 + row["spe_z"]), flux, rest_grid) + covered = ~np.isnan(rest_flux) + flux_sum[covered] += rest_flux[covered] + n_spectra[covered] += 1 + return pd.DataFrame({"wavelength": rest_grid, "flux_sum": flux_sum, "n_spectra": n_spectra}) + + +meta = pd.DataFrame({"wavelength": pd.Series(dtype=float), "flux_sum": pd.Series(dtype=float), "n_spectra": pd.Series(dtype=float)}) +start = time.perf_counter() +stack = sample_spectra.map_partitions(stack_partition, meta=meta).compute().groupby("wavelength").sum() +print(f"Stacked {len(sample_light):,} spectra in {(time.perf_counter() - start) / 60:.1f} minutes") +``` + +We mark some of the emission lines in this wavelength range (vacuum rest wavelengths). +Not every spectrum covers every line: H$\beta$ and [O III] are in the red grism only for the higher-redshift part of the sample. + +```{code-cell} ipython3 +lines = { + r"H$\beta$": 4862.7, + "[O III]": 5008.2, + r"H$\alpha$": 6564.6, + "[N II]": 6585.3, + "[S II]": 6718.3, + "[S III]": 9533.2, +} + +single = wall.iloc[len(wall) // 2] +wavelength, flux = normalized_spectrum(single) + +fig, axes = plt.subplots(2, 1, figsize=(12, 7), sharex=True) +axes[0].plot(wavelength / (1 + single["spe_z"]), flux, lw=0.7) +axes[0].set_title(f"One galaxy (z = {single['spe_z']:.2f})") +axes[1].plot(stack.index, stack["flux_sum"] / stack["n_spectra"], lw=0.7) +axes[1].set_title(f"Stack of the whole sample (up to {int(stack['n_spectra'].max()):,} spectra at each wavelength)") +for ax in axes: + for name, line_wavelength in lines.items(): + ax.axvline(line_wavelength, color="gray", ls=":", lw=0.8) + ax.text(line_wavelength, 1.02, name, transform=ax.get_xaxis_transform(), ha="center", fontsize=8) + ax.set_ylabel("Normalized flux") +axes[1].set_xlabel("Rest-frame wavelength (Angstrom)") +axes[1].set_xlim(rest_grid[0], rest_grid[-1]) +plt.tight_layout() +plt.show() +``` + +[TODO] Check which lines are visible in the stack but not in the single spectrum, and set the y-axis limits. + +[TODO] Optional: stack two groups (for example, bright and faint galaxies) and compare them, as in Dobos et al. (2012). + ++++ + +## References + +- Dobos et al. 2012, *A High Resolution Atlas of Composite SDSS Galaxy Spectra*, [arXiv:1111.1215](https://arxiv.org/abs/1111.1215) +- 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 2025, *Euclid preparation. Predicting star-forming galaxy scaling relations with the spectral stacking code SpectraPyle*, [arXiv:2509.16120](https://arxiv.org/abs/2509.16120) + +## About this notebook + +**Updated:** 2026-11-30 + +**Contact:** [IRSA Helpdesk](https://irsa.ipac.caltech.edu/docs/help_desk.html) From 325fb3b16fdea01071a47095d5785353d39395b2 Mon Sep 17 00:00:00 2001 From: DeekshaMohanty Date: Tue, 1 Dec 2026 13:56:09 -0500 Subject: [PATCH 02/19] Update Euclid DR1 bulk spectra notebook --- ignore_tutorials/ignore_circleci_testing | 4 +- ignore_tutorials/ignore_gha_testing | 2 + .../2-euclid-dr1-hats-bulk-spectra.md | 646 ++++++++++++------ 3 files changed, 453 insertions(+), 199 deletions(-) diff --git a/ignore_tutorials/ignore_circleci_testing b/ignore_tutorials/ignore_circleci_testing index 036d747f..5552fec0 100644 --- a/ignore_tutorials/ignore_circleci_testing +++ b/ignore_tutorials/ignore_circleci_testing @@ -7,4 +7,6 @@ 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 +# Saves about a million spectra (several GB) to local disk, beyond CircleCI resource limits +tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra diff --git a/ignore_tutorials/ignore_gha_testing b/ignore_tutorials/ignore_gha_testing index 19828652..2d38eb60 100644 --- a/ignore_tutorials/ignore_gha_testing +++ b/ignore_tutorials/ignore_gha_testing @@ -1,3 +1,5 @@ # 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 +# Saves about a million spectra (several GB) to local disk, beyond GHA resource limits +tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra 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 index 770ca46a..bdc412ac 100644 --- a/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md +++ b/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md @@ -17,46 +17,63 @@ authors: +++ -This tutorial shows how to select a large number of Euclid DR1 objects and load their combined 1D spectra in bulk from the Euclid DR1 HATS catalogs. - -+++ - ## Learning Goals -In this tutorial, we will: +By the end of this tutorial, you will: -- Load the spectra of many objects at once, starting from catalog values, a list of `object_id`s, a list of positions, or a region of the sky. -- Decide whether to load a result into memory or save it to disk. -- Show tens of thousands of spectra at once, and combine them into one stacked spectrum. +- know how to get the spectra of thousands to millions of Euclid DR1 objects at once from the HATS catalog of combined 1D spectra; +- know how to start from catalog values, a list of positions, a list of object IDs, or a region of the sky, using science cases from Euclid DR1 papers; +- know how long these queries take and how much disk space the results use; +- make a stacked spectrum like Figure 4 of a Euclid DR1 paper. +++ ## 1. Introduction -The combined 1D NISP spectra are stored in the HATS catalog `sir_combined_spectra`, with one spectrum per row in the nested column `spectrum`. -Because the spectra are in the catalog itself, loading many spectra is a catalog query: there is no limit on the number of spectra, and no need to download the original FITS files, each of which holds many spectra. +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. -For an introduction to the catalogs, their paths, and the `spectrum` column, see the [Euclid DR1 HATS Catalogs introduction](1-euclid-dr1-hats-intro.md). +Getting many spectra from the original data products is difficult: +the spectra are packed into FITS files with one spectrum per extension and many spectra per file, and the services that return individual spectra are limited to about 1,000 spectra per query. -How we select the spectra depends on what we start from: +[TODO] Check the 1,000-spectra limit for the DR1 services (it was reported for Q1). -| Case | Starting point | Section | -|---|---|---| -| 1 | Catalog values only, no positions or IDs (e.g., high-quality galaxy spectra) | 4 | -| 2 | A list of `object_id`s | 5 | -| 3 | A list of positions (RA, Dec) | 6 | -| 4 | A region of the sky | 7 | +IRSA provides the Euclid DR1 combined 1D spectra as a HATS catalog, `sir_combined_spectra`, with one spectrum per row. +HATS (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. +Getting many spectra is therefore a catalog query, and the spectra can be joined to the other DR1 catalogs on `object_id`. +For an introduction to the catalogs and the `spectrum` column, see the [Euclid DR1 HATS Catalogs introduction](1-euclid-dr1-hats-intro.md). + +How we select the spectra depends on what we start from. +This notebook covers four cases, each with a science case from a Euclid DR1 paper: -`sir_combined_spectra` contains only the spectra and a few identifying columns (`object_id`, `tileid`, `lrange`, `n_dith`). -Values such as redshifts and quality measurements are in the other DR1 catalogs, so Case 1 selects objects in those catalogs and then joins the selection to the spectra on `object_id`. +| Case | Starting point | Science case | Section | +|---|---|---|---| +| 1 | Catalog values only | The high-quality galaxy sample of Euclid Collaboration: Le Brun et al. (2026), in the Deep Survey and the Wide Survey | 4, 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 | A region of the sky | All spectra in a large region | 8 | + +In Section 9, we use the spectra from Section 4 to make a stacked spectrum like Figure 4 of Euclid Collaboration: Le Brun et al. (2026). +++ -### 1.1 Duplicate object IDs +### 1.1 Duplicate Object IDs As described in the introduction tutorial, `object_id` alone usually does not identify a unique row. In `sir_combined_spectra`, an object can have a red grism spectrum (`lrange` = `RGS`), a blue grism spectrum (`BGS`), or both, and can have more than one spectrum with the same `lrange`. -Every method below therefore returns every spectrum of each selected object. +The methods in Sections 4, 5, 7, and 8 return every spectrum of each selected object. +The cross match in Section 6 is different: it returns the spectra of all objects near each position, up to a maximum number per position. + ++++ + +### 1.2 Runtime + +Several cells in this notebook read large parts of the catalogs, and can take several minutes to run. +They are marked in the text above them, with the time they took on Fornax. +This notebook also saves catalogs of spectra to local disk, up to [TODO] GB in total. + +[TODO] Give the Fornax server size used for the timings. +++ @@ -64,19 +81,31 @@ Every method below therefore returns every spectrum of each selected object. ```{code-cell} ipython3 # # Uncomment the next line to install dependencies if needed. -# %pip install astropy "lsdb>=0.8.1" matplotlib numpy pandas pyarrow s3fs +# %pip install "lsdb>=0.8.1" "dask[distributed]" matplotlib numpy pandas s3fs ``` ```{code-cell} ipython3 -import time # Time the queries +import io # Read the lens catalog from Zenodo +import os # Number of CPUs for the Dask workers +import urllib.request # Download the lens catalog from Zenodo +import zipfile # Read the lens catalog from Zenodo +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 # Stack spectra +import pandas as pd # Read the lens catalog +from dask.distributed import Client # Run LSDB queries in parallel + +plt.style.use("tableau-colorblind10") # Color-blind friendly colors ``` -## 3. Catalog Paths +## 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" @@ -88,297 +117,518 @@ def collection_uri(catalog): return f"s3://{s3_bucket}/{collections_prefix}/{catalog}" -spectra_columns = ["object_id", "tileid", "lrange", "n_dith", "spectrum"] -spectra_catalog = lsdb.open_catalog(collection_uri("sir_combined_spectra"), columns=spectra_columns) -spectra_catalog +spectra_catalog = lsdb.open_catalog( + collection_uri("sir_combined_spectra"), columns=["object_id", "lrange", "spectrum"] +) +``` + +The helper functions below do four things: + +- Join two catalogs on `object_id`. LSDB adds a suffix to the names of the columns that are in both catalogs (here, `object_id` and the position columns); we add it only to the second catalog's columns. +- Keep one row per object. +- Load a query result into memory, or save it to a local HATS catalog, using a Dask client to run the work in parallel. You can follow the progress in the Dask dashboard, at the link that is printed. +- Report the size of a saved catalog on disk. + +Click on the cell to expand it. + +```{code-cell} ipython3 +--- +jupyter: + source_hidden: true +tags: [hide-cell] +--- +def join_on_object_id(left, right, suffix): + """Join two catalogs on object_id, adding `suffix` to overlapping right-catalog columns.""" + 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.""" + return catalog.map_partitions(lambda partition: partition.drop_duplicates("object_id")) + + +def dask_client(catalog): + """A Dask client with one worker per partition, up to the number of CPUs.""" + n_workers = min(os.cpu_count(), catalog.npartitions + 1) + client = Client(n_workers=n_workers, threads_per_worker=1, memory_limit=None) + print(f"You can monitor progress in the Dask dashboard at {client.dashboard_link}") + return client + + +def load(catalog): + """Load a catalog query into memory.""" + with dask_client(catalog): + return catalog.compute() + + +def save(catalog, path): + """Save a catalog query to a local HATS catalog.""" + with dask_client(catalog): + catalog.write_catalog(path, overwrite=True) + + +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 ``` -## 4. Case 1: Select by Catalog Values +## 4. Case 1: Select by Catalog Values (Deep Survey) +++ -Here we start without positions or object IDs and select high-quality galaxy spectra from the Deep Survey, following the sample of [Euclid Collaboration: Le Brun et al. 2026](https://arxiv.org/abs/2611.17960) (Sect. 4.3), who used it to check the Euclid redshifts against the DESI survey and by visual inspection. -Their criteria are spread over three catalogs: +In this case, we have no positions or object IDs: we only know what kind of objects we want. +As an example, we select the high-quality galaxy sample of [Euclid Collaboration: Le Brun et al. (2026)](https://arxiv.org/abs/2611.17960), Sect. 4.3, who used it to check how often the Euclid redshifts are correct. +Their sample contains 76,002 galaxies in the Euclid Deep Field North (EDF-N), the only Euclid Deep Field with several visits in both grisms in DR1 (seven red grism and three blue grism visits). -| Catalog | Criterion | Meaning | -|---|---|---| -| `spectro_z_spe_quality_deep` | `spe_n_dith_med >= 15`, `spe_npix >= 800` | The spectrum is complete and combines many exposures | -| `mer_catalogue_deep_survey` | `point_like_prob < 0.05`, `spurious_prob < 0.5`, `kron_radius < 50` | The object is an extended galaxy (not a star), not very large, and not a spurious detection | -| `spectro_z_spe_galaxy_candidates_deep` | `spe_rank == 0`, `0.85 < spe_z < 1.85`, `spe_z_prob > 0.94`, `spe_z_rel > 0.05` | The best redshift solution, in the range where the H$\alpha$ line is in the red grism, and reliable | +### 4.1 The Selection Criteria -The paper also requires an H$\alpha$ flux above $1.5 \times 10^{-16}$ erg s$^{-1}$ cm$^{-2}$, from `spectro_line_features_spe_line_features_deep`. -We leave out that criterion, because that catalog is large (about 944 million rows), so our sample is larger than the paper's. +Each criterion is a filter (a "cut") on a column of one of the DR1 catalogs. +The catalogs come from three Euclid processing functions: MER (the merged multi-wavelength catalogs of the objects detected in the images), SPE (spectroscopic measurements, such as redshifts and emission lines), and SIR (the spectra themselves). -[TODO] Check whether the paper's sample also requires `spe_class == 'GALAXY'`, and whether the Deep tables cover only the Euclid Deep Field North (the paper's sample). +| Catalog | Criterion | Meaning | +|---|---|---| +| `spectro_z_spe_quality_deep` | `spe_n_dith_med >= 15`, `spe_npix >= 800` | The spectrum combines many exposures, and has few missing pixels | +| `mer_catalogue_deep_survey` | `point_like_prob < 0.05` | The object is extended (a galaxy, not a star) | +| | `spurious_prob < 0.5` | The detection is real, not an image artifact | +| | `kron_radius < 50` | The object is smaller than 50 pixels on the image; larger objects are unlikely to be above redshift 0.85 | +| `spectro_z_spe_galaxy_candidates_deep` | `spe_rank == 0` | The pipeline's best redshift for the galaxy | +| | `0.85 <= spe_z <= 1.85` | The redshift range in which the hydrogen H$\alpha$ line falls in the red grism spectrum | +| | `spe_z_prob > 0.94`, `spe_z_rel > 0.05` | The pipeline is confident in the redshift | +| `spectro_line_features_spe_line_features_deep` | H$\alpha$ line with `spe_line_flux_gf > 1.5e-16`, `spe_line_snr_gf > 0` | The H$\alpha$ line is bright, and detected (signal-to-noise ratio above 0) | +| | Last digit of `spe_line_qual_gf` is 2 or 3 | The line was measured in the red grism, or in both grisms combined | + +The lines catalog has one row per line, redshift candidate, and grism, so a galaxy can have several H$\alpha$ rows. +The quality flag `spe_line_qual_gf` has three digits: the first gives the fitting method, the second the quality of the measurement, and the last the grism (1: blue, 2: red, 3: both combined). +The paper selects on the last digit (the grism) and on `spe_line_snr_gf > 0`, not on the quality digit; see the [Euclid DR1 SPE tutorial](../5_Euclid_intro_SPE_catalog.md) for the meaning of the other digits. + +[TODO] Test whether also requiring a good second digit (1 or 5) brings the number of galaxies closer to the paper's. ```{code-cell} ipython3 quality = lsdb.open_catalog( - collection_uri("spectro_z_spe_quality_deep"), columns=["object_id", "spe_n_dith_med", "spe_npix"] + collection_uri("spectro_z_spe_quality_deep"), + columns=["object_id", "spe_n_dith_med", "spe_npix"], ).query("spe_n_dith_med >= 15 and spe_npix >= 800") mer = lsdb.open_catalog( - collection_uri("mer_catalogue_deep_survey"), columns=["object_id", "point_like_prob", "spurious_prob", "kron_radius"] + collection_uri("mer_catalogue_deep_survey"), + columns=["object_id", "point_like_prob", "spurious_prob", "kron_radius"], ).query("point_like_prob < 0.05 and spurious_prob < 0.5 and kron_radius < 50") galaxies = lsdb.open_catalog( - collection_uri("spectro_z_spe_galaxy_candidates_deep"), columns=["object_id", "spe_rank", "spe_z", "spe_z_prob", "spe_z_rel"] -).query("spe_rank == 0 and spe_z > 0.85 and spe_z < 1.85 and spe_z_prob > 0.94 and spe_z_rel > 0.05") + collection_uri("spectro_z_spe_galaxy_candidates_deep"), + columns=["object_id", "spe_rank", "spe_z", "spe_z_prob", "spe_z_rel"], +).query( + "spe_rank == 0 and spe_z >= 0.85 and spe_z <= 1.85 and spe_z_prob > 0.94 and spe_z_rel > 0.05" +) + +# Quality flags whose last digit is 2 (red grism) or 3 (both grisms combined). +red_or_combined_flags = [flag for flag in range(100, 400) if flag % 10 in (2, 3)] +halpha_criteria = ( + "spe_rank == 0 and spe_line_name == 'Halpha'" + " and spe_line_flux_gf > 1.5e-16 and spe_line_snr_gf > 0" + f" and spe_line_qual_gf in {red_or_combined_flags}" +) +line_columns = [ + "object_id", "spe_rank", "spe_line_name", + "spe_line_flux_gf", "spe_line_snr_gf", "spe_line_qual_gf", +] +halpha = lsdb.open_catalog( + collection_uri("spectro_line_features_spe_line_features_deep"), columns=line_columns +).query(halpha_criteria) ``` -Every Euclid DR1 HATS catalog is partitioned on coordinates calculated from `object_id` (`ra_from_object_id`, `dec_from_object_id`), so the same `object_id` falls in the same HEALPix pixel in every catalog. -We can therefore join the catalogs on `object_id`, and LSDB joins them pixel by pixel. -We keep only the red grism spectra, which contain H$\alpha$ for this redshift range. +These cells run quickly, because LSDB does not read any data yet: it only records the queries. + ++++ + +### 4.2 Combine the Criteria + +Every Euclid DR1 HATS catalog is partitioned using coordinates calculated from `object_id`, so an object falls in the same part of the sky in every catalog, and LSDB can join the catalogs partition by partition. +A galaxy can have two H$\alpha$ rows (red grism and combined), so we keep one row per galaxy. +Then we 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") +``` + +### 4.3 Save the Spectra + +We save the spectra of the sample to a local HATS catalog, which we use again in Section 9. +This cell reads the four Deep catalogs and the spectra of the sample, so it takes [TODO] minutes to run. ```{code-cell} ipython3 -sample = galaxies.join(quality, left_on="object_id", right_on="object_id", suffixes=("", "_quality")) -sample = sample.join(mer, left_on="object_id", right_on="object_id", suffixes=("", "_mer")) +%%time +save(deep_spectra, "euclid_dr1_deep_galaxy_spectra") +``` + +We count the galaxies and spectra in the saved catalog, reading only the `object_id` column. -red_spectra = spectra_catalog.query("lrange == 'RGS'") -sample_spectra = sample.join(red_spectra, left_on="object_id", right_on="object_id", suffixes=("", "_spectra")) -sample_spectra +```{code-cell} ipython3 +saved_deep_ids = lsdb.open_catalog("euclid_dr1_deep_galaxy_spectra", columns=["object_id"]) +deep_ids = saved_deep_ids.compute()["object_id"] +print(f"{deep_ids.nunique():,} galaxies (Euclid Collaboration: Le Brun et al. 2026: 76,002)") +print(f"{len(deep_ids):,} spectra, {disk_size_gb('euclid_dr1_deep_galaxy_spectra'):.1f} GB on disk") ``` -[TODO] Check for duplicate `object_id`s in each catalog before joining (Section 1.1), and count the rows of `sample_spectra`. +We find about 6% more galaxies than the paper ([TODO] final number). +The paper does not give every detail of its selection (for example, the exact data version), so a small difference is expected. +++ -## 5. Case 2: A List of Object IDs +## 5. Case 1 at Scale: The Wide Survey +++ -When we start from a list of `object_id`s (for example, from a table in a paper), we use `id_search`, which looks up the IDs in the catalog's index table on `object_id`. +The Wide Survey covers about 1,900 square degrees in DR1, and its galaxies with a bright H$\alpha$ line are the sample Euclid uses to map the large-scale structure of the Universe. +Euclid Collaboration: Le Brun et al. (2026), Sect. 5.1, define a high-quality sample for Wide Survey spectra with the same criteria as in Section 4, except that they drop the `spe_z_prob` criterion and require only `spe_npix >= 300` and `spe_n_dith_med > 3`, because Wide Survey spectra have fewer exposures. +The paper tests these criteria on single visits of the EDF-N, which have the same exposure setup as the Wide Survey; here we apply them to the Wide Survey catalogs. -[TODO] Replace this stand-in list (taken from the Case 1 sample) with a realistic example. +To keep the run time reasonable, we select a region of the Wide Survey with a cone search, which LSDB uses to read only the files in that region. + +[TODO] Choose the center and radius so that the region contains about one million spectra. ```{code-cell} ipython3 -object_ids = galaxies.head(100)["object_id"].to_list() -id_spectra = spectra_catalog.id_search(values={"object_id": object_ids}) -id_spectra +wide_ra, wide_dec, wide_radius_deg = 69.316, -47.252, 5 # [TODO] degrees + + +def wide_catalog(name, columns, criteria): + """Open a Wide Survey catalog in the region, with the given columns, and apply the criteria.""" + catalog = lsdb.open_catalog(collection_uri(name), columns=columns) + region = catalog.cone_search(ra=wide_ra, dec=wide_dec, radius_arcsec=wide_radius_deg * 3600) + return region.query(criteria) + + +wide_galaxies = wide_catalog( + "spectro_z_spe_galaxy_candidates_wide_survey", + ["object_id", "spe_rank", "spe_z", "spe_z_rel"], + "spe_rank == 0 and spe_z >= 0.85 and spe_z <= 1.85 and spe_z_rel > 0.05", +) +wide_quality = wide_catalog( + "spectro_z_spe_quality_wide_survey", + ["object_id", "spe_n_dith_med", "spe_npix"], + "spe_n_dith_med > 3 and spe_npix >= 300", +) +wide_mer = wide_catalog( + "mer_catalogue_wide_survey", + ["object_id", "point_like_prob", "spurious_prob", "kron_radius"], + "point_like_prob < 0.05 and spurious_prob < 0.5 and kron_radius < 50", +) +wide_halpha = wide_catalog( + "spectro_line_features_spe_line_features_wide_survey", line_columns, halpha_criteria +) + +wide_sample = join_on_object_id(wide_galaxies, wide_quality, "_quality") +wide_sample = join_on_object_id(wide_sample, wide_mer, "_mer") +wide_sample = one_row_per_object(join_on_object_id(wide_sample, wide_halpha, "_halpha")) +wide_spectra = join_on_object_id(wide_sample, spectra_catalog, "_spectra") ``` -## 6. Case 3: A List of Positions +Instead of loading the spectra into memory, we save them to a local HATS catalog, which can be opened again later with `lsdb.open_catalog`. +This cell reads all the spectra of the sample, so it takes [TODO] minutes to run. + +```{code-cell} ipython3 +%%time +save(wide_spectra, "euclid_dr1_wide_galaxy_spectra") +``` + +```{code-cell} ipython3 +saved_wide_ids = lsdb.open_catalog("euclid_dr1_wide_galaxy_spectra", columns=["object_id"]) +wide_ids = saved_wide_ids.compute()["object_id"] +print(f"{wide_ids.nunique():,} galaxies, {len(wide_ids):,} spectra") +print(f"{disk_size_gb('euclid_dr1_wide_galaxy_spectra'):.1f} GB on disk") +``` + +[TODO] Describe the result: the number of spectra, the time, and the size on disk. +++ -When we start from a list of positions, we load the list into LSDB and cross match it against `sir_combined_spectra`. -The list can contain many positions (for example, a million); LSDB matches it pixel by pixel. -We use a match radius of 0.2 arcseconds, as Euclid Collaboration: Le Brun et al. (2026) did when matching Euclid to DESI (Sect. 4.1). +## 6. Case 2: A List of Positions (Strong Lens Candidates) + ++++ -[TODO] Replace this stand-in table (positions from the Case 1 sample) with an external list, such as DESI DR1 positions. +In this case, we start from a published list of positions. +[Euclid Collaboration: Lines et al. (2026)](https://arxiv.org/abs/2611.15883) found 26,662 strong gravitational lens candidates in Euclid DR1 by visual inspection, and published them on Zenodo. +A strong lens is a massive galaxy (the deflector) that bends the light of a more distant galaxy behind it into arcs or multiple images, typically within about 1 arcsecond of the deflector. +Measuring the redshifts of the deflector and of the lensed source needs their spectra; [Euclid Collaboration: Bergamini et al. (2026)](https://arxiv.org/abs/2611.15891) show that this is possible with the Euclid NISP spectra. + +We download the catalog (about 4 MB, a zip file with the catalog and a README) and keep the grade A ("sure lens") and grade B ("probable lens") candidates. ```{code-cell} ipython3 -positions = galaxies.head(100)[["ra_from_object_id", "dec_from_object_id"]].rename( - columns={"ra_from_object_id": "ra", "dec_from_object_id": "dec"} +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: + lenses = pd.read_csv(lens_zip.open("ECLIPSE_object_catalogue/ECLIPSE_object_catalogue.csv")) + +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() +``` + +We load the positions into LSDB and cross match them against `sir_combined_spectra`. +We use a radius of 2 arcseconds and allow up to 10 spectra per lens. +This returns the spectra of the deflector, and of any nearby objects that the MER catalog detected separately, which can include lensed images; arcs that were not detected as separate objects have no spectrum of their own. + +```{code-cell} ipython3 +lens_positions = lsdb.from_dataframe( + lenses[["Unique_Identifier", "RA_obj", "DEC_obj", "Expert_Grade"]], + ra_column="RA_obj", + dec_column="DEC_obj", +) +lens_spectra = lens_positions.crossmatch( + spectra_catalog, radius_arcsec=2, n_neighbors=10, suffixes=("_lens", "") ) -positions_catalog = lsdb.from_dataframe(positions, ra_column="ra", dec_column="dec") -position_spectra = positions_catalog.crossmatch(spectra_catalog, radius_arcsec=0.2, n_neighbors=10, suffixes=("_input", "")) -position_spectra ``` -## 7. Case 4: A Region of the Sky +The lens candidates are spread over the whole DR1 area, so this cell reads files from all over the sky, and takes [TODO] minutes to run. -+++ +```{code-cell} ipython3 +%%time +lens_spectra_table = load(lens_spectra) +n_lenses_found = lens_spectra_table["Unique_Identifier_lens"].nunique() +print( + f"{len(lens_spectra_table):,} spectra within 2 arcsec of" + f" {n_lenses_found:,} of the {len(lenses):,} lens candidates" +) +``` -For all spectra around a single position, we use a cone search. -Here we use a 30 arcminute radius around NGC 6543, in the Euclid Deep Field North. +Here we plot the spectra found near the lens candidate with the most spectra. +As in the introduction tutorial, we skip wavelength bins with an odd `mask` value or a `mask` value of 64 or more, and multiply the flux by the scale factor $10^{-16}$ (FITS keyword `FSCALE`), which the catalog's unit metadata omits. ```{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=30 * 60) -region_spectra +FSCALE = 1e-16 + +busiest_lens = lens_spectra_table["Unique_Identifier_lens"].value_counts().index[0] +fig, ax = plt.subplots(figsize=(10, 4)) +busiest_spectra = lens_spectra_table[lens_spectra_table["Unique_Identifier_lens"] == busiest_lens] +for _, row in busiest_spectra.iterrows(): + spectrum = row["spectrum"] + bad = (spectrum["mask"] % 2 == 1) | (spectrum["mask"] >= 64) + label = f"{row['object_id']} {row['lrange']} ({row['_dist_arcsec']:.1f} arcsec)" + flux = (spectrum["signal"] * FSCALE).where(~bad) + ax.plot(spectrum["wavelength"] / 1e4, flux, lw=0.7, label=label) +ax.set_xlabel("Wavelength (micron)") +ax.set_ylabel("Flux (erg s$^{-1}$ cm$^{-2}$ Å$^{-1}$)") +ax.set_title(f"Spectra within 2 arcsec of lens candidate {busiest_lens}") +ax.legend(fontsize=8) +plt.show() ``` -## 8. Load or Save the Results +[TODO] Describe the plot. +++ -Every result above is lazy: nothing is read until we ask for it. +## 7. Case 3: A List of Object IDs -- **Small results** (up to tens of thousands of spectra): load them into memory with `compute()`. -- **Large results**: each spectrum takes a few kilobytes, so a million spectra take several gigabytes. Save them to a local HATS catalog with `to_hats`, which processes one partition at a time, and open it later with `lsdb.open_catalog`. ++++ -[TODO] Measure the size and run time for each case, and replace "a few kilobytes" and "several gigabytes" with the measured values. +When the list contains Euclid object IDs, we can look them up directly, without a cross match. +The lens catalog gives the Euclid MER `object_id` (column `MER_object_id`) of most candidates. +`id_search` looks up the IDs in the index table that comes with the catalog collection, which records which file holds each `object_id`, and reads only those files. + +[TODO] Check that the `sir_combined_spectra` collection has an index table; if not, remove this section. ```{code-cell} ipython3 -id_spectra_loaded = id_spectra.compute() -id_spectra_loaded[["object_id", "tileid", "lrange", "n_dith"]] +lens_object_ids = lenses["MER_object_id"].dropna().astype("int64").to_list() +print(f"{len(lens_object_ids):,} lens candidates with a MER object_id") ``` +This cell takes [TODO] minutes to run. + ```{code-cell} ipython3 -region_spectra.to_hats("euclid_dr1_ngc6543_spectra") +%%time +id_spectra_table = load(spectra_catalog.id_search(values={"object_id": lens_object_ids})) +n_ids_found = id_spectra_table["object_id"].nunique() +print(f"{len(id_spectra_table):,} spectra of {n_ids_found:,} lens candidates") ``` -## 9. What Many Spectra Make Possible +Unlike the cross match in Section 6, `id_search` returns only the spectra of the objects themselves, not of their neighbors. -+++ +[TODO] Compare the time with Section 6. -Here we use the Case 1 sample to show what loading tens of thousands of spectra at once makes possible. +[TODO] Alternative science case: the 13,122 white dwarfs of Pérez-Couto et al. (2026), whose catalog at the CDS includes the Euclid `object_id`, once it is available. +++ -### 9.1 How many spectra, and where they come from +## 8. Case 4: A Region of the Sky +++ -In the original Euclid data products, the spectra are packed into FITS files with one spectrum per extension, and each Euclid tile has many such files. -Collecting these spectra from the original files would mean finding which tiles they are in, downloading those files, and reading out each spectrum. -Here we count the spectra and the tiles they come from, loading only small columns. +For all spectra in a region around one position, we use a cone search. +Here we take every spectrum within 1 degree of the planetary nebula NGC 6543, in the Euclid Deep Field North, and save them to disk. + +[TODO] Choose the radius. ```{code-cell} ipython3 -spectra_light = lsdb.open_catalog(collection_uri("sir_combined_spectra"), columns=["object_id", "tileid", "lrange"]) -sample_light = sample.join( - spectra_light.query("lrange == 'RGS'"), left_on="object_id", right_on="object_id", suffixes=("", "_spectra") -).compute() +ngc6543_ra, ngc6543_dec = 269.6394799, 66.6329765 # degrees +region_spectra = spectra_catalog.cone_search(ra=ngc6543_ra, dec=ngc6543_dec, radius_arcsec=3600) +``` + +This cell takes [TODO] minutes to run. + +```{code-cell} ipython3 +%%time +save(region_spectra, "euclid_dr1_ngc6543_spectra") +``` -print(f"{len(sample_light):,} red grism spectra of {sample_light['object_id'].nunique():,} galaxies, from {sample_light['tileid'].nunique():,} Euclid tiles") +```{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") ``` -[TODO] Add the number of original FITS files (about 150 per tile in the COMBSPEC checks) once the count is confirmed for this sample. +## 9. A Stacked Spectrum Like Figure 4 of Euclid Collaboration: Le Brun et al. (2026) +++ -### 9.2 A wall 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 no single spectrum shows. -+++ +Figure 4 of Euclid Collaboration: Le Brun et al. (2026) shows stacked spectra of 4,000 randomly chosen galaxies from their sample (Section 4), made with the Euclid stacking code SpectraPyle ([Euclid Collaboration: Quai et al. 2026](https://arxiv.org/abs/2509.16120)). +The paper splits the 4,000 galaxies into four groups by how confident volunteers were in each redshift after looking at the spectra. +Those grades are not public, so here we make a single stack of 4,000 randomly chosen galaxies from our sample. -Redshift stretches every wavelength of a galaxy's light by a factor of $1 + z$. -For example, hydrogen emits the H$\alpha$ line at 6563 Å, which we observe at 13,126 Å for a galaxy at $z = 1$ and at 16,408 Å for a galaxy at $z = 1.5$. -Dividing the observed wavelengths by $1 + z$ returns them to the wavelengths the galaxy emitted (the rest frame). +We follow the paper's recipe: -Here we load a few thousand spectra, sort them by redshift, and draw each one as a row of an image, first at the observed wavelengths and then in the rest frame. +1. Treat the red and blue grism spectra as separate spectra. +2. Shift each spectrum to the rest frame, the wavelengths that the galaxy emitted, by dividing the observed wavelengths by $1 + z$. +3. Divide each spectrum by its median flux, so that bright galaxies do not dominate. +4. Resample onto a common wavelength grid with 5 Å pixels. +5. At each wavelength, take the median of all spectra. + +First we choose 4,000 galaxies and load their spectra from the catalog we saved in Section 4. ```{code-cell} ipython3 -wall = sample_spectra.head(2000).sort_values("spe_z") +rng = np.random.default_rng(seed=0) +stack_ids = set(rng.choice(deep_ids.unique(), size=4000, replace=False)) -observed_grid = np.arange(12000, 19000, 10.0) # Angstrom -rest_grid = np.arange(4000, 10500, 5.0) # Angstrom +saved_deep = lsdb.open_catalog("euclid_dr1_deep_galaxy_spectra") +stack_spectra = saved_deep.map_partitions( + lambda partition: partition[partition["object_id"].isin(stack_ids)] +).compute() +print(f"{len(stack_spectra):,} spectra of {stack_spectra['object_id'].nunique():,} galaxies") +``` +The helper functions below normalize one spectrum and resample it; click on the cell to expand it. -def normalized_spectrum(row): - """Observed wavelengths and median-normalized flux of the good bins of one spectrum.""" - spectrum = row["spectrum"] +```{code-cell} ipython3 +--- +jupyter: + source_hidden: true +tags: [hide-cell] +--- +def normalized_spectrum(spectrum): + """Wavelengths and median-normalized flux of the good bins of one spectrum.""" good = (spectrum["mask"] % 2 == 0) & (spectrum["mask"] < 64) wavelength = spectrum["wavelength"][good].to_numpy() flux = spectrum["signal"][good].to_numpy() - if flux.size == 0 or np.median(flux) <= 0: + median = np.median(flux) if flux.size else 0 + if median <= 0: return None, None - return wavelength, flux / np.median(flux) + return wavelength, flux / median def resample(wavelength, flux, grid): """Flux on a wavelength grid, NaN outside the spectrum's range.""" return np.interp(grid, wavelength, flux, left=np.nan, right=np.nan) - - -observed_image, rest_image, wall_z = [], [], [] -for _, row in wall.iterrows(): - wavelength, flux = normalized_spectrum(row) - if wavelength is None: - continue - observed_image.append(resample(wavelength, flux, observed_grid)) - rest_image.append(resample(wavelength / (1 + row["spe_z"]), flux, rest_grid)) - wall_z.append(row["spe_z"]) ``` -```{code-cell} ipython3 -fig, axes = plt.subplots(1, 2, figsize=(12, 6)) -for ax, image, grid, title in [ - (axes[0], observed_image, observed_grid, "Observed wavelength"), - (axes[1], rest_image, rest_grid, "Rest-frame wavelength"), -]: - ax.imshow( - np.array(image), aspect="auto", origin="lower", vmin=0, vmax=3, cmap="gray_r", - extent=[grid[0], grid[-1], 0, len(image)], - ) - ax.set_xlabel(f"{title} (Angstrom)") - ax.set_title(title) -axes[0].set_ylabel(f"Spectra sorted by redshift ({wall_z[0]:.2f} to {wall_z[-1]:.2f})") -plt.show() -``` - -At the observed wavelengths (left), H$\alpha$ is a bright streak that moves to longer wavelengths as the redshift increases. -In the rest frame (right), it lines up at 6563 Å in every spectrum, so the spectra can be averaged. - -+++ - -### 9.3 Stacking: one spectrum versus the whole sample - -+++ - -A single spectrum is noisy, so faint emission lines are hidden in the noise. -Averaging many rest-frame spectra (stacking) reduces the noise and reveals lines that no single spectrum shows ([Dobos et al. 2012](https://arxiv.org/abs/1111.1215); [Euclid Collaboration 2025](https://arxiv.org/abs/2509.16120)). - -We stack every red grism spectrum of the sample: each spectrum is divided by its median flux (so that bright galaxies do not dominate), shifted to the rest frame, resampled onto a common grid, and averaged. -LSDB runs this on one partition at a time with `map_partitions`, so the spectra are never all in memory at once. +We resample every spectrum onto the rest-frame grid and take the median at each wavelength. ```{code-cell} ipython3 -def stack_partition(partition): - """Sum of normalized rest-frame spectra in one partition, and the number of spectra at each wavelength.""" - flux_sum = np.zeros(rest_grid.size) - n_spectra = np.zeros(rest_grid.size) - for _, row in partition.iterrows(): - wavelength, flux = normalized_spectrum(row) - if wavelength is None: - continue - rest_flux = resample(wavelength / (1 + row["spe_z"]), flux, rest_grid) - covered = ~np.isnan(rest_flux) - flux_sum[covered] += rest_flux[covered] - n_spectra[covered] += 1 - return pd.DataFrame({"wavelength": rest_grid, "flux_sum": flux_sum, "n_spectra": n_spectra}) - - -meta = pd.DataFrame({"wavelength": pd.Series(dtype=float), "flux_sum": pd.Series(dtype=float), "n_spectra": pd.Series(dtype=float)}) -start = time.perf_counter() -stack = sample_spectra.map_partitions(stack_partition, meta=meta).compute().groupby("wavelength").sum() -print(f"Stacked {len(sample_light):,} spectra in {(time.perf_counter() - start) / 60:.1f} minutes") +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()): + wavelength, flux = normalized_spectrum(row["spectrum"]) + if wavelength is not None: + resampled[i] = resample(wavelength / (1 + row["spe_z"]), flux, rest_grid) + +stack = np.nanmedian(resampled, axis=0) +n_contributing = np.sum(~np.isnan(resampled), axis=0) ``` -We mark some of the emission lines in this wavelength range (vacuum rest wavelengths). -Not every spectrum covers every line: H$\beta$ and [O III] are in the red grism only for the higher-redshift part of the sample. +As in the paper's figure, the top panel shows how many spectra contribute at each wavelength, and the bottom panel shows the stacked spectrum, with the emission lines that the paper identifies in its stacks. ```{code-cell} ipython3 +# Approximate rest-frame vacuum wavelengths, in Angstrom, as labeled in Figure 4 of the paper. lines = { - r"H$\beta$": 4862.7, - "[O III]": 5008.2, - r"H$\alpha$": 6564.6, - "[N II]": 6585.3, - "[S II]": 6718.3, - "[S III]": 9533.2, + "[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 II]": 6725, + "[Ar III]": 7138, + "[S III] 9071": 9071, + "[S III] 9533": 9533, } -single = wall.iloc[len(wall) // 2] -wavelength, flux = normalized_spectrum(single) - -fig, axes = plt.subplots(2, 1, figsize=(12, 7), sharex=True) -axes[0].plot(wavelength / (1 + single["spe_z"]), flux, lw=0.7) -axes[0].set_title(f"One galaxy (z = {single['spe_z']:.2f})") -axes[1].plot(stack.index, stack["flux_sum"] / stack["n_spectra"], lw=0.7) -axes[1].set_title(f"Stack of the whole sample (up to {int(stack['n_spectra'].max()):,} spectra at each wavelength)") -for ax in axes: - for name, line_wavelength in lines.items(): - ax.axvline(line_wavelength, color="gray", ls=":", lw=0.8) - ax.text(line_wavelength, 1.02, name, transform=ax.get_xaxis_transform(), ha="center", fontsize=8) - ax.set_ylabel("Normalized flux") -axes[1].set_xlabel("Rest-frame wavelength (Angstrom)") -axes[1].set_xlim(rest_grid[0], rest_grid[-1]) +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() ``` -[TODO] Check which lines are visible in the stack but not in the single spectrum, and set the y-axis limits. +[TODO] Describe which lines are visible, and compare with Figure 4 of the paper. + +The paper (Sect. 4.3) warns that stacking galaxies with wrong redshifts can also produce features at the expected wavelengths, because the noise that misled the redshift measurement gets lined up. +From its visual inspection, the paper finds that about 80% of the redshifts in its sample are correct (Sect. 4.3). -[TODO] Optional: stack two groups (for example, bright and faint galaxies) and compare them, as in Dobos et al. (2012). ++++ + +## 10. Summary + ++++ + +[TODO] Fill in from the timings above. + +| Case | Starting point | Spectra | Time | Size on disk | +|---|---|---|---|---| +| 1 | Catalog values, Deep Survey (Section 4) | | | | +| 1 | Catalog values, Wide Survey region (Section 5) | | | | +| 2 | List of positions (Section 6) | | | | +| 3 | List of object IDs (Section 7) | | | | +| 4 | Region of the sky (Section 8) | | | | +++ ## References -- Dobos et al. 2012, *A High Resolution Atlas of Composite SDSS Galaxy Spectra*, [arXiv:1111.1215](https://arxiv.org/abs/1111.1215) +- 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 2025, *Euclid preparation. Predicting star-forming galaxy scaling relations with the spectral stacking code SpectraPyle*, [arXiv:2509.16120](https://arxiv.org/abs/2509.16120) +- 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) +- Euclid Collaboration: Quai et al. 2026, *Euclid preparation. Predicting star-forming galaxy scaling relations with the spectral stacking code SpectraPyle*, [arXiv:2509.16120](https://arxiv.org/abs/2509.16120) +- Pérez-Couto et al. 2026, *Euclid: Data Release 1 (DR1) -- A deep near-infrared search for low-mass and substellar companions to white dwarfs*, [arXiv:2611.36036](https://arxiv.org/abs/2611.36036) ## About this notebook -**Updated:** 2026-11-30 +**Updated:** 2026-12-01 **Contact:** [IRSA Helpdesk](https://irsa.ipac.caltech.edu/docs/help_desk.html) + +**Runtime:** [TODO] As of the date above, this notebook takes about N minutes to run to completion on Fornax (server size, environment). + +**AI Acknowledgement:** This tutorial was developed with the assistance of AI tools. From 3d9f8226c0dfb3866887fd90e9c86c97873a862e Mon Sep 17 00:00:00 2001 From: DeekshaMohanty Date: Tue, 1 Dec 2026 14:31:14 -0500 Subject: [PATCH 03/19] nb fixups --- .../2-euclid-dr1-hats-bulk-spectra.md | 190 +++++++++++------- 1 file changed, 117 insertions(+), 73 deletions(-) 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 index bdc412ac..77e7168d 100644 --- a/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md +++ b/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md @@ -21,10 +21,10 @@ authors: By the end of this tutorial, you will: -- know how to get the spectra of thousands to millions of Euclid DR1 objects at once from the HATS catalog of combined 1D spectra; -- know how to start from catalog values, a list of positions, a list of object IDs, or a region of the sky, using science cases from Euclid DR1 papers; -- know how long these queries take and how much disk space the results use; -- make a stacked spectrum like Figure 4 of a Euclid DR1 paper. +- know how to get the spectra of thousands to millions of Euclid DR1 objects in one query; +- know how to start from catalog values, a list of positions, a list of object IDs, or a region of the sky; +- know how long these queries take and how much disk space they use; +- stack thousands of spectra to reveal faint emission lines. +++ @@ -96,8 +96,12 @@ import matplotlib.pyplot as plt # Plot spectra import numpy as np # Stack spectra import pandas as pd # Read the lens catalog from dask.distributed import Client # Run LSDB queries in parallel +``` + +We use a color-blind friendly color cycle for all the plots in this notebook. -plt.style.use("tableau-colorblind10") # Color-blind friendly colors +```{code-cell} ipython3 +plt.style.use("tableau-colorblind10") ``` ## 3. Catalog Paths and Helper Functions @@ -126,7 +130,7 @@ The helper functions below do four things: - Join two catalogs on `object_id`. LSDB adds a suffix to the names of the columns that are in both catalogs (here, `object_id` and the position columns); we add it only to the second catalog's columns. - Keep one row per object. -- Load a query result into memory, or save it to a local HATS catalog, using a Dask client to run the work in parallel. You can follow the progress in the Dask dashboard, at the link that is printed. +- Load a query result into memory, or save it to a local HATS catalog, using a Dask client to run the work in parallel on a few workers, with the memory of the machine shared between them. - Report the size of a saved catalog on disk. Click on the cell to expand it. @@ -153,12 +157,10 @@ def one_row_per_object(catalog): return catalog.map_partitions(lambda partition: partition.drop_duplicates("object_id")) -def dask_client(catalog): - """A Dask client with one worker per partition, up to the number of CPUs.""" - n_workers = min(os.cpu_count(), catalog.npartitions + 1) - client = Client(n_workers=n_workers, threads_per_worker=1, memory_limit=None) - print(f"You can monitor progress in the Dask dashboard at {client.dashboard_link}") - return client +def dask_client(catalog, max_workers=4): + """A Dask client with a few workers, each with an equal share of the machine's memory.""" + n_workers = min(max_workers, os.cpu_count(), catalog.npartitions + 1) + return Client(n_workers=n_workers, threads_per_worker=2, memory_limit="auto") def load(catalog): @@ -182,75 +184,108 @@ def disk_size_gb(path): +++ -In this case, we have no positions or object IDs: we only know what kind of objects we want. -As an example, we select the high-quality galaxy sample of [Euclid Collaboration: Le Brun et al. (2026)](https://arxiv.org/abs/2611.17960), Sect. 4.3, who used it to check how often the Euclid redshifts are correct. -Their sample contains 76,002 galaxies in the Euclid Deep Field North (EDF-N), the only Euclid Deep Field with several visits in both grisms in DR1 (seven red grism and three blue grism visits). +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 the high-quality galaxy sample of [Euclid Collaboration: Le Brun et al. (2026)](https://arxiv.org/abs/2611.17960), Sect. 4.3: 76,002 galaxies in the Euclid Deep Field North (EDF-N), which the paper uses to evaluate the performance of the redshift measurement. +The paper uses EDF-N because, with seven red grism and three blue grism visits, it has the most complete spectral coverage of the three Euclid Deep Fields. ### 4.1 The Selection Criteria Each criterion is a filter (a "cut") on a column of one of the DR1 catalogs. -The catalogs come from three Euclid processing functions: MER (the merged multi-wavelength catalogs of the objects detected in the images), SPE (spectroscopic measurements, such as redshifts and emission lines), and SIR (the spectra themselves). +The catalogs come from three Euclid processing functions: MER (multi-wavelength mosaics and the catalog of the objects detected in them), SPE (spectroscopic measurements, such as redshifts and emission lines), and SIR (the NISP spectra). +The table below lists the criteria of Sect. 4.3 of the paper, with the paper's reason for each. +The two criteria marked "this notebook" are not stated in Sect. 4.3; they are how we implement the paper's selection. -| Catalog | Criterion | Meaning | +| Catalog | Criterion | Reason | |---|---|---| -| `spectro_z_spe_quality_deep` | `spe_n_dith_med >= 15`, `spe_npix >= 800` | The spectrum combines many exposures, and has few missing pixels | -| `mer_catalogue_deep_survey` | `point_like_prob < 0.05` | The object is extended (a galaxy, not a star) | -| | `spurious_prob < 0.5` | The detection is real, not an image artifact | -| | `kron_radius < 50` | The object is smaller than 50 pixels on the image; larger objects are unlikely to be above redshift 0.85 | -| `spectro_z_spe_galaxy_candidates_deep` | `spe_rank == 0` | The pipeline's best redshift for the galaxy | -| | `0.85 <= spe_z <= 1.85` | The redshift range in which the hydrogen H$\alpha$ line falls in the red grism spectrum | -| | `spe_z_prob > 0.94`, `spe_z_rel > 0.05` | The pipeline is confident in the redshift | -| `spectro_line_features_spe_line_features_deep` | H$\alpha$ line with `spe_line_flux_gf > 1.5e-16`, `spe_line_snr_gf > 0` | The H$\alpha$ line is bright, and detected (signal-to-noise ratio above 0) | -| | Last digit of `spe_line_qual_gf` is 2 or 3 | The line was measured in the red grism, or in both grisms combined | - -The lines catalog has one row per line, redshift candidate, and grism, so a galaxy can have several H$\alpha$ rows. -The quality flag `spe_line_qual_gf` has three digits: the first gives the fitting method, the second the quality of the measurement, and the last the grism (1: blue, 2: red, 3: both combined). -The paper selects on the last digit (the grism) and on `spe_line_snr_gf > 0`, not on the quality digit; see the [Euclid DR1 SPE tutorial](../5_Euclid_intro_SPE_catalog.md) for the meaning of the other digits. +| `spectro_z_spe_quality_deep` | `spe_n_dith_med >= 15`, `spe_npix >= 800` | "To ensure complete spectra built from a sufficient number of individual visits" | +| `mer_catalogue_deep_survey` | `point_like_prob < 0.05`, `spurious_prob < 0.5`, `kron_radius < 50` | Criteria of the Galaxy Clustering Science Working Group, to exclude point-like objects (mainly stars), large objects ("for which the redshift is unlikely to be actually greater than 0.85"), and objects "whose reality is uncertain". `kron_radius` is in pixels ([MER catalog description](https://euclid.esac.esa.int/dr/dr1/dpdd/merdpd/dpcards/mer_finalcatalog.html)). | +| `spectro_z_spe_galaxy_candidates_deep` | `spe_rank == 0` (this notebook) | The pipeline's best redshift solution for each galaxy, as in the paper's example query (Appendix C) | +| | `0.85 <= spe_z <= 1.85` | "To ensure that the H$\alpha$ line is detected in the RGS [red grism] spectrum" | +| | `spe_z_prob > 0.94`, `spe_z_rel > 0.05` | "To further improve the results"; excluding small values of `spe_z_rel` "allows the exclusion of a small fraction of wrong redshifts without losing the correct ones" | +| `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` | An H$\alpha$ flux above $1.5 \times 10^{-16}$ erg s$^{-1}$ cm$^{-2}$, "to ensure completeness at the level of $2 \times 10^{-16}$" | +| | `spe_line_snr_gf > 0` | To discard "low-quality flux measurements" | +| | Last digit of `spe_line_qual_gf` is 2 or 3 | "Measurements made on either the RGS or combined between the two grisms" | + +The lines catalog has one row per line, redshift solution, and grism. +The quality flag `spe_line_qual_gf` has three digits, defined in Appendix D of the paper: the first gives the fitting method, the second the quality of the measurement, and the last the grism (1: blue, 2: red, 3: both combined). +The paper selects on the grism and on `spe_line_snr_gf > 0`, not on the quality digit; see the [Euclid DR1 SPE tutorial](../5_Euclid_intro_SPE_catalog.md) for more on this flag. [TODO] Test whether also requiring a good second digit (1 or 5) brings the number of galaxies closer to the paper's. ++++ + +### 4.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. +LSDB then applies them while it reads the Parquet files, so it reads and keeps only the rows that pass, instead of loading every row and filtering afterwards. +We also read only the part of the sky around EDF-N, with a cone of 3 degrees around its center, which covers almost all of the field. +The center comes from Table 1 of the [Euclid archive user guide at IRSA](https://irsa.ipac.caltech.edu/data/Euclid/docs/euclid_archive_at_irsa_user_guide.pdf), as in the [IRSA HATS catalogs with LSDB tutorial](../../techniques-and-tools/irsa-hats-with-lsdb.md). + ```{code-cell} ipython3 +# EDF-N: center 17h58m55.9s +66d01m03.7s, and a radius that covers almost all of the field. +edfn = lsdb.ConeSearch(ra=269.732917, dec=66.017694, 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", "spe_n_dith_med", "spe_npix"], -).query("spe_n_dith_med >= 15 and spe_npix >= 800") + 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", "point_like_prob", "spurious_prob", "kron_radius"], -).query("point_like_prob < 0.05 and spurious_prob < 0.5 and kron_radius < 50") + 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_rank", "spe_z", "spe_z_prob", "spe_z_rel"], -).query( - "spe_rank == 0 and spe_z >= 0.85 and spe_z <= 1.85 and spe_z_prob > 0.94 and spe_z_rel > 0.05" + 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], + ], ) -# Quality flags whose last digit is 2 (red grism) or 3 (both grisms combined). +# 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_criteria = ( - "spe_rank == 0 and spe_line_name == 'Halpha'" - " and spe_line_flux_gf > 1.5e-16 and spe_line_snr_gf > 0" - f" and spe_line_qual_gf in {red_or_combined_flags}" -) -line_columns = [ - "object_id", "spe_rank", "spe_line_name", - "spe_line_flux_gf", "spe_line_snr_gf", "spe_line_qual_gf", +halpha_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], ] halpha = lsdb.open_catalog( - collection_uri("spectro_line_features_spe_line_features_deep"), columns=line_columns -).query(halpha_criteria) + collection_uri("spectro_line_features_spe_line_features_deep"), + columns=["object_id"], + search_filter=edfn, + filters=halpha_filters, +) ``` These cells run quickly, because LSDB does not read any data yet: it only records the queries. +++ -### 4.2 Combine the Criteria +### 4.3 Combine the Criteria Every Euclid DR1 HATS catalog is partitioned using coordinates calculated from `object_id`, so an object falls in the same part of the sky in every catalog, and LSDB can join the catalogs partition by partition. -A galaxy can have two H$\alpha$ rows (red grism and combined), so we keep one row per galaxy. + +The lines catalog can have more than one H$\alpha$ row for the same galaxy that passes the criteria: for example, one for the measurement in the red grism alone, and one for the measurement that combines both grisms. +The join would then return that galaxy twice, and in the next step it would get its spectra twice. +So after joining the H$\alpha$ rows, we keep only one row per galaxy. Then we join the galaxies to their spectra. ```{code-cell} ipython3 @@ -260,7 +295,9 @@ 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") ``` -### 4.3 Save the 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. + +### 4.4 Save the Spectra We save the spectra of the sample to a local HATS catalog, which we use again in Section 9. This cell reads the four Deep catalogs and the spectra of the sample, so it takes [TODO] minutes to run. @@ -288,42 +325,49 @@ The paper does not give every detail of its selection (for example, the exact da +++ -The Wide Survey covers about 1,900 square degrees in DR1, and its galaxies with a bright H$\alpha$ line are the sample Euclid uses to map the large-scale structure of the Universe. -Euclid Collaboration: Le Brun et al. (2026), Sect. 5.1, define a high-quality sample for Wide Survey spectra with the same criteria as in Section 4, except that they drop the `spe_z_prob` criterion and require only `spe_npix >= 300` and `spe_n_dith_med > 3`, because Wide Survey spectra have fewer exposures. -The paper tests these criteria on single visits of the EDF-N, which have the same exposure setup as the Wide Survey; here we apply them to the Wide Survey catalogs. +The Wide Survey covers about 1,900 square degrees in DR1 ([Pérez-Couto et al. 2026](https://arxiv.org/abs/2611.36036)), and its galaxies at $0.85 \le z \le 1.85$ with a bright H$\alpha$ line are the cosmology target sample of Euclid (Euclid Collaboration: Le Brun et al. 2026, Sect. 4.3). +In Sect. 5.1, the paper builds a high-quality sample with "the same criteria on all parameters but `spe_z_prob`" as in Section 4, but requiring only 300 valid pixels and a median of more than three dithers. +The paper applies these criteria to single visits of the EDF-N, which have the same exposure setup as the Wide Survey; here we apply them to the Wide Survey catalogs. -To keep the run time reasonable, we select a region of the Wide Survey with a cone search, which LSDB uses to read only the files in that region. +To keep the run time reasonable, we read only a region of the Wide Survey, with a cone search. +As in Section 4, we pass the criteria to `lsdb.open_catalog` as `filters`. [TODO] Choose the center and radius so that the region contains about one million spectra. ```{code-cell} ipython3 -wide_ra, wide_dec, wide_radius_deg = 69.316, -47.252, 5 # [TODO] degrees +# [TODO] Center and radius of the Wide Survey region. +wide_region = lsdb.ConeSearch(ra=69.316, dec=-47.252, radius_arcsec=5 * 3600) -def wide_catalog(name, columns, criteria): - """Open a Wide Survey catalog in the region, with the given columns, and apply the criteria.""" - catalog = lsdb.open_catalog(collection_uri(name), columns=columns) - region = catalog.cone_search(ra=wide_ra, dec=wide_dec, radius_arcsec=wide_radius_deg * 3600) - return region.query(criteria) +def open_wide(name, columns, filters): + """Open a Wide Survey catalog in the region, with the given columns and filters.""" + return lsdb.open_catalog( + collection_uri(name), columns=columns, search_filter=wide_region, filters=filters + ) -wide_galaxies = wide_catalog( +# Redshift: the best solution, in the H-alpha range, with high reliability +# (no spe_z_prob criterion). +wide_galaxies = open_wide( "spectro_z_spe_galaxy_candidates_wide_survey", - ["object_id", "spe_rank", "spe_z", "spe_z_rel"], - "spe_rank == 0 and spe_z >= 0.85 and spe_z <= 1.85 and spe_z_rel > 0.05", + ["object_id", "spe_z"], + [["spe_rank", "==", 0], ["spe_z", ">=", 0.85], ["spe_z", "<=", 1.85], ["spe_z_rel", ">", 0.05]], ) -wide_quality = wide_catalog( +# Spectrum quality, relaxed for the Wide Survey. +wide_quality = open_wide( "spectro_z_spe_quality_wide_survey", - ["object_id", "spe_n_dith_med", "spe_npix"], - "spe_n_dith_med > 3 and spe_npix >= 300", + ["object_id"], + [["spe_n_dith_med", ">", 3], ["spe_npix", ">=", 300]], ) -wide_mer = wide_catalog( +# Object properties, as in Section 4. +wide_mer = open_wide( "mer_catalogue_wide_survey", - ["object_id", "point_like_prob", "spurious_prob", "kron_radius"], - "point_like_prob < 0.05 and spurious_prob < 0.5 and kron_radius < 50", + ["object_id"], + [["point_like_prob", "<", 0.05], ["spurious_prob", "<", 0.5], ["kron_radius", "<", 50]], ) -wide_halpha = wide_catalog( - "spectro_line_features_spe_line_features_wide_survey", line_columns, halpha_criteria +# H-alpha line, as in Section 4. +wide_halpha = open_wide( + "spectro_line_features_spe_line_features_wide_survey", ["object_id"], halpha_filters ) wide_sample = join_on_object_id(wide_galaxies, wide_quality, "_quality") @@ -623,7 +667,7 @@ From its visual inspection, the paper finds that about 80% of the redshifts in i - Euclid Collaboration: Quai et al. 2026, *Euclid preparation. Predicting star-forming galaxy scaling relations with the spectral stacking code SpectraPyle*, [arXiv:2509.16120](https://arxiv.org/abs/2509.16120) - Pérez-Couto et al. 2026, *Euclid: Data Release 1 (DR1) -- A deep near-infrared search for low-mass and substellar companions to white dwarfs*, [arXiv:2611.36036](https://arxiv.org/abs/2611.36036) -## About this notebook +## About This Notebook **Updated:** 2026-12-01 From 76448c45499c83bc48c4ee68e735bf3310d8ab9b Mon Sep 17 00:00:00 2001 From: DeekshaMohanty Date: Tue, 1 Dec 2026 14:55:27 -0500 Subject: [PATCH 04/19] more fixups --- .../hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) 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 index 77e7168d..15920469 100644 --- a/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md +++ b/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md @@ -96,6 +96,7 @@ import matplotlib.pyplot as plt # Plot spectra import numpy as np # Stack spectra import pandas as pd # Read the lens catalog from dask.distributed import Client # Run LSDB queries in parallel +from IPython.display import HTML, display # Clickable link to the Dask dashboard ``` We use a color-blind friendly color cycle for all the plots in this notebook. @@ -130,7 +131,7 @@ The helper functions below do four things: - Join two catalogs on `object_id`. LSDB adds a suffix to the names of the columns that are in both catalogs (here, `object_id` and the position columns); we add it only to the second catalog's columns. - Keep one row per object. -- Load a query result into memory, or save it to a local HATS catalog, using a Dask client to run the work in parallel on a few workers, with the memory of the machine shared between them. +- Load a query result into memory, or save it to a local HATS catalog, using a Dask client to run the work in parallel on a few workers, with the memory of the machine shared between them. A link to the Dask dashboard, where you can follow the progress, is printed when the client starts. - Report the size of a saved catalog on disk. Click on the cell to expand it. @@ -160,7 +161,11 @@ def one_row_per_object(catalog): def dask_client(catalog, max_workers=4): """A Dask client with a few workers, each with an equal share of the machine's memory.""" n_workers = min(max_workers, os.cpu_count(), catalog.npartitions + 1) - return Client(n_workers=n_workers, threads_per_worker=2, memory_limit="auto") + client = Client(n_workers=n_workers, threads_per_worker=2, memory_limit="auto") + # 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): From 4428fc4502f255618a2d72193c494c5cdb2779db Mon Sep 17 00:00:00 2001 From: DeekshaMohanty Date: Tue, 1 Dec 2026 16:04:43 -0500 Subject: [PATCH 05/19] save a smaller sample --- .../2-euclid-dr1-hats-bulk-spectra.md | 67 ++++++++++++------- 1 file changed, 41 insertions(+), 26 deletions(-) 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 index 15920469..9a366ef2 100644 --- a/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md +++ b/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md @@ -96,6 +96,7 @@ import matplotlib.pyplot as plt # Plot spectra import numpy as np # Stack spectra import pandas as pd # Read the lens catalog 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 # Clickable link to the Dask dashboard ``` @@ -158,10 +159,13 @@ def one_row_per_object(catalog): return catalog.map_partitions(lambda partition: partition.drop_duplicates("object_id")) -def dask_client(catalog, max_workers=4): - """A Dask client with a few workers, each with an equal share of the machine's memory.""" +def dask_client(catalog, max_workers=2): + """A Dask client with a few single-threaded workers, sharing the memory equally.""" n_workers = min(max_workers, os.cpu_count(), catalog.npartitions + 1) - client = Client(n_workers=n_workers, threads_per_worker=2, memory_limit="auto") + # 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}.")) @@ -230,7 +234,8 @@ The center comes from Table 1 of the [Euclid archive user guide at IRSA](https:/ ```{code-cell} ipython3 # EDF-N: center 17h58m55.9s +66d01m03.7s, and a radius that covers almost all of the field. -edfn = lsdb.ConeSearch(ra=269.732917, dec=66.017694, radius_arcsec=3 * 3600) +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( @@ -302,28 +307,26 @@ 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. -### 4.4 Save the Spectra +### 4.4 Count the Galaxies -We save the spectra of the sample to a local HATS catalog, which we use again in Section 9. -This cell reads the four Deep catalogs and the spectra of the sample, so it takes [TODO] minutes to run. +First we load only the sample itself, without the spectra, to compare it with the paper. +This reads only small catalog columns, so it is much faster than loading the spectra. -```{code-cell} ipython3 -%%time -save(deep_spectra, "euclid_dr1_deep_galaxy_spectra") -``` - -We count the galaxies and spectra in the saved catalog, reading only the `object_id` column. +[TODO] Time this cell. ```{code-cell} ipython3 -saved_deep_ids = lsdb.open_catalog("euclid_dr1_deep_galaxy_spectra", columns=["object_id"]) -deep_ids = saved_deep_ids.compute()["object_id"] -print(f"{deep_ids.nunique():,} galaxies (Euclid Collaboration: Le Brun et al. 2026: 76,002)") -print(f"{len(deep_ids):,} spectra, {disk_size_gb('euclid_dr1_deep_galaxy_spectra'):.1f} GB on disk") +%%time +deep_sample_table = load(deep_sample) +print(f"{len(deep_sample_table):,} galaxies (Euclid Collaboration: Le Brun et al. 2026: 76,002)") ``` -We find about 6% more galaxies than the paper ([TODO] final number). +We find 80,432 galaxies, about 6% more than the paper's 76,002. The paper does not give every detail of its selection (for example, the exact data version), so a small difference is expected. +These galaxies have 159,720 spectra (about two per galaxy: red grism and blue grism), which take 0.7 GB on disk. +Loading all of them takes about 40 minutes on a Fornax server with 61 GiB of memory, because each file of the spectra catalog holds tens of thousands of spectra and is read whole, even when only a few of them belong to the sample. +In Section 9 we therefore load the spectra of only part of the sample. + +++ ## 5. Case 1 at Scale: The Wide Survey @@ -543,7 +546,10 @@ Averaging many spectra of similar galaxies (stacking) reduces the noise and reve Figure 4 of Euclid Collaboration: Le Brun et al. (2026) shows stacked spectra of 4,000 randomly chosen galaxies from their sample (Section 4), made with the Euclid stacking code SpectraPyle ([Euclid Collaboration: Quai et al. 2026](https://arxiv.org/abs/2509.16120)). The paper splits the 4,000 galaxies into four groups by how confident volunteers were in each redshift after looking at the spectra. -Those grades are not public, so here we make a single stack of 4,000 randomly chosen galaxies from our sample. +Those grades are not public, so here we make a single stack of 4,000 galaxies from our sample. + +As explained in Section 4.4, loading the spectra of the whole sample takes a long time. +A stack does not need galaxies from the whole field, so we take the galaxies of the sample in a small part of EDF-N, whose spectra are in only a few files of the spectra catalog, and choose 4,000 of them at random. We follow the paper's recipe: @@ -553,16 +559,25 @@ We follow the paper's recipe: 4. Resample onto a common wavelength grid with 5 Å pixels. 5. At each wavelength, take the median of all spectra. -First we choose 4,000 galaxies and load their spectra from the catalog we saved in Section 4. +First we load the spectra of the sample galaxies within 0.6 degrees of the center of EDF-N. +This cell takes [TODO] minutes to run. + +[TODO] Check that the region contains at least 4,000 galaxies of the sample; if not, increase the radius. ```{code-cell} ipython3 -rng = np.random.default_rng(seed=0) -stack_ids = set(rng.choice(deep_ids.unique(), size=4000, replace=False)) +%%time +stack_region = deep_spectra.cone_search(ra=edfn_ra, dec=edfn_dec, radius_arcsec=0.6 * 3600) +region_spectra_table = load(stack_region) +print(f"{region_spectra_table['object_id'].nunique():,} galaxies in the region") +``` -saved_deep = lsdb.open_catalog("euclid_dr1_deep_galaxy_spectra") -stack_spectra = saved_deep.map_partitions( - lambda partition: partition[partition["object_id"].isin(stack_ids)] -).compute() +Then we choose 4,000 of these galaxies at random, and keep their spectra. + +```{code-cell} ipython3 +rng = np.random.default_rng(seed=0) +region_ids = region_spectra_table["object_id"].unique() +stack_ids = rng.choice(region_ids, size=min(4000, len(region_ids)), replace=False) +stack_spectra = region_spectra_table[region_spectra_table["object_id"].isin(stack_ids)] print(f"{len(stack_spectra):,} spectra of {stack_spectra['object_id'].nunique():,} galaxies") ``` From c84240cc92169db8ef243bfdd1c424cc96b38c34 Mon Sep 17 00:00:00 2001 From: DeekshaMohanty Date: Tue, 1 Dec 2026 16:15:05 -0500 Subject: [PATCH 06/19] removing harmless errors showing up --- .../2-euclid-dr1-hats-bulk-spectra.md | 22 ++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) 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 index 9a366ef2..13360a5b 100644 --- a/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md +++ b/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md @@ -86,6 +86,7 @@ This notebook also saves catalogs of spectra to local disk, up to [TODO] GB in t ```{code-cell} ipython3 import io # Read the lens catalog from Zenodo +import logging import os # Number of CPUs for the Dask workers import urllib.request # Download the lens catalog from Zenodo import zipfile # Read the lens catalog from Zenodo @@ -97,7 +98,7 @@ import numpy as np # Stack spectra import pandas as pd # Read the lens catalog 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 # Clickable link to the Dask dashboard +from IPython.display import HTML, display ``` We use a color-blind friendly color cycle for all the plots in this notebook. @@ -143,6 +144,10 @@ 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.""" return left.join( @@ -310,9 +315,7 @@ For each join, LSDB prints a table of the columns it renamed because they are in ### 4.4 Count the Galaxies First we load only the sample itself, without the spectra, to compare it with the paper. -This reads only small catalog columns, so it is much faster than loading the spectra. - -[TODO] Time this cell. +This reads only small catalog columns, so it is much faster than loading the spectra: it takes about 2 minutes on a Fornax server with 61 GiB of memory. ```{code-cell} ipython3 %%time @@ -384,7 +387,16 @@ wide_sample = one_row_per_object(join_on_object_id(wide_sample, wide_halpha, "_h wide_spectra = join_on_object_id(wide_sample, spectra_catalog, "_spectra") ``` -Instead of loading the spectra into memory, we save them to a local HATS catalog, which can be opened again later with `lsdb.open_catalog`. +First we count the galaxies in the region, without their spectra, as in Section 4.4. +This cell takes [TODO] minutes to run. + +```{code-cell} ipython3 +%%time +wide_sample_table = load(wide_sample) +print(f"{len(wide_sample_table):,} galaxies in the region") +``` + +Then, instead of loading the spectra into memory, we save them to a local HATS catalog, which can be opened again later with `lsdb.open_catalog`. This cell reads all the spectra of the sample, so it takes [TODO] minutes to run. ```{code-cell} ipython3 From d8cff84287d1cc0b606dcf4d5e94ae140bd91e52 Mon Sep 17 00:00:00 2001 From: DeekshaMohanty Date: Tue, 1 Dec 2026 16:51:34 -0500 Subject: [PATCH 07/19] more fixups based on fornax errors --- .../2-euclid-dr1-hats-bulk-spectra.md | 48 ++++++++++++------- 1 file changed, 30 insertions(+), 18 deletions(-) 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 index 13360a5b..50ea2bc6 100644 --- a/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md +++ b/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md @@ -34,15 +34,16 @@ Euclid Data Release 1 (DR1) provides more than 170 million validated 1D spectra 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 files with one spectrum per extension and many spectra per file, and the services that return individual spectra are limited to about 1,000 spectra per query. +the spectra are packed into FITS (Flexible Image Transport System) files with one spectrum per extension and many spectra per file, and the services that return individual spectra are limited to about 1,000 spectra per query. [TODO] Check the 1,000-spectra limit for the DR1 services (it was reported for Q1). IRSA provides the Euclid DR1 combined 1D spectra as a HATS catalog, `sir_combined_spectra`, with one spectrum per row. HATS (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. +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 (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`. For an introduction to the catalogs and the `spectrum` column, see the [Euclid DR1 HATS Catalogs introduction](1-euclid-dr1-hats-intro.md). +This notebook uses only IRSA data, because IRSA is the NASA archive for Euclid. How we select the spectra depends on what we start from. This notebook covers four cases, each with a science case from a Euclid DR1 paper: @@ -235,7 +236,7 @@ The paper selects on the grism and on `spe_line_snr_gf > 0`, not on the quality We pass the criteria to `lsdb.open_catalog` as `filters`, a list of `[column, operator, value]` conditions that must all be true. LSDB then applies them while it reads the Parquet files, so it reads and keeps only the rows that pass, instead of loading every row and filtering afterwards. We also read only the part of the sky around EDF-N, with a cone of 3 degrees around its center, which covers almost all of the field. -The center comes from Table 1 of the [Euclid archive user guide at IRSA](https://irsa.ipac.caltech.edu/data/Euclid/docs/euclid_archive_at_irsa_user_guide.pdf), as in the [IRSA HATS catalogs with LSDB tutorial](../../techniques-and-tools/irsa-hats-with-lsdb.md). +The center comes from Table 1 of the [Euclid archive user guide at IRSA (PDF, 0.3 MB)](https://irsa.ipac.caltech.edu/data/Euclid/docs/euclid_archive_at_irsa_user_guide.pdf), as in the [IRSA HATS catalogs with LSDB tutorial](../../techniques-and-tools/irsa-hats-with-lsdb.md). ```{code-cell} ipython3 # EDF-N: center 17h58m55.9s +66d01m03.7s, and a radius that covers almost all of the field. @@ -437,7 +438,12 @@ print(f"{len(lenses):,} grade A and B lens candidates") lenses[["Unique_Identifier", "RA_obj", "DEC_obj", "Expert_Grade", "MER_object_id"]].head() ``` -We load the positions into LSDB and cross match them against `sir_combined_spectra`. +The lens candidates are spread over the whole DR1 area. +To find their spectra, LSDB has to read every file of the spectra catalog that contains a lens candidate, and each file holds tens of thousands of spectra. +For all 15,072 candidates, that is about 2,500 files, which would take hours. +Here we keep the candidates within 3 degrees of a position in the Wide Survey with many of them; the same code works for the whole list, given more time. + +We load the positions into LSDB, keep those in the region, and cross match them against `sir_combined_spectra`. We use a radius of 2 arcseconds and allow up to 10 spectra per lens. This returns the spectra of the deflector, and of any nearby objects that the MER catalog detected separately, which can include lensed images; arcs that were not detected as separate objects have no spectrum of their own. @@ -447,12 +453,14 @@ lens_positions = lsdb.from_dataframe( ra_column="RA_obj", dec_column="DEC_obj", ) -lens_spectra = lens_positions.crossmatch( +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", "") ) ``` -The lens candidates are spread over the whole DR1 area, so this cell reads files from all over the sky, and takes [TODO] minutes to run. +This cell takes [TODO] minutes to run. ```{code-cell} ipython3 %%time @@ -460,7 +468,7 @@ lens_spectra_table = load(lens_spectra) n_lenses_found = lens_spectra_table["Unique_Identifier_lens"].nunique() print( f"{len(lens_spectra_table):,} spectra within 2 arcsec of" - f" {n_lenses_found:,} of the {len(lenses):,} lens candidates" + f" {n_lenses_found:,} of the {len(lens_region_table):,} lens candidates in the region" ) ``` @@ -498,11 +506,11 @@ When the list contains Euclid object IDs, we can look them up directly, without The lens catalog gives the Euclid MER `object_id` (column `MER_object_id`) of most candidates. `id_search` looks up the IDs in the index table that comes with the catalog collection, which records which file holds each `object_id`, and reads only those files. -[TODO] Check that the `sir_combined_spectra` collection has an index table; if not, remove this section. +We look up the candidates in the same region as in Section 6. ```{code-cell} ipython3 -lens_object_ids = lenses["MER_object_id"].dropna().astype("int64").to_list() -print(f"{len(lens_object_ids):,} lens candidates with a MER object_id") +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 [TODO] minutes to run. @@ -527,13 +535,13 @@ Unlike the cross match in Section 6, `id_search` returns only the spectra of the +++ For all spectra in a region around one position, we use a cone search. -Here we take every spectrum within 1 degree of the planetary nebula NGC 6543, in the Euclid Deep Field North, and save them to disk. - -[TODO] Choose the radius. +Here we take every spectrum within 0.1 degrees of the planetary nebula NGC 6543, in 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=3600) +region_spectra = spectra_catalog.cone_search( + ra=ngc6543_ra, dec=ngc6543_dec, radius_arcsec=0.1 * 3600 +) ``` This cell takes [TODO] minutes to run. @@ -572,9 +580,8 @@ We follow the paper's recipe: 5. At each wavelength, take the median of all spectra. First we load the spectra of the sample galaxies within 0.6 degrees of the center of EDF-N. -This cell takes [TODO] minutes to run. - -[TODO] Check that the region contains at least 4,000 galaxies of the sample; if not, increase the radius. +This region contains 4,399 galaxies of the sample, whose spectra are in 33 files of the spectra catalog (compared with 440 files for the whole sample). +This cell takes about 4 minutes to run on a Fornax server with 61 GiB of memory. ```{code-cell} ipython3 %%time @@ -667,7 +674,12 @@ plt.tight_layout() plt.show() ``` -[TODO] Describe which lines are visible, and compare with Figure 4 of the paper. +The top panel shows that most spectra cover rest-frame wavelengths between about 4,000 and 9,000 Å; near the edges of the plot, only a few spectra contribute, so the stack is noisy there. + +In the stack, emission lines appear as peaks at the wavelengths marked by the dotted lines, which we placed at the known wavelengths of the lines; nothing was fitted to the data. +The brightest is the H$\alpha$+[N II] complex, as expected for a sample selected for its bright H$\alpha$ line, followed by [O II], H$\beta$, the [O III] doublet, [S II], and the two [S III] lines. +The weaker lines [Ne III], He I, and [O I] are also visible. +These are the lines that the paper identifies in its stacks of galaxies with reliable redshifts (Figure 4). The paper (Sect. 4.3) warns that stacking galaxies with wrong redshifts can also produce features at the expected wavelengths, because the noise that misled the redshift measurement gets lined up. From its visual inspection, the paper finds that about 80% of the redshifts in its sample are correct (Sect. 4.3). From dc43dc4be24dcdeeebf0260adfa6ef403462b83f Mon Sep 17 00:00:00 2001 From: DeekshaMohanty Date: Tue, 1 Dec 2026 19:14:46 -0500 Subject: [PATCH 08/19] Updating lens IDs in section 4 and some TODO comments --- .../2-euclid-dr1-hats-bulk-spectra.md | 123 ++++++++++++------ 1 file changed, 82 insertions(+), 41 deletions(-) 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 index 50ea2bc6..8d51d909 100644 --- a/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md +++ b/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md @@ -135,6 +135,9 @@ The helper functions below do four things: - Join two catalogs on `object_id`. LSDB adds a suffix to the names of the columns that are in both catalogs (here, `object_id` and the position columns); we add it only to the second catalog's columns. - Keep one row per object. - Load a query result into memory, or save it to a local HATS catalog, using a Dask client to run the work in parallel on a few workers, with the memory of the machine shared between them. A link to the Dask dashboard, where you can follow the progress, is printed when the client starts. +- Find the usable wavelength bins of a spectrum. + The `mask` column of a spectrum is a set of quality flags for each bin. + As in the [Euclid DR1 SIR 1D spectra tutorial](../3_Euclid_intro_1D_spectra.md), we consider a bin unusable if its `mask` value is odd (flag `NOT_USE`: invalid flux) or is 64 or more (flag `ABS_FLUX`: suspicious flux calibration); the other flags are warnings. - Report the size of a saved catalog on disk. Click on the cell to expand it. @@ -190,6 +193,11 @@ def save(catalog, path): catalog.write_catalog(path, 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 @@ -388,8 +396,8 @@ wide_sample = one_row_per_object(join_on_object_id(wide_sample, wide_halpha, "_h wide_spectra = join_on_object_id(wide_sample, spectra_catalog, "_spectra") ``` -First we count the galaxies in the region, without their spectra, as in Section 4.4. -This cell takes [TODO] minutes to run. +We count the galaxies in the region, without their spectra, as in Section 4.4. +This cell takes about 4 minutes to run on a Fornax server with 61 GiB of memory. ```{code-cell} ipython3 %%time @@ -397,22 +405,10 @@ wide_sample_table = load(wide_sample) print(f"{len(wide_sample_table):,} galaxies in the region") ``` -Then, instead of loading the spectra into memory, we save them to a local HATS catalog, which can be opened again later with `lsdb.open_catalog`. -This cell reads all the spectra of the sample, so it takes [TODO] minutes to run. - -```{code-cell} ipython3 -%%time -save(wide_spectra, "euclid_dr1_wide_galaxy_spectra") -``` - -```{code-cell} ipython3 -saved_wide_ids = lsdb.open_catalog("euclid_dr1_wide_galaxy_spectra", columns=["object_id"]) -wide_ids = saved_wide_ids.compute()["object_id"] -print(f"{wide_ids.nunique():,} galaxies, {len(wide_ids):,} spectra") -print(f"{disk_size_gb('euclid_dr1_wide_galaxy_spectra'):.1f} GB on disk") -``` - -[TODO] Describe the result: the number of spectra, the time, and the size on disk. +The region contains 221,140 galaxies of the high-quality sample. +Their spectra are the query `wide_spectra` defined above. +We do not load them here: their spectra are spread over about 400 files of the spectra catalog, and in Section 4.4, loading spectra from 440 files took about 40 minutes. +To load or save them, run `load(wide_spectra)` or `save(wide_spectra, "euclid_dr1_wide_galaxy_spectra")`; Section 8 shows how to save spectra to disk on a smaller region. +++ @@ -431,7 +427,12 @@ We download the catalog (about 4 MB, a zip file with the catalog and a README) a 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: - lenses = pd.read_csv(lens_zip.open("ECLIPSE_object_catalogue/ECLIPSE_object_catalogue.csv")) + # 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") @@ -449,7 +450,7 @@ This returns the spectra of the deflector, and of any nearby objects that the ME ```{code-cell} ipython3 lens_positions = lsdb.from_dataframe( - lenses[["Unique_Identifier", "RA_obj", "DEC_obj", "Expert_Grade"]], + lenses[["Unique_Identifier", "RA_obj", "DEC_obj", "Expert_Grade", "MER_object_id"]], ra_column="RA_obj", dec_column="DEC_obj", ) @@ -460,7 +461,7 @@ lens_spectra = lens_region.crossmatch( ) ``` -This cell takes [TODO] minutes to run. +This cell takes about 4 minutes to run on a Fornax server with 61 GiB of memory. ```{code-cell} ipython3 %%time @@ -472,29 +473,20 @@ print( ) ``` -Here we plot the spectra found near the lens candidate with the most spectra. -As in the introduction tutorial, we skip wavelength bins with an odd `mask` value or a `mask` value of 64 or more, and multiply the flux by the scale factor $10^{-16}$ (FITS keyword `FSCALE`), which the catalog's unit metadata omits. +We find 317 spectra within 2 arcseconds of 275 of the 276 lens candidates in the region. -```{code-cell} ipython3 -FSCALE = 1e-16 +Not every spectrum has usable data. +Using the `good_bins` function from Section 3, we count the spectra that have no usable wavelength bins at all. -busiest_lens = lens_spectra_table["Unique_Identifier_lens"].value_counts().index[0] -fig, ax = plt.subplots(figsize=(10, 4)) -busiest_spectra = lens_spectra_table[lens_spectra_table["Unique_Identifier_lens"] == busiest_lens] -for _, row in busiest_spectra.iterrows(): - spectrum = row["spectrum"] - bad = (spectrum["mask"] % 2 == 1) | (spectrum["mask"] >= 64) - label = f"{row['object_id']} {row['lrange']} ({row['_dist_arcsec']:.1f} arcsec)" - flux = (spectrum["signal"] * FSCALE).where(~bad) - ax.plot(spectrum["wavelength"] / 1e4, flux, lw=0.7, label=label) -ax.set_xlabel("Wavelength (micron)") -ax.set_ylabel("Flux (erg s$^{-1}$ cm$^{-2}$ Å$^{-1}$)") -ax.set_title(f"Spectra within 2 arcsec of lens candidate {busiest_lens}") -ax.legend(fontsize=8) -plt.show() +```{code-cell} ipython3 +n_good_bins = [good_bins(row["spectrum"]).sum() for _, row in lens_spectra_table.iterrows()] +n_empty = sum(n == 0 for n in n_good_bins) +print(f"{n_empty:,} of the {len(lens_spectra_table):,} spectra have no usable bins") ``` -[TODO] Describe the plot. +[TODO] Give the number of spectra with no usable bins. + +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. +++ @@ -526,6 +518,55 @@ Unlike the cross match in Section 6, `id_search` returns only the spectra of the [TODO] Compare the time with Section 6. +### 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. +From the Euclid spectra, they measure a redshift of 1.366 for the galaxy in the ring, from its H$\alpha$ emission line (their Table 1 and Figure 4). +At this redshift, the H$\alpha$ line (rest-frame vacuum wavelength 6,564.6 Å) is observed at $6564.6 \times (1 + 1.366) \approx 15{,}532$ Å, in the red grism. + +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"] +lens_columns = ["Unique_Identifier", "RA_obj", "DEC_obj", "Expert_Grade", "MER_object_id"] +known_lens[lens_columns + ["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]) +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 = 6564.6 * (1 + 1.366) # Angstrom + +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 spectrum of the lens galaxy shows a strong emission line at the marked wavelength, where Bergamini et al. (2026) detect the H$\alpha$ emission of the ring in their own extraction of the Euclid data. +The ring is close to the lens galaxy, so its light is likely included in the lens galaxy's spectrum in this catalog. + +[TODO] Check this description against the plot. + [TODO] Alternative science case: the 13,122 white dwarfs of Pérez-Couto et al. (2026), whose catalog at the CDS includes the Euclid `object_id`, once it is available. +++ @@ -610,7 +651,7 @@ tags: [hide-cell] --- def normalized_spectrum(spectrum): """Wavelengths and median-normalized flux of the good bins of one spectrum.""" - good = (spectrum["mask"] % 2 == 0) & (spectrum["mask"] < 64) + good = good_bins(spectrum) wavelength = spectrum["wavelength"][good].to_numpy() flux = spectrum["signal"][good].to_numpy() median = np.median(flux) if flux.size else 0 From 0c7f299b5187c338eb0d1fc52a0e88557f71d564 Mon Sep 17 00:00:00 2001 From: DeekshaMohanty Date: Tue, 1 Dec 2026 20:50:31 -0500 Subject: [PATCH 09/19] more notebook fixups --- deploy_to_fornax_manifest.in | 1 + ignore_tutorials/ignore_circleci_testing | 1 - ignore_tutorials/ignore_gha_testing | 1 - irsa-tutorials-401 | 1 + notebook_metadata.yml | 4 + toc.yml | 2 + tutorials/euclid/euclid.md | 1 + .../2-euclid-dr1-hats-bulk-spectra.md | 530 +++++++++--------- 8 files changed, 276 insertions(+), 265 deletions(-) create mode 160000 irsa-tutorials-401 diff --git a/deploy_to_fornax_manifest.in b/deploy_to_fornax_manifest.in index 9fd259b8..a6051a98 100644 --- a/deploy_to_fornax_manifest.in +++ b/deploy_to_fornax_manifest.in @@ -7,6 +7,7 @@ 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/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 5552fec0..ddd08fc1 100644 --- a/ignore_tutorials/ignore_circleci_testing +++ b/ignore_tutorials/ignore_circleci_testing @@ -8,5 +8,4 @@ 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 -# Saves about a million spectra (several GB) to local disk, beyond CircleCI resource limits tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra diff --git a/ignore_tutorials/ignore_gha_testing b/ignore_tutorials/ignore_gha_testing index 2d38eb60..449c6649 100644 --- a/ignore_tutorials/ignore_gha_testing +++ b/ignore_tutorials/ignore_gha_testing @@ -1,5 +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 -# Saves about a million spectra (several GB) to local disk, beyond GHA resource limits tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra diff --git a/irsa-tutorials-401 b/irsa-tutorials-401 new file mode 160000 index 00000000..b94d6ffd --- /dev/null +++ b/irsa-tutorials-401 @@ -0,0 +1 @@ +Subproject commit b94d6ffd4057da10aba62f52e4b03c123dedf3f4 diff --git a/notebook_metadata.yml b/notebook_metadata.yml index 08449c34..2e5270fe 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, starting from catalog values, positions, object IDs, or a region of the sky, then stack them 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 index 8d51d909..3541788e 100644 --- a/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md +++ b/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md @@ -17,14 +17,19 @@ authors: +++ +This tutorial shows how to get the spectra of thousands of Euclid DR1 objects at once from the HATS catalog of Euclid DR1 combined 1D spectra, and how long these queries take. + ++++ + ## Learning Goals -By the end of this tutorial, you will: +In this tutorial, we will: -- know how to get the spectra of thousands to millions of Euclid DR1 objects in one query; -- know how to start from catalog values, a list of positions, a list of object IDs, or a region of the sky; -- know how long these queries take and how much disk space they use; -- stack thousands of spectra to reveal faint emission lines. +- Get all the spectra in a region of the sky and save them to disk. +- Get the spectra of a list of objects, by position or by Euclid object ID. +- Select galaxies by their catalog values and get their spectra. +- Stack thousands of spectra to reveal faint emission lines. +- Measure how long these queries take, and estimate how long larger ones would take. +++ @@ -34,47 +39,49 @@ Euclid Data Release 1 (DR1) provides more than 170 million validated 1D spectra 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, and the services that return individual spectra are limited to about 1,000 spectra per query. - -[TODO] Check the 1,000-spectra limit for the DR1 services (it was reported for Q1). +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 (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 (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`. For an introduction to the catalogs and the `spectrum` column, see the [Euclid DR1 HATS Catalogs introduction](1-euclid-dr1-hats-intro.md). -This notebook uses only IRSA data, because IRSA is the NASA archive for Euclid. +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 cases, each with a science case from a Euclid DR1 paper: +This notebook covers four starting points: -| Case | Starting point | Science case | Section | -|---|---|---|---| -| 1 | Catalog values only | The high-quality galaxy sample of Euclid Collaboration: Le Brun et al. (2026), in the Deep Survey and the Wide Survey | 4, 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 | A region of the sky | All spectra in a large region | 8 | +| Starting point | Example | Section | +|---|---|---| +| A region of the sky | All spectra around the planetary nebula NGC 6543 | 4 | +| A list of positions | The strong lens candidates of Euclid Collaboration: Lines et al. (2026) | 5 | +| A list of object IDs | The same lens candidates, by their Euclid object ID | 6 | +| Catalog values | The high-quality galaxy sample of Euclid Collaboration: Le Brun et al. (2026) | 7 | -In Section 9, we use the spectra from Section 4 to make a stacked spectrum like Figure 4 of Euclid Collaboration: Le Brun et al. (2026). +In Section 8, we use the spectra from Section 7 to make a stacked spectrum like Figure 4 of Euclid Collaboration: Le Brun et al. (2026). +++ -### 1.1 Duplicate Object IDs +### 1.1 Duplicate object IDs As described in the introduction tutorial, `object_id` alone usually does not identify a unique row. In `sir_combined_spectra`, an object can have a red grism spectrum (`lrange` = `RGS`), a blue grism spectrum (`BGS`), or both, and can have more than one spectrum with the same `lrange`. -The methods in Sections 4, 5, 7, and 8 return every spectrum of each selected object. -The cross match in Section 6 is different: it returns the spectra of all objects near each position, up to a maximum number per position. +The methods in Sections 4, 6, and 7 return every spectrum of each selected object. +The cross match in Section 5 is different: it returns the spectra of all objects near each position, up to a maximum number per position. +++ ### 1.2 Runtime -Several cells in this notebook read large parts of the catalogs, and can take several minutes to run. -They are marked in the text above them, with the time they took on Fornax. -This notebook also saves catalogs of spectra to local disk, up to [TODO] GB in total. +Several cells in this notebook can take several minutes to run. +They are marked in the text above them, with the time they took on Fornax, on a server with 61 GiB of memory ([TODO] server type and environment). +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, even when only a few of them are needed, so the time depends mostly on how many files a query reads, rather than on how many spectra it returns. -[TODO] Give the Fornax server size used for the timings. +This notebook also saves a catalog of spectra to local disk (about 0.2 GB, in Section 4). +++ @@ -130,7 +137,7 @@ spectra_catalog = lsdb.open_catalog( ) ``` -The helper functions below do four things: +The helper functions below do five things: - Join two catalogs on `object_id`. LSDB adds a suffix to the names of the columns that are in both catalogs (here, `object_id` and the position columns); we add it only to the second catalog's columns. - Keep one row per object. @@ -154,6 +161,8 @@ 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", @@ -165,11 +174,13 @@ def join_on_object_id(left, right, suffix): 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=2): """A Dask client with a few 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. @@ -183,12 +194,14 @@ def dask_client(catalog, max_workers=2): 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. with dask_client(catalog): catalog.write_catalog(path, overwrite=True) @@ -203,216 +216,49 @@ def disk_size_gb(path): return sum(file.stat().st_size for file in Path(path).rglob("*") if file.is_file()) / 1e9 ``` -## 4. Case 1: Select by Catalog Values (Deep Survey) - -+++ - -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 the high-quality galaxy sample of [Euclid Collaboration: Le Brun et al. (2026)](https://arxiv.org/abs/2611.17960), Sect. 4.3: 76,002 galaxies in the Euclid Deep Field North (EDF-N), which the paper uses to evaluate the performance of the redshift measurement. -The paper uses EDF-N because, with seven red grism and three blue grism visits, it has the most complete spectral coverage of the three Euclid Deep Fields. - -### 4.1 The Selection Criteria - -Each criterion is a filter (a "cut") on a column of one of the DR1 catalogs. -The catalogs come from three Euclid processing functions: MER (multi-wavelength mosaics and the catalog of the objects detected in them), SPE (spectroscopic measurements, such as redshifts and emission lines), and SIR (the NISP spectra). -The table below lists the criteria of Sect. 4.3 of the paper, with the paper's reason for each. -The two criteria marked "this notebook" are not stated in Sect. 4.3; they are how we implement the paper's selection. - -| Catalog | Criterion | Reason | -|---|---|---| -| `spectro_z_spe_quality_deep` | `spe_n_dith_med >= 15`, `spe_npix >= 800` | "To ensure complete spectra built from a sufficient number of individual visits" | -| `mer_catalogue_deep_survey` | `point_like_prob < 0.05`, `spurious_prob < 0.5`, `kron_radius < 50` | Criteria of the Galaxy Clustering Science Working Group, to exclude point-like objects (mainly stars), large objects ("for which the redshift is unlikely to be actually greater than 0.85"), and objects "whose reality is uncertain". `kron_radius` is in pixels ([MER catalog description](https://euclid.esac.esa.int/dr/dr1/dpdd/merdpd/dpcards/mer_finalcatalog.html)). | -| `spectro_z_spe_galaxy_candidates_deep` | `spe_rank == 0` (this notebook) | The pipeline's best redshift solution for each galaxy, as in the paper's example query (Appendix C) | -| | `0.85 <= spe_z <= 1.85` | "To ensure that the H$\alpha$ line is detected in the RGS [red grism] spectrum" | -| | `spe_z_prob > 0.94`, `spe_z_rel > 0.05` | "To further improve the results"; excluding small values of `spe_z_rel` "allows the exclusion of a small fraction of wrong redshifts without losing the correct ones" | -| `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` | An H$\alpha$ flux above $1.5 \times 10^{-16}$ erg s$^{-1}$ cm$^{-2}$, "to ensure completeness at the level of $2 \times 10^{-16}$" | -| | `spe_line_snr_gf > 0` | To discard "low-quality flux measurements" | -| | Last digit of `spe_line_qual_gf` is 2 or 3 | "Measurements made on either the RGS or combined between the two grisms" | - -The lines catalog has one row per line, redshift solution, and grism. -The quality flag `spe_line_qual_gf` has three digits, defined in Appendix D of the paper: the first gives the fitting method, the second the quality of the measurement, and the last the grism (1: blue, 2: red, 3: both combined). -The paper selects on the grism and on `spe_line_snr_gf > 0`, not on the quality digit; see the [Euclid DR1 SPE tutorial](../5_Euclid_intro_SPE_catalog.md) for more on this flag. - -[TODO] Test whether also requiring a good second digit (1 or 5) brings the number of galaxies closer to the paper's. +## 4. Spectra in a Region of the Sky +++ -### 4.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. -LSDB then applies them while it reads the Parquet files, so it reads and keeps only the rows that pass, instead of loading every row and filtering afterwards. -We also read only the part of the sky around EDF-N, with a cone of 3 degrees around its center, which covers almost all of the field. -The center comes from Table 1 of the [Euclid archive user guide at IRSA (PDF, 0.3 MB)](https://irsa.ipac.caltech.edu/data/Euclid/docs/euclid_archive_at_irsa_user_guide.pdf), as in the [IRSA HATS catalogs with LSDB tutorial](../../techniques-and-tools/irsa-hats-with-lsdb.md). +For all spectra in a region around one position, 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 -# EDF-N: center 17h58m55.9s +66d01m03.7s, and a radius that covers almost all of the field. -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_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], -] -halpha = lsdb.open_catalog( - collection_uri("spectro_line_features_spe_line_features_deep"), - columns=["object_id"], - search_filter=edfn, - filters=halpha_filters, +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 ) ``` -These cells run quickly, because LSDB does not read any data yet: it only records the queries. - -+++ - -### 4.3 Combine the Criteria - -Every Euclid DR1 HATS catalog is partitioned using coordinates calculated from `object_id`, so an object falls in the same part of the sky in every catalog, and LSDB can join the catalogs partition by partition. - -The lines catalog can have more than one H$\alpha$ row for the same galaxy that passes the criteria: for example, one for the measurement in the red grism alone, and one for the measurement that combines both grisms. -The join would then return that galaxy twice, and in the next step it would get its spectra twice. -So after joining the H$\alpha$ rows, we keep only one row per galaxy. -Then we 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. - -### 4.4 Count the Galaxies - -First we load only the sample itself, without the spectra, to compare it with the paper. -This reads only small catalog columns, so it is much faster than loading the spectra: it takes about 2 minutes on a Fornax server with 61 GiB of memory. +This cell takes less than a minute to run. ```{code-cell} ipython3 %%time -deep_sample_table = load(deep_sample) -print(f"{len(deep_sample_table):,} galaxies (Euclid Collaboration: Le Brun et al. 2026: 76,002)") +save(region_spectra, "euclid_dr1_ngc6543_spectra") ``` -We find 80,432 galaxies, about 6% more than the paper's 76,002. -The paper does not give every detail of its selection (for example, the exact data version), so a small difference is expected. - -These galaxies have 159,720 spectra (about two per galaxy: red grism and blue grism), which take 0.7 GB on disk. -Loading all of them takes about 40 minutes on a Fornax server with 61 GiB of memory, because each file of the spectra catalog holds tens of thousands of spectra and is read whole, even when only a few of them belong to the sample. -In Section 9 we therefore load the spectra of only part of the sample. - -+++ - -## 5. Case 1 at Scale: The Wide Survey - -+++ - -The Wide Survey covers about 1,900 square degrees in DR1 ([Pérez-Couto et al. 2026](https://arxiv.org/abs/2611.36036)), and its galaxies at $0.85 \le z \le 1.85$ with a bright H$\alpha$ line are the cosmology target sample of Euclid (Euclid Collaboration: Le Brun et al. 2026, Sect. 4.3). -In Sect. 5.1, the paper builds a high-quality sample with "the same criteria on all parameters but `spe_z_prob`" as in Section 4, but requiring only 300 valid pixels and a median of more than three dithers. -The paper applies these criteria to single visits of the EDF-N, which have the same exposure setup as the Wide Survey; here we apply them to the Wide Survey catalogs. - -To keep the run time reasonable, we read only a region of the Wide Survey, with a cone search. -As in Section 4, we pass the criteria to `lsdb.open_catalog` as `filters`. - -[TODO] Choose the center and radius so that the region contains about one million 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 -# [TODO] Center and radius of the Wide Survey region. -wide_region = lsdb.ConeSearch(ra=69.316, dec=-47.252, radius_arcsec=5 * 3600) - - -def open_wide(name, columns, filters): - """Open a Wide Survey catalog in the region, with the given columns and filters.""" - return lsdb.open_catalog( - collection_uri(name), columns=columns, search_filter=wide_region, filters=filters - ) - - -# Redshift: the best solution, in the H-alpha range, with high reliability -# (no spe_z_prob criterion). -wide_galaxies = open_wide( - "spectro_z_spe_galaxy_candidates_wide_survey", - ["object_id", "spe_z"], - [["spe_rank", "==", 0], ["spe_z", ">=", 0.85], ["spe_z", "<=", 1.85], ["spe_z_rel", ">", 0.05]], -) -# Spectrum quality, relaxed for the Wide Survey. -wide_quality = open_wide( - "spectro_z_spe_quality_wide_survey", - ["object_id"], - [["spe_n_dith_med", ">", 3], ["spe_npix", ">=", 300]], -) -# Object properties, as in Section 4. -wide_mer = open_wide( - "mer_catalogue_wide_survey", - ["object_id"], - [["point_like_prob", "<", 0.05], ["spurious_prob", "<", 0.5], ["kron_radius", "<", 50]], -) -# H-alpha line, as in Section 4. -wide_halpha = open_wide( - "spectro_line_features_spe_line_features_wide_survey", ["object_id"], halpha_filters -) - -wide_sample = join_on_object_id(wide_galaxies, wide_quality, "_quality") -wide_sample = join_on_object_id(wide_sample, wide_mer, "_mer") -wide_sample = one_row_per_object(join_on_object_id(wide_sample, wide_halpha, "_halpha")) -wide_spectra = join_on_object_id(wide_sample, spectra_catalog, "_spectra") +saved_region = lsdb.open_catalog("euclid_dr1_ngc6543_spectra") +saved_region.head() ``` -We count the galaxies in the region, without their spectra, as in Section 4.4. -This cell takes about 4 minutes to run on a Fornax server with 61 GiB of memory. +We count the spectra, reading only the `object_id` column. ```{code-cell} ipython3 -%%time -wide_sample_table = load(wide_sample) -print(f"{len(wide_sample_table):,} galaxies in the region") +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 221,140 galaxies of the high-quality sample. -Their spectra are the query `wide_spectra` defined above. -We do not load them here: their spectra are spread over about 400 files of the spectra catalog, and in Section 4.4, loading spectra from 440 files took about 40 minutes. -To load or save them, run `load(wide_spectra)` or `save(wide_spectra, "euclid_dr1_wide_galaxy_spectra")`; Section 8 shows how to save spectra to disk on a smaller region. +The region contains 32,890 spectra, which take 0.2 GB on disk. +`write_catalog` also saves a margin cache, a copy of the spectra just outside each file's area of the sky, which LSDB uses for cross matches. +++ -## 6. Case 2: A List of Positions (Strong Lens Candidates) +## 5. Spectra for a List of Positions +++ @@ -440,8 +286,7 @@ lenses[["Unique_Identifier", "RA_obj", "DEC_obj", "Expert_Grade", "MER_object_id ``` The lens candidates are spread over the whole DR1 area. -To find their spectra, LSDB has to read every file of the spectra catalog that contains a lens candidate, and each file holds tens of thousands of spectra. -For all 15,072 candidates, that is about 2,500 files, which would take hours. +To find their spectra, LSDB has to read every file of the spectra catalog that contains a lens candidate: about 2,500 files for all 15,072 candidates, which would take hours (Section 9.1). Here we keep the candidates within 3 degrees of a position in the Wide Survey with many of them; the same code works for the whole list, given more time. We load the positions into LSDB, keep those in the region, and cross match them against `sir_combined_spectra`. @@ -457,16 +302,20 @@ lens_positions = lsdb.from_dataframe( 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", "") + spectra_catalog, + radius_arcsec=2, + n_neighbors=10, + suffixes=("_lens", ""), + suffix_method="overlapping_columns", ) ``` -This cell takes about 4 minutes to run on a Fornax server with 61 GiB of memory. +This cell takes about 4 minutes to run. ```{code-cell} ipython3 %%time lens_spectra_table = load(lens_spectra) -n_lenses_found = lens_spectra_table["Unique_Identifier_lens"].nunique() +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" @@ -474,6 +323,11 @@ print( ``` 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() +``` Not every spectrum has usable data. Using the `good_bins` function from Section 3, we count the spectra that have no usable wavelength bins at all. @@ -484,13 +338,13 @@ n_empty = sum(n == 0 for n in n_good_bins) print(f"{n_empty:,} of the {len(lens_spectra_table):,} spectra have no usable bins") ``` -[TODO] Give the number of spectra with no usable bins. +Of the 317 spectra, 13 have no usable bins. -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. +In Section 6.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: A List of Object IDs +## 6. Spectra for a List of Object IDs +++ @@ -498,14 +352,15 @@ When the list contains Euclid object IDs, we can look them up directly, without The lens catalog gives the Euclid MER `object_id` (column `MER_object_id`) of most candidates. `id_search` looks up the IDs in the index table that comes with the catalog collection, which records which file holds each `object_id`, and reads only those files. -We look up the candidates in the same region as in Section 6. +We look up the candidates in the same region as in Section 5. ```{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 [TODO] minutes to run. +This cell takes about 5 minutes to run. +LSDB prints the list of IDs it searches for, and a warning about the estimated size of the files it reads; the result itself is small. ```{code-cell} ipython3 %%time @@ -514,23 +369,27 @@ n_ids_found = id_spectra_table["object_id"].nunique() print(f"{len(id_spectra_table):,} spectra of {n_ids_found:,} lens candidates") ``` -Unlike the cross match in Section 6, `id_search` returns only the spectra of the objects themselves, not of their neighbors. +We find 259 spectra, of 259 of the 260 lens candidates in the region with a MER `object_id`. + +```{code-cell} ipython3 +id_spectra_table[["object_id", "lrange", "spectrum"]].head() +``` -[TODO] Compare the time with Section 6. +Unlike the cross match in Section 5, `id_search` returns only the spectra of the objects themselves, not of their neighbors. +It is not faster than the cross match here (about 5 minutes, compared with about 4), because it also has to read the files of the spectra catalog that hold the objects, after first looking up the IDs in the index table. -### 7.1 A Known Lens: PS1J1821+7130 +### 6.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. From the Euclid spectra, they measure a redshift of 1.366 for the galaxy in the ring, from its H$\alpha$ emission line (their Table 1 and Figure 4). At this redshift, the H$\alpha$ line (rest-frame vacuum wavelength 6,564.6 Å) is observed at $6564.6 \times (1 + 1.366) \approx 15{,}532$ Å, in the red grism. -This lens is also in the lens catalog of Section 6, as `EUCL-DR1-L015763`, with its Euclid `object_id`. +This lens is also in the lens catalog of Section 5, as `EUCL-DR1-L015763`, with its Euclid `object_id`. ```{code-cell} ipython3 known_lens = lenses[lenses["Unique_Identifier"] == "EUCL-DR1-L015763"] -lens_columns = ["Unique_Identifier", "RA_obj", "DEC_obj", "Expert_Grade", "MER_object_id"] -known_lens[lens_columns + ["desi_deflector_specz"]] +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). @@ -562,54 +421,167 @@ ax.legend() plt.show() ``` -The spectrum of the lens galaxy shows a strong emission line at the marked wavelength, where Bergamini et al. (2026) detect the H$\alpha$ emission of the ring in their own extraction of the Euclid data. +The lens galaxy has a red grism spectrum only: PS1J1821+7130 is in the Wide Survey, which is observed with the red grism (Bergamini et al. 2026, Sect. 3). +The gaps in the spectrum are wavelength bins flagged as unusable in the `mask` column, which we do not plot. + +The spectrum shows a strong emission line at the marked wavelength, where Bergamini et al. (2026) detect the H$\alpha$ emission of the ring in their own extraction of the Euclid data. The ring is close to the lens galaxy, so its light is likely included in the lens galaxy's spectrum in this catalog. -[TODO] Check this description against the plot. ++++ -[TODO] Alternative science case: the 13,122 white dwarfs of Pérez-Couto et al. (2026), whose catalog at the CDS includes the Euclid `object_id`, once it is available. +## 7. Spectra for a Catalog Selection +++ -## 8. Case 4: A Region of the Sky +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 the high-quality galaxy sample of [Euclid Collaboration: Le Brun et al. (2026)](https://arxiv.org/abs/2611.17960), Sect. 4.3: 76,002 galaxies in EDF-N, which the paper uses to evaluate the performance of the redshift measurement. +The paper uses EDF-N because, with seven red grism and three blue grism visits, it has the most complete spectral coverage of the three Euclid Deep Fields. + +### 7.1 The selection criteria + +Each criterion is a filter (a "cut") on a column of one of the DR1 catalogs. +The catalogs come from three Euclid processing functions: MER (multi-wavelength mosaics and the catalog of the objects detected in them), SPE (spectroscopic measurements, such as redshifts and emission lines), and SIR (the NISP spectra). +The table below lists the criteria of Sect. 4.3 of the paper, with the reason for each. +The two criteria marked "this notebook" are not stated in Sect. 4.3; they are how we implement the paper's 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, which are unlikely to be at redshift above 0.85. `kron_radius` is in pixels ([MER catalog description](https://euclid.esac.esa.int/dr/dr1/dpdd/merdpd/dpcards/mer_finalcatalog.html)). | +| `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 lines catalog has one row per line, redshift solution, and grism. +The quality flag `spe_line_qual_gf` has three digits, defined in Appendix D of the paper: the first gives the fitting method, the second the quality of the measurement, and the last the grism (1: blue, 2: red, 3: both combined). +The paper selects on the grism and on `spe_line_snr_gf > 0`, not on the quality digit; see the [Euclid DR1 SPE tutorial](../5_Euclid_intro_SPE_catalog.md) for more on this flag. + +[TODO] Test whether also requiring a good second digit (1 or 5) brings the number of galaxies closer to the paper's. +++ -For all spectra in a region around one position, we use a cone search. -Here we take every spectrum within 0.1 degrees of the planetary nebula NGC 6543, in EDF-N, and save them to disk. +### 7.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. +LSDB then applies them while it reads the Parquet files, so it reads and keeps only the rows that pass, instead of loading every row and filtering afterwards. +We also read only the part of the sky around EDF-N, with a cone of 3 degrees around its center, which covers almost all of the field. +The center comes from Table 1 of the [Euclid archive user guide at IRSA (PDF, 0.3 MB)](https://irsa.ipac.caltech.edu/data/Euclid/docs/euclid_archive_at_irsa_user_guide.pdf), as in the [IRSA HATS catalogs with LSDB tutorial](../../techniques-and-tools/irsa-hats-with-lsdb.md). ```{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 +# EDF-N: center 17h58m55.9s +66d01m03.7s, and a radius that covers almost all of the field. +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], + ], ) ``` -This cell takes [TODO] minutes to run. +These cells run quickly, because LSDB does not read any data yet: it only records the queries. + ++++ + +### 7.3 Combine the criteria + +Every Euclid DR1 HATS catalog is partitioned using coordinates calculated from `object_id`, so an object falls in the same part of the sky in every catalog, and LSDB can join the catalogs partition by partition. + +The lines catalog can have more than one H$\alpha$ row for the same galaxy that passes the criteria: for example, one for the measurement in the red grism alone, and one for the measurement that combines both grisms. +The join would then return that galaxy twice, and in the next step it would get its spectra twice. +So after joining the H$\alpha$ rows, we keep only one row per galaxy. +Then we 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. + +### 7.4 Count the galaxies + +First we load only the sample itself, without the spectra, to compare it with the paper. +This reads only small catalog columns, so it is much faster than loading the spectra: it takes about 2 minutes. ```{code-cell} ipython3 %%time -save(region_spectra, "euclid_dr1_ngc6543_spectra") +deep_sample_table = load(deep_sample) +print(f"{len(deep_sample_table):,} galaxies (Euclid Collaboration: Le Brun et al. 2026: 76,002)") ``` +We find 80,432 galaxies, about 6% more than the paper's 76,002. +The paper does not give every detail of its selection (for example, the exact data version), so a small difference is expected. + ```{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") +deep_sample_table[["object_id", "spe_z"]].head() ``` -## 9. A Stacked Spectrum Like Figure 4 of Euclid Collaboration: Le Brun et al. (2026) +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, saving all of them to disk took about 40 minutes, and they took 0.7 GB. +In Section 8 we therefore load the spectra of only part of the sample. + ++++ + +## 8. 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 no single spectrum shows. -Figure 4 of Euclid Collaboration: Le Brun et al. (2026) shows stacked spectra of 4,000 randomly chosen galaxies from their sample (Section 4), made with the Euclid stacking code SpectraPyle ([Euclid Collaboration: Quai et al. 2026](https://arxiv.org/abs/2509.16120)). +Figure 4 of Euclid Collaboration: Le Brun et al. (2026) shows stacked spectra of 4,000 randomly chosen galaxies from their sample (Section 7), made with the Euclid stacking code SpectraPyle ([Euclid Collaboration: Quai et al. 2026](https://arxiv.org/abs/2509.16120)). The paper splits the 4,000 galaxies into four groups by how confident volunteers were in each redshift after looking at the spectra. Those grades are not public, so here we make a single stack of 4,000 galaxies from our sample. -As explained in Section 4.4, loading the spectra of the whole sample takes a long time. +As explained in Section 7.4, loading the spectra of the whole sample takes a long time. A stack does not need galaxies from the whole field, so we take the galaxies of the sample in a small part of EDF-N, whose spectra are in only a few files of the spectra catalog, and choose 4,000 of them at random. We follow the paper's recipe: @@ -622,22 +594,28 @@ We follow the paper's recipe: First we load the spectra of the sample galaxies within 0.6 degrees of the center of EDF-N. This region contains 4,399 galaxies of the sample, whose spectra are in 33 files of the spectra catalog (compared with 440 files for the whole sample). -This cell takes about 4 minutes to run on a Fornax server with 61 GiB of memory. +This cell takes about 5 minutes to run. ```{code-cell} ipython3 %%time stack_region = deep_spectra.cone_search(ra=edfn_ra, dec=edfn_dec, radius_arcsec=0.6 * 3600) -region_spectra_table = load(stack_region) -print(f"{region_spectra_table['object_id'].nunique():,} galaxies in the region") +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. + +```{code-cell} ipython3 +stack_region_table[["object_id", "spe_z", "lrange", "spectrum"]].head() ``` Then we choose 4,000 of these galaxies at random, and keep their spectra. ```{code-cell} ipython3 rng = np.random.default_rng(seed=0) -region_ids = region_spectra_table["object_id"].unique() -stack_ids = rng.choice(region_ids, size=min(4000, len(region_ids)), replace=False) -stack_spectra = region_spectra_table[region_spectra_table["object_id"].isin(stack_ids)] +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") ``` @@ -654,6 +632,7 @@ def normalized_spectrum(spectrum): good = good_bins(spectrum) wavelength = spectrum["wavelength"][good].to_numpy() flux = spectrum["signal"][good].to_numpy() + # Spectra without usable bins, or with a median flux that is not positive, can't be normalized. median = np.median(flux) if flux.size else 0 if median <= 0: return None, None @@ -662,6 +641,7 @@ def normalized_spectrum(spectrum): def resample(wavelength, flux, grid): """Flux on a wavelength grid, NaN outside the spectrum's range.""" + # Linear interpolation; NaN where the grid is outside the spectrum, so those bins don't count. return np.interp(grid, wavelength, flux, left=np.nan, right=np.nan) ``` @@ -675,8 +655,11 @@ for i, (_, row) in enumerate(stack_spectra.iterrows()): if wavelength is not None: resampled[i] = resample(wavelength / (1 + row["spe_z"]), flux, rest_grid) -stack = np.nanmedian(resampled, axis=0) +# 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 stacked spectrum, with the emission lines that the paper identifies in its stacks. @@ -727,19 +710,41 @@ From its visual inspection, the paper finds that about 80% of the redshifts in i +++ -## 10. Summary +## 9. Summary +++ -[TODO] Fill in from the timings above. +The table below summarizes the queries of this notebook, with their run times. + +| Starting point | Result | Time | +|---|---|---| +| Region of 0.1 degrees in radius (Section 4) | 32,890 spectra, saved to disk (0.2 GB) | Less than 1 minute | +| List of 276 positions (Section 5) | 317 spectra | 4 minutes | +| List of 260 object IDs (Section 6) | 259 spectra | 5 minutes | +| Catalog values, Deep Survey (Section 7) | 80,432 galaxies, without their spectra | 2 minutes | +| Stack (Section 8) | 8,002 spectra of 4,000 galaxies | 5 minutes | + +As explained in Section 1.2, the time depends mostly on how many files of the spectra catalog a query reads, rather than on how many spectra it returns. + +### 9.1 Larger queries + +We can use these times to estimate how long larger queries would take. +In our runs, a query took about 5 to 10 seconds for each file of the spectra catalog that it read: about 5 seconds when saving the spectra of the whole sample of Section 7 (440 files in 38.7 minutes), and about 9 seconds for the stack of Section 8 (33 files in about 5 minutes). +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. +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 (5, 10): + 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") +``` -| Case | Starting point | Spectra | Time | Size on disk | -|---|---|---|---|---| -| 1 | Catalog values, Deep Survey (Section 4) | | | | -| 1 | Catalog values, Wide Survey region (Section 5) | | | | -| 2 | List of positions (Section 6) | | | | -| 3 | List of object IDs (Section 7) | | | | -| 4 | Region of the sky (Section 8) | | | | +For example, the full list of 15,072 lens candidates of Section 5 touches about 2,500 files, which would take about 3.5 to 7 hours. +These are rough estimates from our measured times, not measurements. +++ @@ -750,14 +755,13 @@ From its visual inspection, the paper finds that about 80% of the redshifts in i - 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) - Euclid Collaboration: Quai et al. 2026, *Euclid preparation. Predicting star-forming galaxy scaling relations with the spectral stacking code SpectraPyle*, [arXiv:2509.16120](https://arxiv.org/abs/2509.16120) -- Pérez-Couto et al. 2026, *Euclid: Data Release 1 (DR1) -- A deep near-infrared search for low-mass and substellar companions to white dwarfs*, [arXiv:2611.36036](https://arxiv.org/abs/2611.36036) -## About This Notebook +## About this notebook **Updated:** 2026-12-01 **Contact:** [IRSA Helpdesk](https://irsa.ipac.caltech.edu/docs/help_desk.html) -**Runtime:** [TODO] As of the date above, this notebook takes about N minutes to run to completion on Fornax (server size, environment). +**Runtime:** As of the date above, this notebook takes about 25 minutes to run to completion on Fornax, on a server with 61 GiB of memory ([TODO] server type and environment; re-time now that the Wide Survey section, about 4 minutes, is removed). **AI Acknowledgement:** This tutorial was developed with the assistance of AI tools. From 28f77702a9da9ebbfc21c5c60b360c01e499a182 Mon Sep 17 00:00:00 2001 From: DeekshaMohanty Date: Wed, 2 Dec 2026 11:10:08 -0500 Subject: [PATCH 10/19] Updating notebook runtimes and other instruction changes --- .../2-euclid-dr1-hats-bulk-spectra.md | 68 +++++++++---------- 1 file changed, 33 insertions(+), 35 deletions(-) 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 index 3541788e..e89cff39 100644 --- a/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md +++ b/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md @@ -52,12 +52,12 @@ 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: -| Starting point | Example | Section | -|---|---|---| -| A region of the sky | All spectra around the planetary nebula NGC 6543 | 4 | -| A list of positions | The strong lens candidates of Euclid Collaboration: Lines et al. (2026) | 5 | -| A list of object IDs | The same lens candidates, by their Euclid object ID | 6 | -| Catalog values | The high-quality galaxy sample of Euclid Collaboration: Le Brun et al. (2026) | 7 | +| Case | Starting point | Example | Section | +|---|---|---|---| +| 1 | A region of the sky | All spectra around the planetary nebula NGC 6543 | 4 | +| 2 | A list of positions | The strong lens candidates of Euclid Collaboration: Lines et al. (2026) | 5 | +| 3 | A list of object IDs | The same lens candidates, by their Euclid object ID | 6 | +| 4 | Catalog values | The high-quality galaxy sample of Euclid Collaboration: Le Brun et al. (2026) | 7 | In Section 8, we use the spectra from Section 7 to make a stacked spectrum like Figure 4 of Euclid Collaboration: Le Brun et al. (2026). @@ -75,7 +75,7 @@ The cross match in Section 5 is different: it returns the spectra of all objects ### 1.2 Runtime Several cells in this notebook can take several minutes to run. -They are marked in the text above them, with the time they took on Fornax, on a server with 61 GiB of memory ([TODO] server type and environment). +They are marked in the text above them, with the time they took on Fornax, using Server Type: 'Large' (64 GB RAM, 16 CPUs) ([TODO] environment). 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. @@ -87,6 +87,8 @@ This notebook also saves a catalog of spectra to local disk (about 0.2 GB, in Se ## 2. Imports +[TODO] Name the Fornax environment to use. In the Fornax run of 2026-12-01, the `python3` kernel (`/opt/envs/python3`) did not have LSDB, so the `%pip install` line below had to be uncommented; either name an environment that has LSDB, or uncomment the line. + ```{code-cell} ipython3 # # Uncomment the next line to install dependencies if needed. # %pip install "lsdb>=0.8.1" "dask[distributed]" matplotlib numpy pandas s3fs @@ -216,7 +218,7 @@ def disk_size_gb(path): return sum(file.stat().st_size for file in Path(path).rglob("*") if file.is_file()) / 1e9 ``` -## 4. Spectra in a Region of the Sky +## 4. Case 1: Spectra in a Region of the Sky +++ @@ -230,7 +232,7 @@ region_spectra = spectra_catalog.cone_search( ) ``` -This cell takes less than a minute to run. +This cell takes about 1 minute to run. ```{code-cell} ipython3 %%time @@ -258,12 +260,12 @@ The region contains 32,890 spectra, which take 0.2 GB on disk. +++ -## 5. Spectra for a List of Positions +## 5. Case 2: Spectra for a List of Positions +++ In this case, we start from a published list of positions. -[Euclid Collaboration: Lines et al. (2026)](https://arxiv.org/abs/2611.15883) found 26,662 strong gravitational lens candidates in Euclid DR1 by visual inspection, and published them on Zenodo. +[Euclid Collaboration: Lines et al. (2026)](https://arxiv.org/abs/2611.15883) visually inspected and graded 26,662 possible strong gravitational lenses in Euclid DR1, and published the catalog on Zenodo. A strong lens is a massive galaxy (the deflector) that bends the light of a more distant galaxy behind it into arcs or multiple images, typically within about 1 arcsecond of the deflector. Measuring the redshifts of the deflector and of the lensed source needs their spectra; [Euclid Collaboration: Bergamini et al. (2026)](https://arxiv.org/abs/2611.15891) show that this is possible with the Euclid NISP spectra. @@ -286,7 +288,7 @@ lenses[["Unique_Identifier", "RA_obj", "DEC_obj", "Expert_Grade", "MER_object_id ``` The lens candidates are spread over the whole DR1 area. -To find their spectra, LSDB has to read every file of the spectra catalog that contains a lens candidate: about 2,500 files for all 15,072 candidates, which would take hours (Section 9.1). +To find their spectra, LSDB has to read every file of the spectra catalog that contains a lens candidate, which for all 15,072 candidates would take hours (Section 9.1). Here we keep the candidates within 3 degrees of a position in the Wide Survey with many of them; the same code works for the whole list, given more time. We load the positions into LSDB, keep those in the region, and cross match them against `sir_combined_spectra`. @@ -310,7 +312,7 @@ lens_spectra = lens_region.crossmatch( ) ``` -This cell takes about 4 minutes to run. +This cell takes about 5 minutes to run. ```{code-cell} ipython3 %%time @@ -344,7 +346,7 @@ In Section 6.1, we look at the spectrum of one of these lens candidates that was +++ -## 6. Spectra for a List of Object IDs +## 6. Case 3: Spectra for a List of Object IDs +++ @@ -359,7 +361,7 @@ lens_object_ids = lens_region_table["MER_object_id"].dropna().astype("int64").to print(f"{len(lens_object_ids):,} lens candidates in the region with a MER object_id") ``` -This cell takes about 5 minutes to run. +This cell takes about 6 minutes to run. LSDB prints the list of IDs it searches for, and a warning about the estimated size of the files it reads; the result itself is small. ```{code-cell} ipython3 @@ -376,7 +378,7 @@ id_spectra_table[["object_id", "lrange", "spectrum"]].head() ``` Unlike the cross match in Section 5, `id_search` returns only the spectra of the objects themselves, not of their neighbors. -It is not faster than the cross match here (about 5 minutes, compared with about 4), because it also has to read the files of the spectra catalog that hold the objects, after first looking up the IDs in the index table. +It is not faster than the cross match here (about 6 minutes, compared with about 5), because it also has to read the files of the spectra catalog that hold the objects, after first looking up the IDs in the index table. ### 6.1 A known lens: PS1J1821+7130 @@ -424,12 +426,9 @@ plt.show() The lens galaxy has a red grism spectrum only: PS1J1821+7130 is in the Wide Survey, which is observed with the red grism (Bergamini et al. 2026, Sect. 3). The gaps in the spectrum are wavelength bins flagged as unusable in the `mask` column, which we do not plot. -The spectrum shows a strong emission line at the marked wavelength, where Bergamini et al. (2026) detect the H$\alpha$ emission of the ring in their own extraction of the Euclid data. -The ring is close to the lens galaxy, so its light is likely included in the lens galaxy's spectrum in this catalog. - +++ -## 7. Spectra for a Catalog Selection +## 7. Case 4: Spectra for a Catalog Selection +++ @@ -469,11 +468,11 @@ The paper selects on the grism and on `spe_line_snr_gf > 0`, not on the quality We pass the criteria to `lsdb.open_catalog` as `filters`, a list of `[column, operator, value]` conditions that must all be true. LSDB then applies them while it reads the Parquet files, so it reads and keeps only the rows that pass, instead of loading every row and filtering afterwards. -We also read only the part of the sky around EDF-N, with a cone of 3 degrees around its center, which covers almost all of the field. +We also read only the part of the sky within 3 degrees of the center of EDF-N. The center comes from Table 1 of the [Euclid archive user guide at IRSA (PDF, 0.3 MB)](https://irsa.ipac.caltech.edu/data/Euclid/docs/euclid_archive_at_irsa_user_guide.pdf), as in the [IRSA HATS catalogs with LSDB tutorial](../../techniques-and-tools/irsa-hats-with-lsdb.md). ```{code-cell} ipython3 -# EDF-N: center 17h58m55.9s +66d01m03.7s, and a radius that covers almost all of the field. +# 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) @@ -549,7 +548,7 @@ For each join, LSDB prints a table of the columns it renamed because they are in ### 7.4 Count the galaxies First we load only the sample itself, without the spectra, to compare it with the paper. -This reads only small catalog columns, so it is much faster than loading the spectra: it takes about 2 minutes. +This reads only small catalog columns, so it is much faster than loading the spectra: it takes about 2.5 minutes. ```{code-cell} ipython3 %%time @@ -558,7 +557,7 @@ print(f"{len(deep_sample_table):,} galaxies (Euclid Collaboration: Le Brun et al ``` We find 80,432 galaxies, about 6% more than the paper's 76,002. -The paper does not give every detail of its selection (for example, the exact data version), so a small difference is expected. +We have not found the cause of the difference. ```{code-cell} ipython3 deep_sample_table[["object_id", "spe_z"]].head() @@ -594,7 +593,7 @@ We follow the paper's recipe: First we load the spectra of the sample galaxies within 0.6 degrees of the center of EDF-N. This region contains 4,399 galaxies of the sample, whose spectra are in 33 files of the spectra catalog (compared with 440 files for the whole sample). -This cell takes about 5 minutes to run. +This cell takes about 5.5 minutes to run. ```{code-cell} ipython3 %%time @@ -716,20 +715,20 @@ From its visual inspection, the paper finds that about 80% of the redshifts in i The table below summarizes the queries of this notebook, with their run times. -| Starting point | Result | Time | -|---|---|---| -| Region of 0.1 degrees in radius (Section 4) | 32,890 spectra, saved to disk (0.2 GB) | Less than 1 minute | -| List of 276 positions (Section 5) | 317 spectra | 4 minutes | -| List of 260 object IDs (Section 6) | 259 spectra | 5 minutes | -| Catalog values, Deep Survey (Section 7) | 80,432 galaxies, without their spectra | 2 minutes | -| Stack (Section 8) | 8,002 spectra of 4,000 galaxies | 5 minutes | +| Case | Starting point | Result | Time | +|---|---|---|---| +| 1 | Region of 0.1 degrees in radius (Section 4) | 32,890 spectra, saved to disk (0.2 GB) | 1 minute | +| 2 | List of 276 positions (Section 5) | 317 spectra | 5 minutes | +| 3 | List of 260 object IDs (Section 6) | 259 spectra | 6 minutes | +| 4 | Catalog values, Deep Survey (Section 7) | 80,432 galaxies, without their spectra | 2.5 minutes | +| | Stack (Section 8) | 8,002 spectra of 4,000 galaxies | 5.5 minutes | As explained in Section 1.2, the time depends mostly on how many files of the spectra catalog a query reads, rather than on how many spectra it returns. ### 9.1 Larger queries We can use these times to estimate how long larger queries would take. -In our runs, a query took about 5 to 10 seconds for each file of the spectra catalog that it read: about 5 seconds when saving the spectra of the whole sample of Section 7 (440 files in 38.7 minutes), and about 9 seconds for the stack of Section 8 (33 files in about 5 minutes). +In our runs, a query took about 5 to 10 seconds for each file of the spectra catalog that it read: about 5 seconds when saving the spectra of the whole sample of Section 7 (440 files in 38.7 minutes), and about 10 seconds for the stack of Section 8 (33 files in about 5.5 minutes). 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. @@ -743,7 +742,6 @@ for seconds_per_file in (5, 10): print(f"At {seconds_per_file} seconds per file, reading all of them would take about {hours:.0f} hours") ``` -For example, the full list of 15,072 lens candidates of Section 5 touches about 2,500 files, which would take about 3.5 to 7 hours. These are rough estimates from our measured times, not measurements. +++ @@ -762,6 +760,6 @@ These are rough estimates from our measured times, not measurements. **Contact:** [IRSA Helpdesk](https://irsa.ipac.caltech.edu/docs/help_desk.html) -**Runtime:** As of the date above, this notebook takes about 25 minutes to run to completion on Fornax, on a server with 61 GiB of memory ([TODO] server type and environment; re-time now that the Wide Survey section, about 4 minutes, is removed). +**Runtime:** As of the date above, this notebook takes about 23 minutes to run to completion on Fornax using Server Type: 'Large' (64 GB RAM, 16 CPUs) ([TODO] environment). **AI Acknowledgement:** This tutorial was developed with the assistance of AI tools. From 11eb15f57bc3e498cf17287dde2d40a29b343462 Mon Sep 17 00:00:00 2001 From: DeekshaMohanty Date: Thu, 3 Dec 2026 11:51:56 -0500 Subject: [PATCH 11/19] More fix-ups to the narrative --- .../2-euclid-dr1-hats-bulk-spectra.md | 179 ++++++++++-------- 1 file changed, 98 insertions(+), 81 deletions(-) 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 index e89cff39..8295dfac 100644 --- a/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md +++ b/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md @@ -10,14 +10,14 @@ kernelspec: language: python name: python3 authors: - - name: Deeksha Mohanty + - 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 Euclid DR1 combined 1D spectra, and how long these queries take. +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. +++ @@ -25,11 +25,11 @@ This tutorial shows how to get the spectra of thousands of Euclid DR1 objects at In this tutorial, we will: -- Get all the spectra in a region of the sky and save them to disk. -- Get the spectra of a list of objects, by position or by Euclid object ID. -- Select galaxies by their catalog values and get their spectra. +- Get the spectra of all objects in a region of the sky, save them to disk, and compare the time with getting them one at a time. +- 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. -- Measure how long these queries take, and estimate how long larger ones would take. +- See how long each of these queries takes, and estimate how long larger ones would take. +++ @@ -43,8 +43,8 @@ the spectra are packed into FITS (Flexible Image Transport System) files with on 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 (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 (Large Survey DataBase). +[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`. 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. @@ -57,7 +57,7 @@ This notebook covers four starting points: | 1 | A region of the sky | All spectra around the planetary nebula NGC 6543 | 4 | | 2 | A list of positions | The strong lens candidates of Euclid Collaboration: Lines et al. (2026) | 5 | | 3 | A list of object IDs | The same lens candidates, by their Euclid object ID | 6 | -| 4 | Catalog values | The high-quality galaxy sample of Euclid Collaboration: Le Brun et al. (2026) | 7 | +| 4 | Properties of the objects, from other DR1 catalogs | The high-quality galaxy sample of Euclid Collaboration: Le Brun et al. (2026) | 7 | In Section 8, we use the spectra from Section 7 to make a stacked spectrum like Figure 4 of Euclid Collaboration: Le Brun et al. (2026). @@ -65,40 +65,41 @@ In Section 8, we use the spectra from Section 7 to make a stacked spectrum like ### 1.1 Duplicate object IDs -As described in the introduction tutorial, `object_id` alone usually does not identify a unique row. -In `sir_combined_spectra`, an object can have a red grism spectrum (`lrange` = `RGS`), a blue grism spectrum (`BGS`), or both, and can have more than one spectrum with the same `lrange`. -The methods in Sections 4, 6, and 7 return every spectrum of each selected object. -The cross match in Section 5 is different: it returns the spectra of all objects near each position, up to a maximum number per position. +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 -Several cells in this notebook can take several minutes to run. -They are marked in the text above them, with the time they took on Fornax, using Server Type: 'Large' (64 GB RAM, 16 CPUs) ([TODO] environment). +This notebook takes about 23 minutes to run on Fornax, using Server Type: 'Large' (64 GB RAM, 16 CPUs) ([TODO] environment). +The text above each slow cell gives the time it took. 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, even when only a few of them are needed, so the time depends mostly on how many files a query reads, rather than on how many spectra it returns. +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 also saves a catalog of spectra to local disk (about 0.2 GB, in Section 4). +This notebook saves a catalog of spectra to local disk (about 0.2 GB, in Section 4). +++ ## 2. Imports -[TODO] Name the Fornax environment to use. In the Fornax run of 2026-12-01, the `python3` kernel (`/opt/envs/python3`) did not have LSDB, so the `%pip install` line below had to be uncommented; either name an environment that has LSDB, or uncomment the line. +[TODO] Name the Fornax environment to use. In my Fornax run, the `python3` kernel did not have LSDB, so I installed the packages with the `%pip install` line below. ```{code-cell} ipython3 # # Uncomment the next line to install dependencies if needed. -# %pip install "lsdb>=0.8.1" "dask[distributed]" matplotlib numpy pandas s3fs +# %pip install astropy "astroquery>=0.4.10" "lsdb>=0.8.1" "dask[distributed]" matplotlib numpy pandas s3fs ``` ```{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 pathlib import Path # Size of the saved catalogs @@ -106,17 +107,15 @@ 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 ``` -We use a color-blind friendly color cycle for all the plots in this notebook. - -```{code-cell} ipython3 -plt.style.use("tableau-colorblind10") -``` - ## 3. Catalog Paths and Helper Functions +++ @@ -141,8 +140,10 @@ spectra_catalog = lsdb.open_catalog( The helper functions below do five things: -- Join two catalogs on `object_id`. LSDB adds a suffix to the names of the columns that are in both catalogs (here, `object_id` and the position columns); we add it only to the second catalog's columns. -- Keep one row per object. +- Join two catalogs on `object_id`, to combine columns or criteria from different catalogs (Section 7). + Both catalogs have the columns `object_id`, `ra_from_object_id`, and `dec_from_object_id`, with the same values for a matched row, and LSDB needs the two copies to have different names. + We keep the names of the first catalog (the one we join to) and add a suffix, such as `_quality`, to the names of the second. +- Keep one row per object, for a join that returns the same object more than once (Section 7.3). - Load a query result into memory, or save it to a local HATS catalog, using a Dask client to run the work in parallel on a few workers, with the memory of the machine shared between them. A link to the Dask dashboard, where you can follow the progress, is printed when the client starts. - Find the usable wavelength bins of a spectrum. The `mask` column of a spectrum is a set of quality flags for each bin. @@ -222,7 +223,7 @@ def disk_size_gb(path): +++ -For all spectra in a region around one position, we use a cone search. +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 @@ -258,18 +259,47 @@ print(f"{len(region_ids):,} spectra, {disk_size_gb('euclid_dr1_ngc6543_spectra') The region contains 32,890 spectra, which take 0.2 GB on disk. `write_catalog` also saves a margin cache, a copy of the spectra just outside each file's area of the sky, which LSDB uses for cross matches. +### 4.1 Comparison with spectrumDM + +To compare, we get a few 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 spectrumDM request. +We time only the spectrumDM requests, and scale the time to all the spectra of the region. + +```{code-cell} ipython3 +SPECTRUMDM_URL = "https://irsacloud.ipac.caltech.edu/api/spectrumdm/convert/" + +test_ids = ", ".join(str(object_id) for object_id in region_ids.unique()[:5]) +query = f"SELECT objectid, path, hdu FROM euclid.objectid_spectrafile_association_dr1 WHERE objectid IN ({test_ids})" +spectrum_files = Irsa.query_tap(query).to_table() + +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): + warnings.simplefilter("ignore", UnitsWarning) + for path, hdu in zip(spectrum_files["path"], spectrum_files["hdu"]): + QTable.read(f"{SPECTRUMDM_URL}{path}?dataset_id=euclid_combspec_dr1&hdu={hdu}") +seconds_per_spectrum = (time.perf_counter() - start) / len(spectrum_files) + +hours = len(region_ids) * seconds_per_spectrum / 3600 +print(f"spectrumDM: {seconds_per_spectrum:.1f} seconds per spectrum ({len(spectrum_files)} spectra)") +print(f"All {len(region_ids):,} spectra of the region, one request at a time: about {hours:.1f} hours") +``` + +[TODO] Result sentence after the Fornax run, compared with the 1 minute of the HATS query. + +++ ## 5. Case 2: Spectra for a List of Positions +++ -In this case, we start from a published list of positions. -[Euclid Collaboration: Lines et al. (2026)](https://arxiv.org/abs/2611.15883) visually inspected and graded 26,662 possible strong gravitational lenses in Euclid DR1, and published the catalog on Zenodo. -A strong lens is a massive galaxy (the deflector) that bends the light of a more distant galaxy behind it into arcs or multiple images, typically within about 1 arcsecond of the deflector. -Measuring the redshifts of the deflector and of the lensed source needs their spectra; [Euclid Collaboration: Bergamini et al. (2026)](https://arxiv.org/abs/2611.15891) show that this is possible with the Euclid NISP spectra. +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). +A strong lens is a massive galaxy (the deflector) whose gravity bends the light of a more distant galaxy behind it into arcs or multiple images, typically within about 1 arcsecond of the deflector (the paper gives a typical Einstein radius of 0.85 arcseconds). +The spectra can give the redshifts of the deflector and of the lensed galaxy. +Experts inspected 26,662 candidates by eye and graded each one A (sure lens), B (probable lens), C (possible lens), or X (not a lens), as defined in the paper and in the README of the catalog. -We download the catalog (about 4 MB, a zip file with the catalog and a README) and keep the grade A ("sure lens") and grade B ("probable lens") candidates. +We download the catalog from Zenodo (about 4 MB, a zip file with the catalog and its README) 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" @@ -287,13 +317,14 @@ print(f"{len(lenses):,} grade A and B lens candidates") lenses[["Unique_Identifier", "RA_obj", "DEC_obj", "Expert_Grade", "MER_object_id"]].head() ``` -The lens candidates are spread over the whole DR1 area. -To find their spectra, LSDB has to read every file of the spectra catalog that contains a lens candidate, which for all 15,072 candidates would take hours (Section 9.1). -Here we keep the candidates within 3 degrees of a position in the Wide Survey with many of them; the same code works for the whole list, given more time. +The 15,072 candidates are spread over the whole DR1 area, so a cross match with all of them would have to read a large part of the spectra catalog, which would take hours (Section 9.1). +To keep this notebook short, we use only the candidates within 3 degrees of one position in the Wide Survey; the same code works for the whole list. -We load the positions into LSDB, keep those in the region, and cross match them against `sir_combined_spectra`. -We use a radius of 2 arcseconds and allow up to 10 spectra per lens. -This returns the spectra of the deflector, and of any nearby objects that the MER catalog detected separately, which can include lensed images; arcs that were not detected as separate objects have no spectrum of their own. +We load the positions into LSDB, keep those in the region, and cross match them with `sir_combined_spectra`. +The positions are the centers of the deflectors. +We use a radius of 2 arcseconds, larger than the Einstein radius of most lenses, and allow up to 10 spectra per lens. +A cross match finds spectra by position, so it returns the spectrum of the deflector and also the spectra of other objects within 2 arcseconds, which can include lensed images. +The catalog has spectra only for objects detected in the MER catalog, so a lensed arc that was not detected as a separate object has no spectrum of its own. ```{code-cell} ipython3 lens_positions = lsdb.from_dataframe( @@ -331,17 +362,6 @@ Each row is one spectrum, with the lens candidate it was matched to (`Unique_Ide lens_spectra_table[["Unique_Identifier", "object_id", "lrange", "_dist_arcsec", "spectrum"]].head() ``` -Not every spectrum has usable data. -Using the `good_bins` function from Section 3, we count the spectra that have no usable wavelength bins at all. - -```{code-cell} ipython3 -n_good_bins = [good_bins(row["spectrum"]).sum() for _, row in lens_spectra_table.iterrows()] -n_empty = sum(n == 0 for n in n_good_bins) -print(f"{n_empty:,} of the {len(lens_spectra_table):,} spectra have no usable bins") -``` - -Of the 317 spectra, 13 have no usable bins. - In Section 6.1, we look at the spectrum of one of these lens candidates that was studied in detail in a Euclid DR1 paper. +++ @@ -350,9 +370,10 @@ In Section 6.1, we look at the spectrum of one of these lens candidates that was +++ -When the list contains Euclid object IDs, we can look them up directly, without a cross match. -The lens catalog gives the Euclid MER `object_id` (column `MER_object_id`) of most candidates. -`id_search` looks up the IDs in the index table that comes with the catalog collection, which records which file holds each `object_id`, and reads only those files. +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 5 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 5. @@ -362,30 +383,33 @@ print(f"{len(lens_object_ids):,} lens candidates in the region with a MER object ``` This cell takes about 6 minutes to run. -LSDB prints the list of IDs it searches for, and a warning about the estimated size of the files it reads; the result itself is small. +`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 -id_spectra_table = load(spectra_catalog.id_search(values={"object_id": lens_object_ids})) +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:,} lens candidates") +print(f"{len(id_spectra_table):,} spectra of {n_ids_found:,} of the {len(lens_object_ids):,} lens candidates") ``` -We find 259 spectra, of 259 of the 260 lens candidates in the region with a MER `object_id`. +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() ``` -Unlike the cross match in Section 5, `id_search` returns only the spectra of the objects themselves, not of their neighbors. -It is not faster than the cross match here (about 6 minutes, compared with about 5), because it also has to read the files of the spectra catalog that hold the objects, after first looking up the IDs in the index table. +Sections 5 and 6 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 (about 6 minutes, compared with about 5), because it reads the same kind of files whole, after looking up the IDs in the index table. ### 6.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. -From the Euclid spectra, they measure a redshift of 1.366 for the galaxy in the ring, from its H$\alpha$ emission line (their Table 1 and Figure 4). -At this redshift, the H$\alpha$ line (rest-frame vacuum wavelength 6,564.6 Å) is observed at $6564.6 \times (1 + 1.366) \approx 15{,}532$ Å, in the red grism. +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 5, as `EUCL-DR1-L015763`, with its Euclid `object_id`. @@ -408,7 +432,7 @@ We plot the spectra, with the flux multiplied by the scale factor $10^{-16}$ (FI ```{code-cell} ipython3 FSCALE = 1e-16 -ring_halpha = 6564.6 * (1 + 1.366) # Angstrom +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(): @@ -423,19 +447,19 @@ ax.legend() plt.show() ``` -The lens galaxy has a red grism spectrum only: PS1J1821+7130 is in the Wide Survey, which is observed with the red grism (Bergamini et al. 2026, Sect. 3). -The gaps in the spectrum are wavelength bins flagged as unusable in the `mask` column, which we do not plot. +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. +++ -## 7. Case 4: Spectra for a Catalog Selection +## 7. 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 the high-quality galaxy sample of [Euclid Collaboration: Le Brun et al. (2026)](https://arxiv.org/abs/2611.17960), Sect. 4.3: 76,002 galaxies in EDF-N, which the paper uses to evaluate the performance of the redshift measurement. -The paper uses EDF-N because, with seven red grism and three blue grism visits, it has the most complete spectral coverage of the three Euclid Deep Fields. +The paper uses EDF-N because, with seven complete red grism visits and three blue grism visits, it has the most complete spectral coverage of the three Euclid Deep Fields (Sects. 1 and 4.3). ### 7.1 The selection criteria @@ -460,8 +484,6 @@ The lines catalog has one row per line, redshift solution, and grism. The quality flag `spe_line_qual_gf` has three digits, defined in Appendix D of the paper: the first gives the fitting method, the second the quality of the measurement, and the last the grism (1: blue, 2: red, 3: both combined). The paper selects on the grism and on `spe_line_snr_gf > 0`, not on the quality digit; see the [Euclid DR1 SPE tutorial](../5_Euclid_intro_SPE_catalog.md) for more on this flag. -[TODO] Test whether also requiring a good second digit (1 or 5) brings the number of galaxies closer to the paper's. - +++ ### 7.2 Open the catalogs with the criteria @@ -469,7 +491,7 @@ The paper selects on the grism and on `spe_line_snr_gf > 0`, not on the quality We pass the criteria to `lsdb.open_catalog` as `filters`, a list of `[column, operator, value]` conditions that must all be true. LSDB then applies them while it reads the Parquet files, so it reads and keeps only the rows that pass, instead of loading every row and filtering afterwards. We also read only the part of the sky within 3 degrees of the center of EDF-N. -The center comes from Table 1 of the [Euclid archive user guide at IRSA (PDF, 0.3 MB)](https://irsa.ipac.caltech.edu/data/Euclid/docs/euclid_archive_at_irsa_user_guide.pdf), as in the [IRSA HATS catalogs with LSDB tutorial](../../techniques-and-tools/irsa-hats-with-lsdb.md). +The center comes 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), as in the [IRSA HATS catalogs with LSDB tutorial](../../techniques-and-tools/irsa-hats-with-lsdb.md). ```{code-cell} ipython3 # EDF-N: center 17h58m55.9s +66d01m03.7s, and a radius of 3 degrees. @@ -557,7 +579,8 @@ print(f"{len(deep_sample_table):,} galaxies (Euclid Collaboration: Le Brun et al ``` We find 80,432 galaxies, about 6% more than the paper's 76,002. -We have not found the cause of the difference. + +[TODO] Question for reviewers: we have not found the cause of this difference. One open point: Sect. 4.3 of the paper introduces `spe_z_prob > 0.94` and `spe_z_rel > 0.05` just before "We then applied these criteria to the full EDF-N catalogue, resulting in a sample of 76 002 objects", so it is not certain that these two criteria are part of the 76,002 selection; we include them. ```{code-cell} ipython3 deep_sample_table[["object_id", "spe_z"]].head() @@ -588,7 +611,7 @@ We follow the paper's recipe: 1. Treat the red and blue grism spectra as separate spectra. 2. Shift each spectrum to the rest frame, the wavelengths that the galaxy emitted, by dividing the observed wavelengths by $1 + z$. 3. Divide each spectrum by its median flux, so that bright galaxies do not dominate. -4. Resample onto a common wavelength grid with 5 Å pixels. +4. Resample onto a common wavelength grid with 5 Å pixels, so that all spectra have values at the same wavelengths. 5. At each wavelength, take the median of all spectra. First we load the spectra of the sample galaxies within 0.6 degrees of the center of EDF-N. @@ -697,15 +720,9 @@ plt.tight_layout() plt.show() ``` -The top panel shows that most spectra cover rest-frame wavelengths between about 4,000 and 9,000 Å; near the edges of the plot, only a few spectra contribute, so the stack is noisy there. - -In the stack, emission lines appear as peaks at the wavelengths marked by the dotted lines, which we placed at the known wavelengths of the lines; nothing was fitted to the data. -The brightest is the H$\alpha$+[N II] complex, as expected for a sample selected for its bright H$\alpha$ line, followed by [O II], H$\beta$, the [O III] doublet, [S II], and the two [S III] lines. -The weaker lines [Ne III], He I, and [O I] are also visible. -These are the lines that the paper identifies in its stacks of galaxies with reliable redshifts (Figure 4). - -The paper (Sect. 4.3) warns that stacking galaxies with wrong redshifts can also produce features at the expected wavelengths, because the noise that misled the redshift measurement gets lined up. -From its visual inspection, the paper finds that about 80% of the redshifts in its sample are correct (Sect. 4.3). +The stack shows the emission lines that the paper finds in its stacks (Figure 4): H$\alpha$+[N II] is the strongest, 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 of the plot, few spectra contribute (top panel), so the stack is noisy there. +The paper (Sect. 4.3) finds by visual inspection that about 80% of the redshifts in its sample are correct; galaxies with wrong redshifts can also add features at the expected wavelengths. +++ @@ -720,7 +737,7 @@ The table below summarizes the queries of this notebook, with their run times. | 1 | Region of 0.1 degrees in radius (Section 4) | 32,890 spectra, saved to disk (0.2 GB) | 1 minute | | 2 | List of 276 positions (Section 5) | 317 spectra | 5 minutes | | 3 | List of 260 object IDs (Section 6) | 259 spectra | 6 minutes | -| 4 | Catalog values, Deep Survey (Section 7) | 80,432 galaxies, without their spectra | 2.5 minutes | +| 4 | Object properties, Deep Survey (Section 7) | 80,432 galaxies, without their spectra | 2.5 minutes | | | Stack (Section 8) | 8,002 spectra of 4,000 galaxies | 5.5 minutes | As explained in Section 1.2, the time depends mostly on how many files of the spectra catalog a query reads, rather than on how many spectra it returns. From 525fee91add00232156ea6a78c78eb85aeed21cd Mon Sep 17 00:00:00 2001 From: DeekshaMohanty Date: Thu, 3 Dec 2026 14:33:58 -0500 Subject: [PATCH 12/19] adding comparison with spectrumdm --- .../2-euclid-dr1-hats-bulk-spectra.md | 220 +++++++++++++----- 1 file changed, 158 insertions(+), 62 deletions(-) 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 index 8295dfac..6ec7c567 100644 --- a/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md +++ b/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md @@ -25,7 +25,8 @@ This tutorial shows how to get the spectra of thousands of Euclid DR1 objects at In this tutorial, we will: -- Get the spectra of all objects in a region of the sky, save them to disk, and compare the time with getting them one at a time. +- 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. @@ -54,12 +55,13 @@ 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 | 4 | -| 2 | A list of positions | The strong lens candidates of Euclid Collaboration: Lines et al. (2026) | 5 | -| 3 | A list of object IDs | The same lens candidates, by their Euclid object ID | 6 | -| 4 | Properties of the objects, from other DR1 catalogs | The high-quality galaxy sample of Euclid Collaboration: Le Brun et al. (2026) | 7 | +| 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 | The high-quality galaxy sample of Euclid Collaboration: Le Brun et al. (2026) | 8 | -In Section 8, we use the spectra from Section 7 to make a stacked spectrum like Figure 4 of Euclid Collaboration: Le Brun et al. (2026). +Before the cases, Section 4 measures how long spectrumDM takes per spectrum, so that each case can compare the two ways. +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). +++ @@ -79,7 +81,7 @@ 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.2 GB, in Section 4). +This notebook saves a catalog of spectra to local disk (about 0.2 GB, in Section 5). +++ @@ -101,6 +103,7 @@ 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 @@ -140,10 +143,10 @@ spectra_catalog = lsdb.open_catalog( The helper functions below do five things: -- Join two catalogs on `object_id`, to combine columns or criteria from different catalogs (Section 7). +- Join two catalogs on `object_id`, to combine columns or criteria from different catalogs (Section 8). Both catalogs have the columns `object_id`, `ra_from_object_id`, and `dec_from_object_id`, with the same values for a matched row, and LSDB needs the two copies to have different names. We keep the names of the first catalog (the one we join to) and add a suffix, such as `_quality`, to the names of the second. -- Keep one row per object, for a join that returns the same object more than once (Section 7.3). +- 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 a local HATS catalog, using a Dask client to run the work in parallel on a few workers, with the memory of the machine shared between them. A link to the Dask dashboard, where you can follow the progress, is printed when the client starts. - Find the usable wavelength bins of a spectrum. The `mask` column of a spectrum is a set of quality flags for each bin. @@ -219,7 +222,80 @@ def disk_size_gb(path): return sum(file.stat().st_size for file in Path(path).rglob("*") if file.is_file()) / 1e9 ``` -## 4. Case 1: Spectra in a Region of the Sky +## 4. Two Ways to Get Many Spectra + ++++ + +Before the four cases, we measure how long IRSA's spectrumDM service takes to return a spectrum, so that each case can compare it with the HATS query. +The two ways scale differently: + +- spectrumDM returns one spectrum per request, so its time grows with the number of spectra. +- LSDB reads whole files of the HATS catalog, so its time grows with the number of files that a query reads, however few spectra it keeps from each file. + +The number of files and the number of spectra are in the catalog's metadata, so we get them without reading any data. + +```{code-cell} ipython3 +n_files = spectra_catalog.npartitions +n_spectra = spectra_catalog.hc_structure.catalog_info.total_rows +print(f"{n_spectra:,} spectra in {n_files:,} files: about {n_spectra / n_files:,.0f} spectra per file") +``` + +To time spectrumDM, we take 90 spectra from IRSA's association table, which gives the file and HDU of each spectrum, and read them the way the [Euclid DR1 SIR 1D spectra tutorial](../3_Euclid_intro_1D_spectra.md) does, with one request per spectrum. +We read 10 of them one request at a time, and the other 80 with 16 requests at a time, as a script that gets many spectra would. + +[TODO] Check with the spectrumDM team that it is OK for every user of this notebook to send 16 requests at a time. + +```{code-cell} ipython3 +SPECTRUMDM_URL = "https://irsacloud.ipac.caltech.edu/api/spectrumdm/convert/" +N_PARALLEL = 16 # spectrumDM requests at a time + +query = "SELECT TOP 90 objectid, path, hdu FROM euclid.objectid_spectrafile_association_dr1" +spectrum_files = Irsa.query_tap(query).to_table() + + +def read_spectrum(path, hdu): + """Read one spectrum with one spectrumDM request.""" + return QTable.read(f"{SPECTRUMDM_URL}{path}?dataset_id=euclid_combspec_dr1&hdu={hdu}") + + +def seconds_per_spectrum(files, n_parallel): + """Average time per spectrum to read the spectra in `files`, with n_parallel requests at a time.""" + start = time.perf_counter() + with ThreadPoolExecutor(max_workers=n_parallel) as pool: + list(pool.map(read_spectrum, files["path"], files["hdu"])) + return (time.perf_counter() - start) / len(files) + + +# 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): + warnings.simplefilter("ignore", UnitsWarning) + seconds_one = seconds_per_spectrum(spectrum_files[:10], n_parallel=1) + seconds_parallel = seconds_per_spectrum(spectrum_files[10:], n_parallel=N_PARALLEL) +print(f"spectrumDM, one request at a time: {seconds_one:.2f} seconds per spectrum") +print(f"spectrumDM, {N_PARALLEL} requests at a time: {seconds_parallel:.2f} seconds per spectrum") +``` + +When we ran this notebook, spectrumDM took about 1.5 seconds per spectrum one request at a time, and about 0.17 seconds per spectrum with 16 requests at a time. +LSDB, with the 2 Dask workers that this notebook uses, took about 5 to 10 seconds for each file it read (Section 10.1). +So LSDB is faster when a query keeps more than a few dozen spectra from each file it reads, and spectrumDM with parallel requests is faster for a few hundred spectra spread over many files. + +The function below uses the measured times to estimate how long spectrumDM would take for the spectra of each case. + +```{code-cell} ipython3 +def duration(seconds): + """A duration as text, in the largest unit that it is at least one of.""" + 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 measured above.""" + print(f"spectrumDM, {n_spectra:,} spectra: about {duration(n_spectra * seconds_one)} one request at a time, or {duration(n_spectra * seconds_parallel)} with {N_PARALLEL} requests at a time") +``` + +## 5. Case 1: Spectra in a Region of the Sky +++ @@ -259,36 +335,20 @@ print(f"{len(region_ids):,} spectra, {disk_size_gb('euclid_dr1_ngc6543_spectra') The region contains 32,890 spectra, which take 0.2 GB on disk. `write_catalog` also saves a margin cache, a copy of the spectra just outside each file's area of the sky, which LSDB uses for cross matches. -### 4.1 Comparison with spectrumDM - -To compare, we get a few 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 spectrumDM request. -We time only the spectrumDM requests, and scale the time to all the spectra of the region. +LSDB got and saved these spectra in about 1 minute, reading the number of files printed below. +With spectrumDM, the same spectra would take much longer: ```{code-cell} ipython3 -SPECTRUMDM_URL = "https://irsacloud.ipac.caltech.edu/api/spectrumdm/convert/" - -test_ids = ", ".join(str(object_id) for object_id in region_ids.unique()[:5]) -query = f"SELECT objectid, path, hdu FROM euclid.objectid_spectrafile_association_dr1 WHERE objectid IN ({test_ids})" -spectrum_files = Irsa.query_tap(query).to_table() - -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): - warnings.simplefilter("ignore", UnitsWarning) - for path, hdu in zip(spectrum_files["path"], spectrum_files["hdu"]): - QTable.read(f"{SPECTRUMDM_URL}{path}?dataset_id=euclid_combspec_dr1&hdu={hdu}") -seconds_per_spectrum = (time.perf_counter() - start) / len(spectrum_files) - -hours = len(region_ids) * seconds_per_spectrum / 3600 -print(f"spectrumDM: {seconds_per_spectrum:.1f} seconds per spectrum ({len(spectrum_files)} spectra)") -print(f"All {len(region_ids):,} spectra of the region, one request at a time: about {hours:.1f} hours") +print(f"LSDB read {region_spectra.npartitions} files of the spectra catalog") +spectrumdm_estimate(len(region_ids)) ``` -[TODO] Result sentence after the Fornax run, compared with the 1 minute of the HATS query. +When we ran this notebook, spectrumDM would have taken about 13 hours one request at a time, or about 1.5 hours with 16 requests at a time. +LSDB is much faster here because the spectra of a small region are in only a few files of the catalog, so it keeps many spectra from each file it reads. +++ -## 5. Case 2: Spectra for a List of Positions +## 6. Case 2: Spectra for a List of Positions +++ @@ -317,7 +377,7 @@ 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 have to read a large part of the spectra catalog, which would take hours (Section 9.1). +The 15,072 candidates are spread over the whole DR1 area, so a cross match with all of them would have to read a large part of the spectra catalog, which would take hours (Section 10.1). To keep this notebook short, we use only the candidates within 3 degrees of one position in the Wide Survey; the same code works for the whole list. We load the positions into LSDB, keep those in the region, and cross match them with `sir_combined_spectra`. @@ -362,20 +422,30 @@ Each row is one spectrum, with the lens candidate it was matched to (`Unique_Ide lens_spectra_table[["Unique_Identifier", "object_id", "lrange", "_dist_arcsec", "spectrum"]].head() ``` -In Section 6.1, we look at the spectrum of one of these lens candidates that was studied in detail in a Euclid DR1 paper. +With spectrumDM, the same spectra would take: + +```{code-cell} ipython3 +spectrumdm_estimate(len(lens_spectra_table)) +``` + +When we ran this notebook, this was about 8 minutes one request at a time, or about 1 minute with 16 requests at a time. +For this case, spectrumDM with parallel requests is faster than LSDB (about 5 minutes): the lens candidates are spread over a region 6 degrees across, and LSDB reads whole files of tens of thousands of spectra to keep the few near each candidate. +spectrumDM also needs object IDs rather than positions, so the positions would first have to be matched with the MER catalog, for example with a TAP query, which this estimate does not include. + +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. +++ -## 6. Case 3: Spectra for a List of Object IDs +## 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 5 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). +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 5. +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() @@ -393,6 +463,7 @@ with contextlib.redirect_stdout(io.StringIO()): 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. @@ -401,17 +472,27 @@ Of the 260 lens candidates with a MER `object_id`, 259 have a spectrum, one each id_spectra_table[["object_id", "lrange", "spectrum"]].head() ``` -Sections 5 and 6 find the spectra of the same lens candidates in two ways. +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 (about 6 minutes, compared with about 5), because it reads the same kind of files whole, after looking up the IDs in the index table. -### 6.1 A known lens: PS1J1821+7130 +With spectrumDM, the spectra found by `id_search` would take: + +```{code-cell} ipython3 +spectrumdm_estimate(len(id_spectra_table)) +``` + +When we ran this notebook, this was about 6 minutes one request at a time, or about 45 seconds with 16 requests at a time. +As in Section 6, spectrumDM with parallel requests is faster for a few hundred spectra spread over many files. +LSDB is the faster way when a query keeps many spectra from each file, as in Sections 5 and 9, and for lists of objects too long for one request per spectrum (Section 10.1). + +### 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 5, as `EUCL-DR1-L015763`, with its Euclid `object_id`. +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"] @@ -452,7 +533,7 @@ The gaps in the spectrum are wavelength bins that `good_bins` marks as unusable +++ -## 7. Case 4: Spectra of Objects Selected by Their Properties +## 8. Case 4: Spectra of Objects Selected by Their Properties +++ @@ -461,7 +542,7 @@ When we don't start with positions or object IDs, but only know what kind of obj As an example, we select the high-quality galaxy sample of [Euclid Collaboration: Le Brun et al. (2026)](https://arxiv.org/abs/2611.17960), Sect. 4.3: 76,002 galaxies in EDF-N, which the paper uses to evaluate the performance of the redshift measurement. The paper uses EDF-N because, with seven complete red grism visits and three blue grism visits, it has the most complete spectral coverage of the three Euclid Deep Fields (Sects. 1 and 4.3). -### 7.1 The selection criteria +### 8.1 The selection criteria Each criterion is a filter (a "cut") on a column of one of the DR1 catalogs. The catalogs come from three Euclid processing functions: MER (multi-wavelength mosaics and the catalog of the objects detected in them), SPE (spectroscopic measurements, such as redshifts and emission lines), and SIR (the NISP spectra). @@ -486,7 +567,7 @@ The paper selects on the grism and on `spe_line_snr_gf > 0`, not on the quality +++ -### 7.2 Open the catalogs with the criteria +### 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. LSDB then applies them while it reads the Parquet files, so it reads and keeps only the rows that pass, instead of loading every row and filtering afterwards. @@ -549,7 +630,7 @@ These cells run quickly, because LSDB does not read any data yet: it only record +++ -### 7.3 Combine the criteria +### 8.3 Combine the criteria Every Euclid DR1 HATS catalog is partitioned using coordinates calculated from `object_id`, so an object falls in the same part of the sky in every catalog, and LSDB can join the catalogs partition by partition. @@ -567,7 +648,7 @@ 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. -### 7.4 Count the galaxies +### 8.4 Count the galaxies First we load only the sample itself, without the spectra, to compare it with the paper. This reads only small catalog columns, so it is much faster than loading the spectra: it takes about 2.5 minutes. @@ -588,22 +669,23 @@ deep_sample_table[["object_id", "spe_z"]].head() 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, saving all of them to disk took about 40 minutes, and they took 0.7 GB. -In Section 8 we therefore load the spectra of only part of the sample. +With the spectrumDM times of Section 4, they would take about 64 hours one request at a time, or about 7 hours with 16 requests at a time. +In Section 9 we therefore load the spectra of only part of the sample. +++ -## 8. Stack Thousands of Spectra +## 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 no single spectrum shows. -Figure 4 of Euclid Collaboration: Le Brun et al. (2026) shows stacked spectra of 4,000 randomly chosen galaxies from their sample (Section 7), made with the Euclid stacking code SpectraPyle ([Euclid Collaboration: Quai et al. 2026](https://arxiv.org/abs/2509.16120)). +Figure 4 of Euclid Collaboration: Le Brun et al. (2026) shows stacked spectra of 4,000 randomly chosen galaxies from their sample (Section 8), made with the Euclid stacking code SpectraPyle ([Euclid Collaboration: Quai et al. 2026](https://arxiv.org/abs/2509.16120)). The paper splits the 4,000 galaxies into four groups by how confident volunteers were in each redshift after looking at the spectra. Those grades are not public, so here we make a single stack of 4,000 galaxies from our sample. -As explained in Section 7.4, loading the spectra of the whole sample takes a long time. +As explained in Section 8.4, loading the spectra of the whole sample takes a long time. A stack does not need galaxies from the whole field, so we take the galaxies of the sample in a small part of EDF-N, whose spectra are in only a few files of the spectra catalog, and choose 4,000 of them at random. We follow the paper's recipe: @@ -639,8 +721,12 @@ 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") +spectrumdm_estimate(len(stack_spectra)) ``` +LSDB loaded the spectra of all the galaxies in the region in about 5.5 minutes. +When we ran this notebook, spectrumDM would have taken about 3 hours one request at a time, or about 20 minutes with 16 requests at a time, for only the spectra of the 4,000 galaxies we keep. + The helper functions below normalize one spectrum and resample it; click on the cell to expand it. ```{code-cell} ipython3 @@ -726,26 +812,28 @@ The paper (Sect. 4.3) finds by visual inspection that about 80% of the redshifts +++ -## 9. Summary +## 10. Summary +++ -The table below summarizes the queries of this notebook, with their run times. +The table below summarizes the queries of this notebook, with their run times with LSDB, and the times that spectrumDM would take for the same spectra, estimated from the times per spectrum of Section 4. -| Case | Starting point | Result | Time | -|---|---|---|---| -| 1 | Region of 0.1 degrees in radius (Section 4) | 32,890 spectra, saved to disk (0.2 GB) | 1 minute | -| 2 | List of 276 positions (Section 5) | 317 spectra | 5 minutes | -| 3 | List of 260 object IDs (Section 6) | 259 spectra | 6 minutes | -| 4 | Object properties, Deep Survey (Section 7) | 80,432 galaxies, without their spectra | 2.5 minutes | -| | Stack (Section 8) | 8,002 spectra of 4,000 galaxies | 5.5 minutes | +| Case | Starting point | Result | LSDB (2 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.2 GB) | 1 minute | 13 hours / 1.5 hours | +| 2 | List of 276 positions (Section 6) | 317 spectra | 5 minutes | 8 minutes / 1 minute | +| 3 | List of 260 object IDs (Section 7) | 259 spectra | 6 minutes | 6 minutes / 45 seconds | +| 4 | Object properties, Deep Survey (Section 8) | 80,432 galaxies, without their spectra | 2.5 minutes | | +| | Stack (Section 9) | 8,002 spectra of 4,000 galaxies | 5.5 minutes | 3 hours / 20 minutes | -As explained in Section 1.2, the time depends mostly on how many files of the spectra catalog a query reads, rather than on how many spectra it returns. +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. +LSDB is much faster when a query keeps many spectra from each file it reads (Case 1 and the stack). +For a few hundred spectra spread over many files (Cases 2 and 3), spectrumDM with parallel requests is faster. -### 9.1 Larger queries +### 10.1 Larger queries We can use these times to estimate how long larger queries would take. -In our runs, a query took about 5 to 10 seconds for each file of the spectra catalog that it read: about 5 seconds when saving the spectra of the whole sample of Section 7 (440 files in 38.7 minutes), and about 10 seconds for the stack of Section 8 (33 files in about 5.5 minutes). +In our runs, a query took about 5 to 10 seconds for each file of the spectra catalog that it read: about 5 seconds when saving the spectra of the whole sample of Section 8 (440 files in 38.7 minutes), and about 10 seconds for the stack of Section 9 (33 files in about 5.5 minutes). 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. @@ -759,6 +847,14 @@ for seconds_per_file in (5, 10): print(f"At {seconds_per_file} seconds per file, reading all of them would take about {hours:.0f} hours") ``` +With spectrumDM, a million spectra would take: + +```{code-cell} ipython3 +spectrumdm_estimate(1_000_000) +``` + +When we ran this notebook, this was about 17 days one request at a time, or about 2 days with 16 requests at a time, compared with 5 to 10 hours for LSDB to read every file of the catalog. + These are rough estimates from our measured times, not measurements. +++ From a5b93d25170d65c201cba82b4a22cf5d8c4d85cd Mon Sep 17 00:00:00 2001 From: DeekshaMohanty Date: Thu, 3 Dec 2026 15:59:31 -0500 Subject: [PATCH 13/19] adding spectrumDM vs HATS comparison --- .../2-euclid-dr1-hats-bulk-spectra.md | 104 ++++++++---------- 1 file changed, 47 insertions(+), 57 deletions(-) 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 index 6ec7c567..2c544f23 100644 --- a/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md +++ b/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md @@ -60,7 +60,7 @@ This notebook covers four starting points: | 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 | The high-quality galaxy sample of Euclid Collaboration: Le Brun et al. (2026) | 8 | -Before the cases, Section 4 measures how long spectrumDM takes per spectrum, so that each case can compare the two ways. +Section 4 compares the HATS catalog with spectrumDM on the same spectra, and each case then gives the time of both. 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). +++ @@ -141,7 +141,7 @@ spectra_catalog = lsdb.open_catalog( ) ``` -The helper functions below do five things: +The helper functions below do six things: - Join two catalogs on `object_id`, to combine columns or criteria from different catalogs (Section 8). Both catalogs have the columns `object_id`, `ra_from_object_id`, and `dec_from_object_id`, with the same values for a matched row, and LSDB needs the two copies to have different names. @@ -152,6 +152,7 @@ The helper functions below do five things: The `mask` column of a spectrum is a set of quality flags for each bin. As in the [Euclid DR1 SIR 1D spectra tutorial](../3_Euclid_intro_1D_spectra.md), we consider a bin unusable if its `mask` value is odd (flag `NOT_USE`: invalid flux) or is 64 or more (flag `ABS_FLUX`: suspicious flux calibration); the other flags are warnings. - Report the size of a saved catalog on disk. +- Time spectrumDM requests (Section 4), and estimate from these times how long spectrumDM would take for a number of spectra. Click on the cell to expand it. @@ -220,81 +221,70 @@ def good_bins(spectrum): 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 -``` - -## 4. Two Ways to Get Many Spectra - -+++ -Before the four cases, we measure how long IRSA's spectrumDM service takes to return a spectrum, so that each case can compare it with the HATS query. -The two ways scale differently: -- spectrumDM returns one spectrum per request, so its time grows with the number of spectra. -- LSDB reads whole files of the HATS catalog, so its time grows with the number of files that a query reads, however few spectra it keeps from each file. - -The number of files and the number of spectra are in the catalog's metadata, so we get them without reading any data. +SPECTRUMDM_URL = "https://irsacloud.ipac.caltech.edu/api/spectrumdm/convert/" -```{code-cell} ipython3 -n_files = spectra_catalog.npartitions -n_spectra = spectra_catalog.hc_structure.catalog_info.total_rows -print(f"{n_spectra:,} spectra in {n_files:,} files: about {n_spectra / n_files:,.0f} spectra per file") -``` -To time spectrumDM, we take 90 spectra from IRSA's association table, which gives the file and HDU of each spectrum, and read them the way the [Euclid DR1 SIR 1D spectra tutorial](../3_Euclid_intro_1D_spectra.md) does, with one request per spectrum. -We read 10 of them one request at a time, and the other 80 with 16 requests at a time, as a script that gets many spectra would. +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) -[TODO] Check with the spectrumDM team that it is OK for every user of this notebook to send 16 requests at a time. -```{code-cell} ipython3 -SPECTRUMDM_URL = "https://irsacloud.ipac.caltech.edu/api/spectrumdm/convert/" -N_PARALLEL = 16 # spectrumDM requests at a time +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" -query = "SELECT TOP 90 objectid, path, hdu FROM euclid.objectid_spectrafile_association_dr1" -spectrum_files = Irsa.query_tap(query).to_table() +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") +``` -def read_spectrum(path, hdu): - """Read one spectrum with one spectrumDM request.""" - return QTable.read(f"{SPECTRUMDM_URL}{path}?dataset_id=euclid_combspec_dr1&hdu={hdu}") +## 4. HATS Compared with spectrumDM ++++ -def seconds_per_spectrum(files, n_parallel): - """Average time per spectrum to read the spectra in `files`, with n_parallel requests at a time.""" - start = time.perf_counter() - with ThreadPoolExecutor(max_workers=n_parallel) as pool: - list(pool.map(read_spectrum, files["path"], files["hdu"])) - return (time.perf_counter() - start) / len(files) +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. -# 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): - warnings.simplefilter("ignore", UnitsWarning) - seconds_one = seconds_per_spectrum(spectrum_files[:10], n_parallel=1) - seconds_parallel = seconds_per_spectrum(spectrum_files[10:], n_parallel=N_PARALLEL) -print(f"spectrumDM, one request at a time: {seconds_one:.2f} seconds per spectrum") -print(f"spectrumDM, {N_PARALLEL} requests at a time: {seconds_parallel:.2f} seconds per spectrum") +```{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 ``` -When we ran this notebook, spectrumDM took about 1.5 seconds per spectrum one request at a time, and about 0.17 seconds per spectrum with 16 requests at a time. -LSDB, with the 2 Dask workers that this notebook uses, took about 5 to 10 seconds for each file it read (Section 10.1). -So LSDB is faster when a query keeps more than a few dozen spectra from each file it reads, and spectrumDM with parallel requests is faster for a few hundred spectra spread over many files. - -The function below uses the measured times to estimate how long spectrumDM would take for the spectra of each case. +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 -def duration(seconds): - """A duration as text, in the largest unit that it is at least one of.""" - for unit, size in (("days", 86400), ("hours", 3600), ("minutes", 60)): - if seconds >= size: - return f"{seconds / size:.1f} {unit}" - return f"{seconds:.0f} seconds" +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) - -def spectrumdm_estimate(n_spectra): - """Print how long spectrumDM would take for n_spectra spectra, from the times measured above.""" - print(f"spectrumDM, {n_spectra:,} spectra: about {duration(n_spectra * seconds_one)} one request at a time, or {duration(n_spectra * seconds_parallel)} with {N_PARALLEL} requests at a time") +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 [TODO] seconds; with spectrumDM, they would take about 45 hours one request at a time, or about 5 hours with 16 requests at a time. +So LSDB is much faster when we want many spectra from each file it reads. +For a few hundred spectra spread over many files, spectrumDM with parallel requests can be faster, as Cases 2 and 3 show. + ## 5. Case 1: Spectra in a Region of the Sky +++ From 0df0dda526fd16af98a83382bdff77ef2f15d6fa Mon Sep 17 00:00:00 2001 From: DeekshaMohanty Date: Thu, 3 Dec 2026 18:44:32 -0500 Subject: [PATCH 14/19] Using 8 dask workers --- ignore_tutorials/ignore_circleci_testing | 2 +- .../hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/ignore_tutorials/ignore_circleci_testing b/ignore_tutorials/ignore_circleci_testing index ddd08fc1..22178406 100644 --- a/ignore_tutorials/ignore_circleci_testing +++ b/ignore_tutorials/ignore_circleci_testing @@ -8,4 +8,4 @@ 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 -tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra +tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra \ No newline at end of file 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 index 2c544f23..55b51fb8 100644 --- a/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md +++ b/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md @@ -147,7 +147,7 @@ The helper functions below do six things: Both catalogs have the columns `object_id`, `ra_from_object_id`, and `dec_from_object_id`, with the same values for a matched row, and LSDB needs the two copies to have different names. We keep the names of the first catalog (the one we join to) and add a suffix, such as `_quality`, to the names of the second. - 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 a local HATS catalog, using a Dask client to run the work in parallel on a few workers, with the memory of the machine shared between them. A link to the Dask dashboard, where you can follow the progress, is printed when the client starts. +- Load a query result into memory, or save it to a local HATS catalog, using a Dask client to run the work in parallel on up to 8 workers, with the memory of the machine shared between them. A link to the Dask dashboard, where you can follow the progress, is printed when the client starts. - Find the usable wavelength bins of a spectrum. The `mask` column of a spectrum is a set of quality flags for each bin. As in the [Euclid DR1 SIR 1D spectra tutorial](../3_Euclid_intro_1D_spectra.md), we consider a bin unusable if its `mask` value is odd (flag `NOT_USE`: invalid flux) or is 64 or more (flag `ABS_FLUX`: suspicious flux calibration); the other flags are warnings. @@ -185,8 +185,8 @@ def one_row_per_object(catalog): return catalog.map_partitions(lambda partition: partition.drop_duplicates("object_id")) -def dask_client(catalog, max_workers=2): - """A Dask client with a few single-threaded workers, sharing the memory equally.""" +def dask_client(catalog, max_workers=8): + """A Dask client with up to 8 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 @@ -808,7 +808,7 @@ The paper (Sect. 4.3) finds by visual inspection that about 80% of the redshifts The table below summarizes the queries of this notebook, with their run times with LSDB, and the times that spectrumDM would take for the same spectra, estimated from the times per spectrum of Section 4. -| Case | Starting point | Result | LSDB (2 Dask workers) | spectrumDM: 1 request at a time / 16 at a time | +| Case | Starting point | Result | LSDB (8 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.2 GB) | 1 minute | 13 hours / 1.5 hours | | 2 | List of 276 positions (Section 6) | 317 spectra | 5 minutes | 8 minutes / 1 minute | From dc1bccf50cec14ac23f319807c37f313b4d85ee2 Mon Sep 17 00:00:00 2001 From: DeekshaMohanty Date: Thu, 3 Dec 2026 19:13:45 -0500 Subject: [PATCH 15/19] Simplifying the notebook --- .../2-euclid-dr1-hats-bulk-spectra.md | 250 ++++++------------ 1 file changed, 81 insertions(+), 169 deletions(-) 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 index 55b51fb8..63931a85 100644 --- a/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md +++ b/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md @@ -47,6 +47,7 @@ IRSA provides the Euclid DR1 combined 1D spectra as a HATS catalog, `sir_combine [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. @@ -58,9 +59,9 @@ This notebook covers four starting points: | 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 | The high-quality galaxy sample of Euclid Collaboration: Le Brun et al. (2026) | 8 | +| 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 each case then gives the time of both. +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). +++ @@ -74,8 +75,8 @@ Every query in this notebook returns all the spectra of each object it selects, ### 1.2 Runtime -This notebook takes about 23 minutes to run on Fornax, using Server Type: 'Large' (64 GB RAM, 16 CPUs) ([TODO] environment). -The text above each slow cell gives the time it took. +This notebook takes about 15 to 25 minutes to run on Fornax, using Server Type: 'Large' (64 GB RAM, 16 CPUs) ([TODO] environment). +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. @@ -141,18 +142,15 @@ spectra_catalog = lsdb.open_catalog( ) ``` -The helper functions below do six things: +The helper functions below: -- Join two catalogs on `object_id`, to combine columns or criteria from different catalogs (Section 8). - Both catalogs have the columns `object_id`, `ra_from_object_id`, and `dec_from_object_id`, with the same values for a matched row, and LSDB needs the two copies to have different names. - We keep the names of the first catalog (the one we join to) and add a suffix, such as `_quality`, to the names of the second. +- 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 a local HATS catalog, using a Dask client to run the work in parallel on up to 8 workers, with the memory of the machine shared between them. A link to the Dask dashboard, where you can follow the progress, is printed when the client starts. -- Find the usable wavelength bins of a spectrum. - The `mask` column of a spectrum is a set of quality flags for each bin. - As in the [Euclid DR1 SIR 1D spectra tutorial](../3_Euclid_intro_1D_spectra.md), we consider a bin unusable if its `mask` value is odd (flag `NOT_USE`: invalid flux) or is 64 or more (flag `ABS_FLUX`: suspicious flux calibration); the other flags are warnings. +- 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 (Section 4), and estimate from these times how long spectrumDM would take for a number of spectra. +- Time spectrumDM requests, and estimate how long spectrumDM would take for a number of spectra (Section 4). Click on the cell to expand it. @@ -185,8 +183,8 @@ def one_row_per_object(catalog): return catalog.map_partitions(lambda partition: partition.drop_duplicates("object_id")) -def dask_client(catalog, max_workers=8): - """A Dask client with up to 8 single-threaded workers, sharing the memory equally.""" +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 @@ -281,9 +279,10 @@ 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 [TODO] seconds; with spectrumDM, they would take about 45 hours one request at a time, or about 5 hours with 16 requests at a time. +When we ran this notebook, LSDB loaded the 111,262 spectra of this file in about 30 seconds. +With spectrumDM, they would take 10 to 45 hours one request at a time, or 1 to 5 hours with 16 requests at a time; the time per spectrum changed by a factor of about 4 between our runs. So LSDB is much faster when we want many spectra from each file it reads. -For a few hundred spectra spread over many files, spectrumDM with parallel requests can be faster, as Cases 2 and 3 show. +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 @@ -325,16 +324,18 @@ print(f"{len(region_ids):,} spectra, {disk_size_gb('euclid_dr1_ngc6543_spectra') The region contains 32,890 spectra, which take 0.2 GB on disk. `write_catalog` also saves a margin cache, a copy of the spectra just outside each file's area of the sky, which LSDB uses for cross matches. -LSDB got and saved these spectra in about 1 minute, reading the number of files printed below. -With spectrumDM, the same spectra would take much longer: +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 -print(f"LSDB read {region_spectra.npartitions} files of the spectra catalog") -spectrumdm_estimate(len(region_ids)) +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") ``` -When we ran this notebook, spectrumDM would have taken about 13 hours one request at a time, or about 1.5 hours with 16 requests at a time. -LSDB is much faster here because the spectra of a small region are in only a few files of the catalog, so it keeps many spectra from each file it reads. +Multiplying the number of files by about 3 to 10 seconds per file (Section 10.1) gives a rough time. +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. +++ @@ -344,12 +345,9 @@ LSDB is much faster here because the spectra of a small region are in only a few 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). -A strong lens is a massive galaxy (the deflector) whose gravity bends the light of a more distant galaxy behind it into arcs or multiple images, typically within about 1 arcsecond of the deflector (the paper gives a typical Einstein radius of 0.85 arcseconds). -The spectra can give the redshifts of the deflector and of the lensed galaxy. -Experts inspected 26,662 candidates by eye and graded each one A (sure lens), B (probable lens), C (possible lens), or X (not a lens), as defined in the paper and in the README of the catalog. - -We download the catalog from Zenodo (about 4 MB, a zip file with the catalog and its README) and keep the grade A and B candidates. +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" @@ -367,14 +365,11 @@ 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 have to read a large part of the spectra catalog, which would take hours (Section 10.1). -To keep this notebook short, we use only the candidates within 3 degrees of one position in the Wide Survey; the same code works for the whole list. +The 15,072 candidates are spread over the whole DR1 area, so a cross match with all of them would read a large part of the spectra catalog and take hours. +To keep this notebook short, we use only the candidates within 3 degrees of one position in the Wide Survey; the same code works for the whole list, or for a million positions (Section 10.1). -We load the positions into LSDB, keep those in the region, and cross match them with `sir_combined_spectra`. -The positions are the centers of the deflectors. -We use a radius of 2 arcseconds, larger than the Einstein radius of most lenses, and allow up to 10 spectra per lens. -A cross match finds spectra by position, so it returns the spectrum of the deflector and also the spectra of other objects within 2 arcseconds, which can include lensed images. -The catalog has spectra only for objects detected in the MER catalog, so a lensed arc that was not detected as a separate object has no spectrum of its own. +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( @@ -393,7 +388,7 @@ lens_spectra = lens_region.crossmatch( ) ``` -This cell takes about 5 minutes to run. +This cell takes a few minutes to run. ```{code-cell} ipython3 %%time @@ -412,16 +407,6 @@ Each row is one spectrum, with the lens candidate it was matched to (`Unique_Ide lens_spectra_table[["Unique_Identifier", "object_id", "lrange", "_dist_arcsec", "spectrum"]].head() ``` -With spectrumDM, the same spectra would take: - -```{code-cell} ipython3 -spectrumdm_estimate(len(lens_spectra_table)) -``` - -When we ran this notebook, this was about 8 minutes one request at a time, or about 1 minute with 16 requests at a time. -For this case, spectrumDM with parallel requests is faster than LSDB (about 5 minutes): the lens candidates are spread over a region 6 degrees across, and LSDB reads whole files of tens of thousands of spectra to keep the few near each candidate. -spectrumDM also needs object IDs rather than positions, so the positions would first have to be matched with the MER catalog, for example with a TAP query, which this estimate does not include. - 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. +++ @@ -442,7 +427,7 @@ lens_object_ids = lens_region_table["MER_object_id"].dropna().astype("int64").to print(f"{len(lens_object_ids):,} lens candidates in the region with a MER object_id") ``` -This cell takes about 6 minutes to run. +This cell takes a few 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. @@ -464,17 +449,7 @@ 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 (about 6 minutes, compared with about 5), because it reads the same kind of files whole, after looking up the IDs in the index table. - -With spectrumDM, the spectra found by `id_search` would take: - -```{code-cell} ipython3 -spectrumdm_estimate(len(id_spectra_table)) -``` - -When we ran this notebook, this was about 6 minutes one request at a time, or about 45 seconds with 16 requests at a time. -As in Section 6, spectrumDM with parallel requests is faster for a few hundred spectra spread over many files. -LSDB is the faster way when a query keeps many spectra from each file, as in Sections 5 and 9, and for lists of objects too long for one request per spectrum (Section 10.1). +`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 @@ -529,20 +504,18 @@ The gaps in the spectrum are wavelength bins that `good_bins` marks as unusable 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 the high-quality galaxy sample of [Euclid Collaboration: Le Brun et al. (2026)](https://arxiv.org/abs/2611.17960), Sect. 4.3: 76,002 galaxies in EDF-N, which the paper uses to evaluate the performance of the redshift measurement. -The paper uses EDF-N because, with seven complete red grism visits and three blue grism visits, it has the most complete spectral coverage of the three Euclid Deep Fields (Sects. 1 and 4.3). +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 (a "cut") on a column of one of the DR1 catalogs. -The catalogs come from three Euclid processing functions: MER (multi-wavelength mosaics and the catalog of the objects detected in them), SPE (spectroscopic measurements, such as redshifts and emission lines), and SIR (the NISP spectra). -The table below lists the criteria of Sect. 4.3 of the paper, with the reason for each. -The two criteria marked "this notebook" are not stated in Sect. 4.3; they are how we implement the paper's selection. +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 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, which are unlikely to be at redshift above 0.85. `kron_radius` is in pixels ([MER catalog description](https://euclid.esac.esa.int/dr/dr1/dpdd/merdpd/dpcards/mer_finalcatalog.html)). | +| `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 | @@ -551,18 +524,14 @@ The two criteria marked "this notebook" are not stated in Sect. 4.3; they are ho | | `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 lines catalog has one row per line, redshift solution, and grism. -The quality flag `spe_line_qual_gf` has three digits, defined in Appendix D of the paper: the first gives the fitting method, the second the quality of the measurement, and the last the grism (1: blue, 2: red, 3: both combined). -The paper selects on the grism and on `spe_line_snr_gf > 0`, not on the quality digit; see the [Euclid DR1 SPE tutorial](../5_Euclid_intro_SPE_catalog.md) for more on this flag. +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. -LSDB then applies them while it reads the Parquet files, so it reads and keeps only the rows that pass, instead of loading every row and filtering afterwards. -We also read only the part of the sky within 3 degrees of the center of EDF-N. -The center comes 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), as in the [IRSA HATS catalogs with LSDB tutorial](../../techniques-and-tools/irsa-hats-with-lsdb.md). +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. @@ -622,12 +591,8 @@ These cells run quickly, because LSDB does not read any data yet: it only record ### 8.3 Combine the criteria -Every Euclid DR1 HATS catalog is partitioned using coordinates calculated from `object_id`, so an object falls in the same part of the sky in every catalog, and LSDB can join the catalogs partition by partition. - -The lines catalog can have more than one H$\alpha$ row for the same galaxy that passes the criteria: for example, one for the measurement in the red grism alone, and one for the measurement that combines both grisms. -The join would then return that galaxy twice, and in the next step it would get its spectra twice. -So after joining the H$\alpha$ rows, we keep only one row per galaxy. -Then we join the galaxies to their spectra. +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") @@ -640,26 +605,17 @@ For each join, LSDB prints a table of the columns it renamed because they are in ### 8.4 Count the galaxies -First we load only the sample itself, without the spectra, to compare it with the paper. -This reads only small catalog columns, so it is much faster than loading the spectra: it takes about 2.5 minutes. +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 a minute or two. ```{code-cell} ipython3 %%time deep_sample_table = load(deep_sample) -print(f"{len(deep_sample_table):,} galaxies (Euclid Collaboration: Le Brun et al. 2026: 76,002)") -``` - -We find 80,432 galaxies, about 6% more than the paper's 76,002. - -[TODO] Question for reviewers: we have not found the cause of this difference. One open point: Sect. 4.3 of the paper introduces `spe_z_prob > 0.94` and `spe_z_rel > 0.05` just before "We then applied these criteria to the full EDF-N catalogue, resulting in a sample of 76 002 objects", so it is not certain that these two criteria are part of the 76,002 selection; we include them. - -```{code-cell} ipython3 -deep_sample_table[["object_id", "spe_z"]].head() +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, saving all of them to disk took about 40 minutes, and they took 0.7 GB. -With the spectrumDM times of Section 4, they would take about 64 hours one request at a time, or about 7 hours with 16 requests at a time. +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. +++ @@ -671,24 +627,11 @@ In Section 9 we therefore load the spectra of only part of the sample. 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 no single spectrum shows. -Figure 4 of Euclid Collaboration: Le Brun et al. (2026) shows stacked spectra of 4,000 randomly chosen galaxies from their sample (Section 8), made with the Euclid stacking code SpectraPyle ([Euclid Collaboration: Quai et al. 2026](https://arxiv.org/abs/2509.16120)). -The paper splits the 4,000 galaxies into four groups by how confident volunteers were in each redshift after looking at the spectra. -Those grades are not public, so here we make a single stack of 4,000 galaxies from our sample. - -As explained in Section 8.4, loading the spectra of the whole sample takes a long time. -A stack does not need galaxies from the whole field, so we take the galaxies of the sample in a small part of EDF-N, whose spectra are in only a few files of the spectra catalog, and choose 4,000 of them at random. - -We follow the paper's recipe: +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 only a few files of the spectra catalog. -1. Treat the red and blue grism spectra as separate spectra. -2. Shift each spectrum to the rest frame, the wavelengths that the galaxy emitted, by dividing the observed wavelengths by $1 + z$. -3. Divide each spectrum by its median flux, so that bright galaxies do not dominate. -4. Resample onto a common wavelength grid with 5 Å pixels, so that all spectra have values at the same wavelengths. -5. At each wavelength, take the median of all spectra. - -First we load the spectra of the sample galaxies within 0.6 degrees of the center of EDF-N. -This region contains 4,399 galaxies of the sample, whose spectra are in 33 files of the spectra catalog (compared with 440 files for the whole sample). -This cell takes about 5.5 minutes to run. +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 a few minutes to run. ```{code-cell} ipython3 %%time @@ -698,11 +641,6 @@ 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. - -```{code-cell} ipython3 -stack_region_table[["object_id", "spe_z", "lrange", "spectrum"]].head() -``` - Then we choose 4,000 of these galaxies at random, and keep their spectra. ```{code-cell} ipython3 @@ -711,47 +649,21 @@ 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") -spectrumdm_estimate(len(stack_spectra)) -``` - -LSDB loaded the spectra of all the galaxies in the region in about 5.5 minutes. -When we ran this notebook, spectrumDM would have taken about 3 hours one request at a time, or about 20 minutes with 16 requests at a time, for only the spectra of the 4,000 galaxies we keep. - -The helper functions below normalize one spectrum and resample it; click on the cell to expand it. - -```{code-cell} ipython3 ---- -jupyter: - source_hidden: true -tags: [hide-cell] ---- -def normalized_spectrum(spectrum): - """Wavelengths and median-normalized flux of the good bins of one spectrum.""" - good = good_bins(spectrum) - wavelength = spectrum["wavelength"][good].to_numpy() - flux = spectrum["signal"][good].to_numpy() - # Spectra without usable bins, or with a median flux that is not positive, can't be normalized. - median = np.median(flux) if flux.size else 0 - if median <= 0: - return None, None - return wavelength, flux / median - - -def resample(wavelength, flux, grid): - """Flux on a wavelength grid, NaN outside the spectrum's range.""" - # Linear interpolation; NaN where the grid is outside the spectrum, so those bins don't count. - return np.interp(grid, wavelength, flux, left=np.nan, right=np.nan) ``` -We resample every spectrum onto the rest-frame grid and take the median at each wavelength. +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()): - wavelength, flux = normalized_spectrum(row["spectrum"]) - if wavelength is not None: - resampled[i] = resample(wavelength / (1 + row["spe_z"]), flux, rest_grid) + 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) @@ -760,7 +672,7 @@ 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 stacked spectrum, with the emission lines that the paper identifies in its stacks. +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. @@ -772,10 +684,7 @@ lines = { "He I": 5877, "[O I]": 6302, r"H$\alpha$+[N II]": 6565, - "[S II]": 6725, - "[Ar III]": 7138, - "[S III] 9071": 9071, - "[S III] 9533": 9533, + "[S III]": 9533, } fig, (ax_n, ax_stack) = plt.subplots( @@ -796,9 +705,8 @@ plt.tight_layout() plt.show() ``` -The stack shows the emission lines that the paper finds in its stacks (Figure 4): H$\alpha$+[N II] is the strongest, 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 of the plot, few spectra contribute (top panel), so the stack is noisy there. -The paper (Sect. 4.3) finds by visual inspection that about 80% of the redshifts in its sample are correct; galaxies with wrong redshifts can also add features at the expected wavelengths. +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. +++ @@ -806,33 +714,38 @@ The paper (Sect. 4.3) finds by visual inspection that about 80% of the redshifts +++ -The table below summarizes the queries of this notebook, with their run times with LSDB, and the times that spectrumDM would take for the same spectra, estimated from the times per spectrum of Section 4. +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 of Section 4 in our runs. -| Case | Starting point | Result | LSDB (8 Dask workers) | spectrumDM: 1 request at a time / 16 at a time | +| 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.2 GB) | 1 minute | 13 hours / 1.5 hours | -| 2 | List of 276 positions (Section 6) | 317 spectra | 5 minutes | 8 minutes / 1 minute | -| 3 | List of 260 object IDs (Section 7) | 259 spectra | 6 minutes | 6 minutes / 45 seconds | -| 4 | Object properties, Deep Survey (Section 8) | 80,432 galaxies, without their spectra | 2.5 minutes | | -| | Stack (Section 9) | 8,002 spectra of 4,000 galaxies | 5.5 minutes | 3 hours / 20 minutes | +| 1 | Region of 0.1 degrees in radius (Section 5) | 32,890 spectra, saved to disk (0.2 GB) | about 1 minute | 3 to 13 hours / 20 to 90 minutes | +| 2 | List of 276 positions (Section 6) | 317 spectra | a few minutes | 2 to 8 minutes / 10 seconds to 1 minute | +| 3 | List of 260 object IDs (Section 7) | 259 spectra | a few minutes | 1.5 to 6 minutes / 10 to 45 seconds | +| 4 | Object properties, Deep Survey (Section 8) | 80,432 galaxies, without their spectra | a minute or two | | +| | Stack (Section 9) | 8,002 spectra of 4,000 galaxies | a few 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. -LSDB is much faster when a query keeps many spectra from each file it reads (Case 1 and the stack). 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 much faster when a query keeps many spectra from each file it reads, such as the spectra of a region of the sky (Case 1) or of 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. +- Its speed depends on the Dask workers of your own session, not on the load of a shared service. ### 10.1 Larger queries We can use these times to estimate how long larger queries would take. -In our runs, a query took about 5 to 10 seconds for each file of the spectra catalog that it read: about 5 seconds when saving the spectra of the whole sample of Section 8 (440 files in 38.7 minutes), and about 10 seconds for the stack of Section 9 (33 files in about 5.5 minutes). +In our runs, a query took about 3 to 10 seconds for each file of the spectra catalog that it 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; from the sizes in Sections 5 and 8.4, a million spectra take roughly 4 to 6 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 (5, 10): +for seconds_per_file in (3, 10): 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") ``` @@ -843,7 +756,7 @@ With spectrumDM, a million spectra would take: spectrumdm_estimate(1_000_000) ``` -When we ran this notebook, this was about 17 days one request at a time, or about 2 days with 16 requests at a time, compared with 5 to 10 hours for LSDB to read every file of the catalog. +When we ran this notebook, this was 4 to 17 days one request at a time, or 10 to 46 hours with 16 requests at a time, compared with 3 to 10 hours for LSDB to read every file of the catalog. These are rough estimates from our measured times, not measurements. @@ -855,7 +768,6 @@ These are rough estimates from our measured times, not measurements. - 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) -- Euclid Collaboration: Quai et al. 2026, *Euclid preparation. Predicting star-forming galaxy scaling relations with the spectral stacking code SpectraPyle*, [arXiv:2509.16120](https://arxiv.org/abs/2509.16120) ## About this notebook @@ -863,6 +775,6 @@ These are rough estimates from our measured times, not measurements. **Contact:** [IRSA Helpdesk](https://irsa.ipac.caltech.edu/docs/help_desk.html) -**Runtime:** As of the date above, this notebook takes about 23 minutes to run to completion on Fornax using Server Type: 'Large' (64 GB RAM, 16 CPUs) ([TODO] environment). +**Runtime:** As of the date above, this notebook takes about 15 to 25 minutes to run to completion on Fornax using Server Type: 'Large' (64 GB RAM, 16 CPUs) ([TODO] environment). **AI Acknowledgement:** This tutorial was developed with the assistance of AI tools. From c978980792f72a34dab26c8d01c302d7a599cbc5 Mon Sep 17 00:00:00 2001 From: DeekshaMohanty Date: Thu, 3 Dec 2026 19:36:28 -0500 Subject: [PATCH 16/19] Adding notebook env instructions --- deploy_to_fornax_manifest.in | 1 + .../2-euclid-dr1-hats-bulk-spectra.md | 37 ++++++++++++++++--- .../requirements-euclid-dr1-hats.txt | 9 +++++ 3 files changed, 41 insertions(+), 6 deletions(-) create mode 100644 tutorials/euclid/hats-catalogs/requirements-euclid-dr1-hats.txt diff --git a/deploy_to_fornax_manifest.in b/deploy_to_fornax_manifest.in index a6051a98..2ddde093 100644 --- a/deploy_to_fornax_manifest.in +++ b/deploy_to_fornax_manifest.in @@ -8,6 +8,7 @@ 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/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md b/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md index 63931a85..6fec756b 100644 --- a/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md +++ b/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md @@ -6,7 +6,7 @@ jupytext: format_version: 0.13 jupytext_version: 1.18.1 kernelspec: - display_name: Python 3 (ipykernel) + display_name: euclid-dr1-hats language: python name: python3 authors: @@ -75,7 +75,7 @@ Every query in this notebook returns all the spectra of each object it selects, ### 1.2 Runtime -This notebook takes about 15 to 25 minutes to run on Fornax, using Server Type: 'Large' (64 GB RAM, 16 CPUs) ([TODO] environment). +This notebook takes about 15 to 25 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. @@ -88,11 +88,36 @@ This notebook saves a catalog of spectra to local disk (about 0.2 GB, in Section ## 2. Imports -[TODO] Name the Fornax environment to use. In my Fornax run, the `python3` kernel did not have LSDB, so I installed the packages with the `%pip install` line below. ++++ + +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 astropy "astroquery>=0.4.10" "lsdb>=0.8.1" "dask[distributed]" matplotlib numpy pandas s3fs +# Uncomment the next line to install dependencies if needed. +# %pip install -r requirements-euclid-dr1-hats.txt ``` ```{code-cell} ipython3 @@ -775,6 +800,6 @@ These are rough estimates from our measured times, not measurements. **Contact:** [IRSA Helpdesk](https://irsa.ipac.caltech.edu/docs/help_desk.html) -**Runtime:** As of the date above, this notebook takes about 15 to 25 minutes to run to completion on Fornax using Server Type: 'Large' (64 GB RAM, 16 CPUs) ([TODO] environment). +**Runtime:** As of the date above, this notebook takes about 15 to 25 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 From e7549757884723340f8b913367a1aa50f5ede9b8 Mon Sep 17 00:00:00 2001 From: DeekshaMohanty Date: Thu, 3 Dec 2026 19:46:11 -0500 Subject: [PATCH 17/19] setting as_collection False for lsdb --- .../euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 index 6fec756b..42544531 100644 --- a/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md +++ b/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md @@ -232,8 +232,9 @@ def load(catalog): 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, overwrite=True) + catalog.write_catalog(path, as_collection=False, overwrite=True) def good_bins(spectrum): @@ -347,7 +348,6 @@ print(f"{len(region_ids):,} spectra, {disk_size_gb('euclid_dr1_ngc6543_spectra') ``` The region contains 32,890 spectra, which take 0.2 GB on disk. -`write_catalog` also saves a margin cache, a copy of the spectra just outside each file's area of the sky, which LSDB uses for cross matches. 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. From 07a2269c900310e8cd7a22f63ae02d72d493cf97 Mon Sep 17 00:00:00 2001 From: DeekshaMohanty Date: Thu, 3 Dec 2026 20:14:12 -0500 Subject: [PATCH 18/19] Final edits for the initial draft --- irsa-tutorials-401 | 1 - .../2-euclid-dr1-hats-bulk-spectra.md | 69 +++++++++---------- 2 files changed, 31 insertions(+), 39 deletions(-) delete mode 160000 irsa-tutorials-401 diff --git a/irsa-tutorials-401 b/irsa-tutorials-401 deleted file mode 160000 index b94d6ffd..00000000 --- a/irsa-tutorials-401 +++ /dev/null @@ -1 +0,0 @@ -Subproject commit b94d6ffd4057da10aba62f52e4b03c123dedf3f4 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 index 42544531..3a4e1425 100644 --- a/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md +++ b/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md @@ -75,14 +75,14 @@ Every query in this notebook returns all the spectra of each object it selects, ### 1.2 Runtime -This notebook takes about 15 to 25 minutes to run on Fornax, using Server Type: 'Large' (64 GB RAM, 16 CPUs) and the `euclid-dr1-hats` environment (Section 2). +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.2 GB, in Section 5). +This notebook saves a catalog of spectra to local disk (about 0.1 GB, in Section 5). +++ @@ -305,8 +305,8 @@ 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 10 to 45 hours one request at a time, or 1 to 5 hours with 16 requests at a time; the time per spectrum changed by a factor of about 4 between our runs. +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). @@ -347,7 +347,8 @@ 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.2 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. @@ -359,7 +360,7 @@ for radius_deg in (0.1, 1, 3): print(f"Radius of {radius_deg} degrees: {cone.npartitions} files") ``` -Multiplying the number of files by about 3 to 10 seconds per file (Section 10.1) gives a rough time. +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. +++ @@ -390,8 +391,8 @@ 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 a large part of the spectra catalog and take hours. -To keep this notebook short, we use only the candidates within 3 degrees of one position in the Wide Survey; the same code works for the whole list, or for a million positions (Section 10.1). +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. @@ -413,7 +414,7 @@ lens_spectra = lens_region.crossmatch( ) ``` -This cell takes a few minutes to run. +This cell takes about 3 minutes to run. ```{code-cell} ipython3 %%time @@ -452,7 +453,7 @@ lens_object_ids = lens_region_table["MER_object_id"].dropna().astype("int64").to print(f"{len(lens_object_ids):,} lens candidates in the region with a MER object_id") ``` -This cell takes a few minutes to run. +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. @@ -535,7 +536,7 @@ EDF-N has the most complete spectral coverage of the three Euclid Deep Fields (S ### 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 the paper; they are how we implement its selection. +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 | |---|---|---| @@ -631,7 +632,7 @@ For each join, LSDB prints a table of the columns it renamed because they are in ### 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 a minute or two. +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 @@ -650,13 +651,13 @@ In Section 9 we therefore load the spectra of only part of the sample. +++ 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 no single spectrum shows. +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 only a few files of the spectra catalog. +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 a few minutes to run. +This cell takes about 3 minutes to run. ```{code-cell} ipython3 %%time @@ -739,51 +740,43 @@ Near the edges, few spectra contribute (top panel), so the stack is noisy there. +++ -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 of Section 4 in our runs. +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.2 GB) | about 1 minute | 3 to 13 hours / 20 to 90 minutes | -| 2 | List of 276 positions (Section 6) | 317 spectra | a few minutes | 2 to 8 minutes / 10 seconds to 1 minute | -| 3 | List of 260 object IDs (Section 7) | 259 spectra | a few minutes | 1.5 to 6 minutes / 10 to 45 seconds | -| 4 | Object properties, Deep Survey (Section 8) | 80,432 galaxies, without their spectra | a minute or two | | -| | Stack (Section 9) | 8,002 spectra of 4,000 galaxies | a few minutes | 45 minutes to 3 hours / 5 to 20 minutes | +| 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 much faster when a query keeps many spectra from each file it reads, such as the spectra of a region of the sky (Case 1) or of a sample in one field (the stack). +- 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. -- Its speed depends on the Dask workers of your own session, not on the load of a shared service. +- 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 these times to estimate how long larger queries would take. -In our runs, a query took about 3 to 10 seconds for each file of the spectra catalog that it read. +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; from the sizes in Sections 5 and 8.4, a million spectra take roughly 4 to 6 GB on disk. +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, 10): +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") ``` -With spectrumDM, a million spectra would take: - -```{code-cell} ipython3 -spectrumdm_estimate(1_000_000) -``` - -When we ran this notebook, this was 4 to 17 days one request at a time, or 10 to 46 hours with 16 requests at a time, compared with 3 to 10 hours for LSDB to read every file of the catalog. - -These are rough estimates from our measured times, not measurements. +These are rough estimates from the times of this notebook, not measurements. +++ @@ -796,10 +789,10 @@ These are rough estimates from our measured times, not measurements. ## About this notebook -**Updated:** 2026-12-01 +**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 to 25 minutes to run to completion on Fornax using Server Type: 'Large' (64 GB RAM, 16 CPUs) and the `euclid-dr1-hats` environment (Section 2). +**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. From de85e13c8f67200adc9dd790388c23c4d84efa64 Mon Sep 17 00:00:00 2001 From: DeekshaMohanty Date: Thu, 3 Dec 2026 20:16:54 -0500 Subject: [PATCH 19/19] update notebook_metadata.yml --- notebook_metadata.yml | 2 +- .../euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/notebook_metadata.yml b/notebook_metadata.yml index 2e5270fe..87c501ae 100644 --- a/notebook_metadata.yml +++ b/notebook_metadata.yml @@ -41,7 +41,7 @@ - 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, starting from catalog values, positions, object IDs, or a region of the sky, then stack them to reveal faint emission lines. + 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/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md b/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md index 3a4e1425..31f5098a 100644 --- a/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md +++ b/tutorials/euclid/hats-catalogs/2-euclid-dr1-hats-bulk-spectra.md @@ -495,7 +495,8 @@ 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]) -known_lens_spectra = spectra_catalog.id_search(values={"object_id": [known_lens_id]}) +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"]] ```