Skip to main content

khagole_engine/
chart.rs

1//! A complete chart: positions, houses, aspects, fixed stars, lots, temperament and
2//! lunar status, in the JSON shape of the reference's `calculate_chart_data`.
3
4use serde::{Serialize, Serializer};
5use serde_json::Value;
6
7use crate::aspects::{natal_aspects, Aspect, OrbSettings, Point};
8use crate::chinese::calendar::{chinese_calendar, ChineseCalendar};
9use crate::dignities::{
10    antiscia, condition, is_diurnal, receptions, AntisciaContact, Body, Condition, DignityScheme,
11    Reception,
12};
13use crate::ephemeris::KernelSet;
14use crate::error::EngineError;
15use crate::fixed_stars::{fixed_stars, FixedStarPosition};
16use crate::horary::{planetary_hours, PlanetaryHours};
17use crate::houses::{houses_at_sidereal_time, HouseSystem, Houses};
18use crate::instant::UtcInstant;
19use crate::lots::{arabic_parts, Lot};
20use crate::lunar::{lunar_status, LunarStatus};
21use crate::planets::planets_and_sidereal_time_with_options;
22use crate::symbolic::symbolic_degree_number;
23use crate::temperament::{temperament, Temperament};
24use crate::zodiac::{
25    ayanamsa, ayanamsa_info, determine_house, longitude_to_zodiac, AyanamsaInfo, DEFAULT_AYANAMSA,
26};
27
28/// Every body a complete chart carries; missing ones are reported in
29/// `unavailable_bodies` rather than silently dropped.
30const EXPECTED_BODIES: [&str; 16] = [
31    "Sun",
32    "Moon",
33    "Mercury",
34    "Venus",
35    "Mars",
36    "Jupiter",
37    "Saturn",
38    "Uranus",
39    "Neptune",
40    "Pluto",
41    "North Node",
42    "South Node",
43    "Chiron",
44    "Lilith",
45    "Ascendant",
46    "Midheaven",
47];
48
49/// What to compute.
50#[derive(Debug, Clone)]
51pub struct ChartRequest<'a> {
52    /// Moment of the chart.
53    pub instant: UtcInstant,
54    /// Geographic latitude in degrees, north positive.
55    pub latitude: f64,
56    /// Geographic longitude in degrees, east positive.
57    pub longitude: f64,
58    /// House system code, echoed as given; its first letter selects the system.
59    pub house_system: &'a str,
60    /// "tropical" or "sidereal" (anything else is tropical).
61    pub zodiac_type: &'a str,
62    /// Ayanamsa code for sidereal charts (unknown codes use the default).
63    pub ayanamsa: &'a str,
64    /// Caller orb settings, merged over the defaults.
65    pub orb_settings: Option<&'a Value>,
66    /// Doctrine of triplicities and bounds: "lilly" (default) or "dorothean".
67    pub dignity_scheme: &'a str,
68    /// "apparent" (default) or "true" (geometric positions without light-time or aberration).
69    pub position_mode: &'a str,
70    /// "mean" (default) or "true" (osculating lunar node).
71    pub node_type: &'a str,
72    /// Also compute the [`ChineseCalendar`] of the moment (default `false`): a few dozen
73    /// solar-term and new-moon searches.
74    pub chinese_calendar: bool,
75}
76
77impl<'a> ChartRequest<'a> {
78    /// A tropical Placidus request with default orbs.
79    pub fn new(instant: UtcInstant, latitude: f64, longitude: f64) -> Self {
80        ChartRequest {
81            instant,
82            latitude,
83            longitude,
84            house_system: "P",
85            zodiac_type: "tropical",
86            ayanamsa: DEFAULT_AYANAMSA,
87            orb_settings: None,
88            dignity_scheme: "lilly",
89            position_mode: "apparent",
90            node_type: "mean",
91            chinese_calendar: false,
92        }
93    }
94
95    /// The place must be on Earth: a finite latitude within ±90° and a finite longitude
96    /// within ±360° (east or west, or 0-360 east).
97    pub(crate) fn check_place(&self) -> Result<(), EngineError> {
98        let (lat, lon) = (self.latitude, self.longitude);
99        if !(lat.is_finite() && lat.abs() <= 90.0) {
100            return Err(EngineError::InvalidInput(format!(
101                "latitude must be within ±90°, got {lat}"
102            )));
103        }
104        if !(lon.is_finite() && lon.abs() <= 360.0) {
105            return Err(EngineError::InvalidInput(format!(
106                "longitude must be within ±360°, got {lon}"
107            )));
108        }
109        Ok(())
110    }
111}
112
113/// A planet, lunar point or angle placed in the chart.
114#[derive(Debug, Clone, PartialEq, Serialize)]
115pub struct Placement {
116    /// Body or angle name, e.g. "Sun", "North Node", "Ascendant".
117    pub name: &'static str,
118    /// Glyph, e.g. "☉" ("ASC" and "MC" for the angles).
119    pub symbol: &'static str,
120    /// Zodiac sign name, e.g. "Taurus".
121    pub sign: &'static str,
122    /// Zodiac sign glyph, e.g. "♉".
123    pub sign_symbol: &'static str,
124    /// Whole degrees within the sign (0-29).
125    pub degree: i64,
126    /// Arc minutes past `degree` (0-59).
127    pub minute: i64,
128    /// Ecliptic longitude in degrees [0, 360), tropical or sidereal as requested.
129    pub ecliptic_longitude: f64,
130    /// House (1-12) the point falls in.
131    pub house: u8,
132    /// Apparent speed in ecliptic longitude, degrees per day.
133    pub speed: f64,
134    /// Whether the apparent motion is retrograde.
135    pub is_retrograde: bool,
136    /// Symbolic degree (1-30) within the sign, as used by degree symbolism.
137    pub symbolic_degree: i64,
138    /// Essential dignity, sect, phase to the Sun and speed: the seven planets only.
139    #[serde(skip_serializing_if = "Option::is_none")]
140    pub condition: Option<Condition>,
141}
142
143/// The cusp of one house.
144#[derive(Debug, Clone, PartialEq, Serialize)]
145pub struct HouseCusp {
146    /// House number (1-12).
147    pub house_number: u8,
148    /// Zodiac sign name, e.g. "Taurus".
149    pub sign: &'static str,
150    /// Zodiac sign glyph, e.g. "♉".
151    pub sign_symbol: &'static str,
152    /// Whole degrees within the sign (0-29).
153    pub degree: i64,
154    /// Arc minutes past `degree` (0-59).
155    pub minute: i64,
156    /// Ecliptic longitude in degrees [0, 360), tropical or sidereal as requested.
157    pub ecliptic_longitude: f64,
158    /// Symbolic degree (1-30) within the sign, as used by degree symbolism.
159    pub symbolic_degree: i64,
160}
161
162/// A complete chart (`calculate_chart_data`); serializes to the API's JSON.
163#[derive(Debug, Clone, PartialEq, Serialize)]
164pub struct Chart {
165    /// House system code, echoed from the request.
166    pub house_system: String,
167    /// "tropical" or "sidereal".
168    pub zodiac_type: &'static str,
169    /// Position mode: "apparent" or "true" (geometric). Skipped if None.
170    #[serde(skip_serializing_if = "Option::is_none")]
171    pub position_mode: Option<&'static str>,
172    /// Node type: "mean" or "true" (osculating). Skipped if None.
173    #[serde(skip_serializing_if = "Option::is_none")]
174    pub node_type: Option<&'static str>,
175    /// Ayanamsa code; `None` for tropical charts.
176    pub ayanamsa: Option<&'static str>,
177    /// Human-readable ayanamsa name; `None` for tropical charts.
178    pub ayanamsa_name: Option<&'static str>,
179    /// Ayanamsa at the chart instant, in degrees; `None` for tropical charts.
180    pub ayanamsa_value: Option<f64>,
181    /// `ayanamsa_value` as degrees, minutes and seconds; `None` for tropical charts.
182    pub ayanamsa_formatted: Option<String>,
183    /// Mean precession rate used for the fixed stars, arcseconds per year.
184    pub precession_rate_arcsec_yr: f64,
185    /// Orb settings in effect: the defaults merged with the request's.
186    pub orb_settings: Value,
187    /// Planets, lunar points, Chiron, Lilith and the angles.
188    pub planets: Vec<Placement>,
189    /// Expected bodies that could not be computed (e.g. Chiron outside its table).
190    pub unavailable_bodies: Vec<&'static str>,
191    /// The twelve house cusps.
192    pub houses: Vec<HouseCusp>,
193    /// Aspects between chart points, then fixed-star conjunctions.
194    pub aspects: Vec<Aspect>,
195    /// Fixed stars conjunct a chart point.
196    pub fixed_stars: Vec<FixedStarPosition>,
197    /// The Arabic parts (lots).
198    pub arabic_parts: Vec<Lot>,
199    /// Temperament assessment.
200    pub temperament: Temperament,
201    /// Lunar phase and status; `None` (serialized as `{}`) without a Moon.
202    #[serde(serialize_with = "empty_object_if_none")]
203    pub lunar_status: Option<LunarStatus>,
204    /// "diurnal" (the Sun above the horizon) or "nocturnal"; `None` without Sun and Ascendant.
205    pub sect: Option<&'static str>,
206    /// Doctrine of triplicities and bounds used for `condition` and `receptions`.
207    pub dignity_scheme: &'static str,
208    /// Receptions among the seven planets.
209    pub receptions: Vec<Reception>,
210    /// Antiscia and contra-antiscia among the seven planets and the angles.
211    pub antiscia: Vec<AntisciaContact>,
212    /// Planetary day and hour; absent from transit skies.
213    #[serde(skip_serializing_if = "Option::is_none")]
214    pub planetary_hours: Option<PlanetaryHours>,
215    /// The Chinese calendar of the moment, when requested and the kernels cover it.
216    #[serde(skip_serializing_if = "Option::is_none")]
217    pub chinese_calendar: Option<ChineseCalendar>,
218}
219
220fn empty_object_if_none<S: Serializer>(v: &Option<LunarStatus>, s: S) -> Result<S::Ok, S::Error> {
221    match v {
222        Some(status) => status.serialize(s),
223        None => serde_json::Map::new().serialize(s),
224    }
225}
226
227impl Chart {
228    /// The chart's planets and angles as named ecliptic points.
229    pub(crate) fn points(&self) -> Vec<Point<'_>> {
230        self.planets
231            .iter()
232            .map(|p| Point {
233                name: p.name,
234                longitude: p.ecliptic_longitude,
235            })
236            .collect()
237    }
238}
239
240fn symbol_of(name: &str) -> &'static str {
241    match name {
242        "Sun" => "☉",
243        "Moon" => "☽",
244        "Mercury" => "☿",
245        "Venus" => "♀",
246        "Mars" => "♂",
247        "Jupiter" => "♃",
248        "Saturn" => "♄",
249        "Uranus" => "♅",
250        "Neptune" => "♆",
251        "Pluto" => "♇",
252        "North Node" => "☊",
253        "South Node" => "☋",
254        "Chiron" => "⚷",
255        "Lilith" => "⚸",
256        "Ascendant" => "ASC",
257        "Midheaven" => "MC",
258        _ => "",
259    }
260}
261
262/// The positions part of a chart: placements and house cusps, without aspects, fixed
263/// stars, lots or temperament. Electional searches evaluate thousands of these.
264pub(crate) struct Sky {
265    pub zodiac_type: &'static str,
266    pub is_sidereal: bool,
267    pub ayanamsa_code: &'static str,
268    pub info: AyanamsaInfo,
269    pub jd: f64,
270    /// Cusps 1-12, degrees.
271    pub cusps: Vec<f64>,
272    pub house_cusps: Vec<HouseCusp>,
273    pub planets: Vec<Placement>,
274}
275
276/// Placements and houses of a request (the first half of [`calculate_chart`]).
277pub(crate) fn sky(kernels: &KernelSet, req: &ChartRequest) -> Result<Sky, EngineError> {
278    req.check_place()?;
279    let zodiac_type = match req.zodiac_type.trim().to_lowercase().as_str() {
280        "sidereal" => "sidereal",
281        _ => "tropical",
282    };
283    let is_sidereal = zodiac_type == "sidereal";
284    let ayanamsa_code = ayanamsa(req.ayanamsa).code;
285
286    let jd = req.instant.julian_day();
287    let info = ayanamsa_info(jd, ayanamsa_code);
288    let shift = if is_sidereal { info.value } else { 0.0 };
289
290    let is_geometric = req.position_mode.trim().eq_ignore_ascii_case("true")
291        || req.position_mode.trim().eq_ignore_ascii_case("geometric");
292    let is_true_node = req.node_type.trim().eq_ignore_ascii_case("true")
293        || req.node_type.trim().eq_ignore_ascii_case("osculating");
294
295    // The houses reuse the planets' sidereal time (the same instant): one nutation.
296    let (engine, gast_hours) =
297        planets_and_sidereal_time_with_options(kernels, jd, shift, is_geometric, is_true_node)?;
298    let houses = houses_at_sidereal_time(
299        jd,
300        gast_hours,
301        req.latitude,
302        req.longitude,
303        HouseSystem::from_code(req.house_system),
304        shift,
305    );
306    let cusps = houses.cusps.to_vec();
307
308    let house_cusps: Vec<HouseCusp> = houses
309        .cusps
310        .iter()
311        .enumerate()
312        .map(|(i, &lon)| {
313            let z = longitude_to_zodiac(lon);
314            HouseCusp {
315                house_number: i as u8 + 1,
316                sign: z.sign.name,
317                sign_symbol: z.sign.symbol,
318                degree: z.degree,
319                minute: z.minute,
320                ecliptic_longitude: lon,
321                symbolic_degree: symbolic_degree_number(z.degree, z.minute),
322            }
323        })
324        .collect();
325
326    let raw: Vec<(&'static str, f64, f64, bool)> = engine
327        .bodies
328        .iter()
329        .map(|b| (b.name, b.longitude, b.speed, b.is_retrograde))
330        .collect();
331    let planets = placements(raw, &houses);
332
333    Ok(Sky {
334        zodiac_type,
335        is_sidereal,
336        ayanamsa_code,
337        info,
338        jd,
339        cusps,
340        house_cusps,
341        planets,
342    })
343}
344
345/// Placements of bodies given as (name, longitude, speed, retrograde), followed by the
346/// Ascendant and the Midheaven, with their houses.
347pub(crate) fn placements(
348    mut raw: Vec<(&'static str, f64, f64, bool)>,
349    houses: &Houses,
350) -> Vec<Placement> {
351    raw.push(("Ascendant", houses.ascendant, 0.0, false));
352    raw.push(("Midheaven", houses.midheaven, 0.0, false));
353    raw.iter()
354        .map(|&(name, lon, speed, is_retrograde)| {
355            let z = longitude_to_zodiac(lon);
356            Placement {
357                name,
358                symbol: symbol_of(name),
359                sign: z.sign.name,
360                sign_symbol: z.sign.symbol,
361                degree: z.degree,
362                minute: z.minute,
363                ecliptic_longitude: lon,
364                house: determine_house(lon, &houses.cusps),
365                speed,
366                is_retrograde,
367                symbolic_degree: symbolic_degree_number(z.degree, z.minute),
368                condition: None,
369            }
370        })
371        .collect()
372}
373
374/// Set the condition of the seven planets, which needs the Sun and the Ascendant.
375fn add_conditions(planets: &mut [Placement], scheme: DignityScheme) -> Option<&'static str> {
376    let at = |name: &str| {
377        planets
378            .iter()
379            .find(|p| p.name == name)
380            .map(|p| p.ecliptic_longitude)
381    };
382    let (sun, asc) = (at("Sun")?, at("Ascendant")?);
383    for planet in planets.iter_mut() {
384        planet.condition = condition(Body::from(&*planet), sun, asc, scheme);
385    }
386    Some(if is_diurnal(sun, asc) {
387        "diurnal"
388    } else {
389        "nocturnal"
390    })
391}
392
393/// Compute a chart (`calculate_chart_data`), with its planetary day and hour.
394pub fn calculate_chart(kernels: &KernelSet, req: &ChartRequest) -> Result<Chart, EngineError> {
395    let mut chart = chart_without_hours(kernels, req)?;
396    chart.planetary_hours = Some(planetary_hours(
397        kernels,
398        req.instant,
399        req.latitude,
400        req.longitude,
401    ));
402    Ok(chart)
403}
404
405/// A chart without its planetary hours, which cost a sunrise search: for transit skies,
406/// and for the callers that compute the hours themselves.
407pub(crate) fn chart_without_hours(
408    kernels: &KernelSet,
409    req: &ChartRequest,
410) -> Result<Chart, EngineError> {
411    let orbs = OrbSettings::merge(req.orb_settings)?;
412    let scheme = DignityScheme::from_code(req.dignity_scheme);
413    let Sky {
414        zodiac_type,
415        is_sidereal,
416        ayanamsa_code,
417        info,
418        jd,
419        cusps,
420        house_cusps,
421        mut planets,
422    } = sky(kernels, req)?;
423    let sect = add_conditions(&mut planets, scheme);
424    let points: Vec<Point> = planets
425        .iter()
426        .map(|p| Point {
427            name: p.name,
428            longitude: p.ecliptic_longitude,
429        })
430        .collect();
431
432    let mut aspects = natal_aspects(&points, &orbs)?;
433    let (stars, star_aspects) = fixed_stars(
434        jd,
435        &cusps,
436        &points,
437        orbs.fixed_star_orb()?,
438        is_sidereal.then_some(info.value),
439    );
440    aspects.extend(star_aspects);
441
442    let lots = arabic_parts(&points, &cusps);
443    let temperament = temperament(&planets, &aspects);
444    let lunar = lunar_status(&planets);
445    let bodies: Vec<Body> = planets.iter().map(Body::from).collect();
446    let aspect_between = |a: &str, b: &str| {
447        aspects
448            .iter()
449            .find(|x| (x.body1 == a && x.body2 == b) || (x.body1 == b && x.body2 == a))
450            .map(|x| x.aspect_type)
451    };
452    let chart_receptions = receptions(&bodies, aspect_between, scheme);
453    let chart_antiscia = antiscia(&planets);
454
455    let mut unavailable: Vec<&'static str> = EXPECTED_BODIES
456        .iter()
457        .copied()
458        .filter(|name| !planets.iter().any(|p| p.name == *name))
459        .collect();
460    unavailable.sort_unstable();
461
462    Ok(Chart {
463        house_system: req.house_system.to_string(),
464        zodiac_type,
465        position_mode: if req.position_mode.trim().eq_ignore_ascii_case("true")
466            || req.position_mode.trim().eq_ignore_ascii_case("geometric")
467        {
468            Some("true")
469        } else {
470            None
471        },
472        node_type: if req.node_type.trim().eq_ignore_ascii_case("true")
473            || req.node_type.trim().eq_ignore_ascii_case("osculating")
474        {
475            Some("true")
476        } else {
477            None
478        },
479        ayanamsa: is_sidereal.then_some(ayanamsa_code),
480        ayanamsa_name: is_sidereal.then_some(info.name),
481        ayanamsa_value: is_sidereal.then_some(info.value),
482        ayanamsa_formatted: is_sidereal.then(|| info.formatted.clone()),
483        precession_rate_arcsec_yr: info.precession_rate_arcsec_yr,
484        orb_settings: orbs.to_value(),
485        planets,
486        unavailable_bodies: unavailable,
487        houses: house_cusps,
488        aspects,
489        fixed_stars: stars,
490        arabic_parts: lots,
491        temperament,
492        lunar_status: lunar,
493        sect,
494        dignity_scheme: scheme.code(),
495        receptions: chart_receptions,
496        antiscia: chart_antiscia,
497        planetary_hours: None,
498        chinese_calendar: if req.chinese_calendar {
499            chinese_calendar(kernels, req.instant)?
500        } else {
501            None
502        },
503    })
504}