From c66c0988a87750efc4d2ddd8217a45f01431cb25 Mon Sep 17 00:00:00 2001 From: Michael Coughlin Date: Thu, 26 Nov 2026 09:37:09 -0600 Subject: [PATCH 1/3] Add opt-in Pan-STARRS host fallback --- .../catalog/catalogs/panstarrs_hosts.py | 31 +++ .../catalog/catalogs/test_panstarrs_hosts.py | 25 +++ docs/catalogs.md | 33 +++ frontend/src/components/HostCard.tsx | 8 +- frontend/src/lib/api.ts | 1 + src/api/routes/babamul/surveys/objects.rs | 3 + src/catalogs/mod.rs | 42 ++-- src/catalogs/types.rs | 19 ++ src/conf.rs | 3 + src/utils/host/catalog.rs | 2 +- src/utils/host/config.rs | 61 ++++++ src/utils/host/mod.rs | 10 +- src/utils/host/ps1.rs | 198 ++++++++++++++++++ 13 files changed, 413 insertions(+), 23 deletions(-) create mode 100644 boompy/src/boompy/catalog/catalogs/panstarrs_hosts.py create mode 100644 boompy/tests/catalog/catalogs/test_panstarrs_hosts.py create mode 100644 src/utils/host/ps1.rs diff --git a/boompy/src/boompy/catalog/catalogs/panstarrs_hosts.py b/boompy/src/boompy/catalog/catalogs/panstarrs_hosts.py new file mode 100644 index 000000000..0da89fe8a --- /dev/null +++ b/boompy/src/boompy/catalog/catalogs/panstarrs_hosts.py @@ -0,0 +1,31 @@ +"""Stage Pan-STARRS DR2 stack morphology joined to PS1-STRM by objID.""" + +from __future__ import annotations + +import os +from pathlib import Path + +from ..base import Chunk + +ID = "panstarrs-hosts" + + +def staged_dir() -> Path: + return Path(os.getenv("BOOM_CATALOG_DATA_PATH", "data/catalogs")) / "staged" / ID + + +def list_chunks() -> list[Chunk]: + directory = staged_dir() + files = sorted(path.name for path in directory.glob("*.jsonl.gz") if path.is_file()) + if not files: + raise RuntimeError(f"Stage panstarrs-hosts .jsonl.gz chunks in {directory}.") + return [Chunk(id=name, label=name) for name in files] + + +def fetch_chunk(chunk_id: str, dest: Path) -> list[Path]: + if Path(chunk_id).name != chunk_id or not chunk_id.endswith(".jsonl.gz"): + raise ValueError(f"Invalid panstarrs-hosts chunk name: {chunk_id}") + path = staged_dir() / chunk_id + if not path.is_file(): + raise RuntimeError(f"Pan-STARRS host chunk is missing: {path}") + return [path] diff --git a/boompy/tests/catalog/catalogs/test_panstarrs_hosts.py b/boompy/tests/catalog/catalogs/test_panstarrs_hosts.py new file mode 100644 index 000000000..c3f62738a --- /dev/null +++ b/boompy/tests/catalog/catalogs/test_panstarrs_hosts.py @@ -0,0 +1,25 @@ +import gzip + +import pytest + +from boompy.catalog.catalogs import panstarrs_hosts + + +def test_staged_chunks_are_read_in_place(tmp_path, monkeypatch): + monkeypatch.setenv("BOOM_CATALOG_DATA_PATH", str(tmp_path)) + with pytest.raises(RuntimeError, match="Stage panstarrs-hosts"): + panstarrs_hosts.list_chunks() + + directory = tmp_path / "staged" / "panstarrs-hosts" + directory.mkdir(parents=True) + part = directory / "part-0001.jsonl.gz" + with gzip.open(part, "wt") as stream: + stream.write( + '{"_id":191000742646808255,"ra":74.2654807,"dec":69.17252295,' + '"rKronRad":9.7508,"rExtNSigma":41.55,"strm_class":"GALAXY",' + '"strm_prob_galaxy":0.9994,"strm_z_phot":0.0381,"strm_z_phot_err":0.0086}\n' + ) + assert [chunk.id for chunk in panstarrs_hosts.list_chunks()] == [part.name] + assert panstarrs_hosts.fetch_chunk(part.name, tmp_path / "download") == [part] + with pytest.raises(ValueError, match="Invalid"): + panstarrs_hosts.fetch_chunk("../part-0001.jsonl.gz", tmp_path) diff --git a/docs/catalogs.md b/docs/catalogs.md index 9283e4869..f9a144a2a 100644 --- a/docs/catalogs.md +++ b/docs/catalogs.md @@ -156,6 +156,7 @@ still resolves to the same catalog definition. | `galex` | `GALEX` | gzipped CSV | per release | Ultraviolet FUV/NUV photometry from the All-Sky Imaging Survey. | | `vsx` | `VSX` | fixed-width text | 1 | Variability types, magnitudes, epochs and periods for known and suspected variable stars. | | `panstarrs` | `PS1_DR2` | parquet | HEALPix partitions | Mean PSF magnitudes in grizy, from the HATS mirror of the DR2 otmo table. Requester-pays S3. Does not include the PS1-STRM `strm_*` columns crossmatch config projects. | +| `panstarrs-hosts` | `PS1_DR2_HOSTS` | gzipped JSONL, **staged** | one per staged file | DR2 stack radii joined to PS1-STRM for the opt-in host fallback. | | `lsdr9` | `LSDR9` | parquet, from FITS pairs | one per `dr9/north` sweep file | Fluxes, Tractor shapes and photo-z posteriors for the BASS+MzLS reduction, which covers the sky DR10's DECam footprint does not reach. Each chunk is one published sweep file merged with its photo-z counterpart. No i-band: DR9 predates it. | | `lspsc` | `LSPSC` | gzipped JSONL, **staged** | one per exported chunk | Morphological resolved/unresolved scores for 3.1×10⁹ LS DR10 sources ([Liu et al. 2025](https://arxiv.org/abs/2505.17174)). Upstream is a cone-search API, so BOOM ingests an export of its own copy — see below. | | `erass1-main` | `eRASS1_Main` | parquet, from FITS in a tarball | 1 | eROSITA-DE DR1 Main, 930,203 X-ray sources detected in 0.2-2.3 keV, with fluxes, band rates, extent and detection likelihood. German half of the sky only (Galactic longitude 180° to 360°). | @@ -163,6 +164,38 @@ still resolves to the same catalog definition. | `2sxps` | `2SXPS` | parquet, from FITS | 1 | Swift-XRT point sources, the 146,768 of the clean subset, with count rates, hardness ratios, fluxes and variability probabilities. | | `4fgl-dr4` | `4FGL_DR4` | parquet, from FITS | 1 | Fermi-LAT 14-year catalog, 7,195 gamma-ray sources with 95% error ellipses, fluxes, variability and associations. | +### Pan-STARRS host fallback + +Prepare a catalog with one row per Pan-STARRS `objID`. Join +[DR2 stack measurements](https://outerspace.stsci.edu/spaces/PANSTARRS/pages/298812430/PS1%2BStackObjectAttributes%2Btable%2Bfields) +to [PS1-STRM](https://stdatu.stsci.edu/hlsp/ps1-strm) by object ID and resolve +duplicate stack detections when preparing the join. Stage the completed +`.jsonl.gz` parts in `/staged/panstarrs-hosts/`. Each line +uses an integer `_id` for `objID`, stack `ra` and `dec` in degrees, +`rKronRad` in arcseconds, `rExtNSigma`, `strm_class`, and `strm_prob_galaxy`. +The `strm_z_phot` and `strm_z_phot_err` fields are optional. + +Ingest `panstarrs-hosts` from the admin page. Then enable the fallback in a +deployment's host association settings. Omitting `ps1_fallback` disables it. +An empty `ps1_fallback: {}` uses these defaults. + +```yaml +host_galaxy: + enabled: true + ps1_fallback: + radius_arcsec: 45.0 + min_galaxy_score: 0.70 + min_extendedness_sigma: 0.0 + max_dlr: 3.0 +``` + +The fallback runs when NED-LVS and Legacy leave no accepted host. It uses +the r-band Kron radius as a circular size proxy in the existing DLR ranker. +The resulting host carries the catalog and `objID`. A valid STRM photo-z +carries the `photometric` redshift type, with the usual DESI preference for +an available spectrum. The score remains the host ranker's uncalibrated +posterior. The normal Pan-STARRS alert crossmatch has its own settings. + ### Matching within a positional error X-ray and gamma-ray positions are much less precise than optical ones, and diff --git a/frontend/src/components/HostCard.tsx b/frontend/src/components/HostCard.tsx index bc8e2e52c..206039f75 100644 --- a/frontend/src/components/HostCard.tsx +++ b/frontend/src/components/HostCard.tsx @@ -6,6 +6,9 @@ function hostUrl(host: HostSummary): string | null { if (host.catalog === 'NED' && host.name) { return `https://ned.ipac.caltech.edu/byname?objname=${encodeURIComponent(host.name)}`; } + if (host.catalog === 'PS1_DR2_HOSTS' && host.name) { + return `https://catalogs.mast.stsci.edu/api/v0.1/panstarrs/dr2/stack.csv?objID=${encodeURIComponent(host.name)}`; + } if (host.ra == null || host.dec == null) return null; const layer = host.catalog === 'LSDR9' ? 'ls-dr9' : 'ls-dr10'; return `https://www.legacysurvey.org/viewer?ra=${host.ra}&dec=${host.dec}&layer=${layer}&zoom=16&mark=${host.ra},${host.dec}`; @@ -28,7 +31,10 @@ function hostRows(host: HostSummary): [string, ReactNode][] { } if (host.catalog) rows.push(['Catalog', host.catalog]); if (host.z != null) { - rows.push(['Redshift', host.z_err != null ? `${host.z.toFixed(4)} ± ${host.z_err.toFixed(4)}` : host.z.toFixed(4)]); + const label = host.z_type === 'photometric' ? 'Photometric redshift' + : host.z_type === 'spectroscopic' ? 'Spectroscopic redshift' + : 'Redshift'; + rows.push([label, host.z_err != null ? `${host.z.toFixed(4)} ± ${host.z_err.toFixed(4)}` : host.z.toFixed(4)]); } if (host.dist_mpc != null) rows.push(['Distance', `${host.dist_mpc.toFixed(1)} Mpc`]); const sep = `${host.sep_arcsec.toFixed(2)}″`; diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index 35c2c0d44..2d5e303cb 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -404,6 +404,7 @@ export type HostSummary = { dec?: number; z?: number | null; z_err?: number | null; + z_type?: 'photometric' | 'spectroscopic' | null; dist_mpc?: number | null; dist_mpc_method?: string | null; sep_arcsec: number; diff --git a/src/api/routes/babamul/surveys/objects.rs b/src/api/routes/babamul/surveys/objects.rs index 70e5f41cf..49962820a 100644 --- a/src/api/routes/babamul/surveys/objects.rs +++ b/src/api/routes/babamul/surveys/objects.rs @@ -61,6 +61,8 @@ struct ObjHost { dec: f64, z: Option, z_err: Option, + #[serde(default)] + z_type: Option, dist_mpc: Option, dist_mpc_method: Option, sep_arcsec: f64, @@ -77,6 +79,7 @@ impl From<&StoredHostCandidate> for ObjHost { dec: host.dec, z: host.z, z_err: host.z_err, + z_type: host.z_type.clone(), dist_mpc: host.dist_mpc, dist_mpc_method: host.dist_mpc_method.clone(), sep_arcsec: host.sep_arcsec, diff --git a/src/catalogs/mod.rs b/src/catalogs/mod.rs index f910b5fbf..bd9300b3e 100644 --- a/src/catalogs/mod.rs +++ b/src/catalogs/mod.rs @@ -38,6 +38,7 @@ pub const STATE_COLLECTION: &str = "catalog_state"; /// The task type whose runs populate these collections. const TASK_TYPE_CATALOG_INGEST: &str = crate::tasks::catalog_ingest::TASK_TYPE; +pub(crate) const PS1_HOSTS_COLLECTION: &str = "PS1_DR2_HOSTS"; /// Which reader turns this catalog's source files into documents. /// @@ -72,6 +73,7 @@ pub enum Reader { Vsx, /// Pan-STARRS otmo, parquet partitions. PanStarrs, + Ps1Hosts, /// Legacy Survey DR9, parquet merged from the published sweep and photo-z /// FITS pairs. LsDr9, @@ -242,6 +244,16 @@ pub const CATALOGS: &[CatalogDef] = &[ // Configs named PS1_DR1 until #598, though the only mirror was ever DR2. aliases: &["PS1_DR1"], }, + CatalogDef { + id: "panstarrs-hosts", + collection: PS1_HOSTS_COLLECTION, + title: "Pan-STARRS DR2 Host Galaxies", + description: + "Staged DR2 stack sizes and PS1-STRM classifications and photo-zs, joined by objID.", + reader: Reader::Ps1Hosts, + source: Source::Staged, + aliases: &[], + }, CatalogDef { id: "lsdr9", collection: "LSDR9", @@ -377,7 +389,7 @@ pub async fn warn_on_empty_crossmatch_catalogs( } } -/// Collection names crossmatch config actually references, across all surveys. +/// Collection names the alert pipeline queries across all surveys. /// /// Separate from [`declared`] because the two answer different questions now: /// `declared` is "what did config ask for", this is "what will the alert @@ -391,6 +403,9 @@ pub fn crossmatched(config: &crate::conf::AppConfig) -> Vec { .map(|entry| entry.catalog.clone()) .filter(|name| !name.starts_with(crate::api::catalogs::WATCHLIST_PREFIX)) .collect(); + if config.host_galaxy.enabled && config.host_galaxy.ps1_fallback.is_some() { + names.push(PS1_HOSTS_COLLECTION.to_string()); + } names.sort_unstable(); names.dedup(); names @@ -398,9 +413,7 @@ pub fn crossmatched(config: &crate::conf::AppConfig) -> Vec { /// Which catalogs this deployment should hold. /// -/// Derived from `crossmatch.[].catalog`, because that is where a -/// catalog is actually put to use -- a deployment that crossmatches against -/// NED needs NED, and having to say so twice is how two lists drift apart. +/// Derived from crossmatch and host-association config. /// /// Entries are returned as slugs where the name maps to a known catalog, and as /// the raw collection name where it does not, so an unrecognized name surfaces @@ -419,22 +432,10 @@ pub fn declared(config: &crate::conf::AppConfig) -> Vec { } }; - // Sorted for a stable order regardless of the survey map's iteration order, - // so the admin page does not reshuffle its rows between requests. - let mut from_crossmatch: Vec<&str> = config - .crossmatch - .values() - .flatten() - .map(|entry| entry.catalog.as_str()) - .filter(|name| !name.starts_with(crate::api::catalogs::WATCHLIST_PREFIX)) - .collect(); - from_crossmatch.sort_unstable(); - from_crossmatch.dedup(); - - for name in from_crossmatch { - match find_by_collection(name) { + for name in crossmatched(config) { + match find_by_collection(&name) { Some(def) => push(def.id.to_string()), - None => push(name.to_string()), + None => push(name), } } declared @@ -867,6 +868,7 @@ async fn ingest_file( Reader::Galex => Ok(csv::ingest_csv::(inserter, path).await?), Reader::Vsx => Ok(ascii::ingest_ascii::(inserter, path).await?), Reader::PanStarrs => Ok(arrow::ingest_parquet::(inserter, path).await?), + Reader::Ps1Hosts => Ok(jsonl::ingest_jsonl::(inserter, path).await?), Reader::LsDr9 => Ok(arrow::ingest_parquet::(inserter, path).await?), Reader::Lspsc => Ok(jsonl::ingest_jsonl::(inserter, path).await?), Reader::Erass1 => Ok(arrow::ingest_parquet::(inserter, path).await?), @@ -1683,7 +1685,7 @@ mod source_tests { .collect(); // lspsc is an export of BOOM's own copy and the DESI DR1 dwarfs are not // published: neither can be fetched, and their files must not be deleted. - assert_eq!(staged, vec!["desi-dr1-dwarfs", "lspsc"]); + assert_eq!(staged, vec!["desi-dr1-dwarfs", "panstarrs-hosts", "lspsc"]); } #[test] diff --git a/src/catalogs/types.rs b/src/catalogs/types.rs index 1cde7a976..3a197902d 100644 --- a/src/catalogs/types.rs +++ b/src/catalogs/types.rs @@ -1042,6 +1042,25 @@ impl super::arrow::FromRecordBatch for PanStarrs { impl HasCoordinates for PanStarrs {} +/// DR2 stack morphology joined to PS1-STRM by objID. +#[derive(Debug, Serialize, Deserialize)] +pub struct Ps1Host { + #[serde(rename = "_id")] + pub id: i64, + pub ra: f64, + pub dec: f64, + #[serde(rename = "rKronRad")] + pub kron_radius_arcsec: f64, + #[serde(rename = "rExtNSigma")] + pub extendedness_sigma: f64, + pub strm_class: String, + pub strm_prob_galaxy: f64, + pub strm_z_phot: Option, + pub strm_z_phot_err: Option, +} + +impl HasCoordinates for Ps1Host {} + // --------------------------------------------------------------------------- // Legacy Survey DR9 -- parquet, merged from the published sweep and photo-z // FITS pairs by boompy diff --git a/src/conf.rs b/src/conf.rs index 6879d8776..6213b58ac 100644 --- a/src/conf.rs +++ b/src/conf.rs @@ -1972,6 +1972,9 @@ pub fn load_config(config_path: Option<&str>) -> Result Self { + Self { + radius_arcsec: 45.0, + min_galaxy_score: 0.7, + min_extendedness_sigma: 0.0, + max_dlr: 3.0, + } + } +} + +impl Ps1FallbackConfig { + pub(crate) fn validate(&self) -> Result<(), String> { + if self.radius_arcsec > 0.0 + && self.radius_arcsec <= 180.0 * 3600.0 + && (0.0..=1.0).contains(&self.min_galaxy_score) + && self.min_extendedness_sigma.is_finite() + && self.max_dlr.is_finite() + && self.max_dlr > 0.0 + { + return Ok(()); + } + Err( + "invalid host_galaxy.ps1_fallback radius, galaxy score, extendedness, or max_dlr" + .into(), + ) + } +} + /// Host-galaxy association, read from `config.yaml` under `host_galaxy`. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(default)] @@ -47,6 +85,8 @@ pub struct HostGalaxyConfig { /// Cross-match catalog searched at the host's position when no Legacy row is on it. pub ps1_catalog: String, pub photometry_match_arcsec: f64, + /// Enable the separate Pan-STARRS host search when no primary host is accepted. + pub ps1_fallback: Option, /// Cross-match catalog of spectra whose redshift replaces a photometric one. pub desi_catalog: String, /// Largest offset between a spectrum and the galaxy centre, arcsec. @@ -77,6 +117,7 @@ impl Default for HostGalaxyConfig { isophote_mag: super::sersic::MU_25, ps1_catalog: "PS1_DR2".to_string(), photometry_match_arcsec: 2.0, + ps1_fallback: None, desi_catalog: "DESI_DR1".to_string(), spectrum_match_arcsec: 1.0, } @@ -101,6 +142,26 @@ mod tests { #[test] fn test_disabled_by_default() { assert!(!HostGalaxyConfig::default().enabled); + assert!(HostGalaxyConfig::default().ps1_fallback.is_none()); + } + + #[test] + fn ps1_fallback_has_its_own_defaults_and_cutoffs() { + let config: HostGalaxyConfig = + serde_json::from_str(r#"{"enabled":true,"ps1_fallback":{}}"#).unwrap(); + let cuts = config.ps1_fallback.unwrap(); + assert_eq!(config.max_dlr, 5.0); + assert_eq!(cuts.max_dlr, 3.0); + assert_eq!(cuts.radius_arcsec, 45.0); + assert_eq!(cuts.min_galaxy_score, 0.7); + assert_eq!(cuts.min_extendedness_sigma, 0.0); + assert!(cuts.validate().is_ok()); + assert!(Ps1FallbackConfig { + max_dlr: f64::NAN, + ..cuts + } + .validate() + .is_err()); } #[test] diff --git a/src/utils/host/mod.rs b/src/utils/host/mod.rs index 789b7f5bf..ee8728b67 100644 --- a/src/utils/host/mod.rs +++ b/src/utils/host/mod.rs @@ -37,13 +37,14 @@ mod error; mod likelihood; mod photometry; mod prior; +mod ps1; mod sersic; mod types; pub use associate::{associate_host, AssociationConfig, AssociationResult}; pub use association::{HostGalaxyAssociation, HostSummary, StoredHostCandidate}; pub use catalog::{collect_galaxies, galaxy_from_legacy, galaxy_from_ned, LS_DR10, LS_DR9, NED}; -pub use config::HostGalaxyConfig; +pub use config::{HostGalaxyConfig, Ps1FallbackConfig}; pub use dlr::{compute_dlr, DlrResult}; pub use ellipse::Ellipse; pub use error::HostError; @@ -90,6 +91,13 @@ pub async fn associate_with_photometry( db: &mongodb::Database, ) -> Option { let mut association = associate_from_xmatches(ra, dec, xmatches, config)?; + if association.best_host.is_none() { + if let Some(fallback) = + ps1::associate(ra, dec, xmatches, config, survey, object_id, db).await + { + association = fallback; + } + } add_spectrum_at_host_center( &mut association, xmatches, diff --git a/src/utils/host/ps1.rs b/src/utils/host/ps1.rs new file mode 100644 index 000000000..ff8e76d2b --- /dev/null +++ b/src/utils/host/ps1.rs @@ -0,0 +1,198 @@ +use std::collections::HashMap; + +use mongodb::bson::{self, doc, Document}; +use mongodb::Database; +use tracing::warn; + +use crate::catalogs::{types::Ps1Host, PS1_HOSTS_COLLECTION}; +use crate::conf::{arcsec_to_radians, CatalogXmatchConfig}; +use crate::utils::{enums::Survey, spatial::xmatch}; + +use super::catalog::{add_spectroscopic_redshift, PHOTOMETRIC}; +use super::{ + associate_host, GalaxyCandidate, HostGalaxyAssociation, HostGalaxyConfig, Ps1FallbackConfig, + Transient, +}; + +fn candidate(row: Ps1Host, cuts: &Ps1FallbackConfig) -> Option { + if row.strm_class != "GALAXY" + || !(cuts.min_galaxy_score..=1.0).contains(&row.strm_prob_galaxy) + || !row.extendedness_sigma.is_finite() + || row.extendedness_sigma == -999.0 + || row.extendedness_sigma < cuts.min_extendedness_sigma + || !row.kron_radius_arcsec.is_finite() + || row.kron_radius_arcsec <= 0.0 + { + return None; + } + + let redshift = row.strm_z_phot.filter(|z| z.is_finite() && *z > 0.0); + let redshift_err = + redshift.and_then(|_| row.strm_z_phot_err.filter(|e| e.is_finite() && *e > 0.0)); + // The stack Kron aperture is a circular proxy for the galaxy light radius. + Some(GalaxyCandidate { + ra: row.ra, + dec: row.dec, + a_arcsec: row.kron_radius_arcsec, + b_arcsec: row.kron_radius_arcsec, + pa_deg: 0.0, + redshift, + redshift_err, + redshift_type: redshift.map(|_| PHOTOMETRIC.to_string()), + dist_mpc: None, + dist_mpc_method: None, + mag: None, + mag_err: None, + objtype: Some(row.strm_class), + objname: Some(row.id.to_string()), + catalog: Some(PS1_HOSTS_COLLECTION.to_string()), + size_is_isophotal: false, + diam_survey: None, + orientation_is_nominal: true, + rex_snr_band: None, + }) +} + +pub(super) async fn associate( + ra: f64, + dec: f64, + xmatches: &HashMap>, + config: &HostGalaxyConfig, + survey: &Survey, + object_id: &str, + db: &Database, +) -> Option { + let cuts = config.ps1_fallback.as_ref()?; + let search = CatalogXmatchConfig { + catalog: PS1_HOSTS_COLLECTION.to_string(), + radius: arcsec_to_radians(cuts.radius_arcsec), + projection: doc! { + "_id": 1, "ra": 1, "dec": 1, "rExtNSigma": 1, "rKronRad": 1, + "strm_class": 1, "strm_prob_galaxy": 1, "strm_z_phot": 1, "strm_z_phot_err": 1, + }, + ..Default::default() + }; + let mut matches = match xmatch(ra, dec, object_id, survey, &[search], db).await { + Ok(matches) => matches, + Err(error) => { + warn!(object_id, %error, "Pan-STARRS host search failed"); + return None; + } + }; + let galaxies = matches + .remove(PS1_HOSTS_COLLECTION)? + .into_iter() + .filter_map(|row| bson::from_document::(row).ok()) + .filter_map(|row| candidate(row, cuts)) + .map(|mut galaxy| { + if let Some(spectra) = xmatches.get(&config.desi_catalog) { + add_spectroscopic_redshift(&mut galaxy, spectra, config); + } + galaxy + }) + .collect::>(); + let mut association_config = config.association_config(); + association_config.max_fractional_offset = cuts.max_dlr; + let result = associate_host(&Transient::new(ra, dec), &galaxies, &association_config).ok()?; + (result.n_passed_dlr > 0).then(|| HostGalaxyAssociation::from_result(&result)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::utils::host::associate_with_photometry; + use crate::utils::spatial::Coordinates; + use mongodb::IndexModel; + + const RA: f64 = 74.2534823; + const DEC: f64 = 69.1721358; + const HOST: &str = r#"{"_id":191000742646808255,"ra":74.2654807,"dec":69.17252295, + "rKronRad":9.750800132751465,"rExtNSigma":41.554500579833984,"strm_class":"GALAXY", + "strm_prob_galaxy":0.9994375,"strm_z_phot":0.0380897969,"strm_z_phot_err":0.0086123286}"#; + + async fn replay( + db: &Database, + matches: &HashMap>, + config: &HostGalaxyConfig, + ) -> HostGalaxyAssociation { + associate_with_photometry( + RA, + DEC, + matches, + config, + &[], + &Survey::Ztf, + "ZTF26aciomda", + db, + ) + .await + .unwrap() + } + + #[tokio::test] + async fn ps1_fallback_replays_ztf26aciomda() -> anyhow::Result<()> { + let test_db = crate::conf::get_test_db().await; + let db = test_db + .client() + .database(&format!("test_ps1_host_{}", uuid::Uuid::new_v4().simple())); + let catalog = db.collection::(PS1_HOSTS_COLLECTION); + let mut host: Ps1Host = serde_json::from_str(HOST)?; + let mut host_doc = bson::to_document(&host)?; + host_doc.insert( + "coordinates", + bson::to_document(&Coordinates::new(host.ra, host.dec))?, + ); + + // A closer candidate with a valid Kron radius but an insufficient STRM score. + host.id = 1; + host.ra = RA; + host.dec = DEC; + host.strm_prob_galaxy = 0.69; + let mut contaminant = bson::to_document(&host)?; + contaminant.insert( + "coordinates", + bson::to_document(&Coordinates::new(RA, DEC))?, + ); + catalog.insert_many([host_doc, contaminant]).await?; + catalog + .create_index( + IndexModel::builder() + .keys(doc! { "coordinates.radec_geojson": "2dsphere" }) + .build(), + ) + .await?; + + let disabled = HostGalaxyConfig { + enabled: true, + ..Default::default() + }; + let enabled = HostGalaxyConfig { + ps1_fallback: Some(Ps1FallbackConfig::default()), + ..disabled.clone() + }; + let mut matches = HashMap::new(); + let without_fallback = replay(&db, &matches, &disabled).await; + let fallback = replay(&db, &matches, &enabled).await; + matches.insert( + "NED".into(), + vec![doc! { "_id": "control", "ra": RA, "dec": DEC, "Diam": 1.0 }], + ); + let primary = replay(&db, &matches, &enabled).await; + matches.get_mut("NED").unwrap()[0].insert("dec", DEC + 20.0 / 3600.0); + let rejected_primary = replay(&db, &matches, &enabled).await; + db.drop().await?; + + assert_eq!(without_fallback, HostGalaxyAssociation::empty()); + assert_eq!(fallback.n_candidates_searched, 1); + let best = fallback.best_host.as_ref().unwrap(); + assert_eq!(best.objname.as_deref(), Some("191000742646808255")); + assert_eq!(best.catalog.as_deref(), Some(PS1_HOSTS_COLLECTION)); + assert_eq!(best.z_type.as_deref(), Some(PHOTOMETRIC)); + assert_eq!(best.z, Some(0.0380897969)); + assert_eq!(best.z_err, Some(0.0086123286)); + assert!((best.d_dlr - 1.5815).abs() < 0.001); + assert_eq!(primary.best_host.unwrap().catalog.as_deref(), Some("NED")); + assert_eq!(rejected_primary, fallback); + Ok(()) + } +} From 0f2fb1e947994d23158ddc5b847be9ecc5ce00a4 Mon Sep 17 00:00:00 2001 From: Michael Coughlin Date: Thu, 26 Nov 2026 09:39:54 -0600 Subject: [PATCH 2/3] Format Pan-STARRS catalog staging code --- .../src/boompy/catalog/catalogs/panstarrs_hosts.py | 14 +++++++++++--- .../tests/catalog/catalogs/test_panstarrs_hosts.py | 4 +++- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/boompy/src/boompy/catalog/catalogs/panstarrs_hosts.py b/boompy/src/boompy/catalog/catalogs/panstarrs_hosts.py index 0da89fe8a..a31aaf280 100644 --- a/boompy/src/boompy/catalog/catalogs/panstarrs_hosts.py +++ b/boompy/src/boompy/catalog/catalogs/panstarrs_hosts.py @@ -11,14 +11,22 @@ def staged_dir() -> Path: - return Path(os.getenv("BOOM_CATALOG_DATA_PATH", "data/catalogs")) / "staged" / ID + return ( + Path(os.getenv("BOOM_CATALOG_DATA_PATH", "data/catalogs")) + / "staged" + / ID + ) def list_chunks() -> list[Chunk]: directory = staged_dir() - files = sorted(path.name for path in directory.glob("*.jsonl.gz") if path.is_file()) + files = sorted( + path.name for path in directory.glob("*.jsonl.gz") if path.is_file() + ) if not files: - raise RuntimeError(f"Stage panstarrs-hosts .jsonl.gz chunks in {directory}.") + raise RuntimeError( + f"Stage panstarrs-hosts .jsonl.gz chunks in {directory}." + ) return [Chunk(id=name, label=name) for name in files] diff --git a/boompy/tests/catalog/catalogs/test_panstarrs_hosts.py b/boompy/tests/catalog/catalogs/test_panstarrs_hosts.py index c3f62738a..215576d46 100644 --- a/boompy/tests/catalog/catalogs/test_panstarrs_hosts.py +++ b/boompy/tests/catalog/catalogs/test_panstarrs_hosts.py @@ -20,6 +20,8 @@ def test_staged_chunks_are_read_in_place(tmp_path, monkeypatch): '"strm_prob_galaxy":0.9994,"strm_z_phot":0.0381,"strm_z_phot_err":0.0086}\n' ) assert [chunk.id for chunk in panstarrs_hosts.list_chunks()] == [part.name] - assert panstarrs_hosts.fetch_chunk(part.name, tmp_path / "download") == [part] + assert panstarrs_hosts.fetch_chunk(part.name, tmp_path / "download") == [ + part + ] with pytest.raises(ValueError, match="Invalid"): panstarrs_hosts.fetch_chunk("../part-0001.jsonl.gz", tmp_path) From 979cf6078f3dc6be9e01a192cf9bc5f9c1ae217d Mon Sep 17 00:00:00 2001 From: antoine-le-calloch Date: Thu, 26 Nov 2026 17:08:10 -0500 Subject: [PATCH 3/3] Bump host_association and link PS1 hosts to the cutout page --- frontend/src/components/HostCard.tsx | 6 +++--- src/enrichment/version.rs | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/frontend/src/components/HostCard.tsx b/frontend/src/components/HostCard.tsx index 206039f75..009744905 100644 --- a/frontend/src/components/HostCard.tsx +++ b/frontend/src/components/HostCard.tsx @@ -6,10 +6,10 @@ function hostUrl(host: HostSummary): string | null { if (host.catalog === 'NED' && host.name) { return `https://ned.ipac.caltech.edu/byname?objname=${encodeURIComponent(host.name)}`; } - if (host.catalog === 'PS1_DR2_HOSTS' && host.name) { - return `https://catalogs.mast.stsci.edu/api/v0.1/panstarrs/dr2/stack.csv?objID=${encodeURIComponent(host.name)}`; - } if (host.ra == null || host.dec == null) return null; + if (host.catalog === 'PS1_DR2_HOSTS') { + return `https://ps1images.stsci.edu/cgi-bin/ps1cutouts?pos=${host.ra}+${host.dec}&filter=color`; + } const layer = host.catalog === 'LSDR9' ? 'ls-dr9' : 'ls-dr10'; return `https://www.legacysurvey.org/viewer?ra=${host.ra}&dec=${host.dec}&layer=${layer}&zoom=16&mark=${host.ra},${host.dec}`; } diff --git a/src/enrichment/version.rs b/src/enrichment/version.rs index 63165ea30..5d82a3e1d 100644 --- a/src/enrichment/version.rs +++ b/src/enrichment/version.rs @@ -88,7 +88,7 @@ pub const DERIVATIONS: &[(&str, u32)] = &[ ("detection_history", 2), ("variability", 1), // hosted, best_host. Also bump when the DLR scoring parameters change: hosts are rewritten in place. - ("host_association", 4), + ("host_association", 5), // applecider_fusion, applecider_outputs and fusion_embedding. ("applecider_postprocess", 1), // arnett_fit and thermal_fit.