1use 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
28const 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#[derive(Debug, Clone)]
51pub struct ChartRequest<'a> {
52 pub instant: UtcInstant,
54 pub latitude: f64,
56 pub longitude: f64,
58 pub house_system: &'a str,
60 pub zodiac_type: &'a str,
62 pub ayanamsa: &'a str,
64 pub orb_settings: Option<&'a Value>,
66 pub dignity_scheme: &'a str,
68 pub position_mode: &'a str,
70 pub node_type: &'a str,
72 pub chinese_calendar: bool,
75}
76
77impl<'a> ChartRequest<'a> {
78 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 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#[derive(Debug, Clone, PartialEq, Serialize)]
115pub struct Placement {
116 pub name: &'static str,
118 pub symbol: &'static str,
120 pub sign: &'static str,
122 pub sign_symbol: &'static str,
124 pub degree: i64,
126 pub minute: i64,
128 pub ecliptic_longitude: f64,
130 pub house: u8,
132 pub speed: f64,
134 pub is_retrograde: bool,
136 pub symbolic_degree: i64,
138 #[serde(skip_serializing_if = "Option::is_none")]
140 pub condition: Option<Condition>,
141}
142
143#[derive(Debug, Clone, PartialEq, Serialize)]
145pub struct HouseCusp {
146 pub house_number: u8,
148 pub sign: &'static str,
150 pub sign_symbol: &'static str,
152 pub degree: i64,
154 pub minute: i64,
156 pub ecliptic_longitude: f64,
158 pub symbolic_degree: i64,
160}
161
162#[derive(Debug, Clone, PartialEq, Serialize)]
164pub struct Chart {
165 pub house_system: String,
167 pub zodiac_type: &'static str,
169 #[serde(skip_serializing_if = "Option::is_none")]
171 pub position_mode: Option<&'static str>,
172 #[serde(skip_serializing_if = "Option::is_none")]
174 pub node_type: Option<&'static str>,
175 pub ayanamsa: Option<&'static str>,
177 pub ayanamsa_name: Option<&'static str>,
179 pub ayanamsa_value: Option<f64>,
181 pub ayanamsa_formatted: Option<String>,
183 pub precession_rate_arcsec_yr: f64,
185 pub orb_settings: Value,
187 pub planets: Vec<Placement>,
189 pub unavailable_bodies: Vec<&'static str>,
191 pub houses: Vec<HouseCusp>,
193 pub aspects: Vec<Aspect>,
195 pub fixed_stars: Vec<FixedStarPosition>,
197 pub arabic_parts: Vec<Lot>,
199 pub temperament: Temperament,
201 #[serde(serialize_with = "empty_object_if_none")]
203 pub lunar_status: Option<LunarStatus>,
204 pub sect: Option<&'static str>,
206 pub dignity_scheme: &'static str,
208 pub receptions: Vec<Reception>,
210 pub antiscia: Vec<AntisciaContact>,
212 #[serde(skip_serializing_if = "Option::is_none")]
214 pub planetary_hours: Option<PlanetaryHours>,
215 #[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 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
262pub(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 pub cusps: Vec<f64>,
272 pub house_cusps: Vec<HouseCusp>,
273 pub planets: Vec<Placement>,
274}
275
276pub(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 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
345pub(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
374fn 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
393pub 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
405pub(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}