Repository Public
1<!--2ORIX Cosmos3File: Documentation/modules/CosmosAstrodynamics.md4Description: Reference of the CosmosAstrodynamics module: SGP4/SDP4 and element sets, orbit toolkit, transfers, general event finder and astronomical events (phases, eclipses, transits, mutual events); algorithms, conventions, references, validation measured against fetched references, tolerances, benchmarks and limitations.5Author: Simon-Pierre Boucher6Contact: contact@spboucher.ai7-->8# CosmosAstrodynamics910Earth-satellite propagation (SGP4/SDP4), orbit geometry, transfers and astronomical event finding on top of11`CosmosEphemeris`, `CosmosCoordinates` and `CosmosTime`. Pure Swift (Foundation, simd), Swift 6 strict concurrency,12no third-party code. Every public type is a `Sendable` value type; nothing here holds mutable shared state.1314All numbers in this document were measured on 2026-11-24 by the test suite (`[CosmosAstrodynamics]` lines of its15output) against reference data **downloaded that day** and stored with URL, date and SHA-256 in16`Packages/CosmosAstrodynamics/Tests/Fixtures/` (`index.json`, `README.txt`).1718```19swift build --scratch-path .build-astro --target CosmosAstrodynamics20swift test --scratch-path .build-astro --filter CosmosAstrodynamicsTests # 55 tests, 9 suites, ≈ 30 s (debug)21swift run -c release --scratch-path .build-astro cosmos-bench astro.sgp4 astro.phases astro.eclipses astro.lambert22python3 DataPipeline/astrodynamics/fetch_validation.py [--force] # re-download the fixtures23```2425Tests that need the planetary ephemeris look for `Resources/Packs/core-ephemeris` (path derived from the test26file, or `COSMOS_PACKS_DIR`) and **fail** with the command to run when it is absent; they are never skipped.2728## 1. Files and public API2930| File | Main API |31|---|---|32| `SGP4.swift` | `SGP4Propagator` (`init(epochDays1950:bstar:…:gravity:mode:)`, `propagate(minutesSinceEpoch:)` → TEME km, km/s), `SGP4GravityModel` (`.wgs72`, `.wgs72old`, `.wgs84`), `SGP4Error` |33| `SatelliteElements.swift` | `SatelliteElements`, `TLEParser.parse(line1:line2:name:validateChecksums:)`, `TLEParser.parse(text:)`, `TLEParser.checksum`, `TLEParser.catalogNumber` (alpha-5), `OMMParser.parse(_:)` / `parseJSON` / `parseKVN` / `parseXML` |34| `SGP4Ephemeris.swift` | `SGP4Ephemeris` (`EphemerisProvider`, `AnchoredEphemerisProvider`): `epoch`, `age(at:)`, `quality(at:)`, `temeState(at:)`, `state(of:relativeTo:at:)`; `SatellitePredictionQuality`; `TEMEFrame.temeToICRF(at:)` |35| `OrbitToolkit.swift` | `OsculatingOrbit`, `OsculatingConicPolyline`, `TrajectoryPolyline`, `SubPoint`; `OrbitToolkit.osculatingOrbit`, `conicPolyline`, `trajectoryPolyline`, `sphereOfInfluence`, `hillRadius`, `synodicPeriod`, `influenceRadii`, `earthSubPoint`, `subPoint(of:on:…)`, `groundTrack`; `OrbitalElements` extensions (`apoapsisDistance`, `semiLatusRectum`, `periapsisSpeed`, `position(atTrueAnomaly:)`, …) |36| `SatellitePasses.swift` | `SatellitePassPredictor.passes(over:in:minimumElevation:step:)` → `EventSearchResult<SatellitePass>`, `illumination(at:)`; `EarthShadow.illumination` (conical model), `SatelliteIllumination` |37| `Lambert.swift` | `Lambert.solve(gm:r1:r2:timeOfFlight:revolutions:direction:lowPath:referenceNormal:)` → `LambertSolution`, `Lambert.allSolutions(…maxRevolutions:)` |38| `Transfers.swift` | `HohmannTransfer`, `BiEllipticTransfer`, `PlanetaryHohmann`, `Maneuvers.escapeBurn/captureBurn/planeChange`, `DeltaVBudget`, `GravityAssist`, `Porkchop.transfer/grid/launchWindows`, `PorkchopGrid`, `TransferOpportunity` |39| `EventFinder.swift` | `EventFinder.roots(of:in:step:tolerance:direction:maxJump:)`, `extrema(of:in:step:tolerance:kind:)`, `minimum(of:from:to:)`; `EventSearchResult<Event>`, `CoverageLimit`, `TimeRoot`, `TimeExtremum`, `EphemerisSources` |40| `SkyEvents.swift` | `SkyEvents`: `lunarPhases(in:)`, `elongationEvents(of:in:step:)`, `seasons(in:)`, `apsides(of:relativeTo:in:step:)`, `closeApproaches(between:and:in:step:)`, `conjunctions(of:with:in:coordinate:step:)`, `minimumSeparations(of:and:in:step:)`, `illumination(of:at:)`, `eclipticCoordinates`, `equatorialCoordinates`, `apparentPosition`; `AstronomicalEvent`, `Illumination` |41| `Eclipses.swift` | `EclipseFinder`: `solarEclipses(in:)` → `SolarEclipse`, `localSolarEclipse(near:site:)` → `LocalSolarEclipse?`, `lunarEclipses(in:)` → `LunarEclipse`; `EclipseConventions` |42| `MutualEvents.swift` | `MutualEventFinder`: `events(of:across:from:in:step:frontRadius:backRadius:)`, `solarTransits(of:from:in:solarRadius:planetRadius:)`, `eclipses(of:by:in:)` → `MutualEvent`; `shadowTransits(of:on:in:)` → `ShadowTransit` |4344Typical use:4546```swift47// Earth satellite from a TLE or an OMM48let elements = try TLEParser.parse(line1: l1, line2: l2) // or: try OMMParser.parse(data).first!49let sat = try SGP4Ephemeris(elements: elements) // norad:<n> relative to naif:399, ICRF, .estimated50let s = try sat.state(of: sat.object, relativeTo: .naif(399), at: t)51let q = sat.quality(at: t) // epoch, age, grade, order-of-magnitude error, note52let passes = try SatellitePassPredictor(satellite: sat, solarSystem: core.planets).passes(over: site, in: interval)5354// Orbits55let osc = try OrbitToolkit.osculatingOrbit(of: .naif(301), relativeTo: .naif(399), at: t, using: core.planets, constants: core.constants)56let conic = try OrbitToolkit.conicPolyline(osc) // OsculatingConicPolyline57let path = try OrbitToolkit.trajectoryPolyline(of: .naif(301), relativeTo: .naif(399), from: t0, to: t1,58 using: core.planets, tolerance: 50_000) // TrajectoryPolyline5960// Transfers61let l = try Lambert.solve(gm: gm, r1: r1, r2: r2, timeOfFlight: tof)62let grid = try Porkchop(ephemeris: core.planets).grid(from: .naif(399), to: .naif(4), departureWindow: d, arrivalWindow: a)63let windows = try Porkchop(ephemeris: core.planets).launchWindows(from: .naif(399), to: .naif(4), departureWindow: d, timeOfFlight: (120 * 86400)...(420 * 86400))6465// Events66let sky = SkyEvents(ephemeris: core.planets)67let phases = try sky.lunarPhases(in: year) // EventSearchResult<AstronomicalEvent>68let eclipses = try EclipseFinder(ephemeris: core.planets).solarEclipses(in: century)69let local = try EclipseFinder(ephemeris: core.planets, time: timeWithIERS).localSolarEclipse(near: e.greatestEclipse, site: site)70let io = try MutualEventFinder(ephemeris: try core.composite(), constants: core.constants)71 .events(of: .naif(501), across: .naif(599), from: .naif(399), in: week) // .estimated72```7374## 2. SGP4/SDP47576### 2.1 Implementation7778`SGP4Propagator` is a line-by-line Swift transcription of the reference implementation distributed with79D. A. Vallado, P. Crawford, R. Hujsak & T. S. Kelso, "Revisiting Spacetrack Report #3", AIAA 2006-6753 (2006):80`sgp4init`, `initl`, `dscom`, `dpper`, `dsinit`, `dspace`, `sgp4`, `gstime`, `getgravconst`. Near-Earth (period81< 225 min) and deep-space branches (lunar–solar secular and periodic terms, 12-hour and 24-hour resonances with the82720-minute integrator, Lyddane modification below 0.2 rad of inclination) are both present.8384- Constants: **WGS-72** by default (`.wgs72`); `.wgs72old` and `.wgs84` as in the reference code.85- `OperationMode.afspc` ('a') reproduces the operational code and is used for the verification;86 `.improved` ('i', the default, as the paper recommends) differs by at most 1.02 km over one day on the 3387 verification satellites (worst: 23599, a low-inclination resonant orbit where the two node conventions diverge).88- One deliberate difference: the propagator is an immutable value. The resonance integrator is restarted from the89 epoch at every call instead of being continued from the previous call. The reference integrator uses fixed90 720-minute steps from the epoch, so the numbers are the same (verified below), and concurrent use is safe.91- Errors are thrown as `SGP4Error` with the reference codes: 1 mean eccentricity out of range, 2 mean motion not92 positive, 3 perturbed eccentricity out of range, 4 negative semi-latus rectum, 6 decayed (radius below one Earth93 radius); `invalidElements` at initialisation.9495### 2.2 Element sets9697- **TLE** (`TLEParser`): fixed columns; modulo-10 checksums of both lines (digits + 1 per minus sign), required98 unless `validateChecksums: false`; **alpha-5** catalogue numbers (A–Z without I and O = 10–33, so `A0000` =99 100000, `Z9999` = 339999); two-digit epoch years 57–99 → 1957–1999 and 00–56 → 2000–2056; implied-decimal fields100 (`B*`, second derivative); two- and three-line files, CR/LF, `#` comments. Mismatched catalogue numbers, a day of101 year outside the year, a missing line 2 or any unreadable field throws `invalidInput` — nothing is skipped.102- **OMM** (`OMMParser`): JSON (object or array; numeric or string values, i.e. both the CelesTrak and the103 Space-Track styles), KVN, and XML (CCSDS `ndm/omm`, read with Foundation's `XMLParser`). `MEAN_ELEMENT_THEORY`104 other than SGP4, `REF_FRAME` other than TEME, `TIME_SYSTEM` other than UTC or `CENTER_NAME` other than EARTH is105 refused with `unsupported`.106- The epoch is kept as UTC (MJD + seconds of day) and converted to an `Instant` with the leap-second table.107108### 2.3 Frame: TEME → ICRF109110SGP4 returns a state in TEME (true equator, mean equinox of date). `TEMEFrame.temeToICRF(at:)` follows the route111recommended in appendix C of the paper: `r_TOD = R₃(−Eq_eq) r_TEME`, then `r_ICRF = (N·P·B)ᵀ r_TOD`.112113Approximation level: `Eq_eq` and `N·P·B` are the IAU 2006/2000B models of CosmosCoordinates, while SGP4 belongs to114the IAU 1976/1980 system; the two agree to tens of milliarcseconds (about a metre at geostationary distance), far115below SGP4's own accuracy. The rotation is purely celestial (no UT1, no polar motion). Velocity is rotated with the116same matrix (the frame's own precession rate, 1e-12 rad/s, is neglected). The elapsed time is the SI interval117between the instant and the epoch, so a leap second between the two is accounted for.118119### 2.4 Provider, epoch, age and quality120121`SGP4Ephemeris` exposes one object `norad:<n>` relative to `naif:399`, in ICRF axes, with `status == .estimated`122and a name that carries the epoch (`sgp4(norad:25544, epoch 2026-11-23T21:54:38Z)`). It conforms to123`AnchoredEphemerisProvider`, so it can be added to a `CompositeEphemeris`.124125`quality(at:)` returns the element-set **epoch**, the **age** (instant − epoch, signed), a grade and a note:126127| Grade | \|age\| (default policy) | Meaning |128|---|---|---|129| `nominal` | ≤ 3 d | inside the span the element set was meant for |130| `degraded` | ≤ 14 d | usable for display; along-track error may reach tens of km for low orbits |131| `poor` | ≤ 30 d | position along the orbit unreliable |132| — | > 30 d | **refused**: `CosmosError.outOfCoverage`, no state is returned |133134`estimatedPositionError` is the rule of thumb `1 km + 2 km × |age in days|` for near-Earth orbits (the paper and135CelesTrak describe SGP4 as good to about a kilometre at epoch, degrading by 1–3 km per day, mostly along the136track); it is `nil` for deep-space orbits, for which no simple rule holds. It is an order of magnitude, not an137error bar: high-drag, manoeuvring and re-entering objects are far worse. The thresholds are an `AgePolicy` and can138be changed.139140### 2.5 Validation141142**Official verification set.** `SGP4-VER.TLE` (33 element sets, 24 of them deep-space) and the expected output143`tcppver.out` of the reference C++ code. The archive distributed by CelesTrak today no longer contains144`tcppver.out` (it ships per-satellite STK ephemerides and the Fortran/MATLAB outputs); the file used is the one of145the 2012-07-16 edition of the same archive, obtained from the Internet Archive copy of the CelesTrak URL146(SHA-256 `5e32cfd7…61d9`). `SGP4-VER.TLE` is byte-identical in both editions (tested).147148| Quantity | Result |149|---|---|150| States compared (all rows of `tcppver.out` that are results) | 666, 33 satellites |151| **Largest position difference** | **4.12 mm** (4.12e-6 km; satellite 23333, e = 0.97, r = 241 000 km, t = 0) |152| Largest velocity difference | 1.85e-9 km/s |153| Test limits | 1e-5 km, 1e-8 km/s (the file prints 1e-8 km and 1e-9 km/s) |154155The 4 mm is 2e-11 of the radius: rounding of the epoch (the reference rebuilds it through calendar fields) and of156`pow`/trigonometric functions.157158Error cases of the set — each is a thrown `SGP4Error` at exactly the step after the last row of the expected159output, and no earlier step throws:160161| Satellite | First failing time (min) | Error |162|---|---|---|163| 22312 | 494.2028672 | 1, mean eccentricity out of range |164| 28350 | 1560 | 1, mean eccentricity out of range |165| 28872 | 55 | 6, decayed |166| 29141 | 440 | 6, decayed |167| 20413 (second run, 3.5 years from epoch) | 1 844 345 | 6, decayed |168| 33333 ("check error code 4") | 25 | 4, negative semi-latus rectum |169| 33334 (mean motion 1e-5 rev/day) | 0 | 3, perturbed eccentricity out of range |170171For 33334 the reference driver prints a t = 0 row although the propagation failed; the printed numbers are those172of the previous satellite's last row (stale buffer), which the test recognises.173174**End to end against JPL Horizons.** Horizons accepts a user-supplied TLE and returns geocentric ICRF vectors175(its own SGP4 and frame conversion). For the ISS element set of the fixtures, 97 states over two days:176largest difference **2.51 m** in position and 2.9 mm/s in velocity (test limits 50 m, 0.05 m/s). Without the177TEME → ICRF rotation the difference would be 45 km. This checks the UTC epoch, the propagator in `.improved` mode178and the frame route together.179180**Element sets.** The TLE, JSON, KVN and XML files of the same CelesTrak element set parse to the same elements181(1e-9 on angles and mean motion, 0.5 ms on the epoch) and propagate to the same position within 20 m at 12 hours182(epoch rounding of the TLE).183184## 3. Orbit toolkit185186- **Osculating elements** (`OsculatingOrbit`): the geometric state of any body about any centre from any provider,187 converted with `OrbitalElements(position:velocity:gm:epoch:)` of CosmosEphemeris (no duplicate of the Kepler188 code). The type states that these elements describe the motion *at `instant`*; it carries the status and the189 sources of the state. `gm` is supplied, or taken as GM(centre) + GM(body) from the planetary constants.190- **Two polyline types that cannot be confused:** `OsculatingConicPolyline` (points of the conic that osculates at191 one instant; ellipses uniform in eccentric anomaly, open orbits in true anomaly up to a maximum distance) and192 `TrajectoryPolyline` (the real path from the ephemeris between two instants). The latter is sampled by193 **curvature**: from 17 uniform samples, the segment whose midpoint lies farthest from its chord (the sag ∝194 curvature × length²) is split until every sag is below `tolerance` metres or `maxPoints` (default 2048) is195 reached; `reachedPointLimit` and `maximumChordError` report the outcome. Outside coverage it throws.196- `sphereOfInfluence` = a (m/M)^(2/5) (Laplace), `hillRadius` = a (1 − e) (m/3M)^(1/3), `synodicPeriod`.197- **Ground track**: `earthSubPoint` (geodetic latitude/height on WGS 84 through `EarthOrientation`, UT1 from198 `TimeSystem`) and `subPoint(of:on:)` for any body with an IAU orientation model and radii in the PCK199 (planetocentric, or planetodetic on the ellipsoid of the PCK radii). Geometric (no light-time); east longitudes.200- **Passes** (`SatellitePassPredictor`): rise, culmination and set from the roots of the geometric elevation201 (30 s coarse step, 0.01 s tolerance) and its maximum; azimuths, slant range; illumination at the three instants202 and penumbra entry/exit inside the pass; Sun altitude at culmination; `isOpticallyObservable` (sunlit and Sun203 more than 6° below the horizon — a necessary condition, not a brightness prediction).204 **Shadow model: conical** — the Earth is a sphere of radius 6378.137 km, the Sun a sphere of the IAU nominal205 radius; umbra when the Earth's disc covers the Sun's as seen from the satellite, penumbra when they overlap.206 No atmosphere, no flattening, no refraction, no terrain; only complete passes inside the interval are returned.207208Validation:209210| Check | Reference | Result |211|---|---|---|212| Osculating elements of the Mars and Jupiter barycentres about the Sun (3 epochs) | JPL Horizons `ELEMENTS`, ICRF plane, with Horizons' GM | e, q, angles, period to 1e-15 relative (the two agree to the last digit printed) |213| Osculating elements of the Moon about the Earth | same | Δe ≤ 1.0e-10, Δq/q ≤ 4.1e-11, angles ≤ 1.9e-9 rad (DE440 vs DE441 for the Moon) |214| Degenerate orbits | definition | circular equatorial, circular polar, retrograde equatorial, hyperbolic: state reproduced to 1e-5 m; rectilinear motion throws |215| Conic polyline | r = p/(1 + e cos ν), planarity | 1 mm |216| Conic vs trajectory, Moon, one revolution | — | same start point; **15 021 km apart** after one revolution: the osculating conic is not the trajectory |217| Adaptive sampling, Moon, one revolution | — | 257 points for a 50 km sag; 64-point budget with 1 m tolerance → limit reported |218| Synodic period Earth–Mars | interval between the 15 oppositions 2001–2031 found by the event finder | 779.96 d vs 779.77 d (0.02 %) |219| ISS ground track, three revolutions | — | maximum geodetic latitude within −0.6°/+0.23° of the inclination; successive ascending equator crossings 21–25° further west |220| Sub-solar point, two independent routes | `EarthOrientation` vs IAU model of the PCK | within 0.3° |221| Passes of the ISS over Montréal, 2 days | — | 14 passes; elevation at rise/set zero within 1e-5 rad; no sample above the culmination |222223## 4. Transfers224225- **Lambert**: D. Izzo, "Revisiting Lambert's problem", Celest. Mech. Dyn. Astron. 121 (2015) 1–15. Householder226 iterations on the Lancaster–Blanchard variable from Izzo's initial guesses, series form near the parabolic case,227 multi-revolution solutions (both branches) above the minimum time found by Halley iterations. Prograde/retrograde228 with respect to a reference normal. Collinear positions (0° or 180°) throw: the plane is undefined.229- **Hohmann / bi-elliptic**: closed-form coplanar circular analytics; `PlanetaryHohmann` applies them to the230 osculating semi-major axes of two real bodies and says so in `assumptions`.231- **Porkchop**: for each departure/arrival pair, the positions of the two bodies from the ephemeris, a zero-revolution232 prograde Lambert arc about the Sun (`Constants.gmSun`), `C3 = |v₁ − v_body1|²`, arrival `v∞ = |v₂ − v_body2|`,233 transfer angle (type I below 180°, type II above), right ascension and declination of the launch asymptote.234 Point-mass patched conics: no planetary gravity, no deep-space manoeuvre, no launch-site constraint.235- **Launch windows**: coarse grid over (departure, time of flight), local minima refined by a compass search to one236 hour; objectives C3, arrival v∞ or their sum.237- **Gravity assist**: e = 1 + r_p v∞²/μ, turn angle δ = 2 asin(1/e), heliocentric Δv = 2 v∞ sin(δ/2); outgoing238 excess velocity for a chosen flyby plane; `link` gives the periapsis an unpowered flyby needs between two legs239 and the excess-speed mismatch.240- **Burns and budgets**: escape from and capture into a parking orbit, plane change, `DeltaVBudget` with margin and241 Tsiolkovsky mass ratio.242243Validation:244245| Case | Reference (fetched) | Result |246|---|---|---|247| Vallado, *Fundamentals of Astrodynamics and Applications*, example 7-5 | values transcribed in the poliastro test suite (fixture) | \|Δv₁\| = 1.5e-5 km/s, \|Δv₂\| = 1.3e-5 km/s (published to 1e-6 km/s; the reference file itself accepts 1e-5 relative) |248| Curtis, *Orbital Mechanics for Engineering Students*, examples 5.2 and 5.3 (hyperbolic) | same file | 5.1e-5, 4.6e-5, 6.8e-5 km/s (published to 4–5 digits) |249| Multi-revolution Molniya case, 0 and 1 revolution, both branches | same file | ≤ 6.5e-7 km/s |250| 2004 random arcs, 0–2 revolutions, both directions, propagated with the two-body solver of CosmosEphemeris | closure | 2.1e-12 relative |251| **Earth → Mars 2026, type II minimum energy** | NASA/TM-2010-216764 (Burke, Falck & McGuire), table 2: 10/31/26 → 8/19/27, C3 = 9.144 km²/s², v∞ = 2.729 km/s, DLA 23.16°, RLA 130.7° | at the published dates: **C3 = 9.184, v∞ = 2.728 km/s, DLA 23.18°, RLA 130.6°**; refined minimum 2026-10-31 10:30 → 2027-08-19 17:15, C3 = 9.182 (+0.4 %). Test limits: 0.08 km²/s², 0.02 km/s, 1.5° |252| Earth → Mars 2026, type I row of the same table (11/14/26 → 8/9/27, 11.11, 2.915 km/s, DLA 28.28°) | same | at the published dates: C3 = 11.098, v∞ = 2.915, DLA 28.40° |253| Least C3 of the ten opportunities 2026–2045 | same report, table 1 | 9.182 (9.144), 8.995 (8.928), 8.170 (8.237), 7.705 (7.781), 10.262 (10.190, type I), 14.757 (14.840), 12.203 (12.170), 9.760 (9.818), 9.032 (8.969), 8.569 (8.587): **worst difference 0.083 km²/s²** (limit 0.15) |254255The report was produced with the MIDAS patched-conic optimiser and whole-day dates; differences of 0.5–1 % in C3256are the level at which its ephemeris, its Earth departure point and the date rounding differ from this model. For257the type I transfer of 2026 the unconstrained energy minimum of this model lies two days earlier258(2026-11-12 → 2027-08-11, C3 = 10.43): the report's single type I row is not that minimum, but its published259point is reproduced.260261## 5. Event finder262263`EventFinder.roots` / `extrema` sample a scalar function of time every `step` seconds, then refine each sign change264(or each sample lower/higher than both neighbours) with Brent's root finder (minimiser) of CosmosMath, in seconds265relative to the bracket so that the tolerance is absolute.266267- **Step**: chosen by each search from the fastest period that matters (table below) and adjustable. Two roots268 inside one step cancel and are not found; an extremum needs three samples around it.269- **Tolerance**: default 1 ms for roots (`timeTolerance` of every event). An extremum is flat: its abscissa is270 good to about √ε × the time scale of the variation whatever is requested; greatest elongations carry 1 s and a271 note. The tolerance bounds the solver only — agreement with almanacs is in the tables below.272- **Cancellation**: `Task.checkCancellation()` at every coarse sample and between events; a cancelled task throws273 `CancellationError` (tested: a 200-year eclipse search stops within the test's 3 s limit after cancellation).274- **Coverage**: the requested interval is clipped to the coverage of every object involved, 2 days inside each data275 edge (light-time and finite differences reach slightly outside). `EventSearchResult` returns `requested`,276 `searched` and `coverageLimits` (instant, side, reason naming the object and the provider); `isComplete` is false277 when anything was clipped. If a function throws `outOfCoverage` during a scan, the scan stops there with the278 events found so far. Nothing is extrapolated. An object unknown to the provider throws `unknownObject`.279- **Provenance**: every event carries `sources` (names of the data sets that produced the positions) and a280 `ScientificStatus`. With a `CompositeEphemeris` all links of all chains are listed and the weakest status wins,281 so a Keplerian satellite makes the event `.estimated`.282283| Search | Function | Coarse step | Corrections |284|---|---|---|---|285| `lunarPhases` | λ☾ − λ☉ = 0°, 90°, 180°, 270° | 1 d | apparent geocentric (LT+S), true ecliptic of date |286| `seasons` | λ☉ = 0°, 90°, 180°, 270°, true equinox of date | 5 d | apparent geocentric |287| `elongationEvents` | λ_body − λ☉ = 0°, ±90°, 180°; maxima of the elongation | 0.5 d | apparent geocentric |288| `conjunctions`, `minimumSeparations` | equal longitude or right ascension of date; minimum separation | 0.5 d | apparent, from the observer |289| `apsides`, `closeApproaches` | range rate r·v/r = 0 | 1/24 of the revolution suggested by the angular rate; 1 d | **geometric** (as Horizons' range rate) |290| `solarEclipses`, `lunarEclipses` | syzygies, then minimum axis distance on ±4 h | 1 d | apparent geocentric |291| `events` (mutual), `solarTransits` | separation − (r₁ ± r₂) | 10 min; 1 d + 5 min | apparent from the observer body |292| `shadowTransits` | distance of the receiver from the shadow axis − R | 10 min | Sun direction light-time corrected at the caster |293294"Apparent" is SPICE LT+S with a converged light time (`ApparentPosition.state(... iterations: 2)`): Newtonian295light-time and stellar aberration; no relativistic light deflection (≤ 0.004″ at the Sun's limb for a planet in296transit). Ecliptic and equator of date are IAU 2006 precession + IAU 2000B nutation (true obliquity, true equinox).297298### 5.1 Phases, seasons, planetary events, apsides299300Reference: JPL Horizons observer tables (DE441), geocentric apparent ecliptic longitude/latitude of date at 1 h301(Moon) or 6 h (Sun, planets) steps in TT, interpolated (4-point Lagrange) by the test; vector tables with range rate.302303| Event | Reference | Agreement |304|---|---|---|305| Lunar phases, Jan–Mar 2025 (11 events) | Horizons longitudes | worst **+0.009 s**, mean +0.004 s |306| Lunar phases, March 1900 and March 2100 (3 + 3) | same | +0.012 s, +0.015 s |307| Equinoxes and solstices 2025 (2025-03-20 09:01:29, 06-21 02:42:16, 09-22 18:19:20, 12-21 15:03:05 UTC) | Horizons Sun longitude = 0°, 90°, 180°, 270° | **−1.11 … −1.16 s** (see below) |308| Mars opposition 2025-01-16 02:38:35 UTC | Horizons (Mars 499; here barycentre 4) | −0.0 s |309| Jupiter opposition 2026-01-10 08:42:09 UTC | Horizons (599; here barycentre 5) | −0.2 s |310| Venus inferior conjunction 2025-03-23 01:07:30 UTC | Horizons | −0.07 s |311| Venus greatest eastern elongation 2025-01-10, 47.1687° | maximum of the separation built from the Horizons table | same angle to 1e-4°; instants 4 s apart (flat maximum) |312| Earth perihelion 2025-01-04 13:28:06 UTC (147 103 686.3 km), aphelion 2025-07-03 19:54:43 UTC (152 087 737.6 km) | zero of Horizons' range rate | 0.00 s, 0.0 m |313| Moon perigee 2025-01-08 00:01:05 UTC (370 170.692 km), apogee 2025-01-21 04:54:08 UTC (404 298.089 km) | same | 0.00 s, 0.0 m |314315Residuals explained:316- **Seasons, −1.1 s, constant.** Horizons states that its longitude is referred to the "IAU76/80 ecliptic-of-date";317 this module uses the IAU 2006/2000B equinox. The Sun moves 0.041″ per second, so −1.13 s is a 46 mas difference318 of the origin of longitudes. It is attributed to the difference between the two precession–nutation systems319 (constant over the year, absent from every difference of two longitudes: phases, oppositions and conjunctions320 agree to ≤ 0.2 s); the 46 mas were not derived independently.321- **Jupiter, −0.2 s**: the system barycentre (DE440s has no planet centre) versus the planet centre of Horizons.322- **Phases, 5–15 ms**: attributed to the Newtonian aberration used here versus Horizons' relativistic aberration323 and light deflection, and to DE440 versus DE441 for the Moon (a 5 mas change of the elongation is 10 ms).324- Almanacs print these events to the minute; USNO's API could not be reached on 2026-11-24 (connection reset), so325 the comparison is with Horizons only.326327### 5.2 Solar eclipses328329Method (Besselian geometry evaluated directly on vectors): apparent geocentric Sun and Moon; the shadow axis is the330line Sun → Moon; the fundamental plane passes through the geocentre perpendicular to it. **Greatest eclipse** is the331minimum of the axis-to-geocentre distance (Brent minimiser on ±4 h around the conjunction in longitude); **gamma**332is that distance in equatorial radii, signed by the projection of the true pole of date. The axis is intersected333with the WGS 84 ellipsoid (true pole of date); penumbral and umbral radii `L1`, `L2` are evaluated in the plane of334that ground point. Type: partial if only the penumbra reaches the Earth; total/annular by the sign of `L2` at the335ground point; **hybrid** when the sign of `L2` at either end of the central line (axis tangent to the ellipsoid,336found by root search) differs from the sign at greatest eclipse. **Magnitude**: `(L1 − L2)/(L1 + L2)` (ratio of the337apparent diameters) for central eclipses; `(L1 − m)/(L1 + L2)` (fraction of the solar diameter covered) for partial338eclipses and for the rare non-central annular/total eclipses — the catalogue's convention, found by comparison.339The greatest-eclipse point's geodetic coordinates, the Sun's altitude there and the central duration (local340circumstances at that point) are returned.341342Conventions (`EclipseConventions.espenakMeeus`, all adjustable): k = 0.2725076 (penumbra) and 0.272281 (umbra),343solar radius 959.63″ at 1 au (696 000 km), Earth radius 6378.137 km, Moon = centre of mass of the ephemeris (no344centre-of-figure offset), no lunar-limb profile, ΔT only for the longitude.345346**Validation: every solar eclipse from 1850 to 2150 in the NASA/GSFC Five Millennium Catalog** (Espenak & Meeus;347VSOP87/ELP-2000/82), i.e. the whole span of DE440s:348349| Quantity (catalogue resolution) | Result over 683 eclipses |350|---|---|351| Eclipses found / in the catalogue / matched | 683 / 683 / 683, no spurious one |352| Type (partial, annular, total, hybrid) | **0 mismatch** |353| Instant of greatest eclipse (1 s) | worst **−0.6 s** (1871 Jun 18), mean −0.06 s |354| Gamma (1e-4) | ≤ 0.00006 |355| Magnitude (1e-4) | ≤ 0.00010 |356| Latitude of greatest eclipse (1°) | ≤ 0.64° |357| Longitude × cos φ (1°), after moving this module's longitude to the catalogue's ΔT | ≤ 0.48° |358| Central duration, 438 central eclipses (1 s) | worst −0.7 s |359360Named eclipses (Δt of greatest eclipse; gamma and magnitude equal to the catalogue's four decimals in every case):3612017-08-21 total +0.24 s, duration 160.1 s (160); 2023-04-20 hybrid −0.06 s, 76.0 s (76); 2023-10-14 annular362−0.42 s, 317.0 s (317); 2024-04-08 total +0.41 s, 268.0 s (268); 2025-03-29 partial +0.03 s; 2026-08-12 total363−0.27 s, 138.2 s (138); 2027-08-02 total +0.15 s, 382.5 s (383). The sub-second residuals are DE440 versus364VSOP87/ELP-2000/82.365366**Local circumstances** (`localSolarEclipse`): topocentric Sun and Moon (geocentric apparent positions minus the367observer's geocentric position from `EarthOrientation.observerState`, site height included); contacts C1/C4 where368the separation equals the sum of the semi-diameters (penumbral k), C2/C3 where it equals their difference (umbral369k); maximum = greatest magnitude; obscuration = covered area of the solar disc (lens formula); geometric altitudes370of the Sun at C1, maximum and C4 (`isAboveHorizonAtSomePhase`). Contacts are geometric even below the horizon.371372Validation against the NASA path table of 2024 April 8 (central line every 2 min, coordinates to 0.1′, durations to3730.1 s, computed with ΔT = 70.6 s), with IERS UT1 − UTC (ΔT = 69.2 s) and the tabulated longitudes moved to that ΔT:374at 19 points of the central line the eclipse is total, **mid-totality is within 0.95 s of the tabulated instant and375the duration within 0.19 s**; the Sun's altitude within 1°. Example: Montréal (45.5019° N, 73.5674° W, 30 m):376total, C1 18:14:28.3, C2 19:26:50.4, C3 19:28:16.2, C4 20:36:52.2 UTC, totality 85.8 s.377378**ΔT.** Everything that depends on the Earth's rotation (longitudes, local circumstances, passes, ground tracks)379carries `timeValidity` (from `TimeSystem.validity`), `deltaT` and a note. Without an IERS table the status becomes380`.estimated` and the source `deltaTModel`; measured effect for 2024: ΔT 74.03 s instead of 69.20 s moves first381contact at New York by −1.94 s. Far from the present ΔT is uncertain by minutes to hours and dominates everything382else; global circumstances (instant in TT, gamma, magnitude, type, latitude) do not depend on it.383384### 5.3 Lunar eclipses385386Apparent geocentric Sun and Moon; the shadow axis is the anti-solar direction. **Greatest eclipse** is the minimum387of the *angular* distance between the Moon and the axis (minimising the linear distance instead shifts grazing388penumbral eclipses by up to 15 s — measured before the definition was fixed). Shadow radii at the Moon:389390| `shadowEnlargement` | Penumbra | Umbra |391|---|---|---|392| `.danjon` (default; the Canon's rule) | 1.01 π☾ + π☉ + s☉ | 1.01 π☾ + π☉ − s☉ |393| `.chauvenet` | 1.02 (0.998340 π☾ + π☉ + s☉) | 1.02 (0.998340 π☾ + π☉ − s☉) |394| `.none` | π☾ + π☉ + s☉ | π☾ + π☉ − s☉ |395396Magnitudes are `(radius + s☾ − σ)/(2 s☾)`; contacts P1, U1, U2, U3, U4, P4 by root search; gamma in equatorial397radii; k = 0.2725076. **Effect of the convention** (measured on the four eclipses below): Chauvenet's rule gives398penumbral magnitudes larger by 0.025–0.026 and umbral magnitudes larger by 0.0045–0.0055 than Danjon's; no399enlargement gives both smaller by 0.0183. The instant of greatest eclipse does not depend on it.400401**Validation: every lunar eclipse from 1850 to 2150 in the NASA/GSFC Five Millennium Catalog** (Danjon):402403| Quantity (catalogue resolution) | Result over 697 eclipses |404|---|---|405| Found / in the catalogue / matched; type (penumbral, partial, total) | 697 / 697 / 697; **0 mismatch** |406| Instant of greatest eclipse (1 s) | worst −3.1 s (2136 Apr 16), mean −0.05 s |407| Gamma (1e-4) | ≤ 0.00014 |408| Penumbral / umbral magnitude (1e-4) | ≤ 0.00035 / ≤ 0.00026 |409| Duration of the partial / total phase (0.1 min) | ≤ 4.3 s / ≤ 6.7 s |410| Duration of the penumbral phase (0.1 min) | ≤ 49.2 s |4114122025-03-14 total: +0.21 s, umbral 1.1784 (1.1784); 2025-09-07 total: −0.04 s, 1.3618 (1.3619); 2023-10-28413partial: −1.01 s, 0.1220 (0.1220); 2024-03-25 penumbral: +1.06 s, penumbral 0.9556 (0.9557). The zenith point of414the Moon at greatest eclipse agrees with the catalogue's integer degrees (after the ΔT shift) within 0.8°.415416Residuals: the minimum of the separation is flat (the Moon crosses the shadow at 0.5″/s; 0.1″ between DE440 and417ELP-2000/82 is already 0.2 s, and a grazing geometry stretches it to seconds). Penumbral durations of grazing418eclipses change by about a minute for 1e-4 of magnitude, hence the 49 s worst case.419420### 5.4 Transits of Mercury and Venus, mutual events421422`solarTransits` locates the minima of the Sun–planet separation (daily step), keeps those inside the sum of the423radii with the planet in front, and refines contacts I–IV and the least separation with `events`. Radii: the planet424from the PCK (Mercury 2440.53 km, Venus 6051.8 km), the Sun 959.63″ at 1 au by default.425426| Case | Reference | Agreement |427|---|---|---|428| Mercury 2019-11-11, Venus 2012-06-05/06: contacts I–IV | contacts derived by the test from Horizons' apparent RA/Dec and angular diameters (1-min tables), same radii (Sun 695 700 km) | **≤ 0.005 s** on all eight contacts; least separation 75.935″ and 554.370″, identical to 0.001″ |429| Venus 2012, geocentric contacts in UT | NASA/GSFC, Espenak, "The 2012 Transit of Venus", table 1 (22:09:38, 22:27:34, 01:29:36, 04:31:39, 04:49:35) | I +3.7 s, II −4.2 s, greatest +0.7 s, III +4.3 s, IV −3.6 s; least separation 554.4″ (554″) |430| Mercury, every transit 1999–2040 | NASA Seven Century Catalog (dates, least separation) | 7 found = 7 listed; all dates equal, least separations within 1″ |431432The ±4 s pattern on Venus (exterior contacts inside, interior contacts outside the published ones, greatest433unchanged) is the signature of a different planet radius: at the measured rate of 0.054″/s it corresponds to a434Venus radius larger by about 45 km in the published prediction (a cloud-top radius instead of the solid-surface4356051.8 km of the PCK). The page does not state the radii it used, so this explanation is an inference, not a436verified fact; the published times are also UT from a ΔT predicted before the event.437438**Generic mutual events** (`MutualEventFinder.events(of:across:from:)`): spheres at the apparent positions seen from439the centre of the observer body; exterior and interior contacts, least separation, kind `occultation` (the front440disc is larger), `transit` (the front disc is smaller) or `partial`; events in progress at an edge of the interval441have nil contacts and a note. `eclipses(of:by:)` is the occultation of the Sun by the caster seen from the body442(umbra = `occultation`, penumbra only = `partial`); `shadowTransits(of:on:)` times the passage of the shadow axis443over the receiver's disc. The last two are instants at the system: add the light time to an observer.444445**Galilean satellites.** With the core data they are two-body orbits around an estimated planet centre (see446CosmosEphemeris §6.4: Io drifts by about 2 000 km per day from its epoch, 2027-01-01). Their phenomena therefore447carry `status == .estimated`, list `kepler-osculating(…)` among the sources and a note that the times are448indicative; this is tested (4 days at the epoch: 2 transits, 3 occultations, 3 eclipses, 2 shadow transits of Io;449durations and the revolution period consistent with the orbit). No reference comparison is claimed for them. With450a satellite SPK kernel added to the provider the same calls return `.computed` events.451452## 6. Benchmarks453454`cosmos-bench astro.sgp4 | astro.phases | astro.eclipses | astro.lambert` — release build, one thread, Apple M5 Max.455The machine was shared with other builds (1-minute load average 10.8 and 13–15 during the two runs).456457| Benchmark | Run 1 (load 10.8) | Run 2 (load 13–15) |458|---|---|---|459| SGP4 near-Earth, propagations/s | 8.10 M | 7.53 M |460| SDP4 geostationary (1:1 resonance) | 4.56 M | 3.85 M |461| SDP4 Molniya (2:1 resonance) | 2.98 M | 2.54 M |462| `SGP4Ephemeris.state` (TEME → ICRF, IAU 2006/2000B), states/s | 0.66–0.71 M | 0.55–0.61 M |463| Lunar phases of 2025: 49 events | 10.3 ms = 4 780 events/s | 12.0 ms = 4 100 events/s |464| Equinoxes and solstices 2001–2100: 400 events | 131 ms | 146 ms |465| **Solar eclipses 2001–2100**: 224 found (with central durations) | **0.64 s** | 0.71 s |466| **Lunar eclipses 2001–2100**: 228 found (with all contacts) | **0.31 s** | 0.35 s |467| Lambert (Izzo), zero revolutions, solutions/s | 6.54 M | 5.92 M |468| Porkchop Earth → Mars 2026, 1-day grid, 33 565 cells | 7.9 ms | 8.7 ms |469470The provider is ten times slower than the bare propagator because each state evaluates the precession–nutation471matrix (77-term nutation); a caller that needs many states of many satellites at one instant should compute472`TEMEFrame.temeToICRF(at:)` once and use `temeState(at:)`.473474## 7. Data pipeline and fixtures475476`DataPipeline/astrodynamics/fetch_validation.py` (Python 3 standard library; `pdftotext` for one report) downloads477every fixture: sequential requests, one-second pause, generic User-Agent, no personal data, raw archives cached in478`DataPipeline/raw/astrodynamics/` (git-ignored), `index.json` with URL, date, size and SHA-256 of each file.479Sources: celestrak.org (and the Internet Archive copy of its 2012 archive for `tcppver.out`), eclipse.gsfc.nasa.gov,480ssd.jpl.nasa.gov (Horizons API), ntrs.nasa.gov, datacenter.iers.org, raw.githubusercontent.com (poliastro tests,481MIT). Fixtures total 2.7 MB. The module ships **no production data**: `Sources/Resources` holds only its README;482element sets are supplied by the application at run time.483484## 8. Limitations and what is not modelled485486SGP4487- Accuracy is that of the theory and of the element set (kilometres, growing with age); the quality grades and the488 error estimate are documented heuristics, not covariances. No SGP4-XP, no orbit determination or element fitting,489 no manoeuvre detection.490- TEME → ICRF uses IAU 2006/2000B in place of the 1976/1980 theory (metre level). `.improved` mode is the default;491 use `.afspc` to reproduce the operational code exactly.492- Element-set epochs before 1957 or after 2056 cannot be expressed in a TLE; OMM has no such limit.493494Orbit toolkit and passes495- Osculating elements are instantaneous; the toolkit never propagates them as if they were a trajectory.496- Passes: geometric elevation (no refraction — near the horizon refraction lengthens a pass by a few seconds), no497 light-time, no terrain, complete passes only, 30 s coarse step (a pass shorter than the step can be missed).498 Conical shadow of a spherical Earth without atmosphere. Without an IERS table UT1 comes from the ΔT model.499- Sub-points are geometric (no light-time); longitudes on bodies other than the Earth follow the IAU model of the PCK.500501Transfers502- Lambert arcs are two-body; porkchop data are point-mass patched conics with zero revolutions, prograde only.503 No low-thrust, no deep-space manoeuvres, no multi-flyby optimisation, no B-plane targeting, no launch-vehicle504 or launch-site constraints. `launchWindows` returns local minima of a sampled function: a minimum narrower than505 the coarse step, or on the edge of the domain, is not reported.506- `PlanetaryHohmann` idealises the two orbits as coplanar circles.507508Events509- An event is found only if the coarse step resolves it (see the table of §5); the solver tolerance is not an510 accuracy claim. Greatest elongations and appulses are flat extrema (seconds to a minute).511- Light deflection, relativistic aberration terms and the Moon's centre-of-figure offset are not applied512 (≤ 0.004″, ≤ 5e-4″, ≈ 0.5″ respectively; the last moves eclipse contacts by about a second in almanacs that513 apply it).514- Solar eclipses: no lunar-limb profile (Baily's beads; contact times change by 1–3 s), no path limits, path width515 or Besselian-element output, no atmospheric refraction; the hybrid test examines the two ends of the central516 line. Lunar eclipses: circular shadow with a conventional enlargement (no oblate-shadow model such as517 Herald–Sinnott), no brightness (Danjon scale) prediction.518- Mutual events: spherical bodies (Jupiter's flattening of 6.5 % is ignored), centre of the observer body, shadow519 transits time the axis only (no umbra/penumbra extent on the disc). Satellite phenomena are only as good as the520 satellite ephemeris — `.estimated` with the core data.521- Outer planets are system barycentres in DE440s; events of `naif:499` … `naif:999` need the composite provider and522 are then `.estimated` (the offset of the planet from its barycentre is a Keplerian estimate).523- Coverage is that of the ephemeris (1849-12-26 – 2150-01-22 for DE440s, minus 2 days at each end).524525Not implemented in this module: rise/set and twilight of celestial bodies (CosmosObservation), satellite526brightness, conjunction (collision) screening between satellites, numerical orbit propagation with perturbations527(CosmosLaboratory owns the integrators).528529## 9. References530531- D. A. Vallado, P. Crawford, R. Hujsak, T. S. Kelso, "Revisiting Spacetrack Report #3", AIAA 2006-6753, AIAA/AAS532 Astrodynamics Specialist Conference, 2006; code and verification data: https://celestrak.org/publications/AIAA/2006-6753/533- F. R. Hoots, R. L. Roehrich, *Spacetrack Report No. 3: Models for Propagation of NORAD Element Sets*, 1980.534- CCSDS 502.0-B-3, *Orbit Data Messages* (OMM); CelesTrak, "A New Way to Obtain GP Data" (alpha-5 numbering).535- D. Izzo, "Revisiting Lambert's problem", Celestial Mechanics and Dynamical Astronomy 121 (2015) 1–15.536- D. A. Vallado, *Fundamentals of Astrodynamics and Applications*, 4th ed., 2013 (example 7-5; TEME, appendix C of the 2006 paper).537- H. D. Curtis, *Orbital Mechanics for Engineering Students*, 3rd ed., 2014 (examples 5.2, 5.3; Hohmann, bi-elliptic, flybys).538- L. M. Burke, R. D. Falck, M. L. McGuire, *Interplanetary Mission Design Handbook: Earth-to-Mars Mission539 Opportunities 2026 to 2045*, NASA/TM-2010-216764, 2010.540- F. Espenak, J. Meeus, *Five Millennium Canon of Solar Eclipses: −1999 to +3000*, NASA/TP-2006-214141, 2006;541 *Five Millennium Canon of Lunar Eclipses: −1999 to +3000*, NASA/TP-2009-214172, 2009; catalogues and transit542 pages at https://eclipse.gsfc.nasa.gov/ ("Eclipse Predictions by Fred Espenak, NASA's GSFC").543- *Explanatory Supplement to the Astronomical Almanac*, 3rd ed., 2013, chapter 11 (eclipses; Besselian elements,544 shadow enlargement); J. Meeus, *Elements of Solar Eclipses 1951–2200*, 1989 (magnitude formulas).545- R. P. Brent, *Algorithms for Minimization without Derivatives*, 1973 (through CosmosMath).546- JPL Horizons system, https://ssd.jpl.nasa.gov/horizons/ (reference tables; DE441). R. S. Park et al., "The JPL547 Planetary and Lunar Ephemerides DE440 and DE441", AJ 161 (2021) 105.548549## 10. Notes for the lead550551- No change is needed in `Package.swift` or `CosmosCore`.552- `Benchmarks/Sources/main.swift`: one-token edit, `registry` now ends with `+ astrodynamicsBenchmarks`.553- `DATA_SOURCES.md` should list the fixture sources above if test fixtures are tracked there; the module bundles no554 data file.555- An IERS `finals2000A` table (optional in CosmosTime) is what turns local eclipse circumstances from `.estimated`556 (ΔT model, seconds off) into `.computed`, and removes the same error from satellite passes and ground tracks.557- `SGP4.swift` follows the reference code published with AIAA 2006-6753 routine by routine. The archive contains no558 licence file and the sources carry no licence text (checked); the terms of reuse were not established here and559 are for the lead to confirm. If the project keeps third-party notices, the paper should be credited there.560- While this module was written, `swift test` on the real manifest was blocked for a time by a compile error in561 another module (CosmosExport); a throwaway manifest under `/tmp` symlinking the package directories was used562 meanwhile. The final runs reported here (55 tests, benchmarks) are on the real manifest.563