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/starfile.py11# Description : Writer of the binary star catalogue (format documented in12# Packages/CosmosCatalog/Sources/StarFile.swift): fixed13# 112-byte records grouped in HEALPix tiles by magnitude14# band, tile directory with bounding cones, sorted HIP and15# Gaia identifier indices. Deterministic output.16# Module : DataPipeline17# Repository : https://git.spboucher.ai/orix-cosmos18# Project Website : https://www.orixlab.dev19# Created : 2026-11-2420# Last Modified : 2026-11-2421#22# =============================================================================23# AUTHOR & PROFESSIONAL AFFILIATION24# =============================================================================25#26# Author : Simon-Pierre Boucher27# Position : Professor of Finance28# Institution : Université du Québec en Outaouais (UQO)29# Department : Département des sciences administratives30# Organization : SP Boucher31#32# Website : https://spboucher.ai33# Git : https://git.spboucher.ai34#35# =============================================================================36# OFFICIAL CONTACT DIRECTORY37# =============================================================================38#39# General : info@spboucher.ai40# Professional : contact@spboucher.ai41# Direct : simon@spboucher.ai42# Research : research@spboucher.ai43# Development : dev@spboucher.ai44# Support : support@spboucher.ai45# Security/Admin : admin@spboucher.ai46# Notifications : notifications@spboucher.ai47#48# Preferred Contact: support@spboucher.ai49#50# =============================================================================51# COPYRIGHT & INTELLECTUAL PROPERTY52# =============================================================================53#54# Copyright (c) 202655# Simon-Pierre Boucher56#57# All rights reserved where applicable.58#59# This file is governed by the applicable project license,60# copyright notices, institutional agreements and relevant law.61#62# Unless expressly authorized by the applicable license or63# rights holder, copying, redistribution, sublicensing,64# publication and commercial exploitation are not permitted.65#66# Existing third-party rights and notices remain unaffected.67#68# =============================================================================69# CONFIDENTIALITY & SECURITY70# =============================================================================71#72# Classification : Public73# Distribution : Public repository; use is governed by the project license74# Security Contact : admin@spboucher.ai75#76# Access to this source does not independently grant permission77# to redistribute or disclose confidential materials.78#79# Do not embed credentials, private keys, access tokens,80# certificates or confidential personal information.81#82# =============================================================================83# LICENSE & MAINTENANCE84# =============================================================================85#86# License : None specified (no license file in this repository)87# Maintainer : Simon-Pierre Boucher88# Technical Contact: dev@spboucher.ai89#90# =============================================================================91# END OF SP BOUCHER SOURCE HEADER92# =============================================================================9394import math95import struct9697from healpix import ang2pix_nest9899MAGIC = b"COSMSTR1"100VERSION = 1101HEADER_SIZE, RECORD_SIZE, TILE_SIZE, INDEX_SIZE = 128, 112, 48, 12102RECORD = struct.Struct("<QQddf17fBBHI")103TILE = struct.Struct("<QBBHff3ffIII")104assert RECORD.size == RECORD_SIZE and TILE.size == TILE_SIZE105106SOURCE_HIPPARCOS, SOURCE_GAIA, SOURCE_GCNS = 1, 2, 3107DIST_NONE, DIST_BAILER_JONES, DIST_GCNS, DIST_INVERSE, DIST_PUBLISHED = 0, 1, 2, 3, 4108FLAG_STARTER, FLAG_HIPPARCOS, FLAG_NEARBY, FLAG_G10, FLAG_G12 = 1, 2, 4, 8, 16109FLAG_LOW_SNR, FLAG_NONPOSITIVE_PLX, FLAG_NO_PLX, FLAG_HIGH_RUWE = 32, 64, 128, 256110FLAG_DISTANCE_FROM_COUNTERPART, FLAG_AMBIGUOUS_XM = 512, 1024111112# Magnitude bands (upper limits) of the tile levels. A star without magnitude goes to the last level.113LEVEL_LIMITS = [6.0, 8.0, 10.0, 12.0, 14.0, 16.0, float("inf")]114MAX_TILE_POPULATION = 4096115MAX_ORDER = 6116NAN = float("nan")117118119def f32(x):120 """Rounds to the float32 that will be stored (so that sorting uses the stored value)."""121 return struct.unpack("<f", struct.pack("<f", x))[0]122123124def nn(x):125 return NAN if x is None else x126127128class Star:129 """One record. Float fields are None when absent. Units as in the format description."""130 __slots__ = ("source_key", "cross_key", "ra", "dec", "epoch", "parallax", "parallax_error", "pmra", "pmdec",131 "pmra_error", "pmdec_error", "rv", "rv_error", "dist", "dist_lo", "dist_hi", "mag", "colour_a",132 "colour_b", "mag2", "teff", "ruwe", "source", "dist_method", "flags")133134 def __init__(self, **kw):135 for k in self.__slots__:136 setattr(self, k, kw.get(k))137 self.flags = self.flags or 0138 self.dist_method = self.dist_method or 0139 self.cross_key = self.cross_key or 0140141 def hip(self):142 v = self.source_key if self.source == SOURCE_HIPPARCOS else self.cross_key143 return v or None144145 def gaia(self):146 v = self.cross_key if self.source == SOURCE_HIPPARCOS else self.source_key147 return v or None148149 def canonical(self):150 h = self.hip()151 return ("hip", h) if h else ("gaia3", self.source_key)152153 def pack(self):154 return RECORD.pack(self.source_key, self.cross_key, self.ra, self.dec, self.epoch,155 nn(self.parallax), nn(self.parallax_error), nn(self.pmra), nn(self.pmdec), nn(self.pmra_error),156 nn(self.pmdec_error), nn(self.rv), nn(self.rv_error), nn(self.dist), nn(self.dist_lo),157 nn(self.dist_hi), nn(self.mag), nn(self.colour_a), nn(self.colour_b), nn(self.mag2),158 nn(self.teff), nn(self.ruwe), self.source, self.dist_method, self.flags, 0)159160161def unit(ra, dec):162 c = math.cos(dec)163 return (c * math.cos(ra), c * math.sin(ra), math.sin(dec))164165166def separation(a, b):167 cx = a[1] * b[2] - a[2] * b[1]168 cy = a[2] * b[0] - a[0] * b[2]169 cz = a[0] * b[1] - a[1] * b[0]170 return math.atan2(math.sqrt(cx * cx + cy * cy + cz * cz), a[0] * b[0] + a[1] * b[1] + a[2] * b[2])171172173def level_of(mag):174 if mag is None:175 return len(LEVEL_LIMITS) - 1176 for k, limit in enumerate(LEVEL_LIMITS):177 if mag < limit:178 return k179 return len(LEVEL_LIMITS) - 1180181182def write(path, stars):183 """Writes `stars` (list of Star) to `path`. Returns a dict of counts for the manifest."""184 levels = [[] for _ in LEVEL_LIMITS]185 for s in stars:186 if s.mag is not None:187 s.mag = f32(s.mag)188 levels[level_of(s.mag)].append(s)189 tiles = []190 for level, members in enumerate(levels):191 if not members:192 continue193 order = 0194 while len(members) / (12 * 4 ** order) > MAX_TILE_POPULATION and order < MAX_ORDER:195 order += 1196 groups = {}197 for s in members:198 groups.setdefault(ang2pix_nest(order, s.ra, s.dec), []).append(s)199 for pix in sorted(groups):200 tiles.append((level, order, pix, groups[pix]))201 directory = bytearray()202 records = bytearray()203 hip_index, gaia_index = [], []204 first = 0205 for level, order, pix, members in tiles:206 members.sort(key=lambda s: (s.mag if s.mag is not None else float("inf"), s.source_key))207 vectors = [unit(s.ra, s.dec) for s in members]208 sx = sum(v[0] for v in vectors)209 sy = sum(v[1] for v in vectors)210 sz = sum(v[2] for v in vectors)211 norm = math.sqrt(sx * sx + sy * sy + sz * sz)212 c32 = (f32(sx / norm), f32(sy / norm), f32(sz / norm)) if norm > 0 else (0.0, 0.0, 1.0)213 cn = math.sqrt(sum(x * x for x in c32))214 c = tuple(x / cn for x in c32)215 # the stored radius is the float32 at or just above (largest separation + 1e-6 rad)216 radius = max(separation(v, c) for v in vectors) + 1e-6217 radius32 = f32(radius)218 if radius32 < radius:219 radius32 = struct.unpack("<f", struct.pack("<I", struct.unpack("<I", struct.pack("<f", radius32))[0] + 1))[0]220 mags = [s.mag for s in members if s.mag is not None]221 directory += TILE.pack((level << 56) | pix, order, level, 0, min(mags) if mags else NAN, max(mags) if mags else NAN,222 c32[0], c32[1], c32[2], radius32, first, len(members), 0)223 for k, s in enumerate(members):224 records += s.pack()225 if s.hip():226 hip_index.append((s.hip(), first + k))227 if s.gaia():228 gaia_index.append((s.gaia(), first + k))229 first += len(members)230 hip_index.sort()231 gaia_index.sort()232 for name, index in (("HIP", hip_index), ("Gaia", gaia_index)):233 for a, b in zip(index, index[1:]):234 if a[0] == b[0]:235 raise ValueError("%s identifier %d appears twice in %s" % (name, a[0], path))236 records_offset = HEADER_SIZE + len(tiles) * TILE_SIZE237 hip_offset = records_offset + first * RECORD_SIZE238 gaia_offset = hip_offset + len(hip_index) * INDEX_SIZE239 header = MAGIC + struct.pack("<IIIIQIIQQQQQQ", VERSION, HEADER_SIZE, RECORD_SIZE, TILE_SIZE, first, len(tiles), 0,240 HEADER_SIZE, records_offset, hip_offset, len(hip_index), gaia_offset, len(gaia_index))241 header += b"\0" * (HEADER_SIZE - len(header))242 with open(path, "wb") as f:243 f.write(header)244 f.write(directory)245 f.write(records)246 for index in (hip_index, gaia_index):247 f.write(b"".join(struct.pack("<QI", k, i) for k, i in index))248 return {"records": first, "tiles": len(tiles), "hip_index": len(hip_index), "gaia_index": len(gaia_index)}249