Skip to main content

khagole_engine/
planets.rs

1//! Planetary positions (`SkyfieldEngine.calculate_planets`): apparent geocentric
2//! longitudes of date from the JPL kernels, the mean lunar nodes, Chiron and Black Moon
3//! Lilith.
4
5use crate::chiron::chiron;
6use crate::ephemeris::observe::{apparent, ecliptic_latlon, observe};
7use crate::ephemeris::{Kernel, KernelSet};
8use crate::error::EngineError;
9use crate::frames::Orientation;
10use crate::pyfloat;
11use crate::time::Time;
12
13/// Position and kinematic state of a celestial body or astrological point.
14#[derive(Debug, Clone, PartialEq)]
15pub struct BodyPosition {
16    /// Common name of the body (e.g. "Sun", "Moon", "Mars").
17    pub name: &'static str,
18    /// Astronomical or astrological glyph symbol (e.g. "☉", "☽").
19    pub symbol: &'static str,
20    /// Degrees, tropical or sidereal as requested.
21    pub longitude: f64,
22    /// Ecliptic latitude in degrees.
23    pub latitude: f64,
24    /// Distance from Earth center in astronomical units (au).
25    pub distance: f64,
26    /// Daily apparent motion speed in degrees per day.
27    pub speed: f64,
28    /// Whether the body is currently in retrograde motion.
29    pub is_retrograde: bool,
30}
31
32/// (name, NAIF code, symbol, can be retrograde)
33const TARGETS: [(&str, i32, &str, bool); 10] = [
34    ("Sun", 10, "☉", false),
35    ("Moon", 301, "☽", false),
36    ("Mercury", 199, "☿", true),
37    ("Venus", 299, "♀", true),
38    ("Mars", 4, "♂", true),
39    ("Jupiter", 5, "♃", true),
40    ("Saturn", 6, "♄", true),
41    ("Uranus", 7, "♅", true),
42    ("Neptune", 8, "♆", true),
43    ("Pluto", 9, "♇", true),
44];
45
46/// The kernel covering `jd`, raising when none does (`SkyfieldEngine._require_eph`).
47pub fn require_kernel(kernels: &KernelSet, jd: f64) -> Result<&Kernel, EngineError> {
48    kernels.for_jd(jd).ok_or(EngineError::OutOfRange {
49        jd,
50        coverage: kernels.coverage(),
51    })
52}
53
54/// A collection of computed celestial body positions.
55pub struct Planets {
56    /// Bodies that could not be computed (e.g. Chiron outside its table) are left out.
57    pub bodies: Vec<BodyPosition>,
58}
59
60/// All chart bodies at UT1 Julian date `jd`, shifted by `shift` degrees (the ayanamsa for
61/// sidereal charts, 0 for tropical), with the Greenwich apparent sidereal time (hours)
62/// at `jd`.
63pub fn planets_and_sidereal_time(
64    kernels: &KernelSet,
65    jd: f64,
66    shift: f64,
67) -> Result<(Planets, f64), EngineError> {
68    planets_and_sidereal_time_with_mode(kernels, jd, shift, false)
69}
70
71/// All chart bodies at UT1 Julian date `jd`, shifted by `shift` degrees (the ayanamsa for
72/// sidereal charts, 0 for tropical), with the Greenwich apparent sidereal time (hours)
73/// at `jd`. If `geometric` is true, positions are true geometric coordinates without light-time
74/// or aberration.
75pub fn planets_and_sidereal_time_with_mode(
76    kernels: &KernelSet,
77    jd: f64,
78    shift: f64,
79    geometric: bool,
80) -> Result<(Planets, f64), EngineError> {
81    planets_and_sidereal_time_with_options(kernels, jd, shift, geometric, false)
82}
83
84/// All chart bodies at UT1 Julian date `jd`, shifted by `shift` degrees (the ayanamsa for
85/// sidereal charts, 0 for tropical), with the Greenwich apparent sidereal time (hours)
86/// at `jd`.
87/// - `geometric`: true geometric coordinates without light-time or aberration.
88/// - `true_node`: true osculating lunar node (from instantaneous DE440 state vectors) instead of mean node.
89pub fn planets_and_sidereal_time_with_options(
90    kernels: &KernelSet,
91    jd: f64,
92    shift: f64,
93    geometric: bool,
94    true_node: bool,
95) -> Result<(Planets, f64), EngineError> {
96    let sample = SpeedSample::at(kernels, jd, geometric)?;
97    let mut bodies = Vec::with_capacity(14);
98
99    for (name, code, symbol, can_retrograde) in TARGETS {
100        let Ok((lat, lon, dist, speed)) = sample.observe(code) else {
101            continue;
102        };
103        bodies.push(BodyPosition {
104            name,
105            symbol,
106            longitude: pyfloat::rem(lon - shift, 360.0),
107            latitude: lat,
108            distance: dist,
109            speed,
110            is_retrograde: can_retrograde && speed < 0.0,
111        });
112    }
113
114    // Mean lunar ascending node (IAU polynomial).
115    let t_cent = (jd - 2_451_545.0) / 36525.0;
116    let omega = pyfloat::rem(
117        125.0445479 - 1934.1362891 * t_cent
118            + 0.0020754 * t_cent.powf(2.0)
119            + t_cent.powf(3.0) / 467440.0
120            - t_cent.powf(4.0) / 60616000.0,
121        360.0,
122    );
123
124    if true_node {
125        if let Ok((lon, speed, is_retrograde)) = sample.true_lunar_node() {
126            let node_lon = pyfloat::rem(lon - shift, 360.0);
127            for (name, symbol, longitude) in [
128                ("North Node", "☊", node_lon),
129                ("South Node", "☋", pyfloat::rem(node_lon + 180.0, 360.0)),
130            ] {
131                bodies.push(BodyPosition {
132                    name,
133                    symbol,
134                    longitude,
135                    latitude: 0.0,
136                    distance: 0.00257,
137                    speed,
138                    is_retrograde,
139                });
140            }
141        }
142    } else {
143        let mean_node = pyfloat::rem(omega - shift, 360.0);
144        for (name, symbol, longitude) in [
145            ("North Node", "☊", mean_node),
146            ("South Node", "☋", pyfloat::rem(mean_node + 180.0, 360.0)),
147        ] {
148            bodies.push(BodyPosition {
149                name,
150                symbol,
151                longitude,
152                latitude: 0.0,
153                distance: 0.00257,
154                speed: -0.05295,
155                is_retrograde: true,
156            });
157        }
158    }
159
160    if let Some(c) = chiron(jd, shift) {
161        bodies.push(BodyPosition {
162            name: "Chiron",
163            symbol: "⚷",
164            longitude: c.longitude,
165            latitude: 0.0,
166            distance: 0.0,
167            speed: c.speed,
168            is_retrograde: c.is_retrograde,
169        });
170    }
171
172    // Black Moon Lilith: mean lunar apogee projected from the lunar orbit onto the ecliptic.
173    let perigee = pyfloat::rem(
174        83.3532465 + 4069.0137287 * t_cent
175            - 0.01032 * t_cent.powf(2.0)
176            - t_cent.powf(3.0) / 80053.0,
177        360.0,
178    );
179    let apogee = pyfloat::rem(perigee + 180.0, 360.0);
180    let u = pyfloat::rem(apogee - omega, 360.0).to_radians();
181    let inc = 5.1453964_f64.to_radians();
182    let proj_u = (u.sin() * inc.cos()).atan2(u.cos());
183    bodies.push(BodyPosition {
184        name: "Lilith",
185        symbol: "⚸",
186        longitude: pyfloat::rem(proj_u.to_degrees() + omega - shift, 360.0),
187        latitude: 0.0,
188        distance: 0.0027,
189        speed: 0.1114,
190        is_retrograde: false,
191    });
192
193    Ok((Planets { bodies }, sample.orientation.gast_hours))
194}
195
196/// The apparent speed (degrees per day) of the planet `name` at UT1 Julian date `jd`,
197/// exactly as [`planets_and_sidereal_time`] gives it, without computing the other bodies.
198pub fn planet_speed(kernels: &KernelSet, jd: f64, name: &str) -> Result<f64, EngineError> {
199    let (.., code, _, _) = TARGETS
200        .iter()
201        .find(|(n, ..)| *n == name)
202        .ok_or_else(|| EngineError::InvalidInput(format!("not a planet: {name}")))?;
203    Ok(SpeedSample::at(kernels, jd, false)?.observe(*code)?.3)
204}
205
206/// An instant and the instant an hour later (for the speed and the retrograde
207/// flag), with the kernel and the orientations of both.
208struct SpeedSample<'k> {
209    kernel: &'k Kernel,
210    t: Time,
211    t_plus: Time,
212    orientation: Orientation,
213    orientation_plus: Orientation,
214    is_geometric: bool,
215}
216
217impl<'k> SpeedSample<'k> {
218    fn at(kernels: &'k KernelSet, jd: f64, is_geometric: bool) -> Result<Self, EngineError> {
219        let t = Time::from_ut1(jd);
220        let t_plus = Time::from_ut1(t.ut1() + 1.0 / 24.0);
221
222        // Both ends of the speed sample must be covered by the same kernel.
223        let mut kernel = require_kernel(kernels, jd)?;
224        let plus_kernel = kernels.for_jd(t_plus.ut1());
225        if !plus_kernel.is_some_and(|k| std::ptr::eq(k, kernel)) {
226            kernel = require_kernel(kernels, t_plus.ut1())?;
227        }
228        Ok(SpeedSample {
229            kernel,
230            orientation: Orientation::at(&t),
231            orientation_plus: Orientation::at(&t_plus),
232            t,
233            t_plus,
234            is_geometric,
235        })
236    }
237
238    /// Ecliptic latitude, longitude (degrees, tropical), distance (au) and speed
239    /// in longitude (degrees per day) of the body with NAIF code `code`.
240    fn observe(&self, code: i32) -> Result<(f64, f64, f64, f64), EngineError> {
241        let (kernel, t, t_plus) = (self.kernel, &self.t, &self.t_plus);
242        if self.is_geometric {
243            let (pos, _) = kernel.barycentric(code, t)?;
244            let (earth_pos, _) = kernel.barycentric(crate::ephemeris::observe::EARTH, t)?;
245            let geom = [pos[0] - earth_pos[0], pos[1] - earth_pos[1], pos[2] - earth_pos[2]];
246            let (lat, lon, dist) = ecliptic_latlon(&self.orientation, &geom);
247
248            let (pos_plus, _) = kernel.barycentric(code, t_plus)?;
249            let (earth_pos_plus, _) = kernel.barycentric(crate::ephemeris::observe::EARTH, t_plus)?;
250            let geom_plus = [
251                pos_plus[0] - earth_pos_plus[0],
252                pos_plus[1] - earth_pos_plus[1],
253                pos_plus[2] - earth_pos_plus[2],
254            ];
255            let lon_plus = ecliptic_latlon(&self.orientation_plus, &geom_plus).1;
256            let d_lon = pyfloat::wrap180(lon_plus - lon);
257            Ok((lat, lon, dist, d_lon * 24.0))
258        } else {
259            let a = observe(kernel, code, t)?;
260            let app = apparent(kernel, &a, t)?;
261            let a_plus = observe(kernel, code, t_plus)?;
262            let app_plus = apparent(kernel, &a_plus, t_plus)?;
263            let (lat, lon, dist) = ecliptic_latlon(&self.orientation, &app);
264            let lon_plus = ecliptic_latlon(&self.orientation_plus, &app_plus).1;
265            let d_lon = pyfloat::wrap180(lon_plus - lon);
266            Ok((lat, lon, dist, d_lon * 24.0))
267        }
268    }
269
270    /// Osculating (true) lunar node: intersection of the instantaneous osculating lunar
271    /// orbit plane with the true ecliptic of date. Returns (longitude_deg_tropical, speed_deg_day, is_retrograde).
272    fn true_lunar_node(&self) -> Result<(f64, f64, bool), EngineError> {
273        let compute = |t: &Time, ori: &Orientation| -> Result<f64, EngineError> {
274            let (pos_moon, vel_moon) = self.kernel.barycentric(301, t)?;
275            let (pos_earth, vel_earth) = self.kernel.barycentric(crate::ephemeris::observe::EARTH, t)?;
276            let r = [pos_moon[0] - pos_earth[0], pos_moon[1] - pos_earth[1], pos_moon[2] - pos_earth[2]];
277            let v = [vel_moon[0] - vel_earth[0], vel_moon[1] - vel_earth[1], vel_moon[2] - vel_earth[2]];
278            let r_ecl = crate::frames::mxv(&ori.ecliptic, &r);
279            let v_ecl = crate::frames::mxv(&ori.ecliptic, &v);
280            let h_x = r_ecl[1] * v_ecl[2] - r_ecl[2] * v_ecl[1];
281            let h_y = r_ecl[2] * v_ecl[0] - r_ecl[0] * v_ecl[2];
282            Ok(h_x.atan2(-h_y).to_degrees().rem_euclid(360.0))
283        };
284        let lon = compute(&self.t, &self.orientation)?;
285        let lon_plus = compute(&self.t_plus, &self.orientation_plus)?;
286        let d_lon = pyfloat::wrap180(lon_plus - lon);
287        let speed = d_lon * 24.0;
288        let is_retrograde = speed < 0.0;
289        Ok((lon, speed, is_retrograde))
290    }
291}
292