Repository Public
1#!/usr/bin/env python32# =============================================================================3# SP BOUCHER | SOFTWARE & RESEARCH4# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project : ORIX Cosmos10# File : DataPipeline/catalogs/fetch_gaia.py11# Description : Adapter for the Gaia archives (TAP): Hipparcos (new12# reduction + 1997 catalogue), the Gaia DR3 best neighbours13# of Hipparcos stars, the Gaia Catalogue of Nearby Stars,14# and magnitude-limited Gaia DR3 tiers joined to the15# Bailer-Jones et al. (2021) geometric distances.16# Asynchronous, batched, adaptive, resumable.17# Module : DataPipeline18# Repository : https://git.spboucher.ai/orix-cosmos19# Project Website : https://www.orixlab.dev20# Created : 2026-11-2421# Last Modified : 2026-11-2422#23# =============================================================================24# AUTHOR & PROFESSIONAL AFFILIATION25# =============================================================================26#27# Author : Simon-Pierre Boucher28# Position : Professor of Finance29# Institution : Université du Québec en Outaouais (UQO)30# Department : Département des sciences administratives31# Organization : SP Boucher32#33# Website : https://spboucher.ai34# Git : https://git.spboucher.ai35#36# =============================================================================37# OFFICIAL CONTACT DIRECTORY38# =============================================================================39#40# General : info@spboucher.ai41# Professional : contact@spboucher.ai42# Direct : simon@spboucher.ai43# Research : research@spboucher.ai44# Development : dev@spboucher.ai45# Support : support@spboucher.ai46# Security/Admin : admin@spboucher.ai47# Notifications : notifications@spboucher.ai48#49# Preferred Contact: support@spboucher.ai50#51# =============================================================================52# COPYRIGHT & INTELLECTUAL PROPERTY53# =============================================================================54#55# Copyright (c) 202656# Simon-Pierre Boucher57#58# All rights reserved where applicable.59#60# This file is governed by the applicable project license,61# copyright notices, institutional agreements and relevant law.62#63# Unless expressly authorized by the applicable license or64# rights holder, copying, redistribution, sublicensing,65# publication and commercial exploitation are not permitted.66#67# Existing third-party rights and notices remain unaffected.68#69# =============================================================================70# CONFIDENTIALITY & SECURITY71# =============================================================================72#73# Classification : Public74# Distribution : Public repository; use is governed by the project license75# Security Contact : admin@spboucher.ai76#77# Access to this source does not independently grant permission78# to redistribute or disclose confidential materials.79#80# Do not embed credentials, private keys, access tokens,81# certificates or confidential personal information.82#83# =============================================================================84# LICENSE & MAINTENANCE85# =============================================================================86#87# License : None specified (no license file in this repository)88# Maintainer : Simon-Pierre Boucher89# Technical Contact: dev@spboucher.ai90#91# =============================================================================92# END OF SP BOUCHER SOURCE HEADER93# =============================================================================9495"""Usage: fetch_gaia.py hipparcos | hipxm | gcns | tier <gmin> <gmax> [step] | teff <gmin> <gmax> [step]9697Two services are used (both anonymous, one job at a time per service, polled every 10 s):9899* ESA Gaia Archive, https://gea.esac.esa.int/tap-server/tap — the primary archive. Limits observed for anonymous100 users on 2026-11-24: 60 s of execution and 50 000 rows per job (an answer of exactly 50 000 rows is truncated).101 Used for everything that fits those limits without a heavy join: Hipparcos (new reduction and 1997 catalogue),102 the Hipparcos–Gaia DR3 best-neighbour table, the GCNS, and the GSP-Phot effective temperatures of the tiers.103* GAVO Data Center (Heidelberg), https://dc.g-vo.org/tap — the publisher of the Bailer-Jones et al. (2021)104 distance catalogue (`gedr3dist.main`), which also serves `gaia.dr3lite`, a column subset of gaiadr3.gaia_source.105 Used for the magnitude-limited tiers because the join of 10^5–10^6 sources to the distance table does not fit106 the ESA anonymous limits (measured: 62 723 rows for G <= 8 in 95 s at GAVO). Synchronous queries in107 magnitude bins of a few 10^4 rows are used: an asynchronous GAVO job stayed QUEUED for 8 minutes on108 2026-11-24 while the synchronous endpoint answered at once. `gaia.dr3lite` has no109 `teff_gspphot` (fetched separately from ESA, command `teff`) and no `ref_epoch` (2016.0 for all of DR3).110 The Gaia partner mirror at ARI Heidelberg (https://gaia.ari.uni-heidelberg.de/tap) was tried first: the job111 stayed QUEUED for 18 minutes on 2026-11-24 and was withdrawn.112113Licence of everything fetched here: CC BY-NC 3.0 IGO (terms of the ESA Space Science Archives) for Gaia and114Hipparcos data; the distance catalogue is distributed by GAVO with the request to cite Bailer-Jones et al. (2021).115A batch that hits a limit is halved and retried (see `adaptive`).116"""117import sys118import time119120from common import RowLimit, log, tap_async, tap_sync121122ESA = "https://gea.esac.esa.int/tap-server/tap"123GAVO = "https://dc.g-vo.org/tap"124SOURCE = "gaia"125ESA_ROWS = 50000126GAVO_MAXREC = 3000000127128GAIA_COLUMNS = """g.source_id, g.ra, g.dec, g.parallax, g.parallax_error, g.pmra, g.pmra_error,129g.pmdec, g.pmdec_error, g.radial_velocity, g.radial_velocity_error, g.phot_g_mean_mag, g.phot_bp_mean_mag,130g.phot_rp_mean_mag, g.ruwe, g.astrometric_params_solved,131d.r_med_geo, d.r_lo_geo, d.r_hi_geo, d.flag AS dist_flag"""132133GAIA_EXPECTED = ["source_id", "ra", "dec", "parallax", "parallax_error", "pmra", "pmra_error", "pmdec",134 "pmdec_error", "radial_velocity", "radial_velocity_error", "phot_g_mean_mag", "phot_bp_mean_mag",135 "phot_rp_mean_mag", "ruwe", "astrometric_params_solved", "r_med_geo", "r_lo_geo", "r_hi_geo",136 "dist_flag"]137138139def tier_query(gmin, gmax):140 lower = "" if gmin is None else "g.phot_g_mean_mag > %s AND " % gmin141 return ("SELECT " + GAIA_COLUMNS + " FROM gaia.dr3lite AS g "142 "LEFT OUTER JOIN gedr3dist.main AS d ON d.source_id = g.source_id "143 "WHERE " + lower + "g.phot_g_mean_mag <= %s" % gmax)144145146def teff_query(gmin, gmax):147 lower = "" if gmin is None else "phot_g_mean_mag > %s AND " % gmin148 return ("SELECT source_id, teff_gspphot, teff_gspphot_lower, teff_gspphot_upper FROM gaiadr3.gaia_source WHERE "149 + lower + "phot_g_mean_mag <= %s AND teff_gspphot IS NOT NULL" % gmax)150151152TEFF_EXPECTED = ["source_id", "teff_gspphot", "teff_gspphot_lower", "teff_gspphot_upper"]153154155def tier_file(lo, hi):156 return "gaia_dr3_g_%05d_%05d.csv" % (round(lo * 1000), round(hi * 1000))157158159# The cross-match table alone (no join), from the primary archive.160HIPXM_QUERY = ("SELECT source_id, original_ext_source_id AS hip, angular_distance AS hip_angular_distance, "161 "number_of_neighbours AS hip_neighbours FROM gaiadr3.hipparcos2_best_neighbour")162HIPXM_EXPECTED = ["source_id", "hip", "hip_angular_distance", "hip_neighbours"]163164HIP2_QUERY = ("SELECT hip, ra, dec, plx, e_plx, pm_ra, pm_de, e_ra_rad, e_de_rad, e_pm_ra, e_pm_de, sn, "165 "hp_mag, e_hp_mag, b_v, e_b_v, v_i FROM public.hipparcos_newreduction")166HIP2_EXPECTED = ["hip", "ra", "dec", "plx", "e_plx", "pm_ra", "pm_de", "e_pm_ra", "e_pm_de", "sn", "hp_mag",167 "b_v", "e_b_v", "v_i"]168HIP1_QUERY = "SELECT hip, vmag, b_v, e_b_v, v_i, sptype, hd, ccdm, m_hip, ncomp FROM public.hipparcos"169HIP1_EXPECTED = ["hip", "vmag", "b_v", "sptype", "hd", "ccdm"]170171GCNS_QUERY = ("SELECT source_id, ra, dec, parallax, parallax_error, pmra, pmra_error, pmdec, pmdec_error, "172 "phot_g_mean_mag, phot_bp_mean_mag, phot_rp_mean_mag, ruwe, adoptedrv, adoptedrv_error, "173 "adoptedrv_refname, gcns_prob, wd_prob, dist_16, dist_50, dist_84 FROM external.gaiaedr3_gcns_main_1")174GCNS_EXPECTED = ["source_id", "ra", "dec", "parallax", "parallax_error", "pmra", "pmra_error", "pmdec", "pmdec_error",175 "phot_g_mean_mag", "phot_bp_mean_mag", "phot_rp_mean_mag", "ruwe", "adoptedrv", "adoptedrv_error",176 "gcns_prob", "wd_prob", "dist_16", "dist_50", "dist_84"]177178179def adaptive_sync(lo, hi, min_width):180 """Same halving strategy for the synchronous GAVO queries of the tiers (any failure splits the bin:181 a time-out of the service comes back as an error document, which `tap_sync` rejects)."""182 try:183 print(tap_sync(SOURCE, tier_file(lo / 1000.0, hi / 1000.0), GAVO,184 tier_query(None if lo <= 0 else lo / 1000.0, hi / 1000.0),185 maxrec=GAVO_MAXREC, row_limit=GAVO_MAXREC, expected=GAIA_EXPECTED))186 except RuntimeError as exc:187 if hi - lo <= min_width:188 raise189 mid = (lo + hi) // 2190 log("bin (%d, %d]: %s -> splitting at %d" % (lo, hi, str(exc)[:100], mid))191 time.sleep(5)192 adaptive_sync(lo, mid, min_width)193 adaptive_sync(mid, hi, min_width)194195196def adaptive(lo, hi, endpoint, query_of, name_of, min_width, maxrec, row_limit):197 """Runs one job for the interval (lo, hi]; when the service aborts it on its execution-time limit or the198 answer is truncated at the row limit, the interval is halved and each half is tried again. Intervals are199 integers (millimagnitudes, HIP numbers, millidegrees) so that file names are exact."""200 try:201 print(tap_async(SOURCE, name_of(lo, hi), endpoint, query_of(lo, hi), maxrec=maxrec, row_limit=row_limit))202 except RuntimeError as exc:203 splittable = isinstance(exc, RowLimit) or "execution time" in str(exc)204 if not splittable or hi - lo <= min_width:205 raise206 mid = (lo + hi) // 2207 log("interval (%d, %d]: %s -> splitting at %d" % (lo, hi, str(exc)[:80], mid))208 adaptive(lo, mid, endpoint, query_of, name_of, min_width, maxrec, row_limit)209 adaptive(mid, hi, endpoint, query_of, name_of, min_width, maxrec, row_limit)210211212def main(argv):213 if len(argv) < 2:214 sys.exit(__doc__)215 cmd = argv[1]216 if cmd == "hipparcos":217 # HIP numbers run from 1 to 120404218 for table, query in (("hip2", HIP2_QUERY), ("hip1", HIP1_QUERY)):219 for lo in range(0, 120000 + 40000, 40000):220 adaptive(lo, lo + 40000, ESA, lambda a, b, q=query: q + " WHERE hip > %d AND hip <= %d" % (a, b),221 lambda a, b, t=table: "%s_%06d_%06d.csv" % (t, a, b), 500, None, ESA_ROWS)222 elif cmd == "hipxm":223 for lo in range(0, 120000 + 40000, 40000):224 adaptive(lo, lo + 40000, ESA,225 lambda a, b: HIPXM_QUERY + " WHERE original_ext_source_id > %d AND original_ext_source_id <= %d" % (a, b),226 lambda a, b: "hipxm_%06d_%06d.csv" % (a, b), 500, None, ESA_ROWS)227 elif cmd == "gcns":228 for lo in range(0, 360000, 40000):229 adaptive(lo, lo + 40000, ESA,230 lambda a, b: GCNS_QUERY + " WHERE ra > %s AND ra <= %s" % (a / 1000.0 if a > 0 else -1, b / 1000.0),231 lambda a, b: "gcns_ra_%06d_%06d.csv" % (a, b), 500, None, ESA_ROWS)232 elif cmd in ("tier", "teff"):233 gmin, gmax = round(float(argv[2]) * 1000), round(float(argv[3]) * 1000)234 step = round(float(argv[4]) * 1000) if len(argv) > 4 else gmax - gmin235 for lo in range(gmin, gmax, step):236 # the brightest bin has no lower bound (Gaia DR3 has no source brighter than G = 1.7)237 if cmd == "tier":238 adaptive_sync(lo, min(lo + step, gmax), 5)239 else:240 adaptive(lo, min(lo + step, gmax), ESA,241 lambda a, b: teff_query(None if a <= 0 else a / 1000.0, b / 1000.0),242 lambda a, b: "teff_g_%05d_%05d.csv" % (a, b), 5, None, ESA_ROWS)243 else:244 sys.exit(__doc__)245246247if __name__ == "__main__":248 main(sys.argv)249