Skip to main content

khagole_engine/
aspects.rs

1//! Aspects, orbs and cross-aspects (`charts/calc/aspects.py`).
2
3use serde::Serialize;
4use serde_json::{json, Map, Value};
5
6use crate::error::EngineError;
7use crate::pyfloat;
8
9#[derive(Debug, Clone, Copy, PartialEq)]
10pub struct AspectRule {
11    pub name: &'static str,
12    pub angle: f64,
13    pub symbol: &'static str,
14    pub orb: f64,
15    pub is_major: bool,
16}
17
18pub const ASPECT_RULES: [AspectRule; 7] = [
19    AspectRule {
20        name: "Conjunction",
21        angle: 0.0,
22        symbol: "☌",
23        orb: 8.0,
24        is_major: true,
25    },
26    AspectRule {
27        name: "Sextile",
28        angle: 60.0,
29        symbol: "⚹",
30        orb: 6.0,
31        is_major: true,
32    },
33    AspectRule {
34        name: "Square",
35        angle: 90.0,
36        symbol: "□",
37        orb: 7.0,
38        is_major: true,
39    },
40    AspectRule {
41        name: "Trine",
42        angle: 120.0,
43        symbol: "△",
44        orb: 8.0,
45        is_major: true,
46    },
47    AspectRule {
48        name: "Opposition",
49        angle: 180.0,
50        symbol: "☍",
51        orb: 8.0,
52        is_major: true,
53    },
54    AspectRule {
55        name: "Semi-Sextile",
56        angle: 30.0,
57        symbol: "⚺",
58        orb: 2.5,
59        is_major: false,
60    },
61    AspectRule {
62        name: "Quincunx",
63        angle: 150.0,
64        symbol: "⚻",
65        orb: 3.0,
66        is_major: false,
67    },
68];
69
70const ASPECT_WEIGHT_FACTORS: [(&str, f64); 7] = [
71    ("Conjunction", 1.0),
72    ("Opposition", 1.0),
73    ("Trine", 1.0),
74    ("Square", 0.875),
75    ("Sextile", 0.75),
76    ("Semi-Sextile", 0.35),
77    ("Quincunx", 0.4),
78];
79
80/// `DEFAULT_ORB_SETTINGS`, in the reference's key order.
81pub fn default_orb_settings() -> Map<String, Value> {
82    let value = json!({
83        "method": "moiety_hybrid",
84        "include_minor_aspects": false,
85        "include_chiron": false,
86        "include_lilith": false,
87        "aspect_orbs": {
88            "Conjunction": 8.0,
89            "Sextile": 6.0,
90            "Square": 7.0,
91            "Trine": 8.0,
92            "Opposition": 8.0,
93            "Semi-Sextile": 2.5,
94            "Quincunx": 3.0,
95        },
96        "planet_orbs": {
97            "Sun": 15.0,
98            "Moon": 12.0,
99            "Mercury": 7.0,
100            "Venus": 7.0,
101            "Mars": 8.0,
102            "Jupiter": 9.0,
103            "Saturn": 9.0,
104            "Uranus": 5.0,
105            "Neptune": 5.0,
106            "Pluto": 5.0,
107            "North Node": 5.0,
108            "South Node": 5.0,
109            "Chiron": 5.0,
110            "Lilith": 5.0,
111            "Ascendant": 5.0,
112            "Midheaven": 5.0,
113        },
114        "fixed_star_orb": 1.5,
115    });
116    match value {
117        Value::Object(map) => map,
118        _ => unreachable!(),
119    }
120}
121
122/// Python `float(value)` for JSON values: numbers, numeric strings and booleans.
123pub fn py_float(value: &Value) -> Result<f64, EngineError> {
124    match value {
125        Value::Number(n) => n
126            .as_f64()
127            .ok_or_else(|| EngineError::InvalidInput(format!("not a number: {n}"))),
128        Value::Bool(b) => Ok(f64::from(u8::from(*b))),
129        Value::String(s) => {
130            let t = s.trim().to_ascii_lowercase().replace('_', "");
131            match t.as_str() {
132                "inf" | "+inf" | "infinity" | "+infinity" => Ok(f64::INFINITY),
133                "-inf" | "-infinity" => Ok(f64::NEG_INFINITY),
134                "nan" | "+nan" | "-nan" => Ok(f64::NAN),
135                _ => t
136                    .parse()
137                    .map_err(|_| EngineError::InvalidInput(format!("not a number: {s:?}"))),
138            }
139        }
140        other => Err(EngineError::InvalidInput(format!("not a number: {other}"))),
141    }
142}
143
144/// `value`, or an error naming `what` when it is NaN or infinite.
145pub(crate) fn finite(value: f64, what: &str) -> Result<f64, EngineError> {
146    if value.is_finite() {
147        Ok(value)
148    } else {
149        Err(EngineError::InvalidInput(format!(
150            "{what} must be finite, got {value}"
151        )))
152    }
153}
154
155/// Orb settings merged over the defaults, as the orchestrator and cross-aspects do:
156/// only `method`, `fixed_star_orb`, `aspect_orbs` and `planet_orbs` are taken from the
157/// caller, the orb tables key by key. Values are kept as given (they are echoed back in
158/// the chart) and read with Python `float()` semantics when used.
159#[derive(Debug, Clone, PartialEq)]
160pub struct OrbSettings(Map<String, Value>);
161
162impl Default for OrbSettings {
163    fn default() -> Self {
164        OrbSettings(default_orb_settings())
165    }
166}
167
168impl OrbSettings {
169    pub fn merge(custom: Option<&Value>) -> Result<Self, EngineError> {
170        let mut merged = default_orb_settings();
171        // `if orb_settings and isinstance(orb_settings, dict)`: an empty dict keeps defaults.
172        let Some(Value::Object(custom)) = custom else {
173            return Ok(OrbSettings(merged));
174        };
175        if custom.is_empty() {
176            return Ok(OrbSettings(merged));
177        }
178        if let Some(method) = custom.get("method") {
179            merged.insert("method".into(), method.clone());
180        }
181        let star_orb = match custom.get("fixed_star_orb") {
182            Some(v) => finite(py_float(v)?, "fixed_star_orb")?,
183            None => 1.5,
184        };
185        merged.insert("fixed_star_orb".into(), json!(star_orb));
186        for key in ["aspect_orbs", "planet_orbs"] {
187            let table = merged.get_mut(key).and_then(Value::as_object_mut).unwrap();
188            match custom.get(key) {
189                None => {}
190                Some(Value::Object(given)) => {
191                    for (k, v) in given {
192                        // Non-numeric values fail when used, as in the reference; NaN
193                        // and infinite orbs would silently drop or match every aspect.
194                        if let Ok(orb) = py_float(v) {
195                            finite(orb, &format!("{key}.{k}"))?;
196                        }
197                        table.insert(k.clone(), v.clone());
198                    }
199                }
200                Some(other) => {
201                    return Err(EngineError::InvalidInput(format!(
202                        "{key} must be an object, got {other}"
203                    )))
204                }
205            }
206        }
207        Ok(OrbSettings(merged))
208    }
209
210    #[cfg(test)]
211    pub fn as_map(&self) -> &Map<String, Value> {
212        &self.0
213    }
214
215    pub fn to_value(&self) -> Value {
216        Value::Object(self.0.clone())
217    }
218
219    fn table(&self, key: &str) -> Option<&Map<String, Value>> {
220        self.0.get(key).and_then(Value::as_object)
221    }
222
223    fn lookup(&self, table: &str, name: &str, default: f64) -> Result<f64, EngineError> {
224        match self.table(table).and_then(|t| t.get(name)) {
225            Some(v) => py_float(v),
226            None => Ok(default),
227        }
228    }
229
230    pub fn fixed_star_orb(&self) -> Result<f64, EngineError> {
231        match self.0.get("fixed_star_orb") {
232            Some(v) => py_float(v),
233            None => Ok(1.5),
234        }
235    }
236
237    /// `get_effective_max_orb` for two bodies and an aspect.
238    pub fn max_orb(&self, body1: &str, body2: &str, aspect: &str) -> Result<f64, EngineError> {
239        let method = self.0.get("method").and_then(Value::as_str).unwrap_or("");
240        let default_aspect_orb = self.lookup("aspect_orbs", aspect, 8.0)?;
241        match method {
242            "moiety_traditional" | "moiety_aspect_weighted" | "moiety_hybrid" => {
243                let moiety = (self.lookup("planet_orbs", body1, 5.0)?
244                    + self.lookup("planet_orbs", body2, 5.0)?)
245                    / 2.0;
246                Ok(match method {
247                    "moiety_aspect_weighted" => {
248                        let conj = self.lookup("aspect_orbs", "Conjunction", 8.0)?;
249                        let has_aspect = self
250                            .table("aspect_orbs")
251                            .is_some_and(|t| t.contains_key(aspect));
252                        let weight = if conj > 0.0 && has_aspect {
253                            self.lookup("aspect_orbs", aspect, 8.0)? / conj
254                        } else {
255                            ASPECT_WEIGHT_FACTORS
256                                .iter()
257                                .find(|(name, _)| *name == aspect)
258                                .map_or(1.0, |(_, w)| *w)
259                        };
260                        pyfloat::round(moiety * weight, 2)
261                    }
262                    "moiety_hybrid" => {
263                        let capped = if default_aspect_orb < moiety {
264                            default_aspect_orb
265                        } else {
266                            moiety
267                        };
268                        pyfloat::round(capped, 2)
269                    }
270                    _ => pyfloat::round(moiety, 2),
271                })
272            }
273            _ => Ok(default_aspect_orb),
274        }
275    }
276}
277
278/// An aspect between two chart points. Fixed-star conjunctions carry no `is_major`.
279#[derive(Debug, Clone, PartialEq, Serialize)]
280pub struct Aspect {
281    /// First point.
282    pub body1: String,
283    /// Second point.
284    pub body2: String,
285    /// Aspect name, e.g. "Trine".
286    pub aspect_type: &'static str,
287    /// Aspect glyph, e.g. "△".
288    pub symbol: &'static str,
289    /// Exact angle of the aspect, in degrees.
290    pub angle: f64,
291    /// Distance from exactness, in degrees (rounded to 0.01).
292    pub orb: f64,
293    /// Largest orb allowed for this pair and aspect, in degrees.
294    pub max_orb: f64,
295    /// Whether it is a major (Ptolemaic) aspect.
296    #[serde(skip_serializing_if = "Option::is_none")]
297    pub is_major: Option<bool>,
298    /// Always `true`, as in the reference implementation.
299    pub is_applying: bool,
300}
301
302/// A cross-aspect between an overlay body (transit, partner) and a base body (natal).
303#[derive(Debug, Clone, PartialEq, Serialize)]
304pub struct CrossAspect {
305    /// Overlay point (transit, partner).
306    pub body1: String,
307    /// Always "overlay".
308    pub body1_source: &'static str,
309    /// Base point (natal).
310    pub body2: String,
311    /// Always "base".
312    pub body2_source: &'static str,
313    /// Aspect name, e.g. "Trine".
314    pub aspect_type: &'static str,
315    /// Aspect glyph, e.g. "△".
316    pub symbol: &'static str,
317    /// Exact angle of the aspect, in degrees.
318    pub angle: f64,
319    /// Distance from exactness, in degrees (rounded to 0.01).
320    pub orb: f64,
321    /// Largest orb allowed for this pair and aspect, in degrees.
322    pub max_orb: f64,
323    /// Whether it is a major (Ptolemaic) aspect.
324    pub is_major: bool,
325    /// Always `true`, as in the reference implementation.
326    pub is_applying: bool,
327}
328
329/// A named point on the ecliptic.
330#[derive(Debug, Clone, Copy, PartialEq)]
331pub struct Point<'a> {
332    pub name: &'a str,
333    pub longitude: f64,
334}
335
336fn is_node_pair(a: &str, b: &str) -> bool {
337    (a == "North Node" && b == "South Node") || (a == "South Node" && b == "North Node")
338}
339
340/// The first aspect rule within orb for a separation, with its orb and max orb.
341fn find_aspect(
342    orbs: &OrbSettings,
343    a: &str,
344    b: &str,
345    diff: f64,
346) -> Result<Option<(&'static AspectRule, f64, f64)>, EngineError> {
347    for rule in &ASPECT_RULES {
348        let max_orb = orbs.max_orb(a, b, rule.name)?;
349        let orb = (diff - rule.angle).abs();
350        if orb <= max_orb {
351            return Ok(Some((rule, orb, max_orb)));
352        }
353    }
354    Ok(None)
355}
356
357/// Aspects between every pair of chart points, skipping the nodal axis.
358pub fn natal_aspects(points: &[Point], orbs: &OrbSettings) -> Result<Vec<Aspect>, EngineError> {
359    let mut out = Vec::new();
360    for (i, p1) in points.iter().enumerate() {
361        for p2 in &points[i + 1..] {
362            if is_node_pair(p1.name, p2.name) {
363                continue;
364            }
365            let diff = pyfloat::separation(p1.longitude, p2.longitude);
366            if let Some((rule, orb, max_orb)) = find_aspect(orbs, p1.name, p2.name, diff)? {
367                out.push(Aspect {
368                    body1: p1.name.to_string(),
369                    body2: p2.name.to_string(),
370                    aspect_type: rule.name,
371                    symbol: rule.symbol,
372                    angle: rule.angle,
373                    orb: pyfloat::round(orb, 2),
374                    max_orb: pyfloat::round(max_orb, 2),
375                    is_major: Some(rule.is_major),
376                    is_applying: true,
377                });
378            }
379        }
380    }
381    Ok(out)
382}
383
384/// `calculate_cross_aspects`: every overlay body against every base body.
385pub fn cross_aspects(
386    base: &[Point],
387    overlay: &[Point],
388    custom_orbs: Option<&Value>,
389) -> Result<Vec<CrossAspect>, EngineError> {
390    let orbs = OrbSettings::merge(custom_orbs)?;
391    let mut out = Vec::new();
392    for o in overlay {
393        for b in base {
394            if is_node_pair(o.name, b.name) {
395                continue;
396            }
397            let diff = pyfloat::separation(o.longitude, b.longitude);
398            if let Some((rule, orb, max_orb)) = find_aspect(&orbs, o.name, b.name, diff)? {
399                out.push(CrossAspect {
400                    body1: o.name.to_string(),
401                    body1_source: "overlay",
402                    body2: b.name.to_string(),
403                    body2_source: "base",
404                    aspect_type: rule.name,
405                    symbol: rule.symbol,
406                    angle: rule.angle,
407                    orb: pyfloat::round(orb, 2),
408                    max_orb: pyfloat::round(max_orb, 2),
409                    is_major: rule.is_major,
410                    is_applying: true,
411                });
412            }
413        }
414    }
415    Ok(out)
416}
417
418/// Chart points (`name`, `ecliptic_longitude`) from a stored planets list.
419pub fn points_from_json(planets: &Value) -> Result<Vec<Point<'_>>, EngineError> {
420    let list = planets
421        .as_array()
422        .ok_or_else(|| EngineError::InvalidInput("planets must be a list".into()))?;
423    list.iter()
424        .map(|p| {
425            let name = p
426                .get("name")
427                .and_then(Value::as_str)
428                .ok_or_else(|| EngineError::InvalidInput("every planet needs a name".into()))?;
429            let longitude = p.get("ecliptic_longitude").map(py_float).ok_or_else(|| {
430                EngineError::InvalidInput(format!("{name} has no ecliptic_longitude"))
431            })??;
432            let longitude = finite(longitude, &format!("{name}'s ecliptic_longitude"))?;
433            Ok(Point { name, longitude })
434        })
435        .collect()
436}
437
438#[cfg(test)]
439mod tests {
440    use super::*;
441
442    #[test]
443    fn hybrid_orb_is_capped_by_aspect() {
444        let orbs = OrbSettings::default();
445        // Sun 15 + Moon 12 → moiety 13.5, capped by Conjunction 8.
446        assert_eq!(orbs.max_orb("Sun", "Moon", "Conjunction").unwrap(), 8.0);
447        // Uranus 5 + Neptune 5 → 5, under Conjunction's 8.
448        assert_eq!(
449            orbs.max_orb("Uranus", "Neptune", "Conjunction").unwrap(),
450            5.0
451        );
452        assert_eq!(orbs.max_orb("Sun", "Moon", "Semi-Sextile").unwrap(), 2.5);
453    }
454
455    #[test]
456    fn custom_orbs_merge_key_by_key() {
457        let custom = json!({"method": "fixed_aspect", "aspect_orbs": {"Trine": "6"}});
458        let orbs = OrbSettings::merge(Some(&custom)).unwrap();
459        assert_eq!(orbs.max_orb("Sun", "Moon", "Trine").unwrap(), 6.0);
460        assert_eq!(orbs.max_orb("Sun", "Moon", "Square").unwrap(), 7.0);
461        assert_eq!(orbs.as_map()["aspect_orbs"]["Trine"], json!("6"));
462        let weighted = json!({"method": "moiety_aspect_weighted"});
463        let orbs = OrbSettings::merge(Some(&weighted)).unwrap();
464        // moiety 13.5 × (6 / 8)
465        assert_eq!(orbs.max_orb("Sun", "Moon", "Sextile").unwrap(), 10.12); // 10.125, ties to even
466    }
467}