From 8ca4383b2e7180cb9441668b61ecdf5680fbaae0 Mon Sep 17 00:00:00 2001 From: Ryan Malloy Date: Wed, 25 Feb 2026 17:02:08 -0700 Subject: [PATCH] v0.14.0: refracted planet/moon rise/set, constellation identification MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add 4 refracted rise/set functions completing the rise/set feature set: - planet_next_rise/set_refracted: -0.569 deg threshold (refraction only, point source — even Jupiter at opposition is only 24 arcsec) - moon_next_rise/set_refracted: -0.833 deg threshold (refraction + mean semidiameter, same as Sun) Add IAU constellation identification from Roman (1987) CDS VI/42: - 357 boundary segments covering all 88 constellations - Precesses J2000 coordinates to B1875.0 epoch for lookup - Two overloads: constellation(equatorial) and constellation(float8, float8) - IMMUTABLE (compiled-in static data) 141 -> 147 SQL objects. 24 -> 25 regression suites. All 25 pass. --- CLAUDE.md | 30 +- Makefile | 9 +- pg_orrery.control | 2 +- sql/pg_orrery--0.13.0--0.14.0.sql | 48 + sql/pg_orrery--0.14.0.sql | 1562 +++++++++++++++++++++++++++++ src/constellation_data.c | 378 +++++++ src/constellation_data.h | 26 + src/constellation_funcs.c | 175 ++++ src/rise_set_funcs.c | 148 +++ test/expected/constellation.out | 133 +++ test/expected/rise_set.out | 62 ++ test/sql/constellation.sql | 81 ++ test/sql/rise_set.sql | 40 + 13 files changed, 2681 insertions(+), 13 deletions(-) create mode 100644 sql/pg_orrery--0.13.0--0.14.0.sql create mode 100644 sql/pg_orrery--0.14.0.sql create mode 100644 src/constellation_data.c create mode 100644 src/constellation_data.h create mode 100644 src/constellation_funcs.c create mode 100644 test/expected/constellation.out create mode 100644 test/sql/constellation.sql diff --git a/CLAUDE.md b/CLAUDE.md index 6f0fea3..a1eb7a2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,9 +1,9 @@ # pg_orrery — A Database Orrery for PostgreSQL ## What This Is -A database orrery — celestial mechanics types and functions for PostgreSQL. Native C extension using PGXS, 132 SQL objects (124 user-visible functions + 8 GiST support), 9 custom types, covering satellites (SGP4/SDP4), planets (VSOP87 + optional JPL DE441), Moon (ELP2000-82B), 19 planetary moons (L1.2/TASS17/GUST86/MarsSat), stars (with proper motion and annual parallax), comets, asteroids (MPC catalog), Jupiter radio bursts, interplanetary Lambert transfers, equatorial RA/Dec coordinates with GiST-indexed angular separation, atmospheric refraction, annual stellar aberration, and light-time correction. +A database orrery — celestial mechanics types and functions for PostgreSQL. Native C extension using PGXS, 147 SQL objects (131 user-visible functions + 16 GiST support), 9 custom types, covering satellites (SGP4/SDP4), planets (VSOP87 + optional JPL DE441), Moon (ELP2000-82B), 19 planetary moons (L1.2/TASS17/GUST86/MarsSat), stars (with proper motion and annual parallax), comets, asteroids (MPC catalog), Jupiter radio bursts, interplanetary Lambert transfers, equatorial RA/Dec coordinates with GiST-indexed angular separation, atmospheric refraction, annual stellar aberration, light-time correction, rise/set prediction (geometric + refracted), and IAU constellation identification (Roman 1987). -**Current version:** 0.12.0 +**Current version:** 0.14.0 **Repository:** https://git.supported.systems/warehack.ing/pg_orrery **Documentation:** https://pg-orrery.warehack.ing @@ -11,7 +11,7 @@ A database orrery — celestial mechanics types and functions for PostgreSQL. Na ```bash make PG_CONFIG=/usr/bin/pg_config # Compile with PGXS sudo make install PG_CONFIG=/usr/bin/pg_config # Install extension -make installcheck PG_CONFIG=/usr/bin/pg_config # Run 22 regression test suites +make installcheck PG_CONFIG=/usr/bin/pg_config # Run 25 regression test suites ``` Requires: PostgreSQL 17 development headers, GCC, Make. @@ -27,7 +27,7 @@ Image: `git.supported.systems/warehack.ing/pg_orrery:pg17` ## Project Layout ``` -pg_orrery.control # Extension metadata (version 0.12.0) +pg_orrery.control # Extension metadata (version 0.14.0) Makefile # PGXS build + Docker targets sql/ pg_orrery--0.1.0.sql # v0.1.0: satellite types/functions/operators @@ -42,6 +42,8 @@ sql/ pg_orrery--0.10.0.sql # v0.10.0: angular separation, cone search, apparent functions (114 functions) pg_orrery--0.11.0.sql # v0.11.0: orbital_elements constructors, moon equatorial (120 functions) pg_orrery--0.12.0.sql # v0.12.0: equatorial GiST, DE moon equatorial (132 objects) + pg_orrery--0.13.0.sql # v0.13.0: nutation, make_equatorial, rise/set (141 objects) + pg_orrery--0.14.0.sql # v0.14.0: refracted rise/set, constellation ID (147 objects) pg_orrery--0.1.0--0.2.0.sql # Migration: v0.1.0 → v0.2.0 (adds solar system) pg_orrery--0.2.0--0.3.0.sql # Migration: v0.2.0 → v0.3.0 (adds DE ephemeris) pg_orrery--0.3.0--0.4.0.sql # Migration: v0.3.0 → v0.4.0 @@ -53,6 +55,8 @@ sql/ pg_orrery--0.9.0--0.10.0.sql # Migration: v0.9.0 → v0.10.0 (angular separation, cone search) pg_orrery--0.10.0--0.11.0.sql # Migration: v0.10.0 → v0.11.0 (constructors, moon equatorial) pg_orrery--0.11.0--0.12.0.sql # Migration: v0.11.0 → v0.12.0 (equatorial GiST, DE moon equatorial) + pg_orrery--0.12.0--0.13.0.sql # Migration: v0.12.0 → v0.13.0 (nutation, make_equatorial, rise/set) + pg_orrery--0.13.0--0.14.0.sql # Migration: v0.13.0 → v0.14.0 (refracted rise/set, constellation ID) src/ pg_orrery.c # PG_MODULE_MAGIC + _PG_init() (GUC registration) types.h # All struct definitions + constants + DE body ID mapping @@ -79,6 +83,9 @@ src/ orbital_elements_type.c # orbital_elements type, MPC parser, small_body_observe/equatorial/apparent() equatorial_funcs.c # equatorial type I/O, accessors, satellite/planet/sun/moon RA/Dec refraction_funcs.c # atmospheric_refraction(), _ext(), topo_elevation_apparent() + rise_set_funcs.c # planet/sun/moon rise/set (geometric + refracted) + constellation_data.h / .c # Roman (1987) IAU boundary table (CDS VI/42, 357 segments) + constellation_funcs.c # constellation() from equatorial or RA/Dec l12.c / l12.h # L1.2 Galilean moon theory (Lieske 1998) tass17.c / tass17.h # TASS 1.7 Saturn moon theory (Vienne & Duriez 1995) gust86.c / gust86.h # GUST86 Uranus moon theory (Laskar & Jacobson 1987) @@ -103,7 +110,7 @@ src/ PROVENANCE.md # Vendoring decision, modifications, verification LICENSE # MIT license (Bill Gray / Project Pluto) test/ - sql/ # 22 regression test suites + sql/ # 25 regression test suites expected/ # Expected output data/vallado_518.json # 518 Vallado test vectors (AIAA 2006-6753-Rev1) docs/ @@ -130,7 +137,7 @@ All types are fixed-size, `STORAGE = plain`, `ALIGNMENT = double`. No TOAST over | `orbital_elements` | 72 | Classical Keplerian elements for comets/asteroids (epoch, q, e, inc, omega, Omega, tp, H, G) | | `equatorial` | 24 | Apparent RA (hours), Dec (degrees), distance (km) — of date | -## Function Domains (132 SQL objects) +## Function Domains (147 SQL objects) | Domain | Theory | Key Functions | Count | |--------|--------|---------------|-------| @@ -147,6 +154,8 @@ All types are fixed-size, `STORAGE = plain`, `ALIGNMENT = double`. No TOAST over | DE ephemeris | JPL DE440/441 (optional) | `planet_observe_de()`, `*_equatorial_de()`, `*_apparent_de()` | 23 | | GiST index (TLE) | Altitude-band approximation | `&&` (overlap), `<->` (distance) | 8 | | GiST index (equatorial) | Spherical bounding box | `<->` (KNN ordering) | 8 | +| Rise/set | Bisection (60s scan) | `planet_next_rise()`, `sun_next_rise_refracted()`, `moon_next_set_refracted()` | 12 | +| Constellation | Roman (1987) CDS VI/42 | `constellation()` (equatorial + RA/Dec overloads) | 2 | | Diagnostics | -- | `pg_orrery_ephemeris_info()` | 1 | All functions are `PARALLEL SAFE`. VSOP87/ELP82B functions are `IMMUTABLE` (compiled-in coefficients). DE functions are `STABLE` (external file dependency). @@ -280,7 +289,7 @@ All numerical logic is byte-identical to upstream. Verified against 518 Vallado ## Testing -22 regression test suites via `make installcheck`: +25 regression test suites via `make installcheck`: | Suite | What it tests | |-------|--------------| @@ -306,10 +315,13 @@ All numerical logic is byte-identical to upstream. Verified against 518 Vallado | v011_features | make_orbital_elements constructors, moon equatorial functions | | gist_equatorial | Equatorial GiST KNN ordering, RA wrapping, cone search, EXPLAIN index scan | | v012_features | DE moon equatorial fallback to VSOP87, invalid body_id rejection | +| v013_features | Nutation correction, make_equatorial constructor | +| rise_set | Planet/Sun/Moon rise/set (geometric + refracted), circumpolar, polar night | +| constellation | Roman (1987) boundary lookup, known stars, solar system objects, edge cases | ### PG Version Matrix -Test all 22 regression suites + DE reader unit test across PostgreSQL 14-18 using Docker: +Test all 25 regression suites + DE reader unit test across PostgreSQL 14-18 using Docker: ```bash make test-matrix # Full matrix (PG 14-18) @@ -335,7 +347,7 @@ Logs saved to `test/matrix-logs/pg${ver}.log`. The script reuses the Dockerfile Starlight docs at `docs/` — 44+ MDX pages covering all domains. -Sections: Getting Started, Guides (9 domain walkthroughs incl. DE ephemeris), Workflow Translation (Skyfield/Horizons/GMAT/Radio Jupiter Pro comparisons), Reference (all 132 SQL objects incl. DE variants, equatorial GiST, refraction), Architecture (Hamilton's principles, constant custody, observation pipeline), Performance (benchmarks). +Sections: Getting Started, Guides (9 domain walkthroughs incl. DE ephemeris), Workflow Translation (Skyfield/Horizons/GMAT/Radio Jupiter Pro comparisons), Reference (all 147 SQL objects incl. DE variants, equatorial GiST, refraction, rise/set, constellation), Architecture (Hamilton's principles, constant custody, observation pipeline), Performance (benchmarks). ### Local Development ```bash diff --git a/Makefile b/Makefile index 781c9dd..59a5705 100644 --- a/Makefile +++ b/Makefile @@ -11,7 +11,8 @@ DATA = sql/pg_orrery--0.1.0.sql sql/pg_orrery--0.2.0.sql sql/pg_orrery--0.1.0--0 sql/pg_orrery--0.10.0.sql sql/pg_orrery--0.9.0--0.10.0.sql \ sql/pg_orrery--0.11.0.sql sql/pg_orrery--0.10.0--0.11.0.sql \ sql/pg_orrery--0.12.0.sql sql/pg_orrery--0.11.0--0.12.0.sql \ - sql/pg_orrery--0.13.0.sql sql/pg_orrery--0.12.0--0.13.0.sql + sql/pg_orrery--0.13.0.sql sql/pg_orrery--0.12.0--0.13.0.sql \ + sql/pg_orrery--0.14.0.sql sql/pg_orrery--0.13.0--0.14.0.sql # Our extension C sources OBJS = src/pg_orrery.o src/tle_type.o src/eci_type.o src/observer_type.o \ @@ -29,7 +30,8 @@ OBJS = src/pg_orrery.o src/tle_type.o src/eci_type.o src/observer_type.o \ src/equatorial_funcs.o \ src/refraction_funcs.o \ src/gist_equatorial.o \ - src/rise_set_funcs.o + src/rise_set_funcs.o \ + src/constellation_data.o src/constellation_funcs.o # Vendored SGP4/SDP4 sources (pure C, from Bill Gray's sat_code, MIT license) SGP4_DIR = src/sgp4 @@ -47,7 +49,8 @@ REGRESS = tle_parse sgp4_propagate coord_transforms pass_prediction gist_index c de_ephemeris od_fit spgist_tle orbital_elements equatorial refraction \ aberration v011_features vallado_518 \ gist_equatorial v012_features \ - v013_features rise_set + v013_features rise_set \ + constellation REGRESS_OPTS = --inputdir=test # Pure C — no C++ runtime needed. LAPACK for OD solver (dgelss_). diff --git a/pg_orrery.control b/pg_orrery.control index 273faac..61c616e 100644 --- a/pg_orrery.control +++ b/pg_orrery.control @@ -1,4 +1,4 @@ comment = 'A database orrery — celestial mechanics types and functions for PostgreSQL' -default_version = '0.13.0' +default_version = '0.14.0' module_pathname = '$libdir/pg_orrery' relocatable = true diff --git a/sql/pg_orrery--0.13.0--0.14.0.sql b/sql/pg_orrery--0.13.0--0.14.0.sql new file mode 100644 index 0000000..c69c30e --- /dev/null +++ b/sql/pg_orrery--0.13.0--0.14.0.sql @@ -0,0 +1,48 @@ +-- pg_orrery 0.13.0 -> 0.14.0 migration +-- +-- Adds: refracted planet/moon rise/set (4 functions), +-- constellation identification (2 functions). + +-- ============================================================ +-- Refracted rise/set: planets (point source, -0.569 deg) +-- ============================================================ + +CREATE FUNCTION planet_next_rise_refracted(body_id int4, obs observer, t timestamptz) RETURNS timestamptz + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION planet_next_rise_refracted(int4, observer, timestamptz) IS + 'Next refracted rise time for a planet (-0.569 deg threshold: atmospheric refraction only). Earlier than geometric.'; + +CREATE FUNCTION planet_next_set_refracted(body_id int4, obs observer, t timestamptz) RETURNS timestamptz + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION planet_next_set_refracted(int4, observer, timestamptz) IS + 'Next refracted set time for a planet (-0.569 deg threshold: atmospheric refraction only). Later than geometric.'; + +-- ============================================================ +-- Refracted rise/set: Moon (-0.833 deg, same as Sun) +-- ============================================================ + +CREATE FUNCTION moon_next_rise_refracted(obs observer, t timestamptz) RETURNS timestamptz + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION moon_next_rise_refracted(observer, timestamptz) IS + 'Next refracted moonrise (-0.833 deg threshold: refraction + semidiameter). Earlier than geometric.'; + +CREATE FUNCTION moon_next_set_refracted(obs observer, t timestamptz) RETURNS timestamptz + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION moon_next_set_refracted(observer, timestamptz) IS + 'Next refracted moonset (-0.833 deg threshold: refraction + semidiameter). Later than geometric.'; + +-- ============================================================ +-- Constellation identification (Roman 1987, CDS VI/42) +-- ============================================================ + +CREATE FUNCTION constellation(eq equatorial) RETURNS text + AS 'MODULE_PATHNAME', 'constellation_from_equatorial' + LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION constellation(equatorial) IS + 'IAU constellation abbreviation (3 letters) from equatorial coordinates (Roman 1987).'; + +CREATE FUNCTION constellation(ra_hours float8, dec_deg float8) RETURNS text + AS 'MODULE_PATHNAME', 'constellation_from_radec' + LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION constellation(float8, float8) IS + 'IAU constellation from J2000 RA (hours [0,24)) and Dec (degrees [-90,90]).'; diff --git a/sql/pg_orrery--0.14.0.sql b/sql/pg_orrery--0.14.0.sql new file mode 100644 index 0000000..01eba93 --- /dev/null +++ b/sql/pg_orrery--0.14.0.sql @@ -0,0 +1,1562 @@ +-- pg_orrery -- Orbital mechanics types and functions for PostgreSQL +-- +-- Types: tle, eci_position, geodetic, topocentric, observer, pass_event +-- Provides SGP4/SDP4 propagation, coordinate transforms, pass prediction, +-- and GiST indexing on altitude bands for conjunction screening. +-- +-- All propagation uses WGS-72 constants (matching TLE mean element fitting). +-- Coordinate output uses WGS-84 (matching modern geodetic standards). + +-- ============================================================ +-- Shell types (forward declarations) +-- ============================================================ + +CREATE TYPE tle; +CREATE TYPE eci_position; +CREATE TYPE geodetic; +CREATE TYPE topocentric; +CREATE TYPE observer; +CREATE TYPE pass_event; + + +-- ============================================================ +-- TLE type: Two-Line Element set +-- ============================================================ + +CREATE FUNCTION tle_in(cstring) RETURNS tle + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION tle_out(tle) RETURNS cstring + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION tle_recv(internal) RETURNS tle + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION tle_send(tle) RETURNS bytea + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE TYPE tle ( + INPUT = tle_in, + OUTPUT = tle_out, + RECEIVE = tle_recv, + SEND = tle_send, + INTERNALLENGTH = 112, + ALIGNMENT = double, + STORAGE = plain +); + +COMMENT ON TYPE tle IS 'Two-Line Element set — parsed mean orbital elements for SGP4/SDP4 propagation'; + +-- TLE accessor functions + +CREATE FUNCTION tle_epoch(tle) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION tle_epoch(tle) IS 'TLE epoch as Julian date (UTC)'; + +CREATE FUNCTION tle_norad_id(tle) RETURNS int4 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION tle_norad_id(tle) IS 'NORAD catalog number'; + +CREATE FUNCTION tle_inclination(tle) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION tle_inclination(tle) IS 'Orbital inclination in degrees'; + +CREATE FUNCTION tle_eccentricity(tle) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION tle_eccentricity(tle) IS 'Orbital eccentricity (dimensionless)'; + +CREATE FUNCTION tle_raan(tle) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION tle_raan(tle) IS 'Right ascension of ascending node in degrees'; + +CREATE FUNCTION tle_arg_perigee(tle) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION tle_arg_perigee(tle) IS 'Argument of perigee in degrees'; + +CREATE FUNCTION tle_mean_anomaly(tle) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION tle_mean_anomaly(tle) IS 'Mean anomaly in degrees'; + +CREATE FUNCTION tle_mean_motion(tle) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION tle_mean_motion(tle) IS 'Mean motion in revolutions per day'; + +CREATE FUNCTION tle_bstar(tle) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION tle_bstar(tle) IS 'B* drag coefficient (1/earth-radii)'; + +CREATE FUNCTION tle_period(tle) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION tle_period(tle) IS 'Orbital period in minutes'; + +CREATE FUNCTION tle_age(tle, timestamptz) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION tle_age(tle, timestamptz) IS 'TLE age in days (positive = past epoch, negative = before epoch)'; + +CREATE FUNCTION tle_perigee(tle) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION tle_perigee(tle) IS 'Perigee altitude in km above WGS-72 ellipsoid'; + +CREATE FUNCTION tle_apogee(tle) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION tle_apogee(tle) IS 'Apogee altitude in km above WGS-72 ellipsoid'; + +CREATE FUNCTION tle_intl_desig(tle) RETURNS text + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION tle_intl_desig(tle) IS 'International designator (COSPAR ID)'; + +CREATE FUNCTION tle_from_lines(text, text) RETURNS tle + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION tle_from_lines(text, text) IS + 'Construct TLE from separate line1/line2 text columns'; + + +-- ============================================================ +-- ECI position type: True Equator Mean Equinox (TEME) frame +-- ============================================================ + +CREATE FUNCTION eci_in(cstring) RETURNS eci_position + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION eci_out(eci_position) RETURNS cstring + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION eci_recv(internal) RETURNS eci_position + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION eci_send(eci_position) RETURNS bytea + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE TYPE eci_position ( + INPUT = eci_in, + OUTPUT = eci_out, + RECEIVE = eci_recv, + SEND = eci_send, + INTERNALLENGTH = 48, + ALIGNMENT = double, + STORAGE = plain +); + +COMMENT ON TYPE eci_position IS 'Earth-Centered Inertial position and velocity in TEME frame (km, km/s)'; + +-- ECI accessor functions + +CREATE FUNCTION eci_x(eci_position) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION eci_y(eci_position) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION eci_z(eci_position) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION eci_vx(eci_position) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION eci_vy(eci_position) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION eci_vz(eci_position) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION eci_speed(eci_position) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION eci_speed(eci_position) IS 'Velocity magnitude in km/s'; + +CREATE FUNCTION eci_altitude(eci_position) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION eci_altitude(eci_position) IS 'Approximate geocentric altitude in km (radius - WGS72_AE)'; + + +-- ============================================================ +-- Geodetic type: WGS-84 latitude/longitude/altitude +-- ============================================================ + +CREATE FUNCTION geodetic_in(cstring) RETURNS geodetic + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION geodetic_out(geodetic) RETURNS cstring + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION geodetic_recv(internal) RETURNS geodetic + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION geodetic_send(geodetic) RETURNS bytea + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE TYPE geodetic ( + INPUT = geodetic_in, + OUTPUT = geodetic_out, + RECEIVE = geodetic_recv, + SEND = geodetic_send, + INTERNALLENGTH = 24, + ALIGNMENT = double, + STORAGE = plain +); + +COMMENT ON TYPE geodetic IS 'Geodetic coordinates on WGS-84 ellipsoid (lat/lon in degrees, altitude in km)'; + +CREATE FUNCTION geodetic_lat(geodetic) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION geodetic_lon(geodetic) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION geodetic_alt(geodetic) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + + +-- ============================================================ +-- Topocentric type: observer-relative az/el/range +-- ============================================================ + +CREATE FUNCTION topocentric_in(cstring) RETURNS topocentric + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION topocentric_out(topocentric) RETURNS cstring + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION topocentric_recv(internal) RETURNS topocentric + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION topocentric_send(topocentric) RETURNS bytea + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE TYPE topocentric ( + INPUT = topocentric_in, + OUTPUT = topocentric_out, + RECEIVE = topocentric_recv, + SEND = topocentric_send, + INTERNALLENGTH = 32, + ALIGNMENT = double, + STORAGE = plain +); + +COMMENT ON TYPE topocentric IS 'Topocentric coordinates relative to observer (azimuth, elevation, range, range rate)'; + +CREATE FUNCTION topo_azimuth(topocentric) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION topo_azimuth(topocentric) IS 'Azimuth in degrees (0=N, 90=E, 180=S, 270=W)'; + +CREATE FUNCTION topo_elevation(topocentric) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION topo_elevation(topocentric) IS 'Elevation in degrees (0=horizon, 90=zenith)'; + +CREATE FUNCTION topo_range(topocentric) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION topo_range(topocentric) IS 'Slant range in km'; + +CREATE FUNCTION topo_range_rate(topocentric) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION topo_range_rate(topocentric) IS 'Range rate in km/s (positive = receding)'; + + +-- ============================================================ +-- Observer type: ground station location +-- ============================================================ + +CREATE FUNCTION observer_in(cstring) RETURNS observer + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION observer_out(observer) RETURNS cstring + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION observer_recv(internal) RETURNS observer + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION observer_send(observer) RETURNS bytea + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE TYPE observer ( + INPUT = observer_in, + OUTPUT = observer_out, + RECEIVE = observer_recv, + SEND = observer_send, + INTERNALLENGTH = 24, + ALIGNMENT = double, + STORAGE = plain +); + +COMMENT ON TYPE observer IS 'Ground observer location (accepts: 40.0N 105.3W 1655m or decimal degrees)'; + +CREATE FUNCTION observer_lat(observer) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION observer_lat(observer) IS 'Latitude in degrees (positive = North)'; + +CREATE FUNCTION observer_lon(observer) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION observer_lon(observer) IS 'Longitude in degrees (positive = East)'; + +CREATE FUNCTION observer_alt(observer) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION observer_alt(observer) IS 'Altitude in meters above WGS-84 ellipsoid'; + +CREATE FUNCTION observer_from_geodetic(float8, float8, float8 DEFAULT 0.0) RETURNS observer + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION observer_from_geodetic(float8, float8, float8) IS + 'Construct observer from lat (deg), lon (deg), altitude (meters). Avoids text formatting round-trips.'; + + +-- ============================================================ +-- Pass event type: satellite visibility window +-- ============================================================ + +CREATE FUNCTION pass_event_in(cstring) RETURNS pass_event + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION pass_event_out(pass_event) RETURNS cstring + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION pass_event_recv(internal) RETURNS pass_event + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION pass_event_send(pass_event) RETURNS bytea + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE TYPE pass_event ( + INPUT = pass_event_in, + OUTPUT = pass_event_out, + RECEIVE = pass_event_recv, + SEND = pass_event_send, + INTERNALLENGTH = 48, + ALIGNMENT = double, + STORAGE = plain +); + +COMMENT ON TYPE pass_event IS 'Satellite pass event (AOS/MAX/LOS times, max elevation, AOS/LOS azimuths)'; + +CREATE FUNCTION pass_aos_time(pass_event) RETURNS timestamptz + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION pass_aos_time(pass_event) IS 'Acquisition of signal time'; + +CREATE FUNCTION pass_max_el_time(pass_event) RETURNS timestamptz + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION pass_max_el_time(pass_event) IS 'Maximum elevation time'; + +CREATE FUNCTION pass_los_time(pass_event) RETURNS timestamptz + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION pass_los_time(pass_event) IS 'Loss of signal time'; + +CREATE FUNCTION pass_max_elevation(pass_event) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION pass_max_elevation(pass_event) IS 'Maximum elevation in degrees'; + +CREATE FUNCTION pass_aos_azimuth(pass_event) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION pass_aos_azimuth(pass_event) IS 'AOS azimuth in degrees (0=N)'; + +CREATE FUNCTION pass_los_azimuth(pass_event) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION pass_los_azimuth(pass_event) IS 'LOS azimuth in degrees (0=N)'; + +CREATE FUNCTION pass_duration(pass_event) RETURNS interval + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION pass_duration(pass_event) IS 'Pass duration (LOS - AOS)'; + + +-- ============================================================ +-- SGP4/SDP4 propagation functions +-- ============================================================ + +CREATE FUNCTION sgp4_propagate(tle, timestamptz) RETURNS eci_position + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION sgp4_propagate(tle, timestamptz) IS + 'Propagate TLE to a point in time using SGP4 (near-earth) or SDP4 (deep-space). Returns TEME ECI position/velocity.'; + +CREATE FUNCTION sgp4_propagate_safe(tle, timestamptz) RETURNS eci_position + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE PARALLEL SAFE; +COMMENT ON FUNCTION sgp4_propagate_safe(tle, timestamptz) IS + 'Like sgp4_propagate but returns NULL on error instead of raising an exception. For batch queries with potentially invalid TLEs.'; + +CREATE FUNCTION sgp4_propagate_series(tle, timestamptz, timestamptz, interval) + RETURNS TABLE(t timestamptz, x float8, y float8, z float8, vx float8, vy float8, vz float8) + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE + ROWS 100; +COMMENT ON FUNCTION sgp4_propagate_series(tle, timestamptz, timestamptz, interval) IS + 'Propagate TLE over a time range at regular intervals. Returns time series of TEME positions.'; + +CREATE FUNCTION tle_distance(tle, tle, timestamptz) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION tle_distance(tle, tle, timestamptz) IS + 'Euclidean distance in km between two TLEs at a reference time'; + + +-- ============================================================ +-- Coordinate transform functions +-- ============================================================ + +CREATE FUNCTION eci_to_geodetic(eci_position, timestamptz) RETURNS geodetic + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION eci_to_geodetic(eci_position, timestamptz) IS + 'Convert TEME ECI position to WGS-84 geodetic coordinates at given time'; + +CREATE FUNCTION eci_to_topocentric(eci_position, observer, timestamptz) RETURNS topocentric + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION eci_to_topocentric(eci_position, observer, timestamptz) IS + 'Convert TEME ECI position to topocentric (az/el/range) relative to observer'; + +CREATE FUNCTION subsatellite_point(tle, timestamptz) RETURNS geodetic + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION subsatellite_point(tle, timestamptz) IS + 'Subsatellite (nadir) point on WGS-84 ellipsoid at given time'; + +CREATE FUNCTION ground_track(tle, timestamptz, timestamptz, interval) + RETURNS TABLE(t timestamptz, lat float8, lon float8, alt float8) + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE + ROWS 100; +COMMENT ON FUNCTION ground_track(tle, timestamptz, timestamptz, interval) IS + 'Ground track as time series of subsatellite points (lat/lon in degrees, alt in km)'; + +CREATE FUNCTION observe(tle, observer, timestamptz) RETURNS topocentric + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION observe(tle, observer, timestamptz) IS + 'Propagate TLE and compute observer-relative look angles in one call. Returns topocentric (az/el/range/range_rate).'; + +CREATE FUNCTION observe_safe(tle, observer, timestamptz) RETURNS topocentric + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE PARALLEL SAFE; +COMMENT ON FUNCTION observe_safe(tle, observer, timestamptz) IS + 'Like observe() but returns NULL on propagation error. For batch queries with potentially invalid/decayed TLEs.'; + + +-- ============================================================ +-- Pass prediction functions +-- ============================================================ + +CREATE FUNCTION next_pass(tle, observer, timestamptz) RETURNS pass_event + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION next_pass(tle, observer, timestamptz) IS + 'Find the next satellite pass over observer (searches up to 7 days ahead)'; + +CREATE FUNCTION predict_passes(tle, observer, timestamptz, timestamptz, float8 DEFAULT 0.0) + RETURNS SETOF pass_event + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE + ROWS 10; +COMMENT ON FUNCTION predict_passes(tle, observer, timestamptz, timestamptz, float8) IS + 'Predict all satellite passes over observer in time window. Optional min_elevation in degrees.'; + +CREATE FUNCTION pass_visible(tle, observer, timestamptz, timestamptz) RETURNS boolean + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION pass_visible(tle, observer, timestamptz, timestamptz) IS + 'True if any pass occurs over observer in the time window'; + + +-- ============================================================ +-- GiST operator support functions +-- ============================================================ + +-- Overlap operator: do orbital keys overlap in altitude AND inclination? +CREATE FUNCTION tle_overlap(tle, tle) RETURNS boolean + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +-- Altitude distance operator (altitude-only, for KNN ordering) +CREATE FUNCTION tle_alt_distance(tle, tle) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE OPERATOR && ( + LEFTARG = tle, + RIGHTARG = tle, + FUNCTION = tle_overlap, + COMMUTATOR = &&, + RESTRICT = areasel, + JOIN = areajoinsel +); + +COMMENT ON OPERATOR && (tle, tle) IS 'Orbital key overlap (altitude band AND inclination range) — necessary condition for conjunction'; + +CREATE OPERATOR <-> ( + LEFTARG = tle, + RIGHTARG = tle, + FUNCTION = tle_alt_distance, + COMMUTATOR = <-> +); + +COMMENT ON OPERATOR <-> (tle, tle) IS '2-D orbital distance in km: L2 norm of altitude-band gap and inclination gap (radians × Earth radius). Returns 0 when both dimensions overlap.'; + + +-- ============================================================ +-- GiST operator class for 2-D orbital indexing (altitude + inclination) +-- ============================================================ + +-- GiST internal support functions +CREATE FUNCTION gist_tle_compress(internal) RETURNS internal + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION gist_tle_decompress(internal) RETURNS internal + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION gist_tle_consistent(internal, tle, smallint, oid, internal) RETURNS boolean + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION gist_tle_union(internal, internal) RETURNS internal + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION gist_tle_penalty(internal, internal, internal) RETURNS internal + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION gist_tle_picksplit(internal, internal) RETURNS internal + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION gist_tle_same(internal, internal, internal) RETURNS internal + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION gist_tle_distance(internal, tle, smallint, oid, internal) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE OPERATOR CLASS tle_ops + DEFAULT FOR TYPE tle USING gist AS + OPERATOR 3 && , + OPERATOR 15 <-> (tle, tle) FOR ORDER BY float_ops, + FUNCTION 1 gist_tle_consistent(internal, tle, smallint, oid, internal), + FUNCTION 2 gist_tle_union(internal, internal), + FUNCTION 3 gist_tle_compress(internal), + FUNCTION 4 gist_tle_decompress(internal), + FUNCTION 5 gist_tle_penalty(internal, internal, internal), + FUNCTION 6 gist_tle_picksplit(internal, internal), + FUNCTION 7 gist_tle_same(internal, internal, internal), + FUNCTION 8 gist_tle_distance(internal, tle, smallint, oid, internal); + + +-- ============================================================ +-- Heliocentric type: ecliptic J2000 position in AU +-- ============================================================ + +CREATE TYPE heliocentric; + +CREATE FUNCTION heliocentric_in(cstring) RETURNS heliocentric + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION heliocentric_out(heliocentric) RETURNS cstring + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION heliocentric_recv(internal) RETURNS heliocentric + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION heliocentric_send(heliocentric) RETURNS bytea + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE TYPE heliocentric ( + INPUT = heliocentric_in, + OUTPUT = heliocentric_out, + RECEIVE = heliocentric_recv, + SEND = heliocentric_send, + INTERNALLENGTH = 24, + ALIGNMENT = double, + STORAGE = plain +); + +COMMENT ON TYPE heliocentric IS 'Heliocentric position in ecliptic J2000 frame (x, y, z in AU)'; + +CREATE FUNCTION helio_x(heliocentric) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION helio_x(heliocentric) IS 'X component in AU (ecliptic J2000, vernal equinox direction)'; + +CREATE FUNCTION helio_y(heliocentric) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION helio_y(heliocentric) IS 'Y component in AU (ecliptic J2000)'; + +CREATE FUNCTION helio_z(heliocentric) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION helio_z(heliocentric) IS 'Z component in AU (ecliptic J2000, north ecliptic pole)'; + +CREATE FUNCTION helio_distance(heliocentric) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION helio_distance(heliocentric) IS 'Heliocentric distance in AU'; + + +-- ============================================================ +-- Star observation functions +-- ============================================================ + +CREATE FUNCTION star_observe(float8, float8, observer, timestamptz) RETURNS topocentric + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION star_observe(float8, float8, observer, timestamptz) IS + 'Observe a star from (ra_hours J2000, dec_degrees J2000, observer, time). Returns topocentric az/el. Range is 0 (infinite distance).'; + +CREATE FUNCTION star_observe_safe(float8, float8, observer, timestamptz) RETURNS topocentric + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE PARALLEL SAFE; +COMMENT ON FUNCTION star_observe_safe(float8, float8, observer, timestamptz) IS + 'Like star_observe but returns NULL on invalid inputs. For batch queries over star catalogs.'; + + +-- ============================================================ +-- Keplerian propagation functions +-- ============================================================ + +CREATE FUNCTION kepler_propagate( + q_au float8, eccentricity float8, + inclination_deg float8, arg_perihelion_deg float8, + long_asc_node_deg float8, perihelion_jd float8, + t timestamptz +) RETURNS heliocentric + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION kepler_propagate(float8, float8, float8, float8, float8, float8, timestamptz) IS + 'Two-body Keplerian propagation from classical orbital elements. Returns heliocentric ecliptic J2000 position in AU. Handles elliptic, parabolic, and hyperbolic orbits.'; + + +-- ============================================================ +-- Comet observation +-- ============================================================ + +CREATE FUNCTION comet_observe( + q_au float8, eccentricity float8, + inclination_deg float8, arg_perihelion_deg float8, + long_asc_node_deg float8, perihelion_jd float8, + earth_x_au float8, earth_y_au float8, earth_z_au float8, + obs observer, t timestamptz +) RETURNS topocentric + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION comet_observe(float8, float8, float8, float8, float8, float8, float8, float8, float8, observer, timestamptz) IS + 'Observe a comet/asteroid from orbital elements. Requires Earth heliocentric ecliptic J2000 position (AU). Returns topocentric az/el with geocentric range in km.'; + + +-- ============================================================ +-- VSOP87 planets, ELP82B Moon, Sun observation +-- ============================================================ + +CREATE FUNCTION planet_heliocentric(int4, timestamptz) RETURNS heliocentric + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION planet_heliocentric(int4, timestamptz) IS + 'VSOP87 heliocentric ecliptic J2000 position (AU). Body IDs: 0=Sun, 1=Mercury, ..., 8=Neptune.'; + +CREATE FUNCTION planet_observe(int4, observer, timestamptz) RETURNS topocentric + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION planet_observe(int4, observer, timestamptz) IS + 'Observe a planet from (body_id 1-8, observer, time). Returns topocentric az/el with geocentric range in km.'; + +CREATE FUNCTION sun_observe(observer, timestamptz) RETURNS topocentric + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION sun_observe(observer, timestamptz) IS + 'Observe the Sun from (observer, time). Returns topocentric az/el with geocentric range in km.'; + +CREATE FUNCTION moon_observe(observer, timestamptz) RETURNS topocentric + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION moon_observe(observer, timestamptz) IS + 'Observe the Moon via ELP2000-82B from (observer, time). Returns topocentric az/el with geocentric range in km.'; + + +-- ============================================================ +-- Planetary moon observation +-- ============================================================ + +CREATE FUNCTION galilean_observe(int4, observer, timestamptz) RETURNS topocentric + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION galilean_observe(int4, observer, timestamptz) IS + 'Observe a Galilean moon of Jupiter via L1.2 theory. Body IDs: 0=Io, 1=Europa, 2=Ganymede, 3=Callisto.'; + +CREATE FUNCTION saturn_moon_observe(int4, observer, timestamptz) RETURNS topocentric + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION saturn_moon_observe(int4, observer, timestamptz) IS + 'Observe a Saturn moon via TASS 1.7. Body IDs: 0=Mimas, 1=Enceladus, 2=Tethys, 3=Dione, 4=Rhea, 5=Titan, 6=Iapetus, 7=Hyperion.'; + +CREATE FUNCTION uranus_moon_observe(int4, observer, timestamptz) RETURNS topocentric + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION uranus_moon_observe(int4, observer, timestamptz) IS + 'Observe a Uranus moon via GUST86. Body IDs: 0=Miranda, 1=Ariel, 2=Umbriel, 3=Titania, 4=Oberon.'; + +CREATE FUNCTION mars_moon_observe(int4, observer, timestamptz) RETURNS topocentric + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION mars_moon_observe(int4, observer, timestamptz) IS + 'Observe a Mars moon via MarsSat. Body IDs: 0=Phobos, 1=Deimos.'; + + +-- ============================================================ +-- Jupiter decametric radio burst prediction +-- ============================================================ + +CREATE FUNCTION io_phase_angle(timestamptz) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION io_phase_angle(timestamptz) IS + 'Io orbital phase angle in degrees [0,360). 0=superior conjunction (behind Jupiter). Standard Radio JOVE convention.'; + +CREATE FUNCTION jupiter_cml(observer, timestamptz) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION jupiter_cml(observer, timestamptz) IS + 'Jupiter Central Meridian Longitude, System III (1965.0), in degrees [0,360). Light-time corrected.'; + +CREATE FUNCTION jupiter_burst_probability(float8, float8) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION jupiter_burst_probability(float8, float8) IS + 'Estimated Jupiter decametric burst probability (0-1) from (io_phase_deg, cml_deg). Based on Carr et al. (1983) source regions A, B, C, D.'; + + +-- ============================================================ +-- Interplanetary transfer orbits (Lambert solver) +-- ============================================================ + +CREATE FUNCTION lambert_transfer( + dep_body_id int4, arr_body_id int4, + dep_time timestamptz, arr_time timestamptz, + OUT c3_departure float8, OUT c3_arrival float8, + OUT v_inf_departure float8, OUT v_inf_arrival float8, + OUT tof_days float8, OUT transfer_sma float8 +) RETURNS RECORD + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION lambert_transfer(int4, int4, timestamptz, timestamptz) IS + 'Solve Lambert transfer between two planets. Returns C3 (km^2/s^2), v_infinity (km/s), TOF (days), SMA (AU). Body IDs 1-8.'; + +CREATE FUNCTION lambert_c3(int4, int4, timestamptz, timestamptz) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION lambert_c3(int4, int4, timestamptz, timestamptz) IS + 'Departure C3 (km^2/s^2) for a Lambert transfer. Returns NULL if solver fails. For pork chop plots.'; + + +-- ============================================================ +-- DE ephemeris functions (optional high-precision) +-- ============================================================ + +CREATE FUNCTION planet_heliocentric_de(int4, timestamptz) RETURNS heliocentric + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION planet_heliocentric_de(int4, timestamptz) IS + 'Heliocentric ecliptic J2000 position via JPL DE (sub-arcsecond). Falls back to VSOP87 if DE unavailable. Body IDs: 0=Sun, 1-8=Mercury-Neptune.'; + +CREATE FUNCTION planet_observe_de(int4, observer, timestamptz) RETURNS topocentric + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION planet_observe_de(int4, observer, timestamptz) IS + 'Observe planet via JPL DE. Falls back to VSOP87. Body IDs: 1-8 (Mercury-Neptune).'; + +CREATE FUNCTION sun_observe_de(observer, timestamptz) RETURNS topocentric + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION sun_observe_de(observer, timestamptz) IS + 'Observe Sun via JPL DE. Falls back to VSOP87.'; + +CREATE FUNCTION moon_observe_de(observer, timestamptz) RETURNS topocentric + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION moon_observe_de(observer, timestamptz) IS + 'Observe Moon via JPL DE. Falls back to ELP2000-82B.'; + +CREATE FUNCTION lambert_transfer_de( + dep_body_id int4, arr_body_id int4, + dep_time timestamptz, arr_time timestamptz, + OUT c3_departure float8, OUT c3_arrival float8, + OUT v_inf_departure float8, OUT v_inf_arrival float8, + OUT tof_days float8, OUT transfer_sma float8 +) RETURNS RECORD + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION lambert_transfer_de(int4, int4, timestamptz, timestamptz) IS + 'Lambert transfer via JPL DE positions. Falls back to VSOP87. Body IDs 1-8.'; + +CREATE FUNCTION lambert_c3_de(int4, int4, timestamptz, timestamptz) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION lambert_c3_de(int4, int4, timestamptz, timestamptz) IS + 'Departure C3 via JPL DE. Falls back to VSOP87. For pork chop plots.'; + +CREATE FUNCTION galilean_observe_de(int4, observer, timestamptz) RETURNS topocentric + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION galilean_observe_de(int4, observer, timestamptz) IS + 'Observe Galilean moon with JPL DE parent position. L1.2 moon offsets. Body IDs: 0-3 (Io-Callisto).'; + +CREATE FUNCTION saturn_moon_observe_de(int4, observer, timestamptz) RETURNS topocentric + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION saturn_moon_observe_de(int4, observer, timestamptz) IS + 'Observe Saturn moon with JPL DE parent position. TASS 1.7 moon offsets. Body IDs: 0-7 (Mimas-Hyperion).'; + +CREATE FUNCTION uranus_moon_observe_de(int4, observer, timestamptz) RETURNS topocentric + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION uranus_moon_observe_de(int4, observer, timestamptz) IS + 'Observe Uranus moon with JPL DE parent position. GUST86 moon offsets. Body IDs: 0-4 (Miranda-Oberon).'; + +CREATE FUNCTION mars_moon_observe_de(int4, observer, timestamptz) RETURNS topocentric + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION mars_moon_observe_de(int4, observer, timestamptz) IS + 'Observe Mars moon with JPL DE parent position. MarsSat moon offsets. Body IDs: 0-1 (Phobos-Deimos).'; + + +-- Diagnostic function + +CREATE FUNCTION pg_orrery_ephemeris_info( + OUT provider text, OUT file_path text, + OUT start_jd float8, OUT end_jd float8, + OUT version int4, OUT au_km float8 +) RETURNS RECORD + AS 'MODULE_PATHNAME' LANGUAGE C STABLE PARALLEL SAFE; +COMMENT ON FUNCTION pg_orrery_ephemeris_info() IS + 'Returns current ephemeris provider status: VSOP87 or JPL_DE with file path, JD range, version, and AU value.'; + + +-- ============================================================ +-- Orbit determination (TLE fitting from observations) +-- ============================================================ + +-- Fit TLE from ECI position/velocity ephemeris +-- weights: per-observation weighting (NULL = uniform) + +CREATE FUNCTION tle_from_eci( + positions eci_position[], times timestamptz[], + seed tle DEFAULT NULL, fit_bstar boolean DEFAULT false, + max_iter int4 DEFAULT 15, + weights float8[] DEFAULT NULL, + OUT fitted_tle tle, OUT iterations int4, + OUT rms_final float8, OUT rms_initial float8, OUT status text, + OUT condition_number float8, OUT covariance float8[], OUT nstate int4 +) RETURNS RECORD + AS 'MODULE_PATHNAME' LANGUAGE C STABLE PARALLEL SAFE; +COMMENT ON FUNCTION tle_from_eci(eci_position[], timestamptz[], tle, boolean, int4, float8[]) IS + 'Fit a TLE from ECI position/velocity observations via differential correction. Optional per-observation weights for heterogeneous sensor fusion. Returns fitted TLE, RMS residuals, convergence status, condition number, and formal covariance matrix.'; + +-- Fit TLE from topocentric observations (az/el/range) — single observer +-- fit_range_rate: include range_rate as 4th residual component +-- weights: per-observation weighting (NULL = uniform) + +CREATE FUNCTION tle_from_topocentric( + observations topocentric[], times timestamptz[], + obs observer, + seed tle DEFAULT NULL, fit_bstar boolean DEFAULT false, + max_iter int4 DEFAULT 15, + fit_range_rate boolean DEFAULT false, + weights float8[] DEFAULT NULL, + OUT fitted_tle tle, OUT iterations int4, + OUT rms_final float8, OUT rms_initial float8, OUT status text, + OUT condition_number float8, OUT covariance float8[], OUT nstate int4 +) RETURNS RECORD + AS 'MODULE_PATHNAME' LANGUAGE C STABLE PARALLEL SAFE; +COMMENT ON FUNCTION tle_from_topocentric(topocentric[], timestamptz[], observer, tle, boolean, int4, boolean, float8[]) IS + 'Fit a TLE from topocentric (az/el/range) observations via differential correction. Optional range_rate fitting and per-observation weights. Returns fitted TLE, RMS residuals, convergence status, condition number, and formal covariance matrix.'; + +-- Fit TLE from topocentric observations — multiple observers + +CREATE FUNCTION tle_from_topocentric( + observations topocentric[], times timestamptz[], + observers observer[], observer_ids int4[], + seed tle DEFAULT NULL, fit_bstar boolean DEFAULT false, + max_iter int4 DEFAULT 15, + fit_range_rate boolean DEFAULT false, + weights float8[] DEFAULT NULL, + OUT fitted_tle tle, OUT iterations int4, + OUT rms_final float8, OUT rms_initial float8, OUT status text, + OUT condition_number float8, OUT covariance float8[], OUT nstate int4 +) RETURNS RECORD + AS 'MODULE_PATHNAME', 'tle_from_topocentric_multi' + LANGUAGE C STABLE PARALLEL SAFE; +COMMENT ON FUNCTION tle_from_topocentric(topocentric[], timestamptz[], observer[], int4[], tle, boolean, int4, boolean, float8[]) IS + 'Fit a TLE from topocentric observations collected by multiple ground stations. observer_ids[i] indexes into observers[]. Optional range_rate fitting and per-observation weights.'; + +-- Per-observation residuals diagnostic + +CREATE FUNCTION tle_fit_residuals( + fitted tle, + positions eci_position[], + times timestamptz[] +) RETURNS TABLE ( + t timestamptz, + dx_km float8, + dy_km float8, + dz_km float8, + pos_err_km float8 +) + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION tle_fit_residuals(tle, eci_position[], timestamptz[]) IS + 'Compute per-observation position residuals (km) between a TLE and ECI observations. Useful for fit quality assessment.'; + +-- Fit TLE from RA/Dec observations — single observer +-- Uses Gauss method for initial orbit determination when no seed is provided. +-- RA in hours [0,24), Dec in degrees [-90,90] (matches star_observe convention). +-- RMS output is in radians for angles-only mode. + +CREATE FUNCTION tle_from_angles( + ra_hours float8[], dec_degrees float8[], + times timestamptz[], + obs observer, + seed tle DEFAULT NULL, fit_bstar boolean DEFAULT false, + max_iter int4 DEFAULT 15, + weights float8[] DEFAULT NULL, + OUT fitted_tle tle, OUT iterations int4, + OUT rms_final float8, OUT rms_initial float8, OUT status text, + OUT condition_number float8, OUT covariance float8[], OUT nstate int4 +) RETURNS RECORD AS 'MODULE_PATHNAME' LANGUAGE C STABLE PARALLEL SAFE; +COMMENT ON FUNCTION tle_from_angles(float8[], float8[], timestamptz[], observer, tle, boolean, int4, float8[]) IS + 'Fit a TLE from angles-only (RA/Dec) observations via Gauss IOD + differential correction. RA in hours [0,24), Dec in degrees [-90,90]. RMS output in radians. Uses Gauss method for seed-free initial guess.'; + +-- Fit TLE from RA/Dec observations — multiple observers + +CREATE FUNCTION tle_from_angles( + ra_hours float8[], dec_degrees float8[], + times timestamptz[], + observers observer[], observer_ids int4[], + seed tle DEFAULT NULL, fit_bstar boolean DEFAULT false, + max_iter int4 DEFAULT 15, + weights float8[] DEFAULT NULL, + OUT fitted_tle tle, OUT iterations int4, + OUT rms_final float8, OUT rms_initial float8, OUT status text, + OUT condition_number float8, OUT covariance float8[], OUT nstate int4 +) RETURNS RECORD + AS 'MODULE_PATHNAME', 'tle_from_angles_multi' + LANGUAGE C STABLE PARALLEL SAFE; +COMMENT ON FUNCTION tle_from_angles(float8[], float8[], timestamptz[], observer[], int4[], tle, boolean, int4, float8[]) IS + 'Fit a TLE from angles-only (RA/Dec) observations from multiple ground stations via Gauss IOD + differential correction.'; +-- pg_orrery 0.6.0 -> 0.7.0 migration +-- +-- Adds SP-GiST orbital trie index for satellite pass prediction. +-- 2-level trie: SMA (L0) + inclination (L1) with query-time RAAN filter. +-- The &? operator answers "might this satellite be visible?" + +-- ============================================================ +-- observer_window composite type (query parameter bundle) +-- ============================================================ + +CREATE TYPE observer_window AS ( + obs observer, + t_start timestamptz, + t_end timestamptz, + min_el float8 +); + +COMMENT ON TYPE observer_window IS + 'Observation query parameters: observer location, time window, and minimum elevation angle (degrees). Used with the &? visibility cone operator.'; + +-- ============================================================ +-- Visibility cone operator function +-- ============================================================ + +CREATE FUNCTION tle_visibility_possible(tle, observer_window) RETURNS boolean + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; + +COMMENT ON FUNCTION tle_visibility_possible(tle, observer_window) IS + 'Could this satellite be visible from the observer during the time window? Combines altitude, inclination, and RAAN checks. Conservative superset — survivors need SGP4 propagation for ground truth.'; + +-- ============================================================ +-- &? operator (visibility cone check) +-- ============================================================ +-- The indexed column (tle) MUST be the left argument so PostgreSQL +-- can form a ScanKey and pass it to inner_consistent for pruning. + +CREATE OPERATOR &? ( + LEFTARG = tle, + RIGHTARG = observer_window, + FUNCTION = tle_visibility_possible, + RESTRICT = contsel, + JOIN = contjoinsel +); + +COMMENT ON OPERATOR &? (tle, observer_window) IS + 'Visibility cone check: could this satellite be visible from the observer during the time window? Index-accelerated via SP-GiST orbital trie.'; + +-- ============================================================ +-- SP-GiST support functions +-- ============================================================ + +CREATE FUNCTION spgist_tle_config(internal, internal) RETURNS void + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION spgist_tle_choose(internal, internal) RETURNS void + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION spgist_tle_picksplit(internal, internal) RETURNS void + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION spgist_tle_inner_consistent(internal, internal) RETURNS void + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION spgist_tle_leaf_consistent(internal, internal) RETURNS void + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +-- ============================================================ +-- SP-GiST operator class (opt-in, not DEFAULT) +-- ============================================================ + +CREATE OPERATOR CLASS tle_spgist_ops + FOR TYPE tle USING spgist AS + OPERATOR 1 &? (tle, observer_window), + FUNCTION 1 spgist_tle_config(internal, internal), + FUNCTION 2 spgist_tle_choose(internal, internal), + FUNCTION 3 spgist_tle_picksplit(internal, internal), + FUNCTION 4 spgist_tle_inner_consistent(internal, internal), + FUNCTION 5 spgist_tle_leaf_consistent(internal, internal); +-- pg_orrery 0.7.0 -> 0.8.0 migration +-- +-- Adds orbital_elements type for comets/asteroids, MPC MPCORB.DAT parser, +-- and small_body_observe()/small_body_heliocentric() observation functions. + +-- ============================================================ +-- orbital_elements type +-- ============================================================ + +CREATE TYPE orbital_elements; + +CREATE FUNCTION orbital_elements_in(cstring) RETURNS orbital_elements + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION orbital_elements_out(orbital_elements) RETURNS cstring + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION orbital_elements_recv(internal) RETURNS orbital_elements + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION orbital_elements_send(orbital_elements) RETURNS bytea + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE TYPE orbital_elements ( + INPUT = orbital_elements_in, + OUTPUT = orbital_elements_out, + RECEIVE = orbital_elements_recv, + SEND = orbital_elements_send, + INTERNALLENGTH = 72, + ALIGNMENT = double, + STORAGE = plain +); + +COMMENT ON TYPE orbital_elements IS + 'Classical Keplerian orbital elements for comets and asteroids (epoch, q, e, inc, omega, Omega, tp, H, G). 72 bytes, fixed-size.'; + + +-- ============================================================ +-- Accessor functions +-- ============================================================ + +CREATE FUNCTION oe_epoch(orbital_elements) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION oe_epoch(orbital_elements) IS 'Osculation epoch (Julian date)'; + +CREATE FUNCTION oe_perihelion(orbital_elements) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION oe_perihelion(orbital_elements) IS 'Perihelion distance q (AU)'; + +CREATE FUNCTION oe_eccentricity(orbital_elements) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION oe_eccentricity(orbital_elements) IS 'Eccentricity'; + +CREATE FUNCTION oe_inclination(orbital_elements) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION oe_inclination(orbital_elements) IS 'Inclination (degrees)'; + +CREATE FUNCTION oe_arg_perihelion(orbital_elements) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION oe_arg_perihelion(orbital_elements) IS 'Argument of perihelion (degrees)'; + +CREATE FUNCTION oe_raan(orbital_elements) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION oe_raan(orbital_elements) IS 'Longitude of ascending node (degrees)'; + +CREATE FUNCTION oe_tp(orbital_elements) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION oe_tp(orbital_elements) IS 'Time of perihelion passage (Julian date)'; + +CREATE FUNCTION oe_h_mag(orbital_elements) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION oe_h_mag(orbital_elements) IS 'Absolute magnitude H (NaN if unknown)'; + +CREATE FUNCTION oe_g_slope(orbital_elements) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION oe_g_slope(orbital_elements) IS 'Slope parameter G (NaN if unknown)'; + +CREATE FUNCTION oe_semi_major_axis(orbital_elements) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION oe_semi_major_axis(orbital_elements) IS 'Semi-major axis a = q/(1-e) in AU. NULL for parabolic/hyperbolic orbits (e >= 1).'; + +CREATE FUNCTION oe_period_years(orbital_elements) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION oe_period_years(orbital_elements) IS 'Orbital period in years = a^1.5 (Kepler third law). NULL for parabolic/hyperbolic orbits (e >= 1).'; + + +-- ============================================================ +-- MPC MPCORB.DAT parser +-- ============================================================ + +CREATE FUNCTION oe_from_mpc(text) RETURNS orbital_elements + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION oe_from_mpc(text) IS + 'Parse one MPCORB.DAT fixed-width line into orbital_elements. Converts MPC packed epoch, computes perihelion distance and tp from (a, e, M).'; + + +-- ============================================================ +-- Observation functions +-- ============================================================ + +CREATE FUNCTION small_body_heliocentric(orbital_elements, timestamptz) RETURNS heliocentric + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION small_body_heliocentric(orbital_elements, timestamptz) IS + 'Heliocentric ecliptic J2000 position of a comet/asteroid from its orbital elements at a given time.'; + +CREATE FUNCTION small_body_observe(orbital_elements, observer, timestamptz) RETURNS topocentric + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION small_body_observe(orbital_elements, observer, timestamptz) IS + 'Observe a comet/asteroid from orbital elements. Auto-fetches Earth via VSOP87. Returns topocentric az/el with geocentric range in km.'; +-- pg_orrery 0.8.0 -> 0.9.0 migration +-- +-- Adds equatorial type (apparent RA/Dec of date), atmospheric refraction, +-- stellar proper motion, and light-time corrected _apparent() functions. + +-- ============================================================ +-- equatorial type — apparent RA/Dec of date +-- ============================================================ + +CREATE TYPE equatorial; + +CREATE FUNCTION equatorial_in(cstring) RETURNS equatorial + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION equatorial_out(equatorial) RETURNS cstring + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION equatorial_recv(internal) RETURNS equatorial + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION equatorial_send(equatorial) RETURNS bytea + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE TYPE equatorial ( + INPUT = equatorial_in, + OUTPUT = equatorial_out, + RECEIVE = equatorial_recv, + SEND = equatorial_send, + INTERNALLENGTH = 24, + ALIGNMENT = double, + STORAGE = plain +); + +COMMENT ON TYPE equatorial IS + 'Apparent equatorial coordinates of date: RA (hours), Dec (degrees), distance (km). Solar system: J2000 precessed via IAU 1976. Satellites: TEME frame (~of-date to ~arcsecond). 24 bytes, fixed-size.'; + + +-- ============================================================ +-- Equatorial accessor functions +-- ============================================================ + +CREATE FUNCTION eq_ra(equatorial) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION eq_ra(equatorial) IS 'Right ascension in hours [0, 24)'; + +CREATE FUNCTION eq_dec(equatorial) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION eq_dec(equatorial) IS 'Declination in degrees [-90, 90]'; + +CREATE FUNCTION eq_distance(equatorial) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION eq_distance(equatorial) IS 'Distance in km (0 for stars without parallax)'; + + +-- ============================================================ +-- Satellite RA/Dec functions +-- ============================================================ + +CREATE FUNCTION eci_to_equatorial(eci_position, observer, timestamptz) RETURNS equatorial + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION eci_to_equatorial(eci_position, observer, timestamptz) IS + 'Topocentric apparent RA/Dec from ECI position. Observer parallax-corrected — LEO parallax is ~1 degree.'; + +CREATE FUNCTION eci_to_equatorial_geo(eci_position, timestamptz) RETURNS equatorial + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION eci_to_equatorial_geo(eci_position, timestamptz) IS + 'Geocentric apparent RA/Dec from ECI position. Observer-independent — the direction of the TEME position vector.'; + + +-- ============================================================ +-- Solar system equatorial functions (VSOP87) +-- ============================================================ + +CREATE FUNCTION planet_equatorial(int4, timestamptz) RETURNS equatorial + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION planet_equatorial(int4, timestamptz) IS + 'Geocentric apparent RA/Dec of a planet via VSOP87. Body IDs: 1=Mercury through 8=Neptune.'; + +CREATE FUNCTION sun_equatorial(timestamptz) RETURNS equatorial + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION sun_equatorial(timestamptz) IS + 'Geocentric apparent RA/Dec of the Sun via VSOP87.'; + +CREATE FUNCTION moon_equatorial(timestamptz) RETURNS equatorial + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION moon_equatorial(timestamptz) IS + 'Geocentric apparent RA/Dec of the Moon via ELP2000-82B.'; + +CREATE FUNCTION small_body_equatorial(orbital_elements, timestamptz) RETURNS equatorial + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION small_body_equatorial(orbital_elements, timestamptz) IS + 'Geocentric apparent RA/Dec of a comet/asteroid from orbital elements. Earth via VSOP87.'; + +CREATE FUNCTION star_equatorial(float8, float8, timestamptz) RETURNS equatorial + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION star_equatorial(float8, float8, timestamptz) IS + 'Apparent RA/Dec of a star at a given time. Precesses J2000 catalog coordinates (RA hours, Dec degrees) to date via IAU 1976.'; + + +-- ============================================================ +-- Atmospheric refraction (Bennett 1982) +-- ============================================================ + +CREATE FUNCTION atmospheric_refraction(float8) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION atmospheric_refraction(float8) IS + 'Atmospheric refraction correction in degrees for a given geometric elevation (degrees). Standard atmosphere: P=1010 mbar, T=10C. Bennett (1982) formula with domain guard at -1 degree.'; + +CREATE FUNCTION atmospheric_refraction_ext(float8, float8, float8) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION atmospheric_refraction_ext(float8, float8, float8) IS + 'Atmospheric refraction with pressure/temperature correction. Args: elevation_deg, pressure_mbar, temperature_celsius. Meeus P/T factor applied to Bennett formula.'; + +CREATE FUNCTION topo_elevation_apparent(topocentric) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION topo_elevation_apparent(topocentric) IS + 'Apparent elevation in degrees — geometric elevation plus atmospheric refraction correction.'; + + +-- ============================================================ +-- Refracted pass prediction +-- ============================================================ + +CREATE FUNCTION predict_passes_refracted( + tle, observer, timestamptz, timestamptz, float8 DEFAULT 0.0 +) RETURNS SETOF pass_event + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE + ROWS 20; +COMMENT ON FUNCTION predict_passes_refracted(tle, observer, timestamptz, timestamptz, float8) IS + 'Predict satellite passes using a refracted horizon threshold (-0.569 deg geometric). Atmospheric refraction makes satellites visible ~35 seconds earlier at AOS and later at LOS.'; + + +-- ============================================================ +-- Stellar proper motion +-- ============================================================ + +CREATE FUNCTION star_observe_pm( + float8, float8, float8, float8, float8, float8, observer, timestamptz +) RETURNS topocentric + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION star_observe_pm(float8, float8, float8, float8, float8, float8, observer, timestamptz) IS + 'Observe a star with proper motion. Args: ra_hours, dec_deg, pm_ra_masyr (mu_alpha*cos(delta)), pm_dec_masyr, parallax_mas, rv_kms, observer, time. Hipparcos/Gaia convention for pm_ra.'; + +CREATE FUNCTION star_equatorial_pm( + float8, float8, float8, float8, float8, float8, timestamptz +) RETURNS equatorial + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION star_equatorial_pm(float8, float8, float8, float8, float8, float8, timestamptz) IS + 'Apparent RA/Dec of a star with proper motion. Args: ra_hours, dec_deg, pm_ra_masyr, pm_dec_masyr, parallax_mas, rv_kms, time. Distance from parallax if > 0.'; + + +-- ============================================================ +-- Light-time corrected observation functions +-- ============================================================ + +CREATE FUNCTION planet_observe_apparent(int4, observer, timestamptz) RETURNS topocentric + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION planet_observe_apparent(int4, observer, timestamptz) IS + 'Observe a planet with single-iteration light-time correction. Body at retarded time, Earth at observation time. VSOP87.'; + +CREATE FUNCTION sun_observe_apparent(observer, timestamptz) RETURNS topocentric + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION sun_observe_apparent(observer, timestamptz) IS + 'Observe the Sun with light-time correction (~8.3 min). VSOP87.'; + +CREATE FUNCTION small_body_observe_apparent(orbital_elements, observer, timestamptz) RETURNS topocentric + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION small_body_observe_apparent(orbital_elements, observer, timestamptz) IS + 'Observe a comet/asteroid with single-iteration light-time correction. Kepler propagation at retarded time, Earth via VSOP87 at observation time.'; + + +-- ============================================================ +-- Light-time corrected equatorial functions +-- ============================================================ + +CREATE FUNCTION planet_equatorial_apparent(int4, timestamptz) RETURNS equatorial + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION planet_equatorial_apparent(int4, timestamptz) IS + 'Geocentric apparent RA/Dec of a planet with light-time correction. VSOP87.'; + +CREATE FUNCTION moon_equatorial_apparent(timestamptz) RETURNS equatorial + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION moon_equatorial_apparent(timestamptz) IS + 'Geocentric apparent RA/Dec of the Moon with light-time correction (~1.3 sec). ELP2000-82B.'; + +CREATE FUNCTION small_body_equatorial_apparent(orbital_elements, timestamptz) RETURNS equatorial + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION small_body_equatorial_apparent(orbital_elements, timestamptz) IS + 'Geocentric apparent RA/Dec of a comet/asteroid with light-time correction.'; + + +-- ============================================================ +-- DE ephemeris equatorial variants (STABLE) +-- ============================================================ + +CREATE FUNCTION planet_equatorial_de(int4, timestamptz) RETURNS equatorial + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION planet_equatorial_de(int4, timestamptz) IS + 'Geocentric apparent RA/Dec of a planet via JPL DE ephemeris (falls back to VSOP87 + equatorial).'; + +CREATE FUNCTION moon_equatorial_de(timestamptz) RETURNS equatorial + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION moon_equatorial_de(timestamptz) IS + 'Geocentric apparent RA/Dec of the Moon via JPL DE ephemeris (falls back to ELP2000-82B + equatorial).'; +-- pg_orrery 0.9.0 -> 0.10.0 migration +-- +-- Adds annual aberration to existing _apparent() functions, +-- 6 new _apparent_de() variants, equatorial angular separation +-- operator and cone predicate, and stellar annual parallax. + +-- ============================================================ +-- Equatorial angular distance and cone search +-- ============================================================ + +CREATE FUNCTION eq_angular_distance(equatorial, equatorial) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION eq_angular_distance(equatorial, equatorial) IS + 'Angular separation in degrees between two equatorial positions. Vincenty formula (stable at 0 and 180 degrees).'; + +CREATE FUNCTION eq_within_cone(equatorial, equatorial, float8) RETURNS bool + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION eq_within_cone(equatorial, equatorial, float8) IS + 'True if first position is within radius_deg of second position. Cosine shortcut for fast rejection.'; + +CREATE OPERATOR <-> ( + LEFTARG = equatorial, + RIGHTARG = equatorial, + FUNCTION = eq_angular_distance, + COMMUTATOR = <-> +); +COMMENT ON OPERATOR <-> (equatorial, equatorial) IS + 'Angular separation in degrees between two equatorial positions.'; + + +-- ============================================================ +-- DE apparent observation functions (STABLE, light-time + aberration) +-- ============================================================ + +CREATE FUNCTION planet_observe_apparent_de(int4, observer, timestamptz) RETURNS topocentric + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION planet_observe_apparent_de(int4, observer, timestamptz) IS + 'Observe a planet with light-time correction and annual aberration via JPL DE (falls back to VSOP87).'; + +CREATE FUNCTION sun_observe_apparent_de(observer, timestamptz) RETURNS topocentric + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION sun_observe_apparent_de(observer, timestamptz) IS + 'Observe the Sun with aberration via JPL DE (falls back to VSOP87).'; + +CREATE FUNCTION moon_observe_apparent_de(observer, timestamptz) RETURNS topocentric + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION moon_observe_apparent_de(observer, timestamptz) IS + 'Observe the Moon with light-time correction and annual aberration via JPL DE (falls back to ELP2000-82B).'; + +CREATE FUNCTION planet_equatorial_apparent_de(int4, timestamptz) RETURNS equatorial + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION planet_equatorial_apparent_de(int4, timestamptz) IS + 'Geocentric apparent RA/Dec of a planet with light-time correction and annual aberration via JPL DE (falls back to VSOP87).'; + +CREATE FUNCTION moon_equatorial_apparent_de(timestamptz) RETURNS equatorial + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION moon_equatorial_apparent_de(timestamptz) IS + 'Geocentric apparent RA/Dec of the Moon with light-time correction and annual aberration via JPL DE (falls back to ELP2000-82B).'; + +CREATE FUNCTION small_body_observe_apparent_de(orbital_elements, observer, timestamptz) RETURNS topocentric + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION small_body_observe_apparent_de(orbital_elements, observer, timestamptz) IS + 'Observe a comet/asteroid with light-time correction and annual aberration. Earth position via JPL DE (falls back to VSOP87).'; +-- pg_orrery 0.10.0 -> 0.11.0 migration +-- +-- Adds make_orbital_elements() constructors and +-- geocentric equatorial functions for planetary moons. + +-- ============================================================ +-- orbital_elements constructors +-- ============================================================ + +CREATE FUNCTION make_orbital_elements( + epoch_jd float8, q_au float8, e float8, + inc_rad float8, omega_rad float8, node_rad float8, + tp_jd float8, h_mag float8, g_slope float8 +) RETURNS orbital_elements + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION make_orbital_elements(float8,float8,float8,float8,float8,float8,float8,float8,float8) IS + 'Construct orbital_elements from 9 floats (angular elements in radians).'; + +CREATE FUNCTION make_orbital_elements_deg( + epoch_jd float8, q_au float8, e float8, + inc_deg float8, omega_deg float8, node_deg float8, + tp_jd float8, h_mag float8, g_slope float8 +) RETURNS orbital_elements + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION make_orbital_elements_deg(float8,float8,float8,float8,float8,float8,float8,float8,float8) IS + 'Construct orbital_elements from 9 floats (angular elements in degrees). Matches text I/O and most catalog column layouts.'; + + +-- ============================================================ +-- Planetary moon equatorial functions +-- ============================================================ + +CREATE FUNCTION galilean_equatorial(int4, timestamptz) RETURNS equatorial + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION galilean_equatorial(int4, timestamptz) IS + 'Geometric geocentric RA/Dec of a Galilean moon (0=Io, 1=Europa, 2=Ganymede, 3=Callisto). L1.2 theory + VSOP87. No light-time or aberration correction.'; + +CREATE FUNCTION saturn_moon_equatorial(int4, timestamptz) RETURNS equatorial + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION saturn_moon_equatorial(int4, timestamptz) IS + 'Geometric geocentric RA/Dec of a Saturn moon (0=Mimas..7=Hyperion). TASS17 theory + VSOP87. No light-time or aberration correction.'; + +CREATE FUNCTION uranus_moon_equatorial(int4, timestamptz) RETURNS equatorial + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION uranus_moon_equatorial(int4, timestamptz) IS + 'Geometric geocentric RA/Dec of a Uranus moon (0=Miranda..4=Oberon). GUST86 theory + VSOP87. No light-time or aberration correction.'; + +CREATE FUNCTION mars_moon_equatorial(int4, timestamptz) RETURNS equatorial + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION mars_moon_equatorial(int4, timestamptz) IS + 'Geometric geocentric RA/Dec of a Mars moon (0=Phobos, 1=Deimos). MarsSat theory + VSOP87. No light-time or aberration correction.'; +-- pg_orrery 0.11.0 -> 0.12.0 migration +-- +-- Adds equatorial GiST operator class for KNN sky queries +-- and DE moon equatorial functions for all 4 planetary moon families. + +-- ============================================================ +-- GiST support functions for equatorial type +-- ============================================================ + +CREATE FUNCTION gist_eq_consistent(internal, equatorial, smallint, oid, internal) RETURNS bool + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION gist_eq_union(internal, internal) RETURNS internal + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION gist_eq_compress(internal) RETURNS internal + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION gist_eq_decompress(internal) RETURNS internal + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION gist_eq_penalty(internal, internal, internal) RETURNS internal + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION gist_eq_picksplit(internal, internal) RETURNS internal + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION gist_eq_same(internal, internal, internal) RETURNS internal + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +CREATE FUNCTION gist_eq_distance(internal, equatorial, smallint, oid, internal) RETURNS float8 + AS 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +-- ============================================================ +-- Equatorial GiST operator class (KNN ordering only) +-- ============================================================ + +CREATE OPERATOR CLASS eq_gist_ops + DEFAULT FOR TYPE equatorial USING gist AS + OPERATOR 15 <-> (equatorial, equatorial) FOR ORDER BY pg_catalog.float_ops, + FUNCTION 1 gist_eq_consistent(internal, equatorial, smallint, oid, internal), + FUNCTION 2 gist_eq_union(internal, internal), + FUNCTION 3 gist_eq_compress(internal), + FUNCTION 4 gist_eq_decompress(internal), + FUNCTION 5 gist_eq_penalty(internal, internal, internal), + FUNCTION 6 gist_eq_picksplit(internal, internal), + FUNCTION 7 gist_eq_same(internal, internal, internal), + FUNCTION 8 gist_eq_distance(internal, equatorial, smallint, oid, internal); + +-- ============================================================ +-- DE moon equatorial functions (STABLE, fall back to VSOP87) +-- ============================================================ + +CREATE FUNCTION galilean_equatorial_de(int4, timestamptz) RETURNS equatorial + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION galilean_equatorial_de(int4, timestamptz) IS + 'Geocentric RA/Dec of a Galilean moon via DE parent position (falls back to VSOP87). 0=Io, 1=Europa, 2=Ganymede, 3=Callisto.'; + +CREATE FUNCTION saturn_moon_equatorial_de(int4, timestamptz) RETURNS equatorial + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION saturn_moon_equatorial_de(int4, timestamptz) IS + 'Geocentric RA/Dec of a Saturn moon via DE parent position (falls back to VSOP87). 0=Mimas..7=Hyperion.'; + +CREATE FUNCTION uranus_moon_equatorial_de(int4, timestamptz) RETURNS equatorial + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION uranus_moon_equatorial_de(int4, timestamptz) IS + 'Geocentric RA/Dec of a Uranus moon via DE parent position (falls back to VSOP87). 0=Miranda..4=Oberon.'; + +CREATE FUNCTION mars_moon_equatorial_de(int4, timestamptz) RETURNS equatorial + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION mars_moon_equatorial_de(int4, timestamptz) IS + 'Geocentric RA/Dec of a Mars moon via DE parent position (falls back to VSOP87). 0=Phobos, 1=Deimos.'; + + +-- ============================================================ +-- v0.13.0: make_equatorial() constructor +-- ============================================================ + +CREATE FUNCTION make_equatorial(ra_hours float8, dec_deg float8, distance_km float8) + RETURNS equatorial + AS 'MODULE_PATHNAME', 'make_equatorial' + LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; + +COMMENT ON FUNCTION make_equatorial(float8, float8, float8) IS + 'Construct equatorial from RA (hours [0,24)), Dec (degrees [-90,90]), distance (km).'; + + +-- ============================================================ +-- v0.13.0: Rise/set prediction functions +-- ============================================================ + +CREATE FUNCTION planet_next_rise(body_id int4, obs observer, t timestamptz) RETURNS timestamptz + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION planet_next_rise(int4, observer, timestamptz) IS + 'Next geometric rise time for a planet. Returns NULL if no rise within 7 days. body_id: 1=Mercury..8=Neptune.'; + +CREATE FUNCTION planet_next_set(body_id int4, obs observer, t timestamptz) RETURNS timestamptz + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION planet_next_set(int4, observer, timestamptz) IS + 'Next geometric set time for a planet. Returns NULL if no set within 7 days. body_id: 1=Mercury..8=Neptune.'; + +CREATE FUNCTION sun_next_rise(obs observer, t timestamptz) RETURNS timestamptz + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION sun_next_rise(observer, timestamptz) IS + 'Next geometric sunrise. Returns NULL if Sun does not rise within 7 days (polar night).'; + +CREATE FUNCTION sun_next_set(obs observer, t timestamptz) RETURNS timestamptz + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION sun_next_set(observer, timestamptz) IS + 'Next geometric sunset. Returns NULL if Sun does not set within 7 days (midnight sun).'; + +CREATE FUNCTION moon_next_rise(obs observer, t timestamptz) RETURNS timestamptz + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION moon_next_rise(observer, timestamptz) IS + 'Next geometric moonrise. Returns NULL if Moon does not rise within 7 days.'; + +CREATE FUNCTION moon_next_set(obs observer, t timestamptz) RETURNS timestamptz + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION moon_next_set(observer, timestamptz) IS + 'Next geometric moonset. Returns NULL if Moon does not set within 7 days.'; + +CREATE FUNCTION sun_next_rise_refracted(obs observer, t timestamptz) RETURNS timestamptz + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION sun_next_rise_refracted(observer, timestamptz) IS + 'Next refracted sunrise (-0.833 deg threshold: refraction + semidiameter). Earlier than geometric by ~4 min.'; + +CREATE FUNCTION sun_next_set_refracted(obs observer, t timestamptz) RETURNS timestamptz + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION sun_next_set_refracted(observer, timestamptz) IS + 'Next refracted sunset (-0.833 deg threshold: refraction + semidiameter). Later than geometric by ~4 min.'; + + +-- ============================================================ +-- v0.14.0: Refracted planet/moon rise/set +-- ============================================================ + +CREATE FUNCTION planet_next_rise_refracted(body_id int4, obs observer, t timestamptz) RETURNS timestamptz + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION planet_next_rise_refracted(int4, observer, timestamptz) IS + 'Next refracted rise time for a planet (-0.569 deg threshold: atmospheric refraction only). Earlier than geometric.'; + +CREATE FUNCTION planet_next_set_refracted(body_id int4, obs observer, t timestamptz) RETURNS timestamptz + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION planet_next_set_refracted(int4, observer, timestamptz) IS + 'Next refracted set time for a planet (-0.569 deg threshold: atmospheric refraction only). Later than geometric.'; + +CREATE FUNCTION moon_next_rise_refracted(obs observer, t timestamptz) RETURNS timestamptz + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION moon_next_rise_refracted(observer, timestamptz) IS + 'Next refracted moonrise (-0.833 deg threshold: refraction + semidiameter). Earlier than geometric.'; + +CREATE FUNCTION moon_next_set_refracted(obs observer, t timestamptz) RETURNS timestamptz + AS 'MODULE_PATHNAME' LANGUAGE C STABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION moon_next_set_refracted(observer, timestamptz) IS + 'Next refracted moonset (-0.833 deg threshold: refraction + semidiameter). Later than geometric.'; + + +-- ============================================================ +-- v0.14.0: Constellation identification (Roman 1987, CDS VI/42) +-- ============================================================ + +CREATE FUNCTION constellation(eq equatorial) RETURNS text + AS 'MODULE_PATHNAME', 'constellation_from_equatorial' + LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION constellation(equatorial) IS + 'IAU constellation abbreviation (3 letters) from equatorial coordinates (Roman 1987).'; + +CREATE FUNCTION constellation(ra_hours float8, dec_deg float8) RETURNS text + AS 'MODULE_PATHNAME', 'constellation_from_radec' + LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; +COMMENT ON FUNCTION constellation(float8, float8) IS + 'IAU constellation from J2000 RA (hours [0,24)) and Dec (degrees [-90,90]).'; diff --git a/src/constellation_data.c b/src/constellation_data.c new file mode 100644 index 0000000..b62ad6d --- /dev/null +++ b/src/constellation_data.c @@ -0,0 +1,378 @@ +/* + * constellation_data.c -- Roman (1987) IAU constellation boundary table + * + * 357 boundary segments from CDS catalog VI/42. Sorted by descending + * declination (as in the original catalog). Coordinates are B1875.0 + * equatorial: RA in hours, Dec in degrees. + * + * The lookup algorithm scans from the top (north celestial pole) down. + * First entry where point.dec >= entry.dec AND entry.ra_lower <= point.ra + * < entry.ra_upper is the match. + * + * Using float (not double) — boundary precision is 4 decimal places, + * well within float32's 7-digit significand. + */ + +#include "constellation_data.h" + +const roman_boundary roman_boundaries[] = { + { 0.0000f, 24.0000f, 88.0000f, "UMi" }, + { 8.0000f, 14.5000f, 86.5000f, "UMi" }, + { 21.0000f, 23.0000f, 86.1667f, "UMi" }, + { 18.0000f, 21.0000f, 86.0000f, "UMi" }, + { 0.0000f, 8.0000f, 85.0000f, "Cep" }, + { 9.1667f, 10.6667f, 82.0000f, "Cam" }, + { 0.0000f, 5.0000f, 80.0000f, "Cep" }, + { 10.6667f, 14.5000f, 80.0000f, "Cam" }, + { 17.5000f, 18.0000f, 80.0000f, "UMi" }, + { 20.1667f, 21.0000f, 80.0000f, "Dra" }, + { 0.0000f, 3.5083f, 77.0000f, "Cep" }, + { 11.5000f, 13.5833f, 77.0000f, "Cam" }, + { 16.5333f, 17.5000f, 75.0000f, "UMi" }, + { 20.1667f, 20.6667f, 75.0000f, "Cep" }, + { 7.9667f, 9.1667f, 73.5000f, "Cam" }, + { 9.1667f, 11.3333f, 73.5000f, "Dra" }, + { 13.0000f, 16.5333f, 70.0000f, "UMi" }, + { 3.1000f, 3.4167f, 68.0000f, "Cas" }, + { 20.4167f, 20.6667f, 67.0000f, "Dra" }, + { 11.3333f, 12.0000f, 66.5000f, "Dra" }, + { 0.0000f, 0.3333f, 66.0000f, "Cep" }, + { 14.0000f, 15.6667f, 66.0000f, "UMi" }, + { 23.5833f, 24.0000f, 66.0000f, "Cep" }, + { 12.0000f, 13.5000f, 64.0000f, "Dra" }, + { 13.5000f, 14.4167f, 63.0000f, "Dra" }, + { 23.1667f, 23.5833f, 63.0000f, "Cep" }, + { 6.1000f, 7.0000f, 62.0000f, "Cam" }, + { 20.0000f, 20.4167f, 61.5000f, "Dra" }, + { 20.5367f, 20.6000f, 60.9167f, "Cep" }, + { 7.0000f, 7.9667f, 60.0000f, "Cam" }, + { 7.9667f, 8.4167f, 60.0000f, "UMa" }, + { 19.7667f, 20.0000f, 59.5000f, "Dra" }, + { 20.0000f, 20.5367f, 59.5000f, "Cep" }, + { 22.8667f, 23.1667f, 59.0833f, "Cep" }, + { 0.0000f, 2.4333f, 58.5000f, "Cas" }, + { 19.4167f, 19.7667f, 58.0000f, "Dra" }, + { 1.7000f, 1.9083f, 57.5000f, "Cas" }, + { 2.4333f, 3.1000f, 57.0000f, "Cas" }, + { 3.1000f, 3.1667f, 57.0000f, "Cam" }, + { 22.3167f, 22.8667f, 56.2500f, "Cep" }, + { 5.0000f, 6.1000f, 56.0000f, "Cam" }, + { 14.0333f, 14.4167f, 55.5000f, "UMa" }, + { 14.4167f, 19.4167f, 55.5000f, "Dra" }, + { 3.1667f, 3.3333f, 55.0000f, "Cam" }, + { 22.1333f, 22.3167f, 55.0000f, "Cep" }, + { 20.6000f, 21.9667f, 54.8333f, "Cep" }, + { 0.0000f, 1.7000f, 54.0000f, "Cas" }, + { 6.1000f, 6.5000f, 54.0000f, "Lyn" }, + { 12.0833f, 13.5000f, 53.0000f, "UMa" }, + { 15.2500f, 15.7500f, 53.0000f, "Dra" }, + { 21.9667f, 22.1333f, 52.7500f, "Cep" }, + { 3.3333f, 5.0000f, 52.5000f, "Cam" }, + { 22.8667f, 23.3333f, 52.5000f, "Cas" }, + { 15.7500f, 17.0000f, 51.5000f, "Dra" }, + { 2.0417f, 2.5167f, 50.5000f, "Per" }, + { 17.0000f, 18.2333f, 50.5000f, "Dra" }, + { 0.0000f, 1.3667f, 50.0000f, "Cas" }, + { 1.3667f, 1.6667f, 50.0000f, "Per" }, + { 6.5000f, 6.8000f, 50.0000f, "Lyn" }, + { 23.3333f, 24.0000f, 50.0000f, "Cas" }, + { 13.5000f, 14.0333f, 48.5000f, "UMa" }, + { 0.0000f, 1.1167f, 48.0000f, "Cas" }, + { 23.5833f, 24.0000f, 48.0000f, "Cas" }, + { 18.1750f, 18.2333f, 47.5000f, "Her" }, + { 18.2333f, 19.0833f, 47.5000f, "Dra" }, + { 19.0833f, 19.1667f, 47.5000f, "Cyg" }, + { 1.6667f, 2.0417f, 47.0000f, "Per" }, + { 8.4167f, 9.1667f, 47.0000f, "UMa" }, + { 0.1667f, 0.8667f, 46.0000f, "Cas" }, + { 12.0000f, 12.0833f, 45.0000f, "UMa" }, + { 6.8000f, 7.3667f, 44.5000f, "Lyn" }, + { 21.9083f, 21.9667f, 44.0000f, "Cyg" }, + { 21.8750f, 21.9083f, 43.7500f, "Cyg" }, + { 19.1667f, 19.4000f, 43.5000f, "Cyg" }, + { 9.1667f, 10.1667f, 42.0000f, "UMa" }, + { 10.1667f, 10.7833f, 40.0000f, "UMa" }, + { 15.4333f, 15.7500f, 40.0000f, "Boo" }, + { 15.7500f, 16.3333f, 40.0000f, "Her" }, + { 9.2500f, 9.5833f, 39.7500f, "Lyn" }, + { 0.0000f, 2.5167f, 36.7500f, "And" }, + { 2.5167f, 2.5667f, 36.7500f, "Per" }, + { 19.3583f, 19.4000f, 36.5000f, "Lyr" }, + { 4.5000f, 4.6917f, 36.0000f, "Per" }, + { 21.7333f, 21.8750f, 36.0000f, "Cyg" }, + { 21.8750f, 22.0000f, 36.0000f, "Lac" }, + { 6.5333f, 7.3667f, 35.5000f, "Aur" }, + { 7.3667f, 7.7500f, 35.5000f, "Lyn" }, + { 0.0000f, 2.0000f, 35.0000f, "And" }, + { 22.0000f, 22.8167f, 35.0000f, "Lac" }, + { 22.8167f, 22.8667f, 34.5000f, "Lac" }, + { 22.8667f, 23.5000f, 34.5000f, "And" }, + { 2.5667f, 2.7167f, 34.0000f, "Per" }, + { 10.7833f, 11.0000f, 34.0000f, "UMa" }, + { 12.0000f, 12.3333f, 34.0000f, "CVn" }, + { 7.7500f, 9.2500f, 33.5000f, "Lyn" }, + { 9.2500f, 9.8833f, 33.5000f, "LMi" }, + { 0.7167f, 1.4083f, 33.0000f, "And" }, + { 15.1833f, 15.4333f, 33.0000f, "Boo" }, + { 23.5000f, 23.7500f, 32.0833f, "And" }, + { 12.3333f, 13.2500f, 32.0000f, "CVn" }, + { 23.7500f, 24.0000f, 31.3333f, "And" }, + { 13.9583f, 14.0333f, 30.7500f, "CVn" }, + { 2.4167f, 2.7167f, 30.6667f, "Tri" }, + { 2.7167f, 4.5000f, 30.6667f, "Per" }, + { 4.5000f, 4.7500f, 30.0000f, "Aur" }, + { 18.1750f, 19.3583f, 30.0000f, "Lyr" }, + { 11.0000f, 12.0000f, 29.0000f, "UMa" }, + { 19.6667f, 20.9167f, 29.0000f, "Cyg" }, + { 4.7500f, 5.8833f, 28.5000f, "Aur" }, + { 9.8833f, 10.5000f, 28.5000f, "LMi" }, + { 13.2500f, 13.9583f, 28.5000f, "CVn" }, + { 0.0000f, 0.0667f, 28.0000f, "And" }, + { 1.4083f, 1.6667f, 28.0000f, "Tri" }, + { 5.8833f, 6.5333f, 28.0000f, "Aur" }, + { 7.8833f, 8.0000f, 28.0000f, "Gem" }, + { 20.9167f, 21.7333f, 28.0000f, "Cyg" }, + { 19.2583f, 19.6667f, 27.5000f, "Cyg" }, + { 1.9167f, 2.4167f, 27.2500f, "Tri" }, + { 16.1667f, 16.3333f, 27.0000f, "CrB" }, + { 15.0833f, 15.1833f, 26.0000f, "Boo" }, + { 15.1833f, 16.1667f, 26.0000f, "CrB" }, + { 18.3667f, 18.8667f, 26.0000f, "Lyr" }, + { 10.7500f, 11.0000f, 25.5000f, "LMi" }, + { 18.8667f, 19.2583f, 25.5000f, "Lyr" }, + { 1.6667f, 1.9167f, 25.0000f, "Tri" }, + { 0.7167f, 0.8500f, 23.7500f, "Psc" }, + { 10.5000f, 10.7500f, 23.5000f, "LMi" }, + { 21.2500f, 21.4167f, 23.5000f, "Vul" }, + { 5.7000f, 5.8833f, 22.8333f, "Tau" }, + { 0.0667f, 0.1417f, 22.0000f, "And" }, + { 15.9167f, 16.0333f, 22.0000f, "Ser" }, + { 5.8833f, 6.2167f, 21.5000f, "Gem" }, + { 19.8333f, 20.2500f, 21.2500f, "Vul" }, + { 18.8667f, 19.2500f, 21.0833f, "Vul" }, + { 0.1417f, 0.8500f, 21.0000f, "And" }, + { 20.2500f, 20.5667f, 20.5000f, "Vul" }, + { 7.8083f, 7.8833f, 20.0000f, "Gem" }, + { 20.5667f, 21.2500f, 19.5000f, "Vul" }, + { 19.2500f, 19.8333f, 19.1667f, "Vul" }, + { 3.2833f, 3.3667f, 19.0000f, "Ari" }, + { 18.8667f, 19.0000f, 18.5000f, "Sge" }, + { 5.7000f, 5.7667f, 18.0000f, "Ori" }, + { 6.2167f, 6.3083f, 17.5000f, "Gem" }, + { 19.0000f, 19.8333f, 16.1667f, "Sge" }, + { 4.9667f, 5.3333f, 16.0000f, "Tau" }, + { 15.9167f, 16.0833f, 16.0000f, "Her" }, + { 19.8333f, 20.2500f, 15.7500f, "Sge" }, + { 4.6167f, 4.9667f, 15.5000f, "Tau" }, + { 5.3333f, 5.6000f, 15.5000f, "Tau" }, + { 12.8333f, 13.5000f, 15.0000f, "Com" }, + { 17.2500f, 18.2500f, 14.3333f, "Her" }, + { 11.8667f, 12.8333f, 14.0000f, "Com" }, + { 7.5000f, 7.8083f, 13.5000f, "Gem" }, + { 16.7500f, 17.2500f, 12.8333f, "Her" }, + { 0.0000f, 0.1417f, 12.5000f, "Peg" }, + { 5.6000f, 5.7667f, 12.5000f, "Tau" }, + { 7.0000f, 7.5000f, 12.5000f, "Gem" }, + { 21.1167f, 21.3333f, 12.5000f, "Peg" }, + { 6.3083f, 6.9333f, 12.0000f, "Gem" }, + { 18.2500f, 18.8667f, 12.0000f, "Her" }, + { 20.8750f, 21.0500f, 11.8333f, "Del" }, + { 21.0500f, 21.1167f, 11.8333f, "Peg" }, + { 11.5167f, 11.8667f, 11.0000f, "Leo" }, + { 6.2417f, 6.3083f, 10.0000f, "Ori" }, + { 6.9333f, 7.0000f, 10.0000f, "Gem" }, + { 7.8083f, 7.9250f, 10.0000f, "Cnc" }, + { 23.8333f, 24.0000f, 10.0000f, "Peg" }, + { 1.6667f, 3.2833f, 9.9167f, "Ari" }, + { 20.1417f, 20.3000f, 8.5000f, "Del" }, + { 13.5000f, 15.0833f, 8.0000f, "Boo" }, + { 22.7500f, 23.8333f, 7.5000f, "Peg" }, + { 7.9250f, 9.2500f, 7.0000f, "Cnc" }, + { 9.2500f, 10.7500f, 7.0000f, "Leo" }, + { 18.2500f, 18.6622f, 6.2500f, "Oph" }, + { 18.6622f, 18.8667f, 6.2500f, "Aql" }, + { 20.8333f, 20.8750f, 6.0000f, "Del" }, + { 7.0000f, 7.0167f, 5.5000f, "CMi" }, + { 18.2500f, 18.4250f, 4.5000f, "Ser" }, + { 16.0833f, 16.7500f, 4.0000f, "Her" }, + { 18.2500f, 18.4250f, 3.0000f, "Oph" }, + { 21.4667f, 21.6667f, 2.7500f, "Peg" }, + { 0.0000f, 2.0000f, 2.0000f, "Psc" }, + { 18.5833f, 18.8667f, 2.0000f, "Ser" }, + { 20.3000f, 20.8333f, 2.0000f, "Del" }, + { 20.8333f, 21.3333f, 2.0000f, "Equ" }, + { 21.3333f, 21.4667f, 2.0000f, "Peg" }, + { 22.0000f, 22.7500f, 2.0000f, "Peg" }, + { 21.6667f, 22.0000f, 1.7500f, "Peg" }, + { 7.0167f, 7.2000f, 1.5000f, "CMi" }, + { 3.5833f, 4.6167f, 0.0000f, "Tau" }, + { 4.6167f, 4.6667f, 0.0000f, "Ori" }, + { 7.2000f, 8.0833f, 0.0000f, "CMi" }, + { 14.6667f, 15.0833f, 0.0000f, "Vir" }, + { 17.8333f, 18.2500f, 0.0000f, "Oph" }, + { 2.6500f, 3.2833f, -1.7500f, "Cet" }, + { 3.2833f, 3.5833f, -1.7500f, "Tau" }, + { 15.0833f, 16.2667f, -3.2500f, "Ser" }, + { 4.6667f, 5.0833f, -4.0000f, "Ori" }, + { 5.8333f, 6.2417f, -4.0000f, "Ori" }, + { 17.8333f, 17.9667f, -4.0000f, "Ser" }, + { 18.2500f, 18.5833f, -4.0000f, "Ser" }, + { 18.5833f, 18.8667f, -4.0000f, "Aql" }, + { 22.7500f, 23.8333f, -4.0000f, "Psc" }, + { 10.7500f, 11.5167f, -6.0000f, "Leo" }, + { 11.5167f, 11.8333f, -6.0000f, "Vir" }, + { 0.0000f, 0.3333f, -7.0000f, "Psc" }, + { 23.8333f, 24.0000f, -7.0000f, "Psc" }, + { 14.2500f, 14.6667f, -8.0000f, "Vir" }, + { 15.9167f, 16.2667f, -8.0000f, "Oph" }, + { 20.0000f, 20.5333f, -9.0000f, "Aql" }, + { 21.3333f, 21.8667f, -9.0000f, "Aqr" }, + { 17.1667f, 17.9667f, -10.0000f, "Oph" }, + { 5.8333f, 8.0833f, -11.0000f, "Mon" }, + { 4.9167f, 5.0833f, -11.0000f, "Eri" }, + { 5.0833f, 5.8333f, -11.0000f, "Ori" }, + { 8.0833f, 8.3667f, -11.0000f, "Hya" }, + { 9.5833f, 10.7500f, -11.0000f, "Sex" }, + { 11.8333f, 12.8333f, -11.0000f, "Vir" }, + { 17.5833f, 17.6667f, -11.6667f, "Oph" }, + { 18.8667f, 20.0000f, -12.0333f, "Aql" }, + { 4.8333f, 4.9167f, -14.5000f, "Eri" }, + { 20.5333f, 21.3333f, -15.0000f, "Aqr" }, + { 17.1667f, 18.2500f, -16.0000f, "Ser" }, + { 18.2500f, 18.8667f, -16.0000f, "Sct" }, + { 8.3667f, 8.5833f, -17.0000f, "Hya" }, + { 16.2667f, 16.3750f, -18.2500f, "Oph" }, + { 8.5833f, 9.0833f, -19.0000f, "Hya" }, + { 10.7500f, 10.8333f, -19.0000f, "Crt" }, + { 16.2667f, 16.3750f, -19.2500f, "Sco" }, + { 15.6667f, 15.9167f, -20.0000f, "Lib" }, + { 12.5833f, 12.8333f, -22.0000f, "Crv" }, + { 12.8333f, 14.2500f, -22.0000f, "Vir" }, + { 9.0833f, 9.7500f, -24.0000f, "Hya" }, + { 1.6667f, 2.6500f, -24.3833f, "Cet" }, + { 2.6500f, 3.7500f, -24.3833f, "Eri" }, + { 10.8333f, 11.8333f, -24.5000f, "Crt" }, + { 11.8333f, 12.5833f, -24.5000f, "Crv" }, + { 14.2500f, 14.9167f, -24.5000f, "Lib" }, + { 16.2667f, 16.7500f, -24.5833f, "Oph" }, + { 0.0000f, 1.6667f, -25.5000f, "Cet" }, + { 21.3333f, 21.8667f, -25.5000f, "Cap" }, + { 21.8667f, 23.8333f, -25.5000f, "Aqr" }, + { 23.8333f, 24.0000f, -25.5000f, "Cet" }, + { 9.7500f, 10.2500f, -26.5000f, "Hya" }, + { 4.7000f, 4.8333f, -27.2500f, "Eri" }, + { 4.8333f, 6.1167f, -27.2500f, "Lep" }, + { 20.0000f, 21.3333f, -28.0000f, "Cap" }, + { 10.2500f, 10.5833f, -29.1667f, "Hya" }, + { 12.5833f, 14.9167f, -29.5000f, "Hya" }, + { 14.9167f, 15.6667f, -29.5000f, "Lib" }, + { 15.6667f, 16.0000f, -29.5000f, "Sco" }, + { 4.5833f, 4.7000f, -30.0000f, "Eri" }, + { 16.7500f, 17.6000f, -30.0000f, "Oph" }, + { 17.6000f, 17.8333f, -30.0000f, "Sgr" }, + { 10.5833f, 10.8333f, -31.1667f, "Hya" }, + { 6.1167f, 7.3667f, -33.0000f, "CMa" }, + { 12.2500f, 12.5833f, -33.0000f, "Hya" }, + { 10.8333f, 12.2500f, -35.0000f, "Hya" }, + { 3.5000f, 3.7500f, -36.0000f, "For" }, + { 8.3667f, 9.3667f, -36.7500f, "Pyx" }, + { 4.2667f, 4.5833f, -37.0000f, "Eri" }, + { 17.8333f, 19.1667f, -37.0000f, "Sgr" }, + { 21.3333f, 23.0000f, -37.0000f, "PsA" }, + { 23.0000f, 23.3333f, -37.0000f, "Scl" }, + { 3.0000f, 3.5000f, -39.5833f, "For" }, + { 9.3667f, 11.0000f, -39.7500f, "Ant" }, + { 0.0000f, 1.6667f, -40.0000f, "Scl" }, + { 1.6667f, 3.0000f, -40.0000f, "For" }, + { 3.8667f, 4.2667f, -40.0000f, "Eri" }, + { 23.3333f, 24.0000f, -40.0000f, "Scl" }, + { 14.1667f, 14.9167f, -42.0000f, "Cen" }, + { 15.6667f, 16.0000f, -42.0000f, "Lup" }, + { 16.0000f, 16.4208f, -42.0000f, "Sco" }, + { 4.8333f, 5.0000f, -43.0000f, "Cae" }, + { 5.0000f, 6.5833f, -43.0000f, "Col" }, + { 8.0000f, 8.3667f, -43.0000f, "Pup" }, + { 3.4167f, 3.8667f, -44.0000f, "Eri" }, + { 16.4208f, 17.8333f, -45.5000f, "Sco" }, + { 17.8333f, 19.1667f, -45.5000f, "CrA" }, + { 19.1667f, 20.3333f, -45.5000f, "Sgr" }, + { 20.3333f, 21.3333f, -45.5000f, "Mic" }, + { 3.0000f, 3.4167f, -46.0000f, "Eri" }, + { 4.5000f, 4.8333f, -46.5000f, "Cae" }, + { 15.3333f, 15.6667f, -48.0000f, "Lup" }, + { 0.0000f, 2.3333f, -48.1667f, "Phe" }, + { 2.6667f, 3.0000f, -49.0000f, "Eri" }, + { 4.0833f, 4.2667f, -49.0000f, "Hor" }, + { 4.2667f, 4.5000f, -49.0000f, "Cae" }, + { 21.3333f, 22.0000f, -50.0000f, "Gru" }, + { 6.0000f, 8.0000f, -50.7500f, "Pup" }, + { 8.0000f, 8.1667f, -50.7500f, "Vel" }, + { 2.4167f, 2.6667f, -51.0000f, "Eri" }, + { 3.8333f, 4.0833f, -51.0000f, "Hor" }, + { 0.0000f, 1.8333f, -51.5000f, "Phe" }, + { 6.0000f, 6.1667f, -52.5000f, "Car" }, + { 8.1667f, 8.4500f, -53.0000f, "Vel" }, + { 3.5000f, 3.8333f, -53.1667f, "Hor" }, + { 3.8333f, 4.0000f, -53.1667f, "Dor" }, + { 0.0000f, 1.5833f, -53.5000f, "Phe" }, + { 2.1667f, 2.4167f, -54.0000f, "Eri" }, + { 4.5000f, 5.0000f, -54.0000f, "Pic" }, + { 15.0500f, 15.3333f, -54.0000f, "Lup" }, + { 8.4500f, 8.8333f, -54.5000f, "Vel" }, + { 6.1667f, 6.5000f, -55.0000f, "Car" }, + { 11.8333f, 12.8333f, -55.0000f, "Cen" }, + { 14.1667f, 15.0500f, -55.0000f, "Lup" }, + { 15.0500f, 15.3333f, -55.0000f, "Nor" }, + { 4.0000f, 4.3333f, -56.5000f, "Dor" }, + { 8.8333f, 11.0000f, -56.5000f, "Vel" }, + { 11.0000f, 11.2500f, -56.5000f, "Cen" }, + { 17.5000f, 18.0000f, -57.0000f, "Ara" }, + { 18.0000f, 20.3333f, -57.0000f, "Tel" }, + { 22.0000f, 23.3333f, -57.0000f, "Gru" }, + { 3.2000f, 3.5000f, -57.5000f, "Hor" }, + { 5.0000f, 5.5000f, -57.5000f, "Pic" }, + { 6.5000f, 6.8333f, -58.0000f, "Car" }, + { 0.0000f, 1.3333f, -58.5000f, "Phe" }, + { 1.3333f, 2.1667f, -58.5000f, "Eri" }, + { 23.3333f, 24.0000f, -58.5000f, "Phe" }, + { 4.3333f, 4.5833f, -59.0000f, "Dor" }, + { 15.3333f, 16.4208f, -60.0000f, "Nor" }, + { 20.3333f, 21.3333f, -60.0000f, "Ind" }, + { 5.5000f, 6.0000f, -61.0000f, "Pic" }, + { 15.1667f, 15.3333f, -61.0000f, "Cir" }, + { 16.4208f, 16.5833f, -61.0000f, "Ara" }, + { 14.9167f, 15.1667f, -63.5833f, "Cir" }, + { 16.5833f, 16.7500f, -63.5833f, "Ara" }, + { 6.0000f, 6.8333f, -64.0000f, "Pic" }, + { 6.8333f, 9.0333f, -64.0000f, "Car" }, + { 11.2500f, 11.8333f, -64.0000f, "Cen" }, + { 11.8333f, 12.8333f, -64.0000f, "Cru" }, + { 12.8333f, 14.5333f, -64.0000f, "Cen" }, + { 13.5000f, 13.6667f, -65.0000f, "Cir" }, + { 16.7500f, 16.8333f, -65.0000f, "Ara" }, + { 2.1667f, 3.2000f, -67.5000f, "Hor" }, + { 3.2000f, 4.5833f, -67.5000f, "Ret" }, + { 14.7500f, 14.9167f, -67.5000f, "Cir" }, + { 16.8333f, 17.5000f, -67.5000f, "Ara" }, + { 17.5000f, 18.0000f, -67.5000f, "Pav" }, + { 22.0000f, 23.3333f, -67.5000f, "Tuc" }, + { 4.5833f, 6.5833f, -70.0000f, "Dor" }, + { 13.6667f, 14.7500f, -70.0000f, "Cir" }, + { 14.7500f, 17.0000f, -70.0000f, "TrA" }, + { 0.0000f, 1.3333f, -75.0000f, "Tuc" }, + { 3.5000f, 4.5833f, -75.0000f, "Hyi" }, + { 6.5833f, 9.0333f, -75.0000f, "Vol" }, + { 9.0333f, 11.2500f, -75.0000f, "Car" }, + { 11.2500f, 13.6667f, -75.0000f, "Mus" }, + { 18.0000f, 21.3333f, -75.0000f, "Pav" }, + { 21.3333f, 23.3333f, -75.0000f, "Ind" }, + { 23.3333f, 24.0000f, -75.0000f, "Tuc" }, + { 0.7500f, 1.3333f, -76.0000f, "Tuc" }, + { 0.0000f, 3.5000f, -82.5000f, "Hyi" }, + { 7.6667f, 13.6667f, -82.5000f, "Cha" }, + { 13.6667f, 18.0000f, -82.5000f, "Aps" }, + { 3.5000f, 7.6667f, -85.0000f, "Men" }, + { 0.0000f, 24.0000f, -90.0000f, "Oct" }, +}; + +const int roman_boundary_count = sizeof(roman_boundaries) / sizeof(roman_boundaries[0]); diff --git a/src/constellation_data.h b/src/constellation_data.h new file mode 100644 index 0000000..2accd33 --- /dev/null +++ b/src/constellation_data.h @@ -0,0 +1,26 @@ +/* + * constellation_data.h -- Roman (1987) IAU constellation boundaries + * + * Data source: CDS catalog VI/42 + * "Identification of a Constellation From a Position" + * Nancy G. Roman, Publications of the Astronomical Society of the Pacific, + * Vol. 99, p. 695, July 1987. + * + * Boundaries are defined in B1875.0 equatorial coordinates. + */ + +#ifndef PG_ORRERY_CONSTELLATION_DATA_H +#define PG_ORRERY_CONSTELLATION_DATA_H + +typedef struct roman_boundary +{ + float ra_lower; /* hours [0, 24) */ + float ra_upper; /* hours [0, 24) */ + float dec; /* degrees, lower limit */ + char abbr[4]; /* 3-letter IAU abbreviation + null */ +} roman_boundary; + +extern const roman_boundary roman_boundaries[]; +extern const int roman_boundary_count; + +#endif /* PG_ORRERY_CONSTELLATION_DATA_H */ diff --git a/src/constellation_funcs.c b/src/constellation_funcs.c new file mode 100644 index 0000000..dd8b0ba --- /dev/null +++ b/src/constellation_funcs.c @@ -0,0 +1,175 @@ +/* + * constellation_funcs.c -- IAU constellation identification + * + * Identifies which of the 88 IAU constellations contains a given + * position, using the Roman (1987) boundary table (CDS VI/42). + * + * Algorithm: + * 1. Precess input J2000 RA/Dec to B1875.0 epoch + * 2. Convert to hours + degrees + * 3. Linear scan of boundary table (sorted by descending Dec) + * 4. First entry where point.dec >= entry.dec AND + * entry.ra_lower <= point.ra < entry.ra_upper is the match + * + * The B1875.0 epoch is used because that's the epoch of the original + * IAU boundary definitions (Delporte 1930, codified by Roman 1987). + */ + +#include "postgres.h" +#include "fmgr.h" +#include "utils/builtins.h" + +#include "types.h" +#include "astro_math.h" +#include "constellation_data.h" +#include + +PG_FUNCTION_INFO_V1(constellation_from_equatorial); +PG_FUNCTION_INFO_V1(constellation_from_radec); + +/* B1875.0 epoch as Julian date. + * JD(B) = 2415020.31352 + (B - 1900.0) * 365.242198781 + * JD(B1875.0) = 2415020.31352 + (-25.0) * 365.242198781 = 2405889.25855 */ +#define JD_B1875 2405889.25855 + + +/* + * find_constellation -- look up IAU abbreviation from B1875.0 RA/Dec + * + * ra_hours: [0, 24), dec_deg: [-90, 90] + * Returns pointer to 3-letter abbreviation (static storage), or NULL + * if no match (should never happen for valid coordinates). + */ +static const char * +find_constellation(double ra_hours, double dec_deg) +{ + int i; + + for (i = 0; i < roman_boundary_count; i++) + { + if (dec_deg >= (double)roman_boundaries[i].dec && + ra_hours >= (double)roman_boundaries[i].ra_lower && + ra_hours < (double)roman_boundaries[i].ra_upper) + { + return roman_boundaries[i].abbr; + } + } + + return NULL; /* should not happen for valid coordinates */ +} + + +/* ================================================================ + * constellation(equatorial) -> text + * + * Takes an equatorial coordinate (apparent RA/Dec of date) and + * returns the 3-letter IAU constellation abbreviation. + * + * The equatorial type stores RA/Dec in radians (of date). Since + * the observation pipeline already precesses J2000 -> of date, + * and the Roman table uses B1875.0, we need J2000 coordinates. + * + * However, for practical purposes the precession from J2000 to + * "of date" (±25 years from J2000) shifts positions by at most + * ~6 arcminutes — negligible compared to constellation boundaries + * that span degrees. We treat the equatorial input as J2000-ish + * and precess directly to B1875.0. + * + * For high accuracy near boundaries, pass J2000 RA/Dec via the + * (float8, float8) overload. + * ================================================================ + */ +Datum +constellation_from_equatorial(PG_FUNCTION_ARGS) +{ + pg_equatorial *eq = (pg_equatorial *) PG_GETARG_POINTER(0); + double ra_j2000, dec_j2000; + double ra_1875, dec_1875; + double ra_hours, dec_deg; + const char *abbr; + + /* equatorial stores RA/Dec in radians */ + ra_j2000 = eq->ra; + dec_j2000 = eq->dec; + + /* Precess to B1875.0 */ + precess_j2000_to_date(JD_B1875, ra_j2000, dec_j2000, &ra_1875, &dec_1875); + + /* Convert to hours and degrees */ + ra_hours = ra_1875 * (12.0 / M_PI); /* radians -> hours */ + dec_deg = dec_1875 * (180.0 / M_PI); /* radians -> degrees */ + + /* Normalize RA to [0, 24) */ + if (ra_hours < 0.0) + ra_hours += 24.0; + if (ra_hours >= 24.0) + ra_hours -= 24.0; + + abbr = find_constellation(ra_hours, dec_deg); + + if (abbr == NULL) + ereport(ERROR, + (errcode(ERRCODE_INTERNAL_ERROR), + errmsg("constellation: no match for RA=%.4f h, Dec=%.4f deg (B1875.0)", + ra_hours, dec_deg))); + + PG_RETURN_TEXT_P(cstring_to_text(abbr)); +} + + +/* ================================================================ + * constellation(ra_hours float8, dec_deg float8) -> text + * + * Takes J2000 RA (hours [0,24)) and Dec (degrees [-90,90]). + * Precesses to B1875.0 and looks up the constellation. + * ================================================================ + */ +Datum +constellation_from_radec(PG_FUNCTION_ARGS) +{ + double ra_hours_j2000 = PG_GETARG_FLOAT8(0); + double dec_deg_j2000 = PG_GETARG_FLOAT8(1); + double ra_rad, dec_rad; + double ra_1875, dec_1875; + double ra_hours, dec_deg; + const char *abbr; + + /* Validate input ranges */ + if (ra_hours_j2000 < 0.0 || ra_hours_j2000 >= 24.0) + ereport(ERROR, + (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), + errmsg("constellation: RA must be in [0, 24), got %.4f", + ra_hours_j2000))); + + if (dec_deg_j2000 < -90.0 || dec_deg_j2000 > 90.0) + ereport(ERROR, + (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), + errmsg("constellation: Dec must be in [-90, 90], got %.4f", + dec_deg_j2000))); + + /* Convert to radians */ + ra_rad = ra_hours_j2000 * (M_PI / 12.0); /* hours -> radians */ + dec_rad = dec_deg_j2000 * (M_PI / 180.0); /* degrees -> radians */ + + /* Precess J2000 to B1875.0 */ + precess_j2000_to_date(JD_B1875, ra_rad, dec_rad, &ra_1875, &dec_1875); + + /* Convert back to hours and degrees */ + ra_hours = ra_1875 * (12.0 / M_PI); + dec_deg = dec_1875 * (180.0 / M_PI); + + if (ra_hours < 0.0) + ra_hours += 24.0; + if (ra_hours >= 24.0) + ra_hours -= 24.0; + + abbr = find_constellation(ra_hours, dec_deg); + + if (abbr == NULL) + ereport(ERROR, + (errcode(ERRCODE_INTERNAL_ERROR), + errmsg("constellation: no match for RA=%.4f h, Dec=%.4f deg (B1875.0)", + ra_hours, dec_deg))); + + PG_RETURN_TEXT_P(cstring_to_text(abbr)); +} diff --git a/src/rise_set_funcs.c b/src/rise_set_funcs.c index 3e1223a..3b0f44e 100644 --- a/src/rise_set_funcs.c +++ b/src/rise_set_funcs.c @@ -30,6 +30,10 @@ PG_FUNCTION_INFO_V1(moon_next_rise); PG_FUNCTION_INFO_V1(moon_next_set); PG_FUNCTION_INFO_V1(sun_next_rise_refracted); PG_FUNCTION_INFO_V1(sun_next_set_refracted); +PG_FUNCTION_INFO_V1(planet_next_rise_refracted); +PG_FUNCTION_INFO_V1(planet_next_set_refracted); +PG_FUNCTION_INFO_V1(moon_next_rise_refracted); +PG_FUNCTION_INFO_V1(moon_next_set_refracted); #define COARSE_STEP_JD (60.0 / 86400.0) /* 60 seconds */ #define BISECT_TOL_JD (0.1 / 86400.0) /* 0.1 second */ @@ -49,6 +53,14 @@ PG_FUNCTION_INFO_V1(sun_next_set_refracted); */ #define SUN_MOON_REFRACTED_HORIZON_RAD (-0.01454) /* -0.833 deg */ +/* + * Refraction-only horizon for point sources (planets). + * No semidiameter correction needed — even Jupiter at opposition + * subtends only ~24" (0.4 arcmin), negligible against 34' refraction. + * Error from treating planets as point sources: <1 second in time. + */ +#define REFRACTION_ONLY_HORIZON_RAD (-0.00993) /* -0.569 deg */ + /* ---------------------------------------------------------------- * elevation_at_jd_body -- compute topocentric elevation for a body @@ -409,3 +421,139 @@ sun_next_set_refracted(PG_FUNCTION_ARGS) PG_RETURN_TIMESTAMPTZ(jd_to_timestamptz(result_jd)); } + + +/* ================================================================ + * planet_next_rise_refracted(body_id, observer, timestamptz) -> timestamptz + * + * Uses -0.569 degree threshold (refraction only, point source). + * Planets are too small for semidiameter to matter — Jupiter at + * opposition is 24 arcseconds, <1 second of time error. + * ================================================================ + */ +Datum +planet_next_rise_refracted(PG_FUNCTION_ARGS) +{ + int32 body_id = PG_GETARG_INT32(0); + pg_observer *obs = (pg_observer *) PG_GETARG_POINTER(1); + int64 ts = PG_GETARG_INT64(2); + double start_jd, stop_jd, result_jd; + + if (body_id < BODY_MERCURY || body_id > BODY_NEPTUNE) + ereport(ERROR, + (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), + errmsg("planet_next_rise_refracted: body_id %d must be 1-8 (Mercury-Neptune)", + body_id))); + + if (body_id == BODY_EARTH) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("cannot observe Earth from Earth"))); + + start_jd = timestamptz_to_jd(ts); + stop_jd = start_jd + DEFAULT_WINDOW_DAYS; + + result_jd = find_next_crossing(BTYPE_PLANET, body_id, obs, + start_jd, stop_jd, + REFRACTION_ONLY_HORIZON_RAD, true); + + if (result_jd < 0.0) + PG_RETURN_NULL(); + + PG_RETURN_TIMESTAMPTZ(jd_to_timestamptz(result_jd)); +} + + +/* ================================================================ + * planet_next_set_refracted(body_id, observer, timestamptz) -> timestamptz + * + * Refracted planet set is later than geometric. + * ================================================================ + */ +Datum +planet_next_set_refracted(PG_FUNCTION_ARGS) +{ + int32 body_id = PG_GETARG_INT32(0); + pg_observer *obs = (pg_observer *) PG_GETARG_POINTER(1); + int64 ts = PG_GETARG_INT64(2); + double start_jd, stop_jd, result_jd; + + if (body_id < BODY_MERCURY || body_id > BODY_NEPTUNE) + ereport(ERROR, + (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), + errmsg("planet_next_set_refracted: body_id %d must be 1-8 (Mercury-Neptune)", + body_id))); + + if (body_id == BODY_EARTH) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("cannot observe Earth from Earth"))); + + start_jd = timestamptz_to_jd(ts); + stop_jd = start_jd + DEFAULT_WINDOW_DAYS; + + result_jd = find_next_crossing(BTYPE_PLANET, body_id, obs, + start_jd, stop_jd, + REFRACTION_ONLY_HORIZON_RAD, false); + + if (result_jd < 0.0) + PG_RETURN_NULL(); + + PG_RETURN_TIMESTAMPTZ(jd_to_timestamptz(result_jd)); +} + + +/* ================================================================ + * moon_next_rise_refracted(observer, timestamptz) -> timestamptz + * + * Uses -0.833 degree threshold (same as Sun: 0.569 deg refraction + + * 0.264 deg mean lunar semidiameter). Moon semidiameter varies + * 14.7'-16.7'; mean value error is ~1 arcmin → ~15 seconds in time. + * ================================================================ + */ +Datum +moon_next_rise_refracted(PG_FUNCTION_ARGS) +{ + pg_observer *obs = (pg_observer *) PG_GETARG_POINTER(0); + int64 ts = PG_GETARG_INT64(1); + double start_jd, stop_jd, result_jd; + + start_jd = timestamptz_to_jd(ts); + stop_jd = start_jd + DEFAULT_WINDOW_DAYS; + + result_jd = find_next_crossing(BTYPE_MOON, 0, obs, + start_jd, stop_jd, + SUN_MOON_REFRACTED_HORIZON_RAD, true); + + if (result_jd < 0.0) + PG_RETURN_NULL(); + + PG_RETURN_TIMESTAMPTZ(jd_to_timestamptz(result_jd)); +} + + +/* ================================================================ + * moon_next_set_refracted(observer, timestamptz) -> timestamptz + * + * Refracted moonset is later than geometric. + * ================================================================ + */ +Datum +moon_next_set_refracted(PG_FUNCTION_ARGS) +{ + pg_observer *obs = (pg_observer *) PG_GETARG_POINTER(0); + int64 ts = PG_GETARG_INT64(1); + double start_jd, stop_jd, result_jd; + + start_jd = timestamptz_to_jd(ts); + stop_jd = start_jd + DEFAULT_WINDOW_DAYS; + + result_jd = find_next_crossing(BTYPE_MOON, 0, obs, + start_jd, stop_jd, + SUN_MOON_REFRACTED_HORIZON_RAD, false); + + if (result_jd < 0.0) + PG_RETURN_NULL(); + + PG_RETURN_TIMESTAMPTZ(jd_to_timestamptz(result_jd)); +} diff --git a/test/expected/constellation.out b/test/expected/constellation.out new file mode 100644 index 0000000..a587162 --- /dev/null +++ b/test/expected/constellation.out @@ -0,0 +1,133 @@ +-- constellation.sql -- Tests for v0.14.0: IAU constellation identification +-- +-- Verifies the Roman (1987) boundary lookup against well-known +-- stellar positions and solar system objects. +CREATE EXTENSION IF NOT EXISTS pg_orrery; +NOTICE: extension "pg_orrery" already exists, skipping +-- ============================================================ +-- Known stars via J2000 RA/Dec overload +-- ============================================================ +-- Polaris (Alpha UMi): RA 2.5303h, Dec +89.264 +SELECT constellation(2.5303, 89.264) AS polaris_constellation; + polaris_constellation +----------------------- + UMi +(1 row) + +-- Sirius (Alpha CMa): RA 6.7525h, Dec -16.716 +SELECT constellation(6.7525, -16.716) AS sirius_constellation; + sirius_constellation +---------------------- + CMa +(1 row) + +-- Betelgeuse (Alpha Ori): RA 5.9195h, Dec +7.407 +SELECT constellation(5.9195, 7.407) AS betelgeuse_constellation; + betelgeuse_constellation +-------------------------- + Ori +(1 row) + +-- Vega (Alpha Lyr): RA 18.6156h, Dec +38.784 +SELECT constellation(18.6156, 38.784) AS vega_constellation; + vega_constellation +-------------------- + Lyr +(1 row) + +-- Antares (Alpha Sco): RA 16.4901h, Dec -26.432 +SELECT constellation(16.4901, -26.432) AS antares_constellation; + antares_constellation +----------------------- + Sco +(1 row) + +-- Deneb (Alpha Cyg): RA 20.6905h, Dec +45.280 +SELECT constellation(20.6905, 45.280) AS deneb_constellation; + deneb_constellation +--------------------- + Cyg +(1 row) + +-- Rigel (Beta Ori): RA 5.2423h, Dec -8.202 +SELECT constellation(5.2423, -8.202) AS rigel_constellation; + rigel_constellation +--------------------- + Ori +(1 row) + +-- ============================================================ +-- Celestial poles +-- ============================================================ +-- South celestial pole -> Octans +SELECT constellation(0.0, -90.0) AS south_pole_constellation; + south_pole_constellation +-------------------------- + Oct +(1 row) + +-- Near north celestial pole -> Ursa Minor +SELECT constellation(0.0, 89.0) AS north_pole_constellation; + north_pole_constellation +-------------------------- + UMi +(1 row) + +-- ============================================================ +-- Solar system objects via equatorial overload +-- ============================================================ +-- Sun at 2024 summer solstice should be in Gemini (not Cancer -- +-- precession has shifted the solstice point) +SELECT constellation(sun_equatorial('2024-06-21 12:00:00+00'::timestamptz)) + AS sun_solstice_constellation; + sun_solstice_constellation +---------------------------- + Gem +(1 row) + +-- Jupiter in Jan 2024 should be in Aries +SELECT constellation(planet_equatorial(5, '2024-01-15 12:00:00+00'::timestamptz)) + AS jupiter_jan2024_constellation; + jupiter_jan2024_constellation +------------------------------- + Ari +(1 row) + +-- ============================================================ +-- Both overloads should agree for the same position +-- ============================================================ +SELECT constellation(18.6156, 38.784) + = constellation(make_equatorial(18.6156, 38.784, 0.0)) + AS overloads_agree; + overloads_agree +----------------- + t +(1 row) + +-- ============================================================ +-- RA boundary edge case near 0h/24h wrap +-- ============================================================ +-- RA just above 0h at various declinations +SELECT constellation(0.01, 45.0) IS NOT NULL AS ra_near_zero_valid; + ra_near_zero_valid +-------------------- + t +(1 row) + +SELECT constellation(23.99, -30.0) IS NOT NULL AS ra_near_24_valid; + ra_near_24_valid +------------------ + t +(1 row) + +-- ============================================================ +-- Error cases +-- ============================================================ +-- RA out of range +DO $$ BEGIN PERFORM constellation(24.1, 0.0); EXCEPTION WHEN OTHERS THEN RAISE NOTICE 'RA=24.1: %', SQLERRM; END $$; +NOTICE: RA=24.1: constellation: RA must be in [0, 24), got 24.1000 +DO $$ BEGIN PERFORM constellation(-0.1, 0.0); EXCEPTION WHEN OTHERS THEN RAISE NOTICE 'RA=-0.1: %', SQLERRM; END $$; +NOTICE: RA=-0.1: constellation: RA must be in [0, 24), got -0.1000 +-- Dec out of range +DO $$ BEGIN PERFORM constellation(12.0, 91.0); EXCEPTION WHEN OTHERS THEN RAISE NOTICE 'Dec=91: %', SQLERRM; END $$; +NOTICE: Dec=91: constellation: Dec must be in [-90, 90], got 91.0000 diff --git a/test/expected/rise_set.out b/test/expected/rise_set.out index 296b059..bc7d109 100644 --- a/test/expected/rise_set.out +++ b/test/expected/rise_set.out @@ -145,6 +145,68 @@ SELECT sun_next_rise('(70.0,25.0,0)'::observer, '2024-12-21 00:00:00+00'::timest t (1 row) +-- ============================================================ +-- Planet refracted rise/set (v0.14.0) +-- ============================================================ +-- Planet refracted rise should be earlier than geometric +SELECT planet_next_rise_refracted(5, '(43.7,-116.4,800)'::observer, '2024-01-15 00:00:00+00'::timestamptz) + < planet_next_rise(5, '(43.7,-116.4,800)'::observer, '2024-01-15 00:00:00+00'::timestamptz) + AS planet_refracted_rise_earlier; + planet_refracted_rise_earlier +------------------------------- + t +(1 row) + +-- Planet refracted set should be later than geometric +SELECT planet_next_set_refracted(5, '(43.7,-116.4,800)'::observer, '2024-01-15 00:00:00+00'::timestamptz) + > planet_next_set(5, '(43.7,-116.4,800)'::observer, '2024-01-15 00:00:00+00'::timestamptz) + AS planet_refracted_set_later; + planet_refracted_set_later +---------------------------- + t +(1 row) + +-- Planet refraction offset should be reasonable (30-300 seconds) +SELECT abs(extract(epoch FROM + planet_next_rise(5, '(43.7,-116.4,800)'::observer, '2024-01-15 00:00:00+00'::timestamptz) + - planet_next_rise_refracted(5, '(43.7,-116.4,800)'::observer, '2024-01-15 00:00:00+00'::timestamptz))) + BETWEEN 30 AND 300 AS planet_refraction_offset_reasonable; + planet_refraction_offset_reasonable +------------------------------------- + t +(1 row) + +-- ============================================================ +-- Moon refracted rise/set (v0.14.0) +-- ============================================================ +-- Moon refracted rise should be earlier than geometric +SELECT moon_next_rise_refracted('(43.7,-116.4,800)'::observer, '2024-01-15 00:00:00+00'::timestamptz) + < moon_next_rise('(43.7,-116.4,800)'::observer, '2024-01-15 00:00:00+00'::timestamptz) + AS moon_refracted_rise_earlier; + moon_refracted_rise_earlier +----------------------------- + t +(1 row) + +-- Moon refracted set should be later than geometric +SELECT moon_next_set_refracted('(43.7,-116.4,800)'::observer, '2024-01-15 00:00:00+00'::timestamptz) + > moon_next_set('(43.7,-116.4,800)'::observer, '2024-01-15 00:00:00+00'::timestamptz) + AS moon_refracted_set_later; + moon_refracted_set_later +-------------------------- + t +(1 row) + +-- Moon refraction offset should be reasonable (60-600 seconds) +SELECT abs(extract(epoch FROM + moon_next_rise('(43.7,-116.4,800)'::observer, '2024-01-15 00:00:00+00'::timestamptz) + - moon_next_rise_refracted('(43.7,-116.4,800)'::observer, '2024-01-15 00:00:00+00'::timestamptz))) + BETWEEN 60 AND 600 AS moon_refraction_offset_reasonable; + moon_refraction_offset_reasonable +----------------------------------- + t +(1 row) + -- ============================================================ -- Error cases -- ============================================================ diff --git a/test/sql/constellation.sql b/test/sql/constellation.sql new file mode 100644 index 0000000..abaefaf --- /dev/null +++ b/test/sql/constellation.sql @@ -0,0 +1,81 @@ +-- constellation.sql -- Tests for v0.14.0: IAU constellation identification +-- +-- Verifies the Roman (1987) boundary lookup against well-known +-- stellar positions and solar system objects. + +CREATE EXTENSION IF NOT EXISTS pg_orrery; + +-- ============================================================ +-- Known stars via J2000 RA/Dec overload +-- ============================================================ + +-- Polaris (Alpha UMi): RA 2.5303h, Dec +89.264 +SELECT constellation(2.5303, 89.264) AS polaris_constellation; + +-- Sirius (Alpha CMa): RA 6.7525h, Dec -16.716 +SELECT constellation(6.7525, -16.716) AS sirius_constellation; + +-- Betelgeuse (Alpha Ori): RA 5.9195h, Dec +7.407 +SELECT constellation(5.9195, 7.407) AS betelgeuse_constellation; + +-- Vega (Alpha Lyr): RA 18.6156h, Dec +38.784 +SELECT constellation(18.6156, 38.784) AS vega_constellation; + +-- Antares (Alpha Sco): RA 16.4901h, Dec -26.432 +SELECT constellation(16.4901, -26.432) AS antares_constellation; + +-- Deneb (Alpha Cyg): RA 20.6905h, Dec +45.280 +SELECT constellation(20.6905, 45.280) AS deneb_constellation; + +-- Rigel (Beta Ori): RA 5.2423h, Dec -8.202 +SELECT constellation(5.2423, -8.202) AS rigel_constellation; + +-- ============================================================ +-- Celestial poles +-- ============================================================ + +-- South celestial pole -> Octans +SELECT constellation(0.0, -90.0) AS south_pole_constellation; + +-- Near north celestial pole -> Ursa Minor +SELECT constellation(0.0, 89.0) AS north_pole_constellation; + +-- ============================================================ +-- Solar system objects via equatorial overload +-- ============================================================ + +-- Sun at 2024 summer solstice should be in Gemini (not Cancer -- +-- precession has shifted the solstice point) +SELECT constellation(sun_equatorial('2024-06-21 12:00:00+00'::timestamptz)) + AS sun_solstice_constellation; + +-- Jupiter in Jan 2024 should be in Aries +SELECT constellation(planet_equatorial(5, '2024-01-15 12:00:00+00'::timestamptz)) + AS jupiter_jan2024_constellation; + +-- ============================================================ +-- Both overloads should agree for the same position +-- ============================================================ + +SELECT constellation(18.6156, 38.784) + = constellation(make_equatorial(18.6156, 38.784, 0.0)) + AS overloads_agree; + +-- ============================================================ +-- RA boundary edge case near 0h/24h wrap +-- ============================================================ + +-- RA just above 0h at various declinations +SELECT constellation(0.01, 45.0) IS NOT NULL AS ra_near_zero_valid; +SELECT constellation(23.99, -30.0) IS NOT NULL AS ra_near_24_valid; + +-- ============================================================ +-- Error cases +-- ============================================================ + +-- RA out of range +DO $$ BEGIN PERFORM constellation(24.1, 0.0); EXCEPTION WHEN OTHERS THEN RAISE NOTICE 'RA=24.1: %', SQLERRM; END $$; +DO $$ BEGIN PERFORM constellation(-0.1, 0.0); EXCEPTION WHEN OTHERS THEN RAISE NOTICE 'RA=-0.1: %', SQLERRM; END $$; + +-- Dec out of range +DO $$ BEGIN PERFORM constellation(12.0, 91.0); EXCEPTION WHEN OTHERS THEN RAISE NOTICE 'Dec=91: %', SQLERRM; END $$; diff --git a/test/sql/rise_set.sql b/test/sql/rise_set.sql index dea20c4..d615101 100644 --- a/test/sql/rise_set.sql +++ b/test/sql/rise_set.sql @@ -98,6 +98,46 @@ SELECT sun_next_set('(70.0,25.0,0)'::observer, '2024-06-21 00:00:00+00'::timesta SELECT sun_next_rise('(70.0,25.0,0)'::observer, '2024-12-21 00:00:00+00'::timestamptz) IS NULL AS polar_night_no_rise; +-- ============================================================ +-- Planet refracted rise/set (v0.14.0) +-- ============================================================ + +-- Planet refracted rise should be earlier than geometric +SELECT planet_next_rise_refracted(5, '(43.7,-116.4,800)'::observer, '2024-01-15 00:00:00+00'::timestamptz) + < planet_next_rise(5, '(43.7,-116.4,800)'::observer, '2024-01-15 00:00:00+00'::timestamptz) + AS planet_refracted_rise_earlier; + +-- Planet refracted set should be later than geometric +SELECT planet_next_set_refracted(5, '(43.7,-116.4,800)'::observer, '2024-01-15 00:00:00+00'::timestamptz) + > planet_next_set(5, '(43.7,-116.4,800)'::observer, '2024-01-15 00:00:00+00'::timestamptz) + AS planet_refracted_set_later; + +-- Planet refraction offset should be reasonable (30-300 seconds) +SELECT abs(extract(epoch FROM + planet_next_rise(5, '(43.7,-116.4,800)'::observer, '2024-01-15 00:00:00+00'::timestamptz) + - planet_next_rise_refracted(5, '(43.7,-116.4,800)'::observer, '2024-01-15 00:00:00+00'::timestamptz))) + BETWEEN 30 AND 300 AS planet_refraction_offset_reasonable; + +-- ============================================================ +-- Moon refracted rise/set (v0.14.0) +-- ============================================================ + +-- Moon refracted rise should be earlier than geometric +SELECT moon_next_rise_refracted('(43.7,-116.4,800)'::observer, '2024-01-15 00:00:00+00'::timestamptz) + < moon_next_rise('(43.7,-116.4,800)'::observer, '2024-01-15 00:00:00+00'::timestamptz) + AS moon_refracted_rise_earlier; + +-- Moon refracted set should be later than geometric +SELECT moon_next_set_refracted('(43.7,-116.4,800)'::observer, '2024-01-15 00:00:00+00'::timestamptz) + > moon_next_set('(43.7,-116.4,800)'::observer, '2024-01-15 00:00:00+00'::timestamptz) + AS moon_refracted_set_later; + +-- Moon refraction offset should be reasonable (60-600 seconds) +SELECT abs(extract(epoch FROM + moon_next_rise('(43.7,-116.4,800)'::observer, '2024-01-15 00:00:00+00'::timestamptz) + - moon_next_rise_refracted('(43.7,-116.4,800)'::observer, '2024-01-15 00:00:00+00'::timestamptz))) + BETWEEN 60 AND 600 AS moon_refraction_offset_reasonable; + -- ============================================================ -- Error cases -- ============================================================