SPB Git

Repository Public

build_stars.py 27.9 KB 572 lines python

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/build_stars.py11# Description      : Builds the star packs from the cached raw files:12#                    stars-hipparcos, stars-gaia-nearby, stars-gaia-g10,13#                    stars-gaia-g12 and the star part of the starter pack.14#                    Cross-identifies Hipparcos and Gaia DR3 (one object, two15#                    identifiers), sets distances without naive parallax16#                    inversion, computes the membership flags that de-duplicate17#                    overlapping packs. Deterministic.18# Module           : DataPipeline19# Repository       : https://git.spboucher.ai/orix-cosmos20# Project Website  : https://www.orixlab.dev21# Created          : 2026-11-2422# Last Modified    : 2026-11-2423#24# =============================================================================25# AUTHOR & PROFESSIONAL AFFILIATION26# =============================================================================27#28# Author           : Simon-Pierre Boucher29# Position         : Professor of Finance30# Institution      : Université du Québec en Outaouais (UQO)31# Department       : Département des sciences administratives32# Organization     : SP Boucher33#34# Website          : https://spboucher.ai35# Git              : https://git.spboucher.ai36#37# =============================================================================38# OFFICIAL CONTACT DIRECTORY39# =============================================================================40#41# General          : info@spboucher.ai42# Professional     : contact@spboucher.ai43# Direct           : simon@spboucher.ai44# Research         : research@spboucher.ai45# Development      : dev@spboucher.ai46# Support          : support@spboucher.ai47# Security/Admin   : admin@spboucher.ai48# Notifications    : notifications@spboucher.ai49#50# Preferred Contact: support@spboucher.ai51#52# =============================================================================53# COPYRIGHT & INTELLECTUAL PROPERTY54# =============================================================================55#56# Copyright (c) 202657# Simon-Pierre Boucher58#59# All rights reserved where applicable.60#61# This file is governed by the applicable project license,62# copyright notices, institutional agreements and relevant law.63#64# Unless expressly authorized by the applicable license or65# rights holder, copying, redistribution, sublicensing,66# publication and commercial exploitation are not permitted.67#68# Existing third-party rights and notices remain unaffected.69#70# =============================================================================71# CONFIDENTIALITY & SECURITY72# =============================================================================73#74# Classification   : Public75# Distribution     : Public repository; use is governed by the project license76# Security Contact : admin@spboucher.ai77#78# Access to this source does not independently grant permission79# to redistribute or disclose confidential materials.80#81# Do not embed credentials, private keys, access tokens,82# certificates or confidential personal information.83#84# =============================================================================85# LICENSE & MAINTENANCE86# =============================================================================87#88# License          : None specified (no license file in this repository)89# Maintainer       : Simon-Pierre Boucher90# Technical Contact: dev@spboucher.ai91#92# =============================================================================93# END OF SP BOUCHER SOURCE HEADER94# =============================================================================9596"""Usage: build_stars.py [--out DIR]9798Reads DataPipeline/raw/catalogs/{gaia,iau,hyg,nea,stellarium}; writes <out>/<pack>/stars.bin, catalog.sqlite and99pack.json (manifest draft; finalize.py adds file sizes and SHA-256 once the Swift tool has added the octree).100Default <out> is Resources/Packs. Fails loudly when a raw file lacks an expected column.101"""102import glob103import json104import math105import os106import re107import sys108109import fetch_gaia110import sources111import starfile as sf112from common import PACKS, RAW, SchemaError, fnum, inum, log, read_csv, write_json113from designations import CON_CASE, GREEK_LETTER_OF, normalize114from store import Store115116RAD = math.pi / 180.0117VERSION = "1.0.0"118STARTER_VMAG = 6.5119STARTER_NEAR_PC = 25.0120STARTER_GAIA_NEAR_PC = 10.0121MIN_SNR = 5.0  # below this parallax/error no distance is derived from a parallax alone122HYG_BAYER = {"Alp": "alf", "Bet": "bet", "Gam": "gam", "Del": "del", "Eps": "eps", "Zet": "zet", "Eta": "eta",123             "The": "tet", "Iot": "iot", "Kap": "kap", "Lam": "lam", "Mu": "mu", "Nu": "nu", "Xi": "ksi", "Omi": "omi",124             "Pi": "pi", "Rho": "rho", "Sig": "sig", "Tau": "tau", "Ups": "ups", "Phi": "phi", "Chi": "chi", "Psi": "psi",125             "Ome": "ome"}126127128def raw_files(pattern):129    files = sorted(glob.glob(os.path.join(RAW, "gaia", pattern)))130    return [f for f in files if not f.endswith(".meta.json") and os.path.exists(f + ".meta.json")]131132133def inverse_parallax(plx, err):134    """(distance pc, low, high) from a parallax in mas, only when parallax/error >= MIN_SNR; else None."""135    if plx is None or err is None or err <= 0 or plx <= 0 or plx / err < MIN_SNR:136        return None137    return (1000.0 / plx, 1000.0 / (plx + err), 1000.0 / (plx - err))138139140def parallax_flags(plx, err):141    flags = 0142    if plx is None:143        return sf.FLAG_NO_PLX144    if plx <= 0:145        flags |= sf.FLAG_NONPOSITIVE_PLX146    if err is None or err <= 0 or plx / err < MIN_SNR:147        flags |= sf.FLAG_LOW_SNR148    return flags149150151def load_hipparcos():152    hip2, hip1 = {}, {}153    for f in raw_files("hip2_*.csv"):154        for r in read_csv(f, fetch_gaia.HIP2_EXPECTED):155            hip2[int(r["hip"])] = r156    for f in raw_files("hip1_*.csv"):157        for r in read_csv(f, fetch_gaia.HIP1_EXPECTED):158            hip1[int(r["hip"])] = r159    if len(hip2) != 117955:160        raise SchemaError("Hipparcos new reduction: %d rows, 117955 expected" % len(hip2))161    return hip2, hip1162163164def load_crossmatch(hip2):165    """HIP <-> Gaia DR3 from gaiadr3.hipparcos2_best_neighbour, forced one-to-one: when several Hipparcos entries166    claim one Gaia source, the closest keeps it. Returns (hip -> (source_id, ambiguous), source_id -> hip)."""167    rows = []168    for f in raw_files("hipxm_*.csv"):169        for r in read_csv(f, fetch_gaia.HIPXM_EXPECTED):170            rows.append((float(r["hip_angular_distance"]), int(r["hip"]), int(r["source_id"]), int(r["hip_neighbours"])))171    rows.sort()172    by_hip, by_gaia = {}, {}173    dropped = 0174    for dist, hip, sid, nnb in rows:175        if hip not in hip2 or hip in by_hip or sid in by_gaia:176            dropped += 1177            continue178        by_hip[hip] = (sid, nnb > 1)179        by_gaia[sid] = hip180    log("cross-match: %d Hipparcos stars have a Gaia DR3 counterpart, %d rows dropped (not one-to-one or unknown HIP)"181        % (len(by_hip), dropped))182    return by_hip, by_gaia183184185def tier_coverage():186    """Magnitude bins present on disk, checked for gaps and overlaps. Returns (files, limit) where limit is the187    faint end of the contiguous coverage starting at the bright end."""188    bins = []189    for f in raw_files("gaia_dr3_g_*.csv"):190        m = re.search(r"g_(\d{5})_(\d{5})\.csv$", f)191        bins.append((int(m.group(1)), int(m.group(2)), f))192    bins.sort()193    out, edge = [], 0194    for lo, hi, f in bins:195        if lo != edge:196            if lo < edge:197                raise SchemaError("overlapping Gaia magnitude bins at G = %.3f (%s)" % (lo / 1000.0, f))198            break199        out.append((lo, hi, f))200        edge = hi201    return out, edge202203204def load_teff():205    teff = {}206    for f in raw_files("teff_g_*.csv"):207        for r in read_csv(f, fetch_gaia.TEFF_EXPECTED):208            teff[int(r["source_id"])] = float(r["teff_gspphot"])209    return teff210211212def gaia_star(r, teff, by_gaia):213    sid = int(r["source_id"])214    plx, eplx = fnum(r["parallax"]), fnum(r["parallax_error"])215    s = sf.Star(source_key=sid, cross_key=by_gaia.get(sid, 0), ra=float(r["ra"]) * RAD, dec=float(r["dec"]) * RAD,216                epoch=2016.0, parallax=plx, parallax_error=eplx, pmra=fnum(r["pmra"]), pmdec=fnum(r["pmdec"]),217                pmra_error=fnum(r["pmra_error"]), pmdec_error=fnum(r["pmdec_error"]), rv=fnum(r["radial_velocity"]),218                rv_error=fnum(r["radial_velocity_error"]), mag=fnum(r["phot_g_mean_mag"]),219                colour_a=fnum(r["phot_bp_mean_mag"]), colour_b=fnum(r["phot_rp_mean_mag"]), teff=teff.get(sid),220                ruwe=fnum(r["ruwe"]), source=sf.SOURCE_GAIA)221    s.flags = parallax_flags(plx, eplx)222    if s.ruwe is not None and s.ruwe > 1.4:223        s.flags |= sf.FLAG_HIGH_RUWE224    med = fnum(r["r_med_geo"])225    if med is not None:226        # Bailer-Jones et al. (2021) geometric distance: posterior median and 16th/84th percentiles. For a low227        # signal-to-noise or negative parallax it is dominated by the prior; the record keeps FLAG_LOW_SNR.228        s.dist, s.dist_lo, s.dist_hi, s.dist_method = med, fnum(r["r_lo_geo"]), fnum(r["r_hi_geo"]), sf.DIST_BAILER_JONES229    return s230231232def hyg_table():233    """HIP -> dict(hr, gl, bayer, flam, con, proper) and the list of Gliese stars without a Hipparcos number."""234    by_hip, no_hip = {}, []235    path = os.path.join(RAW, "hyg", "hygdata_v41.csv")236    for r in read_csv(path, ["hip", "hd", "hr", "gl", "proper", "ra", "dec", "dist", "bayer", "flam", "con", "pmra", "pmdec", "mag"]):237        entry = {k: r[k].strip() for k in ("hr", "gl", "bayer", "flam", "con", "proper", "hd")}238        if r["hip"].strip():239            by_hip[int(r["hip"])] = entry240        elif entry["gl"] or entry["proper"]:241            if r["id"] == "0":242                continue  # the Sun243            entry.update(ra=float(r["ra"]) * 15 * RAD, dec=float(r["dec"]) * RAD, dist=fnum(r["dist"]), mag=fnum(r["mag"]))244            no_hip.append(entry)245    return by_hip, no_hip246247248def csn_table():249    """HIP -> (ascii name, name with diacritics) from the IAU Catalog of Star Names."""250    names = {}251    with open(os.path.join(RAW, "iau", "IAU-CSN.txt"), encoding="utf-8") as f:252        for line in f:253            if line.startswith(("#", "$")) or not line.strip():254                continue255            tokens = line.split()256            dates = [i for i, t in enumerate(tokens) if re.fullmatch(r"\d{4}-\d{2}-\d{2}", t)]257            if not dates:258                raise SchemaError("IAU-CSN: no approval date in line: " + line[:60])259            hip = tokens[dates[-1] - 4]260            if hip == "_":261                continue262            names[int(hip)] = (line[0:18].strip(), line[18:36].strip())263    if not 300 <= len(names) <= 600 or names.get(32349, ("",))[0] != "Sirius":264        raise SchemaError("IAU-CSN: unexpected layout (%d names with HIP, HIP 32349 = %r)" % (len(names), names.get(32349)))265    return names266267268def star_designations(hip, h1, hyg, csn):269    """Display name and designation list (role, catalog, text) of a Hipparcos star."""270    out = []271    name = None272    if hip in csn:273        ascii_name, diacritic = csn[hip]274        name = diacritic or ascii_name275        out.append((1, "IAU-CSN", name))276        if ascii_name != name:277            out.append((1, "IAU-CSN", ascii_name))278    e = hyg.get(hip, {})279    if e.get("proper") and normalize(e["proper"]) not in [normalize(d[2]) for d in out]:280        out.append((1, "HYG", e["proper"]))281        name = name or e["proper"]282    con = CON_CASE.get(e.get("con", "").lower())283    if e.get("bayer") and con:284        parts = e["bayer"].split("-")285        abbr = HYG_BAYER.get(parts[0])286        letter = GREEK_LETTER_OF.get(abbr, parts[0]) if abbr else parts[0]287        text = "%s%s %s" % (letter, parts[1] if len(parts) > 1 else "", con)288        out.append((2, "Bayer", text))289        name = name or text290    if e.get("flam") and con:291        text = "%s %s" % (e["flam"], con)292        out.append((2, "Flamsteed", text))293        name = name or text294    if e.get("hr"):295        out.append((2, "HR", "HR " + e["hr"]))296        name = name or "HR " + e["hr"]297    hd = (h1 or {}).get("hd", "").strip()298    if hd:299        out.append((2, "HD", "HD " + hd))300        name = name or "HD " + hd301    if e.get("gl"):302        gl = re.sub(r"^(Gl|GJ|NN|Wo)\s*", "GJ ", e["gl"])303        out.append((2, "GJ", gl))304    out.insert(0, (0, "HIP", "HIP %d" % hip))305    return name or "HIP %d" % hip, out306307308def match_nearby_names(gcns_near, hyg_no_hip):309    """Names for nearby Gaia stars that have no Hipparcos number (Wolf 359, ...): HYG entries with a Gliese or310    proper name are matched by position. The Gaia position (J2016.0) is moved back to J2000.0 with the Gaia311    proper motion; a match needs a separation under 60 arcsec, a distance agreeing within 25 %, and must be312    unique in both directions. Returns source_id -> HYG entry."""313    candidates = {}314    for s in gcns_near:315        dt = 2000.0 - 2016.0316        mas = RAD / 3.6e6317        dec = s.dec + (s.pmdec or 0.0) * mas * dt318        ra = s.ra + (s.pmra or 0.0) * mas * dt / max(1e-6, math.cos(s.dec))319        u = sf.unit(ra, dec)320        best = []321        for k, e in enumerate(hyg_no_hip):322            if e["dist"] is None or s.dist is None or abs(e["dist"] - s.dist) > 0.25 * s.dist:323                continue324            sep = sf.separation(u, sf.unit(e["ra"], e["dec"]))325            if sep < 60.0 / 3600.0 * RAD:326                best.append((sep, k))327        if len(best) == 1:328            candidates.setdefault(best[0][1], []).append(s.source_key)329    return {sids[0]: hyg_no_hip[k] for k, sids in candidates.items() if len(sids) == 1}330331332def nearby_designations(sid, e):333    out = [(0, "Gaia DR3", "Gaia DR3 %d" % sid, False)]334    name = None335    if e.get("proper"):336        out.append((1, "HYG", e["proper"]))337        name = e["proper"]338    if e.get("gl"):339        gl = re.sub(r"^(Gl|GJ|NN|Wo)\s*", "GJ ", e["gl"])340        out.append((2, "GJ", gl))341        name = name or gl342    return name or "Gaia DR3 %d" % sid, out343344345def write_pack(out_dir, pack_id, title, stars, flag, prov_ids, objects, licence, ack, redistribution, coverage, extra_sources=()):346    """Writes stars.bin and catalog.sqlite of one star pack. `objects`: list of (id, name, prov, ra, dec, mag,347    designations, spectral type) rows for the stars that have names or designations beyond their own key."""348    pack_dir = os.path.join(out_dir, pack_id)349    os.makedirs(pack_dir, exist_ok=True)350    counts = sf.write(os.path.join(pack_dir, "stars.bin"), stars)351    table = sources.all_sources()352    built = max(table[p]["retrieved"] for p in prov_ids)353    store = Store(os.path.join(pack_dir, "catalog.sqlite"), pack_id, VERSION, built)354    sources.register(store, prov_ids)355    for oid, name, prov, ra, dec, mag, designations, sptype in objects:356        store.add(oid, "star", name, "observed", prov, ra=ra, dec=dec, mag=mag, designations=designations, count=False)357        store.star_text(oid, sptype)358    store.close()359    with_distance = sum(1 for s in stars if s.dist is not None)360    draft = {"id": pack_id, "title": title, "version": VERSION, "retrieved": built, "licence": licence,361             "acknowledgement": ack, "redistribution": redistribution, "sources": store.provenances,362             "counts": {"star": counts["records"], "star_with_distance": with_distance, "star_named_rows": len(objects),363                        "tiles": counts["tiles"]},364             "coverage": coverage, "starFlag": flag}365    write_json(os.path.join(pack_dir, "pack.json"), draft)366    log("pack %s: %d stars (%d with a distance), %d tiles, %d database rows" % (pack_id, counts["records"], with_distance, counts["tiles"], len(objects)))367368369def main(argv):370    out_dir = argv[argv.index("--out") + 1] if "--out" in argv else PACKS371    hip2, hip1 = load_hipparcos()372    by_hip, by_gaia = load_crossmatch(hip2)373    teff = load_teff()374    hyg, hyg_no_hip = hyg_table()375    csn = csn_table()376377    # ---- Gaia magnitude tiers378    tiers, limit = tier_coverage()379    log("Gaia tiers: contiguous coverage to G = %.3f in %d files" % (limit / 1000.0, len(tiers)))380    if limit < 10000:381        raise SchemaError("Gaia tiers must reach G = 10 (run fetch_gaia.py tier)")382    g10, g12, gaia_of = [], [], {}383    build_g12 = limit >= 12000384    for lo, hi, f in tiers:385        if hi > 10000 and (not build_g12 or hi > 12000):386            continue387        n = 0388        for r in read_csv(f, fetch_gaia.GAIA_EXPECTED):389            s = gaia_star(r, teff, by_gaia)390            (g10 if hi <= 10000 else g12).append(s)391            if s.cross_key:392                gaia_of[s.source_key] = s393            n += 1394        if n == 0 and hi > 3000:395            raise SchemaError("empty Gaia bin " + f)396    g10_ids = {s.source_key for s in g10}397    g12_ids = {s.source_key for s in g12}398399    # ---- GCNS400    gcns = []401    for f in raw_files("gcns_ra_*.csv"):402        for r in read_csv(f, fetch_gaia.GCNS_EXPECTED):403            sid = int(r["source_id"])404            plx, eplx = fnum(r["parallax"]), fnum(r["parallax_error"])405            s = sf.Star(source_key=sid, cross_key=by_gaia.get(sid, 0), ra=float(r["ra"]) * RAD, dec=float(r["dec"]) * RAD,406                        epoch=2016.0, parallax=plx, parallax_error=eplx, pmra=fnum(r["pmra"]), pmdec=fnum(r["pmdec"]),407                        pmra_error=fnum(r["pmra_error"]), pmdec_error=fnum(r["pmdec_error"]), rv=fnum(r["adoptedrv"]),408                        rv_error=fnum(r["adoptedrv_error"]), mag=fnum(r["phot_g_mean_mag"]),409                        colour_a=fnum(r["phot_bp_mean_mag"]), colour_b=fnum(r["phot_rp_mean_mag"]), teff=teff.get(sid),410                        ruwe=fnum(r["ruwe"]), source=sf.SOURCE_GCNS)411            s.flags = parallax_flags(plx, eplx) | (sf.FLAG_HIGH_RUWE if (s.ruwe or 0) > 1.4 else 0)412            d50 = fnum(r["dist_50"])413            if d50 is not None:414                s.dist, s.dist_lo, s.dist_hi, s.dist_method = d50 * 1000, fnum(r["dist_16"]) * 1000, fnum(r["dist_84"]) * 1000, sf.DIST_GCNS415            gcns.append(s)416    if len(gcns) != 331312:417        raise SchemaError("GCNS: %d rows, 331312 expected" % len(gcns))418    gcns_ids = {s.source_key for s in gcns}419420    # ---- Hipparcos421    hip_stars = {}422    for hip in sorted(hip2):423        r, h1 = hip2[hip], hip1.get(hip)424        plx, eplx = fnum(r["plx"]), fnum(r["e_plx"])425        vmag = fnum(h1["vmag"]) if h1 else None426        bv = fnum(r["b_v"])427        if bv is None and h1:428            bv = fnum(h1["b_v"])429        s = sf.Star(source_key=hip, ra=float(r["ra"]) * RAD, dec=float(r["dec"]) * RAD, epoch=1991.25, parallax=plx,430                    parallax_error=eplx, pmra=fnum(r["pm_ra"]), pmdec=fnum(r["pm_de"]), pmra_error=fnum(r["e_pm_ra"]),431                    pmdec_error=fnum(r["e_pm_de"]), mag=vmag, mag2=fnum(r["hp_mag"]), colour_a=bv, colour_b=fnum(r["v_i"]),432                    source=sf.SOURCE_HIPPARCOS)433        s.flags = parallax_flags(plx, eplx)434        own = inverse_parallax(plx, eplx)435        if hip in by_hip:436            sid, ambiguous = by_hip[hip]437            s.cross_key = sid438            if ambiguous:439                s.flags |= sf.FLAG_AMBIGUOUS_XM440            g = gaia_of.get(sid)441            if g is not None:442                s.rv, s.rv_error, s.teff = g.rv, g.rv_error, g.teff443                # the Bailer-Jones distance of the Gaia counterpart replaces the Hipparcos parallax only when the444                # identification is unambiguous, the Gaia solution is well behaved and more precise445                if (g.dist is not None and not ambiguous and g.ruwe is not None and g.ruwe <= 1.4446                        and g.parallax_error is not None and eplx is not None and g.parallax_error < eplx447                        and not (g.flags & sf.FLAG_LOW_SNR)):448                    s.dist, s.dist_lo, s.dist_hi, s.dist_method = g.dist, g.dist_lo, g.dist_hi, sf.DIST_BAILER_JONES449                    s.flags |= sf.FLAG_DISTANCE_FROM_COUNTERPART450        if s.dist is None and own:451            s.dist, s.dist_lo, s.dist_hi, s.dist_method = own[0], own[1], own[2], sf.DIST_INVERSE452        hip_stars[hip] = s453454    # ---- starter selection455    exo_hips = set()456    nea = os.path.join(RAW, "nea", "pscomppars.csv")457    if os.path.exists(nea):458        for r in read_csv(nea, ["hip_name"]):459            m = re.match(r"HIP (\d+)", r["hip_name"].strip())460            if m:461                exo_hips.add(int(m.group(1)))462    figure_hips = set()463    stell = [p for p in glob.glob(os.path.join(RAW, "stellarium", "modern_index_*.json")) if not p.endswith(".meta.json")]464    if stell:465        with open(sorted(stell)[-1], encoding="utf-8") as f:466            for c in json.load(f)["constellations"]:467                for line in c["lines"]:468                    figure_hips.update(int(h) for h in line if isinstance(h, int))469    starter_hips = set()470    for hip, s in hip_stars.items():471        bright = (s.mag if s.mag is not None else (s.mag2 if s.mag2 is not None else 99)) <= STARTER_VMAG472        near = s.dist is not None and s.dist <= STARTER_NEAR_PC473        if bright or near or hip in csn or hip in exo_hips or hip in figure_hips:474            starter_hips.add(hip)475    gcns_near = [s for s in gcns if not s.cross_key and s.dist is not None and s.dist <= STARTER_GAIA_NEAR_PC]476    starter_gaia = {s.source_key for s in gcns_near}477    names_near = match_nearby_names([s for s in gcns if not s.cross_key and s.dist is not None and s.dist <= 25.0], hyg_no_hip)478    log("starter: %d Hipparcos stars, %d Gaia-only stars within %.0f pc; %d nearby Gaia stars named from HYG"479        % (len(starter_hips), len(starter_gaia), STARTER_GAIA_NEAR_PC, len(names_near)))480481    # ---- membership flags: the same star in other packs482    def membership(s):483        hip, gaia = s.hip(), s.gaia()484        m = 0485        if hip:486            m |= sf.FLAG_HIPPARCOS487            if hip in starter_hips:488                m |= sf.FLAG_STARTER489        if gaia:490            if gaia in starter_gaia:491                m |= sf.FLAG_STARTER492            if gaia in gcns_ids:493                m |= sf.FLAG_NEARBY494            if gaia in g10_ids:495                m |= sf.FLAG_G10496            if gaia in g12_ids:497                m |= sf.FLAG_G12498        return m499    for group in (hip_stars.values(), gcns, g10, g12):500        for s in group:501            s.flags |= membership(s)502503    # ---- database rows504    def hip_object(hip):505        s = hip_stars[hip]506        name, designations = star_designations(hip, hip1.get(hip), hyg, csn)507        sptype = (hip1.get(hip) or {}).get("sptype", "").strip() or None508        return ("hip:%d" % hip, name, "esa-hipparcos-2007", s.ra, s.dec, s.mag if s.mag is not None else s.mag2, designations, sptype)509510    def gaia_objects(stars):511        rows = []512        for s in stars:513            e = names_near.get(s.source_key)514            if e and not s.cross_key:515                name, designations = nearby_designations(s.source_key, e)516                rows.append(("gaia3:%d" % s.source_key, name, "gaia-edr3-gcns", s.ra, s.dec, s.mag, designations, None))517        return rows518519    esa = ("non-commercial", "Gaia and Hipparcos data: CC BY-NC 3.0 IGO (ESA). Free redistribution with the ESA/Gaia "520           "acknowledgement for non-commercial use; any commercial distribution needs prior authorisation from ESA "521           "(data.licences@esa.int). Cross-identifications from HYG: CC BY-SA 4.0. Star names: IAU, CC BY.")522    licence = "CC BY-NC 3.0 IGO (ESA Hipparcos/Gaia data); CC BY-SA 4.0 (HYG cross-identifications); CC BY (IAU star names)"523    zero_point = ("Stored Gaia parallaxes are the published values: the zero-point correction of Lindegren et al. (2021, "524                  "A&A 649, A4; a few tens of microarcseconds, depending on magnitude, colour and position) is NOT applied. "525                  "The Bailer-Jones et al. (2021) distances include it.")526    distances = ("No naive 1/parallax: Gaia records carry the Bailer-Jones et al. (2021) geometric distance (posterior "527                 "median, 16th-84th percentiles) or none; Hipparcos records use the Bailer-Jones distance of their Gaia DR3 "528                 "counterpart when it is unambiguous, has RUWE <= 1.4 and a smaller parallax error, otherwise 1/parallax "529                 "only when parallax/error >= 5, otherwise no distance (direction only).")530531    hip_all = [hip_stars[h] for h in sorted(hip_stars)]532    write_pack(out_dir, "stars-hipparcos", "Hipparcos stars (new reduction, 117 955 stars) with Gaia DR3 cross-identification",533               hip_all, sf.FLAG_HIPPARCOS, ["esa-hipparcos-2007", "esa-hipparcos-1997", "esa-gaia-dr3", "bailer-jones-2021", "iau-csn", "hyg-v41"],534               [hip_object(h) for h in sorted(hip_stars)], licence, sources.GAIA_ACK + " Hipparcos: ESA, van Leeuwen (2007).", esa,535               {"limit": "Hipparcos catalogue: complete to V = 7.3-9.0 depending on galactic latitude and spectral type; faintest entries V ~ 12.4.",536                "epoch": "J1991.25 (ICRS)", "distances": distances,537                "cross_identification": "Gaia DR3 counterpart from gaiadr3.hipparcos2_best_neighbour, forced one-to-one; %d of 117 955 stars matched. Unmatched: mostly the brightest stars (saturated in Gaia) and close binaries." % len(by_hip)})538539    write_pack(out_dir, "stars-gaia-nearby", "Gaia Catalogue of Nearby Stars (100 pc, 331 312 stars)",540               gcns, sf.FLAG_NEARBY, ["gaia-edr3-gcns", "esa-gaia-dr3", "hyg-v41"], gaia_objects(gcns), licence, sources.GAIA_ACK, esa,541               {"limit": "Sources of Gaia EDR3 with a probability > 0 of lying within 100 pc; about 92 % complete for spectral types up to M9 at 100 pc. Stars brighter than G ~ 3 are missing from Gaia (use the Hipparcos pack).",542                "epoch": "J2016.0 (ICRS)", "distances": "GCNS posterior distance: median (dist_50) with the 16th and 84th percentiles.",543                "parallax_zero_point": zero_point})544545    gaia_cov = {"epoch": "J2016.0 (ICRS)", "distances": distances, "parallax_zero_point": zero_point,546                "teff": "GSP-Phot effective temperatures (model-dependent, status 'estimated') only for G <= 10 where the supplement was fetched."}547    write_pack(out_dir, "stars-gaia-g10", "Gaia DR3 stars to G = 10",548               g10, sf.FLAG_G10, ["esa-gaia-dr3", "bailer-jones-2021"], [], licence, sources.GAIA_ACK, esa,549               dict(gaia_cov, limit="All Gaia DR3 sources with phot_g_mean_mag <= 10 (%d). Gaia is incomplete brighter than G ~ 3 and unreliable brighter than G ~ 6 (saturation): the Hipparcos pack supplies those stars." % len(g10)))550    if build_g12:551        write_pack(out_dir, "stars-gaia-g12", "Gaia DR3 stars, 10 < G <= 12",552                   g12, sf.FLAG_G12, ["esa-gaia-dr3", "bailer-jones-2021"], [], licence, sources.GAIA_ACK, esa,553                   dict(gaia_cov, limit="All Gaia DR3 sources with 10 < phot_g_mean_mag <= 12 (%d). Increment of the G <= 10 pack: install both for a complete G <= 12 sky." % len(g12)))554    else:555        log("stars-gaia-g12 NOT built: tiers reach only G = %.3f" % (limit / 1000.0))556557    starter = [hip_stars[h] for h in sorted(starter_hips)] + sorted(gcns_near, key=lambda s: s.source_key)558    rows = [hip_object(h) for h in sorted(starter_hips)] + gaia_objects(gcns_near)559    pack_dir = os.path.join(out_dir, "starter")560    os.makedirs(pack_dir, exist_ok=True)561    counts = sf.write(os.path.join(pack_dir, "stars.bin"), starter)562    write_json(os.path.join(pack_dir, "stars_part.json"),563               {"counts": counts, "rows": rows, "with_distance": sum(1 for s in starter if s.dist is not None),564                "selection": "Hipparcos stars with V <= %.1f, or within %.0f pc, or named by the IAU, or used by a constellation figure, or hosting a confirmed exoplanet (%d stars); Gaia Catalogue of Nearby Stars sources within %.0f pc that have no Hipparcos number (%d)."565                             % (STARTER_VMAG, STARTER_NEAR_PC, len(starter_hips), STARTER_GAIA_NEAR_PC, len(gcns_near)),566                "distances": distances, "zero_point": zero_point, "licence": licence, "redistribution": esa})567    log("starter stars: %d records" % counts["records"])568569570if __name__ == "__main__":571    main(sys.argv)572
Files main
Menu

Theme