Add horoscope-api, synastry, and backend services
- horoscope-api: Swiss Ephemeris natal charts, timezone/place resolution, POST /v1/natal and POST /v1/synastry - backend: users with roles, email/password and Google login, saved charts, synastries and invites, analyses with credit ledger, public shares, admin - shared crates: astro-engine, db (migrations), horoscope-client, service-kit - docker-compose with postgres, legacy Java project for reference Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "astro-engine"
|
||||
description = "Natal chart calculation on top of a replaceable ephemeris engine"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[features]
|
||||
default = ["swisseph"]
|
||||
swisseph = ["dep:swisseph-sys"]
|
||||
|
||||
[dependencies]
|
||||
serde.workspace = true
|
||||
thiserror.workspace = true
|
||||
swisseph-sys = { workspace = true, optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json.workspace = true
|
||||
@@ -0,0 +1,71 @@
|
||||
//! Angle helpers (all angles in degrees).
|
||||
|
||||
/// Normalizes an angle into `[0, 360)`.
|
||||
pub fn normalize(deg: f64) -> f64 {
|
||||
let r = deg.rem_euclid(360.0);
|
||||
// rem_euclid can return 360.0 for tiny negative inputs due to rounding
|
||||
if r >= 360.0 { 0.0 } else { r }
|
||||
}
|
||||
|
||||
/// Shortest angular distance between two longitudes, in `[0, 180]`.
|
||||
pub fn separation(a: f64, b: f64) -> f64 {
|
||||
let d = normalize(a - b);
|
||||
if d > 180.0 { 360.0 - d } else { d }
|
||||
}
|
||||
|
||||
/// Forward arc from `from` to `to` (counter-clockwise, increasing longitude), in `[0, 360)`.
|
||||
pub fn arc(from: f64, to: f64) -> f64 {
|
||||
normalize(to - from)
|
||||
}
|
||||
|
||||
/// Formats an unsigned angle as `DD°MM'SS"`.
|
||||
pub fn dms(deg: f64) -> String {
|
||||
let (d, m, s) = split_dms(deg.abs());
|
||||
format!("{d}°{m:02}'{s:02}\"")
|
||||
}
|
||||
|
||||
/// Formats a signed angle as `+DD°MM'SS"` / `-DD°MM'SS"`.
|
||||
pub fn signed_dms(deg: f64) -> String {
|
||||
let sign = if deg < 0.0 { '-' } else { '+' };
|
||||
format!("{sign}{}", dms(deg))
|
||||
}
|
||||
|
||||
/// Formats hours as `HH:MM:SS`.
|
||||
pub fn hms(hours: f64) -> String {
|
||||
let (h, m, s) = split_dms(hours.rem_euclid(24.0));
|
||||
format!("{:02}:{m:02}:{s:02}", h % 24)
|
||||
}
|
||||
|
||||
/// Splits a non-negative value into whole units, minutes and seconds, rounding
|
||||
/// to the nearest second without producing 60 minutes or seconds.
|
||||
fn split_dms(value: f64) -> (u32, u32, u32) {
|
||||
let total = (value * 3600.0).round() as u64;
|
||||
((total / 3600) as u32, ((total / 60) % 60) as u32, (total % 60) as u32)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn normalizes() {
|
||||
assert_eq!(normalize(-10.0), 350.0);
|
||||
assert_eq!(normalize(720.5), 0.5);
|
||||
assert_eq!(normalize(-1e-15), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separations() {
|
||||
assert_eq!(separation(350.0, 10.0), 20.0);
|
||||
assert_eq!(separation(10.0, 190.0), 180.0);
|
||||
assert_eq!(arc(350.0, 10.0), 20.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formats() {
|
||||
assert_eq!(dms(21.8866), "21°53'12\"");
|
||||
assert_eq!(dms(29.99999), "30°00'00\"");
|
||||
assert_eq!(signed_dms(-1.5), "-1°30'00\"");
|
||||
assert_eq!(hms(25.5), "01:30:00");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,921 @@
|
||||
//! Engine-independent natal chart construction.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::angle::{self, normalize, separation};
|
||||
use crate::engine::{BodyState, EngineError, Ephemeris, Frame, GeoPosition, HouseResult, Obliquity};
|
||||
use crate::types::{
|
||||
AspectSet, Ayanamsa, Body, Dignity, Element, HouseSystem, LilithType, Modality, NodeType, ZodiacSign, ZodiacType,
|
||||
dignities,
|
||||
};
|
||||
|
||||
/// Calculation options (all have sensible defaults).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct ChartOptions {
|
||||
pub house_system: HouseSystem,
|
||||
pub zodiac: ZodiacType,
|
||||
/// Used only with the sidereal zodiac.
|
||||
pub ayanamsa: Ayanamsa,
|
||||
pub node_type: NodeType,
|
||||
pub lilith_type: LilithType,
|
||||
pub aspect_set: AspectSet,
|
||||
/// Scales every orb (1.0 = default orbs).
|
||||
pub orb_multiplier: f64,
|
||||
/// Topocentric instead of geocentric positions (matters mostly for the Moon).
|
||||
pub topocentric: bool,
|
||||
/// Include Ceres, Pallas, Juno and Vesta.
|
||||
pub include_asteroids: bool,
|
||||
}
|
||||
|
||||
impl Default for ChartOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
house_system: HouseSystem::default(),
|
||||
zodiac: ZodiacType::default(),
|
||||
ayanamsa: Ayanamsa::default(),
|
||||
node_type: NodeType::default(),
|
||||
lilith_type: LilithType::default(),
|
||||
aspect_set: AspectSet::default(),
|
||||
orb_multiplier: 1.0,
|
||||
topocentric: false,
|
||||
include_asteroids: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct ChartInput {
|
||||
/// Moment of birth as Julian Day (UT).
|
||||
pub jd_ut: f64,
|
||||
pub observer: GeoPosition,
|
||||
/// `false` when the birth time is unknown: houses, angles and lots are
|
||||
/// omitted and the Moon position is flagged as approximate.
|
||||
pub time_known: bool,
|
||||
pub options: ChartOptions,
|
||||
}
|
||||
|
||||
/// Identifier of a chart point (bodies, calculated points and angles).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PointId {
|
||||
Sun,
|
||||
Moon,
|
||||
Mercury,
|
||||
Venus,
|
||||
Mars,
|
||||
Jupiter,
|
||||
Saturn,
|
||||
Uranus,
|
||||
Neptune,
|
||||
Pluto,
|
||||
NorthNode,
|
||||
SouthNode,
|
||||
Lilith,
|
||||
Chiron,
|
||||
Ceres,
|
||||
Pallas,
|
||||
Juno,
|
||||
Vesta,
|
||||
Ascendant,
|
||||
Midheaven,
|
||||
}
|
||||
|
||||
impl PointId {
|
||||
fn from_planet(body: Body) -> PointId {
|
||||
match body {
|
||||
Body::Sun => PointId::Sun,
|
||||
Body::Moon => PointId::Moon,
|
||||
Body::Mercury => PointId::Mercury,
|
||||
Body::Venus => PointId::Venus,
|
||||
Body::Mars => PointId::Mars,
|
||||
Body::Jupiter => PointId::Jupiter,
|
||||
Body::Saturn => PointId::Saturn,
|
||||
Body::Uranus => PointId::Uranus,
|
||||
Body::Neptune => PointId::Neptune,
|
||||
Body::Pluto => PointId::Pluto,
|
||||
Body::Chiron => PointId::Chiron,
|
||||
Body::Ceres => PointId::Ceres,
|
||||
Body::Pallas => PointId::Pallas,
|
||||
Body::Juno => PointId::Juno,
|
||||
Body::Vesta => PointId::Vesta,
|
||||
Body::MeanNode | Body::TrueNode => PointId::NorthNode,
|
||||
Body::MeanLilith | Body::TrueLilith => PointId::Lilith,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_luminary(self) -> bool {
|
||||
matches!(self, PointId::Sun | PointId::Moon)
|
||||
}
|
||||
|
||||
/// Sensitive points that get reduced orbs.
|
||||
fn is_minor_point(self) -> bool {
|
||||
matches!(self, PointId::NorthNode | PointId::SouthNode | PointId::Lilith | PointId::Chiron)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PointKind {
|
||||
Luminary,
|
||||
Planet,
|
||||
LunarNode,
|
||||
LunarApogee,
|
||||
Centaur,
|
||||
Asteroid,
|
||||
}
|
||||
|
||||
/// Position on the ecliptic expressed in zodiac terms.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct ZodiacPosition {
|
||||
/// Ecliptic longitude, degrees `[0, 360)`.
|
||||
pub longitude: f64,
|
||||
pub sign: ZodiacSign,
|
||||
/// Degrees within the sign `[0, 30)`.
|
||||
pub degree_in_sign: f64,
|
||||
/// Degrees within the sign as `DD°MM'SS"`.
|
||||
pub degree_in_sign_dms: String,
|
||||
/// Decan within the sign (1..=3).
|
||||
pub decan: u8,
|
||||
}
|
||||
|
||||
impl ZodiacPosition {
|
||||
pub fn new(longitude: f64) -> Self {
|
||||
let longitude = normalize(longitude);
|
||||
let sign = ZodiacSign::from_longitude(longitude);
|
||||
let degree_in_sign = longitude - sign.index() as f64 * 30.0;
|
||||
Self {
|
||||
longitude,
|
||||
sign,
|
||||
degree_in_sign,
|
||||
degree_in_sign_dms: angle::dms(degree_in_sign),
|
||||
decan: ((degree_in_sign / 10.0).floor() as u8 + 1).min(3),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Point {
|
||||
pub id: PointId,
|
||||
pub kind: PointKind,
|
||||
/// `"true"` / `"mean"` for lunar nodes and Lilith.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub variant: Option<&'static str>,
|
||||
#[serde(flatten)]
|
||||
pub position: ZodiacPosition,
|
||||
/// Ecliptic latitude, degrees.
|
||||
pub latitude: f64,
|
||||
pub distance_au: f64,
|
||||
/// Daily motion in longitude, degrees/day.
|
||||
pub speed: f64,
|
||||
pub retrograde: bool,
|
||||
pub right_ascension: f64,
|
||||
pub declination: f64,
|
||||
/// Declination beyond the obliquity of the ecliptic.
|
||||
pub out_of_bounds: bool,
|
||||
/// House (1..=12); `null` when the birth time is unknown.
|
||||
pub house: Option<u8>,
|
||||
/// Essential dignities (planets only).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub dignities: Option<Vec<Dignity>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct AnglePoint {
|
||||
#[serde(flatten)]
|
||||
pub position: ZodiacPosition,
|
||||
/// Daily motion, degrees/day.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub speed: Option<f64>,
|
||||
}
|
||||
|
||||
impl AnglePoint {
|
||||
fn new(longitude: f64, speed: Option<f64>) -> Self {
|
||||
Self { position: ZodiacPosition::new(longitude), speed }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Angles {
|
||||
pub ascendant: AnglePoint,
|
||||
pub midheaven: AnglePoint,
|
||||
pub descendant: AnglePoint,
|
||||
pub imum_coeli: AnglePoint,
|
||||
pub vertex: AnglePoint,
|
||||
pub antivertex: AnglePoint,
|
||||
/// Equatorial ascendant ("East Point").
|
||||
pub east_point: AnglePoint,
|
||||
/// Right ascension of the MC, degrees.
|
||||
pub armc: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct HouseCusp {
|
||||
pub house: u8,
|
||||
#[serde(flatten)]
|
||||
pub position: ZodiacPosition,
|
||||
/// Size of the house in degrees.
|
||||
pub size: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Houses {
|
||||
pub system: HouseSystem,
|
||||
pub requested_system: HouseSystem,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub fallback_reason: Option<String>,
|
||||
pub cusps: Vec<HouseCusp>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AspectKind {
|
||||
Conjunction,
|
||||
Semisextile,
|
||||
Semisquare,
|
||||
Sextile,
|
||||
Quintile,
|
||||
Square,
|
||||
Trine,
|
||||
Sesquiquadrate,
|
||||
Biquintile,
|
||||
Quincunx,
|
||||
Opposition,
|
||||
}
|
||||
|
||||
impl AspectKind {
|
||||
const MAJOR: [AspectKind; 5] =
|
||||
[AspectKind::Conjunction, AspectKind::Sextile, AspectKind::Square, AspectKind::Trine, AspectKind::Opposition];
|
||||
const MINOR: [AspectKind; 6] = [
|
||||
AspectKind::Semisextile,
|
||||
AspectKind::Semisquare,
|
||||
AspectKind::Quintile,
|
||||
AspectKind::Sesquiquadrate,
|
||||
AspectKind::Biquintile,
|
||||
AspectKind::Quincunx,
|
||||
];
|
||||
|
||||
pub fn angle(self) -> f64 {
|
||||
match self {
|
||||
AspectKind::Conjunction => 0.0,
|
||||
AspectKind::Semisextile => 30.0,
|
||||
AspectKind::Semisquare => 45.0,
|
||||
AspectKind::Sextile => 60.0,
|
||||
AspectKind::Quintile => 72.0,
|
||||
AspectKind::Square => 90.0,
|
||||
AspectKind::Trine => 120.0,
|
||||
AspectKind::Sesquiquadrate => 135.0,
|
||||
AspectKind::Biquintile => 144.0,
|
||||
AspectKind::Quincunx => 150.0,
|
||||
AspectKind::Opposition => 180.0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_major(self) -> bool {
|
||||
Self::MAJOR.contains(&self)
|
||||
}
|
||||
|
||||
/// Traditional character of the aspect.
|
||||
pub fn nature(self) -> AspectNature {
|
||||
match self {
|
||||
AspectKind::Sextile | AspectKind::Trine | AspectKind::Quintile | AspectKind::Biquintile => {
|
||||
AspectNature::Harmonious
|
||||
}
|
||||
AspectKind::Square
|
||||
| AspectKind::Opposition
|
||||
| AspectKind::Semisquare
|
||||
| AspectKind::Sesquiquadrate
|
||||
| AspectKind::Quincunx => AspectNature::Challenging,
|
||||
AspectKind::Conjunction | AspectKind::Semisextile => AspectNature::Neutral,
|
||||
}
|
||||
}
|
||||
|
||||
/// Default orb between two planets.
|
||||
fn base_orb(self) -> f64 {
|
||||
match self {
|
||||
AspectKind::Conjunction | AspectKind::Opposition => 8.0,
|
||||
AspectKind::Trine | AspectKind::Square => 7.0,
|
||||
AspectKind::Sextile => 5.0,
|
||||
AspectKind::Quincunx => 3.0,
|
||||
_ => 2.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Orb for a concrete pair of points.
|
||||
pub(crate) fn orb_for(self, a: PointId, b: PointId, multiplier: f64) -> f64 {
|
||||
let mut orb = self.base_orb();
|
||||
if a.is_luminary() || b.is_luminary() {
|
||||
orb += if self.is_major() { 2.0 } else { 1.0 };
|
||||
}
|
||||
if a.is_minor_point() || b.is_minor_point() {
|
||||
orb = orb.min(if self.is_major() { 4.0 } else { 1.0 });
|
||||
}
|
||||
orb * multiplier
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AspectNature {
|
||||
Harmonious,
|
||||
Challenging,
|
||||
Neutral,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Aspect {
|
||||
pub point1: PointId,
|
||||
pub point2: PointId,
|
||||
pub aspect: AspectKind,
|
||||
pub major: bool,
|
||||
/// Exact angle of the aspect (e.g. 120 for a trine).
|
||||
pub exact_angle: f64,
|
||||
/// Actual angular separation of the two points.
|
||||
pub separation: f64,
|
||||
/// Deviation from exactness, degrees.
|
||||
pub orb: f64,
|
||||
/// Maximum orb allowed for this pair.
|
||||
pub max_orb: f64,
|
||||
/// `true` = applying (getting tighter), `false` = separating.
|
||||
pub applying: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct OrbEntry {
|
||||
pub aspect: AspectKind,
|
||||
pub angle: f64,
|
||||
pub orb: f64,
|
||||
pub orb_with_luminary: f64,
|
||||
pub orb_with_minor_point: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Lot {
|
||||
#[serde(flatten)]
|
||||
pub position: ZodiacPosition,
|
||||
pub house: u8,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Lots {
|
||||
/// Pars Fortunae: day = Asc + Moon - Sun, night = Asc + Sun - Moon.
|
||||
pub fortune: Lot,
|
||||
/// Pars Spiritus: day = Asc + Sun - Moon, night = Asc + Moon - Sun.
|
||||
pub spirit: Lot,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum MoonPhaseName {
|
||||
NewMoon,
|
||||
WaxingCrescent,
|
||||
FirstQuarter,
|
||||
WaxingGibbous,
|
||||
FullMoon,
|
||||
WaningGibbous,
|
||||
LastQuarter,
|
||||
WaningCrescent,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct MoonPhase {
|
||||
/// Moon longitude minus Sun longitude, degrees `[0, 360)`.
|
||||
pub elongation: f64,
|
||||
/// One of the eight 45° lunation phases.
|
||||
pub phase: MoonPhaseName,
|
||||
/// Illuminated fraction of the Moon's disc (0..1).
|
||||
pub illumination: f64,
|
||||
pub waxing: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Sect {
|
||||
Day,
|
||||
Night,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize)]
|
||||
pub struct Tally {
|
||||
pub count: usize,
|
||||
pub points: Vec<PointId>,
|
||||
}
|
||||
|
||||
impl Tally {
|
||||
fn add(&mut self, id: PointId) {
|
||||
self.count += 1;
|
||||
self.points.push(id);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize)]
|
||||
pub struct ElementTally {
|
||||
pub fire: Tally,
|
||||
pub earth: Tally,
|
||||
pub air: Tally,
|
||||
pub water: Tally,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize)]
|
||||
pub struct ModalityTally {
|
||||
pub cardinal: Tally,
|
||||
pub fixed: Tally,
|
||||
pub mutable: Tally,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize)]
|
||||
pub struct HemisphereTally {
|
||||
pub above_horizon: Tally,
|
||||
pub below_horizon: Tally,
|
||||
pub eastern: Tally,
|
||||
pub western: Tally,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct RulerInfo {
|
||||
pub planet: PointId,
|
||||
pub sign: ZodiacSign,
|
||||
pub house: Option<u8>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct ChartRuler {
|
||||
pub ascendant_sign: ZodiacSign,
|
||||
pub traditional: RulerInfo,
|
||||
pub modern: RulerInfo,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Summary {
|
||||
/// Counted over the ten planets (Sun..Pluto).
|
||||
pub elements: ElementTally,
|
||||
pub modalities: ModalityTally,
|
||||
pub hemispheres: Option<HemisphereTally>,
|
||||
pub sect: Option<Sect>,
|
||||
pub chart_ruler: Option<ChartRuler>,
|
||||
pub retrograde: Vec<PointId>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Astronomy {
|
||||
pub julian_day_ut: f64,
|
||||
pub julian_day_tt: f64,
|
||||
pub delta_t_seconds: f64,
|
||||
/// Greenwich apparent sidereal time.
|
||||
pub greenwich_sidereal_time: f64,
|
||||
pub greenwich_sidereal_time_hms: String,
|
||||
/// Local apparent sidereal time.
|
||||
pub local_sidereal_time: f64,
|
||||
pub local_sidereal_time_hms: String,
|
||||
pub obliquity: Obliquity,
|
||||
/// Ayanamsa in degrees (sidereal zodiac only).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub ayanamsa: Option<f64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Settings {
|
||||
#[serde(flatten)]
|
||||
pub options: ChartOptions,
|
||||
pub orbs: Vec<OrbEntry>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct NatalChart {
|
||||
pub settings: Settings,
|
||||
pub astronomy: Astronomy,
|
||||
pub points: Vec<Point>,
|
||||
pub angles: Option<Angles>,
|
||||
pub houses: Option<Houses>,
|
||||
pub aspects: Vec<Aspect>,
|
||||
pub lots: Option<Lots>,
|
||||
pub moon_phase: MoonPhase,
|
||||
pub summary: Summary,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// Builds a complete natal chart.
|
||||
pub fn calculate_chart(engine: &dyn Ephemeris, input: &ChartInput) -> Result<NatalChart, EngineError> {
|
||||
let opts = input.options;
|
||||
let jd = input.jd_ut;
|
||||
let mut warnings = Vec::new();
|
||||
|
||||
let sidereal = (opts.zodiac == ZodiacType::Sidereal).then_some(opts.ayanamsa);
|
||||
let frame = Frame { sidereal, topocentric: opts.topocentric.then_some(input.observer) };
|
||||
|
||||
// --- astronomy -----------------------------------------------------------
|
||||
let delta_t = engine.delta_t(jd);
|
||||
let obliquity = engine.obliquity(jd)?;
|
||||
let gast = engine.sidereal_time(jd);
|
||||
let last = (gast + input.observer.longitude / 15.0).rem_euclid(24.0);
|
||||
let astronomy = Astronomy {
|
||||
julian_day_ut: jd,
|
||||
julian_day_tt: jd + delta_t,
|
||||
delta_t_seconds: delta_t * 86_400.0,
|
||||
greenwich_sidereal_time: gast,
|
||||
greenwich_sidereal_time_hms: angle::hms(gast),
|
||||
local_sidereal_time: last,
|
||||
local_sidereal_time_hms: angle::hms(last),
|
||||
obliquity,
|
||||
ayanamsa: sidereal.map(|a| engine.ayanamsa(jd, a)).transpose()?,
|
||||
};
|
||||
|
||||
// --- houses and angles ---------------------------------------------------
|
||||
let house_result = if input.time_known {
|
||||
let h = engine.houses(jd, &input.observer, opts.house_system, &frame)?;
|
||||
if let Some(reason) = &h.fallback_reason {
|
||||
warnings.push(format!("{reason}; {:?} houses were used instead", h.used));
|
||||
}
|
||||
Some(h)
|
||||
} else {
|
||||
warnings.push(
|
||||
"Birth time unknown: the chart is calculated for 12:00 local time; houses, angles and lots are omitted \
|
||||
and the Moon may be off by up to ±7°."
|
||||
.into(),
|
||||
);
|
||||
None
|
||||
};
|
||||
|
||||
// --- bodies --------------------------------------------------------------
|
||||
let node_body = match opts.node_type {
|
||||
NodeType::True => Body::TrueNode,
|
||||
NodeType::Mean => Body::MeanNode,
|
||||
};
|
||||
let lilith_body = match opts.lilith_type {
|
||||
LilithType::Mean => Body::MeanLilith,
|
||||
LilithType::True => Body::TrueLilith,
|
||||
};
|
||||
let mut bodies: Vec<Body> = Body::PLANETS.to_vec();
|
||||
bodies.extend([node_body, lilith_body, Body::Chiron]);
|
||||
if opts.include_asteroids {
|
||||
bodies.extend(Body::ASTEROIDS);
|
||||
}
|
||||
|
||||
let mut points = Vec::with_capacity(bodies.len() + 1);
|
||||
let mut degraded = Vec::new();
|
||||
for body in bodies {
|
||||
let state = match engine.position(body, jd, &frame) {
|
||||
Ok(s) => s,
|
||||
// Chiron and the asteroids need data files that may not cover the date.
|
||||
Err(e) if matches!(body, Body::Chiron) || Body::ASTEROIDS.contains(&body) => {
|
||||
warnings.push(format!("{body:?} omitted: {e}"));
|
||||
continue;
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
if state.degraded_precision {
|
||||
degraded.push(format!("{body:?}"));
|
||||
}
|
||||
let point = make_point(body, &state, &obliquity, house_result.as_ref());
|
||||
let is_node = matches!(body, Body::TrueNode | Body::MeanNode);
|
||||
points.push(point);
|
||||
if is_node {
|
||||
points.push(south_node(points.last().expect("just pushed"), house_result.as_ref()));
|
||||
}
|
||||
}
|
||||
if !degraded.is_empty() {
|
||||
warnings.push(format!(
|
||||
"No ephemeris data file covers this date; reduced-precision analytical ephemeris used for: {}",
|
||||
degraded.join(", ")
|
||||
));
|
||||
}
|
||||
|
||||
// --- angles --------------------------------------------------------------
|
||||
let angles = house_result.as_ref().map(|h| Angles {
|
||||
ascendant: AnglePoint::new(h.ascendant, Some(h.ascendant_speed)),
|
||||
midheaven: AnglePoint::new(h.midheaven, Some(h.midheaven_speed)),
|
||||
descendant: AnglePoint::new(h.ascendant + 180.0, Some(h.ascendant_speed)),
|
||||
imum_coeli: AnglePoint::new(h.midheaven + 180.0, Some(h.midheaven_speed)),
|
||||
vertex: AnglePoint::new(h.vertex, Some(h.vertex_speed)),
|
||||
antivertex: AnglePoint::new(h.vertex + 180.0, Some(h.vertex_speed)),
|
||||
east_point: AnglePoint::new(h.equatorial_ascendant, None),
|
||||
armc: h.armc,
|
||||
});
|
||||
let houses = house_result.as_ref().map(|h| Houses {
|
||||
system: h.used,
|
||||
requested_system: h.requested,
|
||||
fallback_reason: h.fallback_reason.clone(),
|
||||
cusps: (0..12)
|
||||
.map(|i| HouseCusp {
|
||||
house: i as u8 + 1,
|
||||
position: ZodiacPosition::new(h.cusps[i]),
|
||||
size: angle::arc(h.cusps[i], h.cusps[(i + 1) % 12]),
|
||||
})
|
||||
.collect(),
|
||||
});
|
||||
|
||||
// --- aspects -------------------------------------------------------------
|
||||
let aspects = find_aspects(&aspect_points(&points, angles.as_ref()), opts.aspect_set, opts.orb_multiplier);
|
||||
|
||||
// --- sun / moon derived data --------------------------------------------
|
||||
let lon_of = |id: PointId| points.iter().find(|p| p.id == id).map(|p| p.position.longitude);
|
||||
let sun = lon_of(PointId::Sun).expect("sun is always calculated");
|
||||
let moon = lon_of(PointId::Moon).expect("moon is always calculated");
|
||||
|
||||
let elongation = normalize(moon - sun);
|
||||
let moon_phase = MoonPhase {
|
||||
elongation,
|
||||
phase: phase_name(elongation),
|
||||
illumination: engine.illumination(Body::Moon, jd)?,
|
||||
waxing: elongation < 180.0,
|
||||
};
|
||||
|
||||
let sect = house_result.as_ref().map(|h| if above_horizon(sun, h.ascendant) { Sect::Day } else { Sect::Night });
|
||||
let lots = house_result.as_ref().zip(sect).map(|(h, sect)| {
|
||||
let (fortune, spirit) = match sect {
|
||||
Sect::Day => (h.ascendant + moon - sun, h.ascendant + sun - moon),
|
||||
Sect::Night => (h.ascendant + sun - moon, h.ascendant + moon - sun),
|
||||
};
|
||||
let lot = |lon: f64| Lot { position: ZodiacPosition::new(lon), house: house_of(normalize(lon), &h.cusps) };
|
||||
Lots { fortune: lot(fortune), spirit: lot(spirit) }
|
||||
});
|
||||
|
||||
let summary = summarize(&points, house_result.as_ref(), sect);
|
||||
|
||||
Ok(NatalChart {
|
||||
settings: Settings { options: opts, orbs: orb_table(opts.aspect_set, opts.orb_multiplier) },
|
||||
astronomy,
|
||||
points,
|
||||
angles,
|
||||
houses,
|
||||
aspects,
|
||||
lots,
|
||||
moon_phase,
|
||||
summary,
|
||||
warnings,
|
||||
})
|
||||
}
|
||||
|
||||
fn point_kind(body: Body) -> PointKind {
|
||||
match body {
|
||||
Body::Sun | Body::Moon => PointKind::Luminary,
|
||||
Body::MeanNode | Body::TrueNode => PointKind::LunarNode,
|
||||
Body::MeanLilith | Body::TrueLilith => PointKind::LunarApogee,
|
||||
Body::Chiron => PointKind::Centaur,
|
||||
Body::Ceres | Body::Pallas | Body::Juno | Body::Vesta => PointKind::Asteroid,
|
||||
_ => PointKind::Planet,
|
||||
}
|
||||
}
|
||||
|
||||
fn variant(body: Body) -> Option<&'static str> {
|
||||
match body {
|
||||
Body::TrueNode | Body::TrueLilith => Some("true"),
|
||||
Body::MeanNode | Body::MeanLilith => Some("mean"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn make_point(body: Body, s: &BodyState, obl: &Obliquity, houses: Option<&HouseResult>) -> Point {
|
||||
let position = ZodiacPosition::new(s.longitude);
|
||||
let sign = position.sign;
|
||||
Point {
|
||||
id: PointId::from_planet(body),
|
||||
kind: point_kind(body),
|
||||
variant: variant(body),
|
||||
house: houses.map(|h| house_of(s.longitude, &h.cusps)),
|
||||
position,
|
||||
latitude: s.latitude,
|
||||
distance_au: s.distance,
|
||||
speed: s.speed_longitude,
|
||||
retrograde: s.speed_longitude < 0.0,
|
||||
right_ascension: s.right_ascension,
|
||||
declination: s.declination,
|
||||
out_of_bounds: s.declination.abs() > obl.true_obliquity,
|
||||
dignities: body.is_planet().then(|| dignities(body, sign)),
|
||||
}
|
||||
}
|
||||
|
||||
/// South node: the point opposite the north node (antipodal on the sphere).
|
||||
fn south_node(north: &Point, houses: Option<&HouseResult>) -> Point {
|
||||
let lon = normalize(north.position.longitude + 180.0);
|
||||
Point {
|
||||
id: PointId::SouthNode,
|
||||
position: ZodiacPosition::new(lon),
|
||||
latitude: -north.latitude,
|
||||
right_ascension: normalize(north.right_ascension + 180.0),
|
||||
declination: -north.declination,
|
||||
house: houses.map(|h| house_of(lon, &h.cusps)),
|
||||
..north.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// House (1..=12) containing an ecliptic longitude.
|
||||
pub fn house_of(lon: f64, cusps: &[f64; 12]) -> u8 {
|
||||
for i in 0..12 {
|
||||
let start = cusps[i];
|
||||
let end = cusps[(i + 1) % 12];
|
||||
let width = angle::arc(start, end);
|
||||
if angle::arc(start, lon) < width {
|
||||
return i as u8 + 1;
|
||||
}
|
||||
}
|
||||
// Only reachable with degenerate cusps (all equal); fall back to house 1.
|
||||
1
|
||||
}
|
||||
|
||||
/// Whether an ecliptic point is above the horizon: houses 7..12 lie on the
|
||||
/// ecliptic arc from the descendant to the ascendant.
|
||||
fn above_horizon(lon: f64, ascendant: f64) -> bool {
|
||||
angle::arc(ascendant, lon) >= 180.0
|
||||
}
|
||||
|
||||
fn phase_name(elongation: f64) -> MoonPhaseName {
|
||||
use MoonPhaseName::*;
|
||||
[NewMoon, WaxingCrescent, FirstQuarter, WaxingGibbous, FullMoon, WaningGibbous, LastQuarter, WaningCrescent]
|
||||
[((elongation / 45.0).floor() as usize).min(7)]
|
||||
}
|
||||
|
||||
/// Points taking part in aspects as `(id, longitude, speed)`: everything but
|
||||
/// the asteroids and the south node (it mirrors the north node), plus the
|
||||
/// ascendant and the midheaven when known.
|
||||
pub(crate) fn aspect_points(points: &[Point], angles: Option<&Angles>) -> Vec<(PointId, f64, f64)> {
|
||||
let mut out: Vec<(PointId, f64, f64)> = points
|
||||
.iter()
|
||||
.filter(|p| !matches!(p.kind, PointKind::Asteroid) && p.id != PointId::SouthNode)
|
||||
.map(|p| (p.id, p.position.longitude, p.speed))
|
||||
.collect();
|
||||
if let Some(a) = angles {
|
||||
out.push((PointId::Ascendant, a.ascendant.position.longitude, a.ascendant.speed.unwrap_or(0.0)));
|
||||
out.push((PointId::Midheaven, a.midheaven.position.longitude, a.midheaven.speed.unwrap_or(0.0)));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub(crate) fn aspect_kinds(set: AspectSet) -> Vec<AspectKind> {
|
||||
let mut kinds = AspectKind::MAJOR.to_vec();
|
||||
if set == AspectSet::Extended {
|
||||
kinds.extend(AspectKind::MINOR);
|
||||
}
|
||||
kinds
|
||||
}
|
||||
|
||||
pub(crate) fn orb_table(set: AspectSet, multiplier: f64) -> Vec<OrbEntry> {
|
||||
aspect_kinds(set)
|
||||
.into_iter()
|
||||
.map(|k| OrbEntry {
|
||||
aspect: k,
|
||||
angle: k.angle(),
|
||||
orb: k.orb_for(PointId::Mars, PointId::Venus, multiplier),
|
||||
orb_with_luminary: k.orb_for(PointId::Sun, PointId::Venus, multiplier),
|
||||
orb_with_minor_point: k.orb_for(PointId::NorthNode, PointId::Venus, multiplier),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The tightest aspect within orb between two points: `(kind, orb, max_orb)`.
|
||||
pub(crate) fn best_aspect(
|
||||
kinds: &[AspectKind],
|
||||
(id1, lon1): (PointId, f64),
|
||||
(id2, lon2): (PointId, f64),
|
||||
multiplier: f64,
|
||||
) -> Option<(AspectKind, f64, f64)> {
|
||||
let sep = separation(lon1, lon2);
|
||||
kinds
|
||||
.iter()
|
||||
.map(|&k| (k, (sep - k.angle()).abs(), k.orb_for(id1, id2, multiplier)))
|
||||
.filter(|&(_, orb, max)| orb <= max)
|
||||
.min_by(|a, b| a.1.total_cmp(&b.1))
|
||||
}
|
||||
|
||||
/// Finds the tightest matching aspect for every pair of points.
|
||||
pub(crate) fn find_aspects(points: &[(PointId, f64, f64)], set: AspectSet, multiplier: f64) -> Vec<Aspect> {
|
||||
const DT: f64 = 1.0 / 1440.0; // one minute, in days
|
||||
let kinds = aspect_kinds(set);
|
||||
let mut out = Vec::new();
|
||||
for (i, &(id1, lon1, speed1)) in points.iter().enumerate() {
|
||||
for &(id2, lon2, speed2) in &points[i + 1..] {
|
||||
let sep = separation(lon1, lon2);
|
||||
let Some((kind, orb, max_orb)) = best_aspect(&kinds, (id1, lon1), (id2, lon2), multiplier) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let applying = (speed1 != 0.0 || speed2 != 0.0).then(|| {
|
||||
let later = separation(lon1 + speed1 * DT, lon2 + speed2 * DT);
|
||||
(later - kind.angle()).abs() < orb
|
||||
});
|
||||
out.push(Aspect {
|
||||
point1: id1,
|
||||
point2: id2,
|
||||
aspect: kind,
|
||||
major: kind.is_major(),
|
||||
exact_angle: kind.angle(),
|
||||
separation: sep,
|
||||
orb,
|
||||
max_orb,
|
||||
applying,
|
||||
});
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| a.orb.total_cmp(&b.orb));
|
||||
out
|
||||
}
|
||||
|
||||
fn summarize(points: &[Point], houses: Option<&HouseResult>, sect: Option<Sect>) -> Summary {
|
||||
let mut elements = ElementTally::default();
|
||||
let mut modalities = ModalityTally::default();
|
||||
let mut hemispheres = houses.map(|_| HemisphereTally::default());
|
||||
|
||||
for p in points.iter().filter(|p| matches!(p.kind, PointKind::Luminary | PointKind::Planet)) {
|
||||
match p.position.sign.element() {
|
||||
Element::Fire => elements.fire.add(p.id),
|
||||
Element::Earth => elements.earth.add(p.id),
|
||||
Element::Air => elements.air.add(p.id),
|
||||
Element::Water => elements.water.add(p.id),
|
||||
}
|
||||
match p.position.sign.modality() {
|
||||
Modality::Cardinal => modalities.cardinal.add(p.id),
|
||||
Modality::Fixed => modalities.fixed.add(p.id),
|
||||
Modality::Mutable => modalities.mutable.add(p.id),
|
||||
}
|
||||
if let (Some(t), Some(h)) = (hemispheres.as_mut(), houses) {
|
||||
let lon = p.position.longitude;
|
||||
if above_horizon(lon, h.ascendant) {
|
||||
t.above_horizon.add(p.id)
|
||||
} else {
|
||||
t.below_horizon.add(p.id)
|
||||
}
|
||||
// Eastern half: from the MC through the ascendant to the IC.
|
||||
if angle::arc(h.midheaven, lon) < 180.0 { t.eastern.add(p.id) } else { t.western.add(p.id) }
|
||||
}
|
||||
}
|
||||
|
||||
let chart_ruler = houses.map(|h| {
|
||||
let asc_sign = ZodiacSign::from_longitude(h.ascendant);
|
||||
let info = |body: Body| {
|
||||
let id = PointId::from_planet(body);
|
||||
let p = points.iter().find(|p| p.id == id).expect("rulers are always calculated");
|
||||
RulerInfo { planet: id, sign: p.position.sign, house: p.house }
|
||||
};
|
||||
ChartRuler {
|
||||
ascendant_sign: asc_sign,
|
||||
traditional: info(asc_sign.traditional_ruler()),
|
||||
modern: info(asc_sign.modern_ruler()),
|
||||
}
|
||||
});
|
||||
|
||||
Summary {
|
||||
elements,
|
||||
modalities,
|
||||
hemispheres,
|
||||
sect,
|
||||
chart_ruler,
|
||||
retrograde: points
|
||||
.iter()
|
||||
.filter(|p| p.retrograde && !matches!(p.kind, PointKind::LunarNode | PointKind::LunarApogee))
|
||||
.map(|p| p.id)
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn house_lookup_wraps_around_aries() {
|
||||
// Cusps crossing 0° Aries between house 3 and 4.
|
||||
let cusps = [270.0, 300.0, 330.0, 10.0, 40.0, 70.0, 90.0, 120.0, 150.0, 190.0, 220.0, 250.0];
|
||||
assert_eq!(house_of(275.0, &cusps), 1);
|
||||
assert_eq!(house_of(359.0, &cusps), 3);
|
||||
assert_eq!(house_of(5.0, &cusps), 3);
|
||||
assert_eq!(house_of(10.0, &cusps), 4);
|
||||
assert_eq!(house_of(269.9, &cusps), 12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn horizon_and_phase() {
|
||||
// Ascendant at 0° Aries: Cancer (90°) is below (IC side), Capricorn (270°) above.
|
||||
assert!(!above_horizon(90.0, 0.0));
|
||||
assert!(above_horizon(270.0, 0.0));
|
||||
assert_eq!(phase_name(0.0), MoonPhaseName::NewMoon);
|
||||
assert_eq!(phase_name(185.0), MoonPhaseName::FullMoon);
|
||||
assert_eq!(phase_name(359.9), MoonPhaseName::WaningCrescent);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aspects_choose_tightest_and_detect_applying() {
|
||||
let pts = [
|
||||
(PointId::Sun, 10.0, 1.0),
|
||||
(PointId::Moon, 132.0, 13.0), // trine, orb 2, separation growing past 120
|
||||
(PointId::Mars, 100.5, 0.5), // square to Sun, orb 0.5
|
||||
];
|
||||
let aspects = find_aspects(&pts, AspectSet::Major, 1.0);
|
||||
let sun_mars = aspects.iter().find(|a| a.point2 == PointId::Mars && a.point1 == PointId::Sun).unwrap();
|
||||
assert_eq!(sun_mars.aspect, AspectKind::Square);
|
||||
assert!((sun_mars.orb - 0.5).abs() < 1e-9);
|
||||
assert_eq!(sun_mars.applying, Some(true)); // faster Sun closes the 90.5° gap
|
||||
let sun_moon = aspects.iter().find(|a| a.point2 == PointId::Moon).unwrap();
|
||||
assert_eq!(sun_moon.aspect, AspectKind::Trine);
|
||||
assert_eq!(sun_moon.applying, Some(false));
|
||||
// sorted by orb
|
||||
assert!(aspects.windows(2).all(|w| w[0].orb <= w[1].orb));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn minor_points_get_small_orbs() {
|
||||
assert_eq!(AspectKind::Conjunction.orb_for(PointId::Sun, PointId::Moon, 1.0), 10.0);
|
||||
assert_eq!(AspectKind::Conjunction.orb_for(PointId::Sun, PointId::NorthNode, 1.0), 4.0);
|
||||
assert_eq!(AspectKind::Quincunx.orb_for(PointId::Mars, PointId::Lilith, 1.0), 1.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
//! The replaceable astronomical backend.
|
||||
//!
|
||||
//! Everything the chart logic needs from an ephemeris is behind the
|
||||
//! [`Ephemeris`] trait. A new engine (e.g. one based on JPL DE440 in pure Rust)
|
||||
//! only has to implement this trait.
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::types::{Ayanamsa, Body, HouseSystem};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum EngineError {
|
||||
#[error("{0}")]
|
||||
Calculation(String),
|
||||
#[error("ephemeris engine is not available: {0}")]
|
||||
Unavailable(String),
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, EngineError>;
|
||||
|
||||
/// Geographic observer position.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
|
||||
pub struct GeoPosition {
|
||||
/// Degrees, north positive.
|
||||
pub latitude: f64,
|
||||
/// Degrees, east positive.
|
||||
pub longitude: f64,
|
||||
/// Meters above sea level.
|
||||
pub elevation: f64,
|
||||
}
|
||||
|
||||
/// Reference frame of ecliptic positions.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Frame {
|
||||
/// `None` = tropical zodiac, `Some` = sidereal zodiac with this ayanamsa.
|
||||
pub sidereal: Option<Ayanamsa>,
|
||||
/// `Some` = topocentric positions for this observer, `None` = geocentric.
|
||||
pub topocentric: Option<GeoPosition>,
|
||||
}
|
||||
|
||||
impl Frame {
|
||||
pub const TROPICAL_GEOCENTRIC: Frame = Frame { sidereal: None, topocentric: None };
|
||||
}
|
||||
|
||||
/// Position and motion of a body.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct BodyState {
|
||||
/// Ecliptic longitude, degrees `[0, 360)`.
|
||||
pub longitude: f64,
|
||||
/// Ecliptic latitude, degrees.
|
||||
pub latitude: f64,
|
||||
/// Distance in AU.
|
||||
pub distance: f64,
|
||||
/// Daily motion in longitude, degrees/day (negative = retrograde).
|
||||
pub speed_longitude: f64,
|
||||
pub speed_latitude: f64,
|
||||
pub speed_distance: f64,
|
||||
/// Right ascension (equator of date), degrees.
|
||||
pub right_ascension: f64,
|
||||
/// Declination (equator of date), degrees.
|
||||
pub declination: f64,
|
||||
/// The engine had to fall back to a less precise method (e.g. a data file
|
||||
/// does not cover the date).
|
||||
pub degraded_precision: bool,
|
||||
}
|
||||
|
||||
/// House cusps and angles.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct HouseResult {
|
||||
pub requested: HouseSystem,
|
||||
/// System actually used (differs from `requested` when the requested one is
|
||||
/// undefined at the given latitude and the engine fell back).
|
||||
pub used: HouseSystem,
|
||||
pub fallback_reason: Option<String>,
|
||||
/// Cusps of houses 1..=12, degrees.
|
||||
pub cusps: [f64; 12],
|
||||
pub ascendant: f64,
|
||||
pub midheaven: f64,
|
||||
/// Right ascension of the MC (sidereal time in degrees).
|
||||
pub armc: f64,
|
||||
pub vertex: f64,
|
||||
pub equatorial_ascendant: f64,
|
||||
pub co_ascendant_koch: f64,
|
||||
pub co_ascendant_munkasey: f64,
|
||||
pub polar_ascendant: f64,
|
||||
/// Daily motion of the ascendant / MC / vertex, degrees/day.
|
||||
pub ascendant_speed: f64,
|
||||
pub midheaven_speed: f64,
|
||||
pub vertex_speed: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
|
||||
pub struct Obliquity {
|
||||
/// True obliquity of the ecliptic (with nutation), degrees.
|
||||
pub true_obliquity: f64,
|
||||
pub mean_obliquity: f64,
|
||||
/// Nutation in longitude, degrees.
|
||||
pub nutation_longitude: f64,
|
||||
/// Nutation in obliquity, degrees.
|
||||
pub nutation_obliquity: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct EphemerisInfo {
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
/// Years covered with full precision (data files), if limited.
|
||||
pub precise_years: Option<(i32, i32)>,
|
||||
pub license: String,
|
||||
}
|
||||
|
||||
pub trait Ephemeris: Send + Sync {
|
||||
fn info(&self) -> EphemerisInfo;
|
||||
|
||||
/// Delta T (TT - UT) in days.
|
||||
fn delta_t(&self, jd_ut: f64) -> f64;
|
||||
|
||||
/// Greenwich apparent sidereal time, hours.
|
||||
fn sidereal_time(&self, jd_ut: f64) -> f64;
|
||||
|
||||
fn obliquity(&self, jd_ut: f64) -> Result<Obliquity>;
|
||||
|
||||
fn position(&self, body: Body, jd_ut: f64, frame: &Frame) -> Result<BodyState>;
|
||||
|
||||
fn houses(&self, jd_ut: f64, observer: &GeoPosition, system: HouseSystem, frame: &Frame) -> Result<HouseResult>;
|
||||
|
||||
/// Illuminated fraction of the body's disc (0..1).
|
||||
fn illumination(&self, body: Body, jd_ut: f64) -> Result<f64>;
|
||||
|
||||
/// Ayanamsa value in degrees.
|
||||
fn ayanamsa(&self, jd_ut: f64, ayanamsa: Ayanamsa) -> Result<f64>;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
//! Natal chart calculation.
|
||||
//!
|
||||
//! The astronomical work is done by an [`Ephemeris`] implementation (currently
|
||||
//! Swiss Ephemeris, see [`swiss::SwissEphemeris`]); everything astrological on
|
||||
//! top of it (signs, houses, aspects, dignities, lots, summaries) lives in
|
||||
//! [`chart`] and is independent of the engine, so the engine can be replaced
|
||||
//! without touching the chart logic. [`synastry`] compares two charts.
|
||||
|
||||
pub mod angle;
|
||||
pub mod chart;
|
||||
pub mod engine;
|
||||
pub mod synastry;
|
||||
pub mod time;
|
||||
pub mod types;
|
||||
|
||||
#[cfg(feature = "swisseph")]
|
||||
pub mod swiss;
|
||||
|
||||
pub use chart::{ChartInput, ChartOptions, NatalChart, calculate_chart};
|
||||
pub use engine::{BodyState, EngineError, Ephemeris, EphemerisInfo, Frame, GeoPosition, HouseResult, Obliquity};
|
||||
pub use synastry::{Synastry, calculate_synastry};
|
||||
pub use types::{AspectSet, Ayanamsa, Body, HouseSystem, LilithType, NodeType, ZodiacSign, ZodiacType};
|
||||
@@ -0,0 +1,343 @@
|
||||
//! [`Ephemeris`] implementation backed by the Swiss Ephemeris C library.
|
||||
//!
|
||||
//! The C library keeps process-wide state (ephemeris path, sidereal mode,
|
||||
//! observer position, open files), so all calls go through one global lock.
|
||||
//! A chart needs a few dozen calls of microseconds each, so the lock is not a
|
||||
//! bottleneck for an HTTP service.
|
||||
|
||||
use std::ffi::{CStr, CString};
|
||||
use std::os::raw::c_char;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Mutex, MutexGuard, OnceLock};
|
||||
|
||||
use swisseph_sys as sys;
|
||||
|
||||
use crate::angle::normalize;
|
||||
use crate::engine::{
|
||||
BodyState, EngineError, Ephemeris, EphemerisInfo, Frame, GeoPosition, HouseResult, Obliquity, Result,
|
||||
};
|
||||
use crate::types::{Ayanamsa, Body, HouseSystem};
|
||||
|
||||
static LOCK: Mutex<()> = Mutex::new(());
|
||||
static EPHE_PATH: OnceLock<PathBuf> = OnceLock::new();
|
||||
|
||||
pub struct SwissEphemeris {
|
||||
precise_years: Option<(i32, i32)>,
|
||||
version: String,
|
||||
}
|
||||
|
||||
impl SwissEphemeris {
|
||||
/// Initializes the library with the directory holding the `*.se1` files.
|
||||
/// The library is process-global: only one path can be used per process.
|
||||
pub fn new(ephe_dir: impl AsRef<Path>) -> Result<Self> {
|
||||
let dir = ephe_dir.as_ref().to_path_buf();
|
||||
if !dir.is_dir() {
|
||||
return Err(EngineError::Unavailable(format!("ephemeris directory {} does not exist", dir.display())));
|
||||
}
|
||||
let first = EPHE_PATH.get_or_init(|| dir.clone());
|
||||
if *first != dir {
|
||||
return Err(EngineError::Unavailable(format!(
|
||||
"Swiss Ephemeris already initialized with {}",
|
||||
first.display()
|
||||
)));
|
||||
}
|
||||
let c_path = CString::new(dir.to_string_lossy().as_bytes())
|
||||
.map_err(|_| EngineError::Unavailable("ephemeris path contains a NUL byte".into()))?;
|
||||
let version = {
|
||||
let _guard = lock();
|
||||
let mut buf = [0 as c_char; sys::AS_MAXCH];
|
||||
// SAFETY: valid NUL-terminated path; buffers sized AS_MAXCH as required.
|
||||
unsafe {
|
||||
sys::swe_set_ephe_path(c_path.as_ptr());
|
||||
sys::swe_version(buf.as_mut_ptr());
|
||||
}
|
||||
c_string(&buf)
|
||||
};
|
||||
Ok(Self { precise_years: planet_file_coverage(&dir), version })
|
||||
}
|
||||
}
|
||||
|
||||
fn lock() -> MutexGuard<'static, ()> {
|
||||
// A panic while holding the lock cannot leave the C state inconsistent in
|
||||
// a way that matters for subsequent independent calls.
|
||||
LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
}
|
||||
|
||||
fn c_string(buf: &[c_char]) -> String {
|
||||
// SAFETY: the library always NUL-terminates within AS_MAXCH; the buffer is
|
||||
// zero-initialized so a terminator exists even if nothing was written.
|
||||
unsafe { CStr::from_ptr(buf.as_ptr()) }.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// Year range covered by the planetary files (`sepl_18.se1` = 1800..2399,
|
||||
/// `seplm06.se1` = 600 BC..1 BC, ...).
|
||||
fn planet_file_coverage(dir: &Path) -> Option<(i32, i32)> {
|
||||
let mut range: Option<(i32, i32)> = None;
|
||||
for entry in std::fs::read_dir(dir).ok()?.flatten() {
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
let Some(rest) = name.strip_prefix("sepl").and_then(|r| r.strip_suffix(".se1")) else { continue };
|
||||
let (negative, digits) = match rest.strip_prefix('m') {
|
||||
Some(d) => (true, d),
|
||||
None => (false, rest.trim_start_matches('_')),
|
||||
};
|
||||
let Ok(century) = digits.parse::<i32>() else { continue };
|
||||
let start = if negative { -century * 100 } else { century * 100 };
|
||||
let end = start + 599;
|
||||
range = Some(match range {
|
||||
Some((lo, hi)) => (lo.min(start), hi.max(end)),
|
||||
None => (start, end),
|
||||
});
|
||||
}
|
||||
range
|
||||
}
|
||||
|
||||
fn body_id(body: Body) -> i32 {
|
||||
match body {
|
||||
Body::Sun => sys::SE_SUN,
|
||||
Body::Moon => sys::SE_MOON,
|
||||
Body::Mercury => sys::SE_MERCURY,
|
||||
Body::Venus => sys::SE_VENUS,
|
||||
Body::Mars => sys::SE_MARS,
|
||||
Body::Jupiter => sys::SE_JUPITER,
|
||||
Body::Saturn => sys::SE_SATURN,
|
||||
Body::Uranus => sys::SE_URANUS,
|
||||
Body::Neptune => sys::SE_NEPTUNE,
|
||||
Body::Pluto => sys::SE_PLUTO,
|
||||
Body::MeanNode => sys::SE_MEAN_NODE,
|
||||
Body::TrueNode => sys::SE_TRUE_NODE,
|
||||
Body::MeanLilith => sys::SE_MEAN_APOG,
|
||||
Body::TrueLilith => sys::SE_OSCU_APOG,
|
||||
Body::Chiron => sys::SE_CHIRON,
|
||||
Body::Ceres => sys::SE_CERES,
|
||||
Body::Pallas => sys::SE_PALLAS,
|
||||
Body::Juno => sys::SE_JUNO,
|
||||
Body::Vesta => sys::SE_VESTA,
|
||||
}
|
||||
}
|
||||
|
||||
fn sid_mode(ayanamsa: Ayanamsa) -> i32 {
|
||||
match ayanamsa {
|
||||
Ayanamsa::Lahiri => sys::SE_SIDM_LAHIRI,
|
||||
Ayanamsa::FaganBradley => sys::SE_SIDM_FAGAN_BRADLEY,
|
||||
Ayanamsa::Raman => sys::SE_SIDM_RAMAN,
|
||||
Ayanamsa::Krishnamurti => sys::SE_SIDM_KRISHNAMURTI,
|
||||
Ayanamsa::DeLuce => sys::SE_SIDM_DELUCE,
|
||||
Ayanamsa::Yukteshwar => sys::SE_SIDM_YUKTESHWAR,
|
||||
Ayanamsa::TrueCitra => sys::SE_SIDM_TRUE_CITRA,
|
||||
Ayanamsa::GalacticCenter0Sag => sys::SE_SIDM_GALCENT_0SAG,
|
||||
}
|
||||
}
|
||||
|
||||
fn house_code(system: HouseSystem) -> u8 {
|
||||
match system {
|
||||
HouseSystem::Placidus => b'P',
|
||||
HouseSystem::Koch => b'K',
|
||||
HouseSystem::Porphyry => b'O',
|
||||
HouseSystem::Regiomontanus => b'R',
|
||||
HouseSystem::Campanus => b'C',
|
||||
HouseSystem::Equal => b'E',
|
||||
HouseSystem::WholeSign => b'W',
|
||||
HouseSystem::Alcabitius => b'B',
|
||||
HouseSystem::Morinus => b'M',
|
||||
HouseSystem::Topocentric => b'T',
|
||||
HouseSystem::Meridian => b'X',
|
||||
HouseSystem::Vehlow => b'V',
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies the frame to the C library state and returns the matching flags.
|
||||
/// Must be called with the lock held.
|
||||
fn apply_frame(frame: &Frame) -> i32 {
|
||||
let mut flags = 0;
|
||||
if let Some(ayanamsa) = frame.sidereal {
|
||||
// SAFETY: plain value arguments.
|
||||
unsafe { sys::swe_set_sid_mode(sid_mode(ayanamsa), 0.0, 0.0) };
|
||||
flags |= sys::SEFLG_SIDEREAL;
|
||||
}
|
||||
if let Some(obs) = frame.topocentric {
|
||||
// SAFETY: plain value arguments.
|
||||
unsafe { sys::swe_set_topo(obs.longitude, obs.latitude, obs.elevation) };
|
||||
flags |= sys::SEFLG_TOPOCTR;
|
||||
}
|
||||
flags
|
||||
}
|
||||
|
||||
/// One `swe_calc_ut` call; returns the 6 result values and the returned flags.
|
||||
/// Must be called with the lock held.
|
||||
fn calc(jd_ut: f64, ipl: i32, flags: i32) -> Result<([f64; 6], i32)> {
|
||||
let mut xx = [0.0f64; 6];
|
||||
let mut serr = [0 as c_char; sys::AS_MAXCH];
|
||||
// SAFETY: xx has the 6 elements and serr the AS_MAXCH bytes the API requires.
|
||||
let ret = unsafe { sys::swe_calc_ut(jd_ut, ipl, flags, xx.as_mut_ptr(), serr.as_mut_ptr()) };
|
||||
if ret == sys::ERR {
|
||||
return Err(EngineError::Calculation(c_string(&serr)));
|
||||
}
|
||||
Ok((xx, ret))
|
||||
}
|
||||
|
||||
impl Ephemeris for SwissEphemeris {
|
||||
fn info(&self) -> EphemerisInfo {
|
||||
EphemerisInfo {
|
||||
name: "Swiss Ephemeris".into(),
|
||||
version: self.version.clone(),
|
||||
precise_years: self.precise_years,
|
||||
license: "AGPL-3.0 (or Swiss Ephemeris Professional License)".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn delta_t(&self, jd_ut: f64) -> f64 {
|
||||
let _guard = lock();
|
||||
let mut serr = [0 as c_char; sys::AS_MAXCH];
|
||||
// SAFETY: serr has AS_MAXCH bytes.
|
||||
unsafe { sys::swe_deltat_ex(jd_ut, sys::SEFLG_SWIEPH, serr.as_mut_ptr()) }
|
||||
}
|
||||
|
||||
fn sidereal_time(&self, jd_ut: f64) -> f64 {
|
||||
let _guard = lock();
|
||||
// SAFETY: plain value argument.
|
||||
unsafe { sys::swe_sidtime(jd_ut) }
|
||||
}
|
||||
|
||||
fn obliquity(&self, jd_ut: f64) -> Result<Obliquity> {
|
||||
let _guard = lock();
|
||||
let (xx, _) = calc(jd_ut, sys::SE_ECL_NUT, sys::SEFLG_SWIEPH)?;
|
||||
Ok(Obliquity {
|
||||
true_obliquity: xx[0],
|
||||
mean_obliquity: xx[1],
|
||||
nutation_longitude: xx[2],
|
||||
nutation_obliquity: xx[3],
|
||||
})
|
||||
}
|
||||
|
||||
fn position(&self, body: Body, jd_ut: f64, frame: &Frame) -> Result<BodyState> {
|
||||
let _guard = lock();
|
||||
let frame_flags = apply_frame(frame);
|
||||
let base = sys::SEFLG_SWIEPH | sys::SEFLG_SPEED;
|
||||
let ipl = body_id(body);
|
||||
|
||||
let (ecl, ret) = calc(jd_ut, ipl, base | frame_flags)?;
|
||||
// Equatorial coordinates are independent of the zodiac (no sidereal flag).
|
||||
let topo = frame_flags & sys::SEFLG_TOPOCTR;
|
||||
let (equ, _) = calc(jd_ut, ipl, base | topo | sys::SEFLG_EQUATORIAL)?;
|
||||
|
||||
Ok(BodyState {
|
||||
longitude: normalize(ecl[0]),
|
||||
latitude: ecl[1],
|
||||
distance: ecl[2],
|
||||
speed_longitude: ecl[3],
|
||||
speed_latitude: ecl[4],
|
||||
speed_distance: ecl[5],
|
||||
right_ascension: normalize(equ[0]),
|
||||
declination: equ[1],
|
||||
// The library silently switches to the Moshier ephemeris when no data
|
||||
// file covers the date.
|
||||
degraded_precision: ret & sys::SEFLG_MOSEPH != 0,
|
||||
})
|
||||
}
|
||||
|
||||
fn houses(&self, jd_ut: f64, observer: &GeoPosition, system: HouseSystem, frame: &Frame) -> Result<HouseResult> {
|
||||
let _guard = lock();
|
||||
// Houses are always geocentric; only the zodiac matters here.
|
||||
let flags = apply_frame(&Frame { sidereal: frame.sidereal, topocentric: None });
|
||||
// 37 slots: large enough even for the Gauquelin sectors.
|
||||
let mut cusps = [0.0f64; 37];
|
||||
let mut ascmc = [0.0f64; 10];
|
||||
let mut cusp_speed = [0.0f64; 37];
|
||||
let mut ascmc_speed = [0.0f64; 10];
|
||||
let mut serr = [0 as c_char; sys::AS_MAXCH];
|
||||
// SAFETY: all buffers are at least as large as the API requires.
|
||||
let ret = unsafe {
|
||||
sys::swe_houses_ex2(
|
||||
jd_ut,
|
||||
flags,
|
||||
observer.latitude,
|
||||
observer.longitude,
|
||||
house_code(system) as i32,
|
||||
cusps.as_mut_ptr(),
|
||||
ascmc.as_mut_ptr(),
|
||||
cusp_speed.as_mut_ptr(),
|
||||
ascmc_speed.as_mut_ptr(),
|
||||
serr.as_mut_ptr(),
|
||||
)
|
||||
};
|
||||
// On failure (quadrant systems inside the polar circles) the library
|
||||
// returns ERR and fills the cusps with Porphyry houses.
|
||||
let (used, fallback_reason) = if ret == sys::ERR {
|
||||
let msg = c_string(&serr);
|
||||
let reason = if msg.is_empty() {
|
||||
format!("{system:?} houses are undefined at latitude {:.2}°", observer.latitude)
|
||||
} else {
|
||||
msg
|
||||
};
|
||||
(HouseSystem::Porphyry, Some(reason))
|
||||
} else {
|
||||
(system, None)
|
||||
};
|
||||
|
||||
let mut out = [0.0f64; 12];
|
||||
for (i, c) in out.iter_mut().enumerate() {
|
||||
*c = normalize(cusps[i + 1]);
|
||||
}
|
||||
Ok(HouseResult {
|
||||
requested: system,
|
||||
used,
|
||||
fallback_reason,
|
||||
cusps: out,
|
||||
ascendant: normalize(ascmc[0]),
|
||||
midheaven: normalize(ascmc[1]),
|
||||
armc: normalize(ascmc[2]),
|
||||
vertex: normalize(ascmc[3]),
|
||||
equatorial_ascendant: normalize(ascmc[4]),
|
||||
co_ascendant_koch: normalize(ascmc[5]),
|
||||
co_ascendant_munkasey: normalize(ascmc[6]),
|
||||
polar_ascendant: normalize(ascmc[7]),
|
||||
ascendant_speed: ascmc_speed[0],
|
||||
midheaven_speed: ascmc_speed[1],
|
||||
vertex_speed: ascmc_speed[3],
|
||||
})
|
||||
}
|
||||
|
||||
fn illumination(&self, body: Body, jd_ut: f64) -> Result<f64> {
|
||||
let _guard = lock();
|
||||
let mut attr = [0.0f64; 20];
|
||||
let mut serr = [0 as c_char; sys::AS_MAXCH];
|
||||
// SAFETY: attr has the 20 elements the API requires.
|
||||
let ret =
|
||||
unsafe { sys::swe_pheno_ut(jd_ut, body_id(body), sys::SEFLG_SWIEPH, attr.as_mut_ptr(), serr.as_mut_ptr()) };
|
||||
if ret == sys::ERR {
|
||||
return Err(EngineError::Calculation(c_string(&serr)));
|
||||
}
|
||||
Ok(attr[1])
|
||||
}
|
||||
|
||||
fn ayanamsa(&self, jd_ut: f64, ayanamsa: Ayanamsa) -> Result<f64> {
|
||||
let _guard = lock();
|
||||
let mut daya = 0.0f64;
|
||||
let mut serr = [0 as c_char; sys::AS_MAXCH];
|
||||
// SAFETY: plain values and buffers of the required size.
|
||||
let ret = unsafe {
|
||||
sys::swe_set_sid_mode(sid_mode(ayanamsa), 0.0, 0.0);
|
||||
sys::swe_get_ayanamsa_ex_ut(jd_ut, sys::SEFLG_SWIEPH, &mut daya, serr.as_mut_ptr())
|
||||
};
|
||||
if ret == sys::ERR {
|
||||
return Err(EngineError::Calculation(c_string(&serr)));
|
||||
}
|
||||
Ok(daya)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn coverage_from_file_names() {
|
||||
let dir = std::env::temp_dir().join(format!("swe-cov-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
for f in ["sepl_18.se1", "sepl_12.se1", "semo_18.se1"] {
|
||||
std::fs::write(dir.join(f), b"").unwrap();
|
||||
}
|
||||
assert_eq!(planet_file_coverage(&dir), Some((1200, 2399)));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
//! Relationship charts built from two natal charts: synastry (inter-chart
|
||||
//! aspects and house overlays) and the midpoint composite chart.
|
||||
//!
|
||||
//! Both charts must be calculated with the same [`ChartOptions`]; only
|
||||
//! `aspect_set` and `orb_multiplier` are read here.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::angle::{self, normalize, separation};
|
||||
use crate::chart::{
|
||||
Aspect, AspectKind, AspectNature, ChartOptions, HouseCusp, NatalChart, OrbEntry, PointId, ZodiacPosition,
|
||||
aspect_kinds, aspect_points, best_aspect, find_aspects, house_of, orb_table,
|
||||
};
|
||||
|
||||
/// Aspect between a point of the first chart and a point of the second.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct InterAspect {
|
||||
/// Point of the first person's chart.
|
||||
pub person1: PointId,
|
||||
/// Point of the second person's chart.
|
||||
pub person2: PointId,
|
||||
pub aspect: AspectKind,
|
||||
pub nature: AspectNature,
|
||||
pub major: bool,
|
||||
pub exact_angle: f64,
|
||||
pub separation: f64,
|
||||
/// Deviation from exactness, degrees.
|
||||
pub orb: f64,
|
||||
pub max_orb: f64,
|
||||
}
|
||||
|
||||
/// A point of one chart placed in the houses of the other.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct HouseOverlay {
|
||||
pub point: PointId,
|
||||
pub sign: crate::types::ZodiacSign,
|
||||
pub house: u8,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct HouseOverlays {
|
||||
/// The first person's points in the second person's houses; `null` when
|
||||
/// the second person's birth time is unknown.
|
||||
pub person1_in_person2: Option<Vec<HouseOverlay>>,
|
||||
/// The second person's points in the first person's houses; `null` when
|
||||
/// the first person's birth time is unknown.
|
||||
pub person2_in_person1: Option<Vec<HouseOverlay>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize)]
|
||||
pub struct NatureTally {
|
||||
pub harmonious: usize,
|
||||
pub challenging: usize,
|
||||
pub neutral: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct SynastrySummary {
|
||||
pub aspect_count: usize,
|
||||
/// Inter-chart aspects by character (harmonious: sextile, trine,
|
||||
/// quintile, biquintile; challenging: square, opposition, semisquare,
|
||||
/// sesquiquadrate, quincunx; neutral: conjunction, semisextile).
|
||||
pub by_nature: NatureTally,
|
||||
pub by_aspect: BTreeMap<AspectKind, usize>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct CompositePoint {
|
||||
pub id: PointId,
|
||||
#[serde(flatten)]
|
||||
pub position: ZodiacPosition,
|
||||
/// Composite house; `null` without composite houses.
|
||||
pub house: Option<u8>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct CompositeAngles {
|
||||
pub ascendant: ZodiacPosition,
|
||||
pub midheaven: ZodiacPosition,
|
||||
pub descendant: ZodiacPosition,
|
||||
pub imum_coeli: ZodiacPosition,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct CompositeHouses {
|
||||
/// `midpoint_of_cusps`: each cusp is the midpoint of the two natal cusps.
|
||||
pub method: &'static str,
|
||||
pub cusps: Vec<HouseCusp>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Composite {
|
||||
/// `midpoint`: every point is the nearer midpoint of the two natal points.
|
||||
pub method: &'static str,
|
||||
pub points: Vec<CompositePoint>,
|
||||
/// `null` unless both birth times are known.
|
||||
pub angles: Option<CompositeAngles>,
|
||||
/// `null` unless both birth times are known.
|
||||
pub houses: Option<CompositeHouses>,
|
||||
pub aspects: Vec<Aspect>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct SynastrySettings {
|
||||
pub aspect_set: crate::types::AspectSet,
|
||||
pub orb_multiplier: f64,
|
||||
pub orbs: Vec<OrbEntry>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Synastry {
|
||||
pub settings: SynastrySettings,
|
||||
/// Inter-chart aspects, tightest first.
|
||||
pub aspects: Vec<InterAspect>,
|
||||
pub house_overlays: HouseOverlays,
|
||||
pub summary: SynastrySummary,
|
||||
pub composite: Composite,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// Compares two natal charts calculated with the same `options`.
|
||||
pub fn calculate_synastry(person1: &NatalChart, person2: &NatalChart, options: &ChartOptions) -> Synastry {
|
||||
let mut warnings = Vec::new();
|
||||
let aspects = inter_aspects(person1, person2, options);
|
||||
let house_overlays = HouseOverlays {
|
||||
person1_in_person2: overlays(person1, person2),
|
||||
person2_in_person1: overlays(person2, person1),
|
||||
};
|
||||
let (composite, composite_warning) = composite(person1, person2, options);
|
||||
warnings.extend(composite_warning);
|
||||
|
||||
let mut by_nature = NatureTally::default();
|
||||
let mut by_aspect = BTreeMap::new();
|
||||
for a in &aspects {
|
||||
match a.nature {
|
||||
AspectNature::Harmonious => by_nature.harmonious += 1,
|
||||
AspectNature::Challenging => by_nature.challenging += 1,
|
||||
AspectNature::Neutral => by_nature.neutral += 1,
|
||||
}
|
||||
*by_aspect.entry(a.aspect).or_insert(0) += 1;
|
||||
}
|
||||
|
||||
Synastry {
|
||||
settings: SynastrySettings {
|
||||
aspect_set: options.aspect_set,
|
||||
orb_multiplier: options.orb_multiplier,
|
||||
orbs: orb_table(options.aspect_set, options.orb_multiplier),
|
||||
},
|
||||
summary: SynastrySummary { aspect_count: aspects.len(), by_nature, by_aspect },
|
||||
aspects,
|
||||
house_overlays,
|
||||
composite,
|
||||
warnings,
|
||||
}
|
||||
}
|
||||
|
||||
/// Every point of the first chart against every point of the second.
|
||||
fn inter_aspects(person1: &NatalChart, person2: &NatalChart, options: &ChartOptions) -> Vec<InterAspect> {
|
||||
let kinds = aspect_kinds(options.aspect_set);
|
||||
let points2 = aspect_points(&person2.points, person2.angles.as_ref());
|
||||
let mut out = Vec::new();
|
||||
for (id1, lon1, _) in aspect_points(&person1.points, person1.angles.as_ref()) {
|
||||
for &(id2, lon2, _) in &points2 {
|
||||
let Some((kind, orb, max_orb)) = best_aspect(&kinds, (id1, lon1), (id2, lon2), options.orb_multiplier)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
out.push(InterAspect {
|
||||
person1: id1,
|
||||
person2: id2,
|
||||
aspect: kind,
|
||||
nature: kind.nature(),
|
||||
major: kind.is_major(),
|
||||
exact_angle: kind.angle(),
|
||||
separation: separation(lon1, lon2),
|
||||
orb,
|
||||
max_orb,
|
||||
});
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| a.orb.total_cmp(&b.orb));
|
||||
out
|
||||
}
|
||||
|
||||
fn cusps_of(chart: &NatalChart) -> Option<[f64; 12]> {
|
||||
let houses = chart.houses.as_ref()?;
|
||||
let mut cusps = [0.0; 12];
|
||||
for (c, h) in cusps.iter_mut().zip(&houses.cusps) {
|
||||
*c = h.position.longitude;
|
||||
}
|
||||
Some(cusps)
|
||||
}
|
||||
|
||||
/// The points of `guest` (planets, nodes, Lilith, Chiron, asteroids and the
|
||||
/// angles) in the houses of `host`.
|
||||
fn overlays(guest: &NatalChart, host: &NatalChart) -> Option<Vec<HouseOverlay>> {
|
||||
let cusps = cusps_of(host)?;
|
||||
let mut list: Vec<(PointId, f64)> = guest.points.iter().map(|p| (p.id, p.position.longitude)).collect();
|
||||
if let Some(a) = &guest.angles {
|
||||
list.push((PointId::Ascendant, a.ascendant.position.longitude));
|
||||
list.push((PointId::Midheaven, a.midheaven.position.longitude));
|
||||
}
|
||||
Some(
|
||||
list.into_iter()
|
||||
.map(|(point, lon)| HouseOverlay {
|
||||
point,
|
||||
sign: crate::types::ZodiacSign::from_longitude(lon),
|
||||
house: house_of(lon, &cusps),
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Midpoint of two longitudes on the shorter arc between them.
|
||||
pub fn midpoint(a: f64, b: f64) -> f64 {
|
||||
let mut d = normalize(b - a);
|
||||
if d > 180.0 {
|
||||
d -= 360.0;
|
||||
}
|
||||
normalize(a + d / 2.0)
|
||||
}
|
||||
|
||||
/// Midpoints of the natal cusps, kept in zodiacal order: when two natal cusps
|
||||
/// are nearly opposite, the nearer midpoint may land on the wrong side, so a
|
||||
/// cusp that would lie more than 180° past its predecessor is flipped.
|
||||
/// Returns `None` when no consistent sequence exists.
|
||||
fn composite_cusps(c1: &[f64; 12], c2: &[f64; 12]) -> Option<[f64; 12]> {
|
||||
let mut cusps = [0.0; 12];
|
||||
for i in 0..12 {
|
||||
cusps[i] = midpoint(c1[i], c2[i]);
|
||||
}
|
||||
for i in 1..12 {
|
||||
if angle::arc(cusps[i - 1], cusps[i]) > 180.0 {
|
||||
cusps[i] = normalize(cusps[i] + 180.0);
|
||||
}
|
||||
}
|
||||
let total: f64 = (0..12).map(|i| angle::arc(cusps[i], cusps[(i + 1) % 12])).sum();
|
||||
((total - 360.0).abs() < 1e-6).then_some(cusps)
|
||||
}
|
||||
|
||||
fn composite(person1: &NatalChart, person2: &NatalChart, options: &ChartOptions) -> (Composite, Option<String>) {
|
||||
let mut warning = None;
|
||||
let cusps = match (cusps_of(person1), cusps_of(person2)) {
|
||||
(Some(c1), Some(c2)) => {
|
||||
let cusps = composite_cusps(&c1, &c2);
|
||||
if cusps.is_none() {
|
||||
warning =
|
||||
Some("The composite house cusps could not be put in order; composite houses are omitted.".into());
|
||||
}
|
||||
cusps
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let points: Vec<CompositePoint> = person1
|
||||
.points
|
||||
.iter()
|
||||
.filter_map(|p1| {
|
||||
let p2 = person2.points.iter().find(|p2| p2.id == p1.id)?;
|
||||
let lon = midpoint(p1.position.longitude, p2.position.longitude);
|
||||
Some(CompositePoint {
|
||||
id: p1.id,
|
||||
position: ZodiacPosition::new(lon),
|
||||
house: cusps.as_ref().map(|c| house_of(lon, c)),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
let angles = cusps.map(|c| CompositeAngles {
|
||||
ascendant: ZodiacPosition::new(c[0]),
|
||||
midheaven: ZodiacPosition::new(c[9]),
|
||||
descendant: ZodiacPosition::new(c[0] + 180.0),
|
||||
imum_coeli: ZodiacPosition::new(c[9] + 180.0),
|
||||
});
|
||||
let houses = cusps.map(|c| CompositeHouses {
|
||||
method: "midpoint_of_cusps",
|
||||
cusps: (0..12)
|
||||
.map(|i| HouseCusp {
|
||||
house: i as u8 + 1,
|
||||
position: ZodiacPosition::new(c[i]),
|
||||
size: angle::arc(c[i], c[(i + 1) % 12]),
|
||||
})
|
||||
.collect(),
|
||||
});
|
||||
|
||||
// Same participants as natal aspects; composite points have no motion.
|
||||
let mut aspect_list: Vec<(PointId, f64, f64)> = points
|
||||
.iter()
|
||||
.filter(|p| {
|
||||
!matches!(p.id, PointId::SouthNode | PointId::Ceres | PointId::Pallas | PointId::Juno | PointId::Vesta)
|
||||
})
|
||||
.map(|p| (p.id, p.position.longitude, 0.0))
|
||||
.collect();
|
||||
if let Some(a) = &angles {
|
||||
aspect_list.push((PointId::Ascendant, a.ascendant.longitude, 0.0));
|
||||
aspect_list.push((PointId::Midheaven, a.midheaven.longitude, 0.0));
|
||||
}
|
||||
let aspects = find_aspects(&aspect_list, options.aspect_set, options.orb_multiplier);
|
||||
|
||||
(Composite { method: "midpoint", points, angles, houses, aspects }, warning)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn midpoints_take_the_shorter_arc() {
|
||||
assert!((midpoint(10.0, 50.0) - 30.0).abs() < 1e-9);
|
||||
assert!((midpoint(350.0, 30.0) - 10.0).abs() < 1e-9);
|
||||
assert!((midpoint(30.0, 350.0) - 10.0).abs() < 1e-9);
|
||||
assert!((midpoint(100.0, 100.0) - 100.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composite_cusps_stay_in_order() {
|
||||
let c1 = [0.0, 30.0, 60.0, 90.0, 120.0, 150.0, 180.0, 210.0, 240.0, 270.0, 300.0, 330.0];
|
||||
// Nearly opposite second chart: some nearer midpoints fall on the far side.
|
||||
let c2 = c1.map(|c| normalize(c + 178.0 + if (120.0..300.0).contains(&c) { 4.0 } else { 0.0 }));
|
||||
let cusps = composite_cusps(&c1, &c2).expect("ordered");
|
||||
let total: f64 = (0..12).map(|i| angle::arc(cusps[i], cusps[(i + 1) % 12])).sum();
|
||||
assert!((total - 360.0).abs() < 1e-6);
|
||||
assert!((0..12).all(|i| angle::arc(cusps[i], cusps[(i + 1) % 12]) < 180.0));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
//! Calendar and Julian Day helpers that do not depend on the ephemeris engine.
|
||||
|
||||
/// Julian Day of the Unix epoch (1970-01-01T00:00:00Z).
|
||||
const UNIX_EPOCH_JD: f64 = 2_440_587.5;
|
||||
|
||||
/// Julian Day (UT) for a Unix timestamp given in seconds.
|
||||
pub fn jd_from_unix_seconds(seconds: f64) -> f64 {
|
||||
UNIX_EPOCH_JD + seconds / 86_400.0
|
||||
}
|
||||
|
||||
/// Julian Day Number (at noon) of a Julian-calendar date.
|
||||
pub fn jdn_from_julian_calendar(year: i32, month: u32, day: u32) -> i64 {
|
||||
let a = (14 - month as i64) / 12;
|
||||
let y = year as i64 + 4800 - a;
|
||||
let m = month as i64 + 12 * a - 3;
|
||||
day as i64 + (153 * m + 2) / 5 + 365 * y + y.div_euclid(4) - 32083
|
||||
}
|
||||
|
||||
/// Proleptic Gregorian calendar date of a Julian Day Number.
|
||||
pub fn gregorian_from_jdn(jdn: i64) -> (i32, u32, u32) {
|
||||
let a = jdn + 32044;
|
||||
let b = (4 * a + 3).div_euclid(146_097);
|
||||
let c = a - (146_097 * b).div_euclid(4);
|
||||
let d = (4 * c + 3).div_euclid(1461);
|
||||
let e = c - (1461 * d).div_euclid(4);
|
||||
let m = (5 * e + 2).div_euclid(153);
|
||||
let day = e - (153 * m + 2).div_euclid(5) + 1;
|
||||
let month = m + 3 - 12 * m.div_euclid(10);
|
||||
let year = 100 * b + d - 4800 + m.div_euclid(10);
|
||||
(year as i32, month as u32, day as u32)
|
||||
}
|
||||
|
||||
/// Converts a Julian-calendar date (as recorded e.g. in Russia before 1918)
|
||||
/// to the proleptic Gregorian date of the same day.
|
||||
pub fn julian_to_gregorian(year: i32, month: u32, day: u32) -> (i32, u32, u32) {
|
||||
gregorian_from_jdn(jdn_from_julian_calendar(year, month, day))
|
||||
}
|
||||
|
||||
/// Validates a Julian-calendar date (every 4th year is a leap year).
|
||||
pub fn is_valid_julian_date(year: i32, month: u32, day: u32) -> bool {
|
||||
let leap = year.rem_euclid(4) == 0;
|
||||
let days = match month {
|
||||
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
|
||||
4 | 6 | 9 | 11 => 30,
|
||||
2 if leap => 29,
|
||||
2 => 28,
|
||||
_ => return false,
|
||||
};
|
||||
(1..=days).contains(&day)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn unix_epoch() {
|
||||
assert_eq!(jd_from_unix_seconds(0.0), 2_440_587.5);
|
||||
// J2000.0 = 2000-01-01T12:00:00 = 946728000
|
||||
assert!((jd_from_unix_seconds(946_728_000.0) - 2_451_545.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn julian_calendar_conversion() {
|
||||
// Russian October Revolution: 25 Oct 1917 (Julian) = 7 Nov 1917 (Gregorian)
|
||||
assert_eq!(julian_to_gregorian(1917, 10, 25), (1917, 11, 7));
|
||||
// Last Julian day before the Gregorian reform: 4 Oct 1582 -> 14 Oct 1582
|
||||
assert_eq!(julian_to_gregorian(1582, 10, 4), (1582, 10, 14));
|
||||
assert!(is_valid_julian_date(1900, 2, 29));
|
||||
assert!(!is_valid_julian_date(1901, 2, 29));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
//! Engine-independent astrological vocabulary.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// A body or calculated point the ephemeris engine can compute.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Body {
|
||||
Sun,
|
||||
Moon,
|
||||
Mercury,
|
||||
Venus,
|
||||
Mars,
|
||||
Jupiter,
|
||||
Saturn,
|
||||
Uranus,
|
||||
Neptune,
|
||||
Pluto,
|
||||
MeanNode,
|
||||
TrueNode,
|
||||
/// Mean lunar apogee (Black Moon Lilith).
|
||||
MeanLilith,
|
||||
/// Osculating lunar apogee ("true" Lilith).
|
||||
TrueLilith,
|
||||
Chiron,
|
||||
Ceres,
|
||||
Pallas,
|
||||
Juno,
|
||||
Vesta,
|
||||
}
|
||||
|
||||
impl Body {
|
||||
pub const PLANETS: [Body; 10] = [
|
||||
Body::Sun,
|
||||
Body::Moon,
|
||||
Body::Mercury,
|
||||
Body::Venus,
|
||||
Body::Mars,
|
||||
Body::Jupiter,
|
||||
Body::Saturn,
|
||||
Body::Uranus,
|
||||
Body::Neptune,
|
||||
Body::Pluto,
|
||||
];
|
||||
pub const ASTEROIDS: [Body; 4] = [Body::Ceres, Body::Pallas, Body::Juno, Body::Vesta];
|
||||
|
||||
pub fn is_luminary(self) -> bool {
|
||||
matches!(self, Body::Sun | Body::Moon)
|
||||
}
|
||||
|
||||
pub fn is_planet(self) -> bool {
|
||||
Self::PLANETS.contains(&self)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum NodeType {
|
||||
#[default]
|
||||
True,
|
||||
Mean,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum LilithType {
|
||||
#[default]
|
||||
Mean,
|
||||
True,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ZodiacType {
|
||||
#[default]
|
||||
Tropical,
|
||||
Sidereal,
|
||||
}
|
||||
|
||||
/// Sidereal zodiac reference (ayanamsa).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Ayanamsa {
|
||||
#[default]
|
||||
Lahiri,
|
||||
FaganBradley,
|
||||
Raman,
|
||||
Krishnamurti,
|
||||
DeLuce,
|
||||
Yukteshwar,
|
||||
TrueCitra,
|
||||
GalacticCenter0Sag,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AspectSet {
|
||||
/// Conjunction, sextile, square, trine, opposition.
|
||||
#[default]
|
||||
Major,
|
||||
/// Major aspects plus semisextile, semisquare, quintile, sesquiquadrate, biquintile, quincunx.
|
||||
Extended,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum HouseSystem {
|
||||
#[default]
|
||||
Placidus,
|
||||
Koch,
|
||||
Porphyry,
|
||||
Regiomontanus,
|
||||
Campanus,
|
||||
Equal,
|
||||
WholeSign,
|
||||
Alcabitius,
|
||||
Morinus,
|
||||
Topocentric,
|
||||
Meridian,
|
||||
Vehlow,
|
||||
}
|
||||
|
||||
impl HouseSystem {
|
||||
pub const ALL: [HouseSystem; 12] = [
|
||||
HouseSystem::Placidus,
|
||||
HouseSystem::Koch,
|
||||
HouseSystem::Porphyry,
|
||||
HouseSystem::Regiomontanus,
|
||||
HouseSystem::Campanus,
|
||||
HouseSystem::Equal,
|
||||
HouseSystem::WholeSign,
|
||||
HouseSystem::Alcabitius,
|
||||
HouseSystem::Morinus,
|
||||
HouseSystem::Topocentric,
|
||||
HouseSystem::Meridian,
|
||||
HouseSystem::Vehlow,
|
||||
];
|
||||
|
||||
/// Quadrant systems that are undefined inside the polar circles.
|
||||
pub fn fails_at_polar_latitudes(self) -> bool {
|
||||
matches!(self, HouseSystem::Placidus | HouseSystem::Koch | HouseSystem::Topocentric)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Element {
|
||||
Fire,
|
||||
Earth,
|
||||
Air,
|
||||
Water,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Modality {
|
||||
Cardinal,
|
||||
Fixed,
|
||||
Mutable,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ZodiacSign {
|
||||
Aries,
|
||||
Taurus,
|
||||
Gemini,
|
||||
Cancer,
|
||||
Leo,
|
||||
Virgo,
|
||||
Libra,
|
||||
Scorpio,
|
||||
Sagittarius,
|
||||
Capricorn,
|
||||
Aquarius,
|
||||
Pisces,
|
||||
}
|
||||
|
||||
impl ZodiacSign {
|
||||
pub const ALL: [ZodiacSign; 12] = [
|
||||
ZodiacSign::Aries,
|
||||
ZodiacSign::Taurus,
|
||||
ZodiacSign::Gemini,
|
||||
ZodiacSign::Cancer,
|
||||
ZodiacSign::Leo,
|
||||
ZodiacSign::Virgo,
|
||||
ZodiacSign::Libra,
|
||||
ZodiacSign::Scorpio,
|
||||
ZodiacSign::Sagittarius,
|
||||
ZodiacSign::Capricorn,
|
||||
ZodiacSign::Aquarius,
|
||||
ZodiacSign::Pisces,
|
||||
];
|
||||
|
||||
/// Sign at an ecliptic longitude.
|
||||
pub fn from_longitude(lon: f64) -> ZodiacSign {
|
||||
let idx = (crate::angle::normalize(lon) / 30.0).floor() as usize;
|
||||
Self::ALL[idx.min(11)]
|
||||
}
|
||||
|
||||
pub fn index(self) -> usize {
|
||||
self as usize
|
||||
}
|
||||
|
||||
pub fn element(self) -> Element {
|
||||
[Element::Fire, Element::Earth, Element::Air, Element::Water][self.index() % 4]
|
||||
}
|
||||
|
||||
pub fn modality(self) -> Modality {
|
||||
[Modality::Cardinal, Modality::Fixed, Modality::Mutable][self.index() % 3]
|
||||
}
|
||||
|
||||
pub fn opposite(self) -> ZodiacSign {
|
||||
Self::ALL[(self.index() + 6) % 12]
|
||||
}
|
||||
|
||||
/// Traditional (pre-telescopic) ruler.
|
||||
pub fn traditional_ruler(self) -> Body {
|
||||
use ZodiacSign::*;
|
||||
match self {
|
||||
Aries | Scorpio => Body::Mars,
|
||||
Taurus | Libra => Body::Venus,
|
||||
Gemini | Virgo => Body::Mercury,
|
||||
Cancer => Body::Moon,
|
||||
Leo => Body::Sun,
|
||||
Sagittarius | Pisces => Body::Jupiter,
|
||||
Capricorn | Aquarius => Body::Saturn,
|
||||
}
|
||||
}
|
||||
|
||||
/// Modern ruler (outer planets for Scorpio, Aquarius, Pisces).
|
||||
pub fn modern_ruler(self) -> Body {
|
||||
match self {
|
||||
ZodiacSign::Scorpio => Body::Pluto,
|
||||
ZodiacSign::Aquarius => Body::Uranus,
|
||||
ZodiacSign::Pisces => Body::Neptune,
|
||||
other => other.traditional_ruler(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Essential dignity of a planet in a sign.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Dignity {
|
||||
Domicile,
|
||||
Exaltation,
|
||||
Detriment,
|
||||
Fall,
|
||||
}
|
||||
|
||||
/// Signs ruled by a planet (traditional and modern rulerships combined).
|
||||
fn domiciles(body: Body) -> &'static [ZodiacSign] {
|
||||
use ZodiacSign::*;
|
||||
match body {
|
||||
Body::Sun => &[Leo],
|
||||
Body::Moon => &[Cancer],
|
||||
Body::Mercury => &[Gemini, Virgo],
|
||||
Body::Venus => &[Taurus, Libra],
|
||||
Body::Mars => &[Aries, Scorpio],
|
||||
Body::Jupiter => &[Sagittarius, Pisces],
|
||||
Body::Saturn => &[Capricorn, Aquarius],
|
||||
Body::Uranus => &[Aquarius],
|
||||
Body::Neptune => &[Pisces],
|
||||
Body::Pluto => &[Scorpio],
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
|
||||
/// Traditional exaltations (outer planets have no generally accepted one).
|
||||
fn exaltation(body: Body) -> Option<ZodiacSign> {
|
||||
use ZodiacSign::*;
|
||||
match body {
|
||||
Body::Sun => Some(Aries),
|
||||
Body::Moon => Some(Taurus),
|
||||
Body::Mercury => Some(Virgo),
|
||||
Body::Venus => Some(Pisces),
|
||||
Body::Mars => Some(Capricorn),
|
||||
Body::Jupiter => Some(Cancer),
|
||||
Body::Saturn => Some(Libra),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// All essential dignities/debilities of `body` in `sign`.
|
||||
pub fn dignities(body: Body, sign: ZodiacSign) -> Vec<Dignity> {
|
||||
let mut out = Vec::new();
|
||||
let homes = domiciles(body);
|
||||
if homes.contains(&sign) {
|
||||
out.push(Dignity::Domicile);
|
||||
}
|
||||
if exaltation(body) == Some(sign) {
|
||||
out.push(Dignity::Exaltation);
|
||||
}
|
||||
if homes.iter().any(|s| s.opposite() == sign) {
|
||||
out.push(Dignity::Detriment);
|
||||
}
|
||||
if exaltation(body).map(ZodiacSign::opposite) == Some(sign) {
|
||||
out.push(Dignity::Fall);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sign_properties() {
|
||||
assert_eq!(ZodiacSign::from_longitude(0.0), ZodiacSign::Aries);
|
||||
assert_eq!(ZodiacSign::from_longitude(359.999), ZodiacSign::Pisces);
|
||||
assert_eq!(ZodiacSign::from_longitude(-0.5), ZodiacSign::Pisces);
|
||||
assert_eq!(ZodiacSign::Leo.element(), Element::Fire);
|
||||
assert_eq!(ZodiacSign::Capricorn.modality(), Modality::Cardinal);
|
||||
assert_eq!(ZodiacSign::Pisces.modality(), Modality::Mutable);
|
||||
assert_eq!(ZodiacSign::Scorpio.traditional_ruler(), Body::Mars);
|
||||
assert_eq!(ZodiacSign::Scorpio.modern_ruler(), Body::Pluto);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dignity_table() {
|
||||
assert_eq!(dignities(Body::Mercury, ZodiacSign::Virgo), vec![Dignity::Domicile, Dignity::Exaltation]);
|
||||
assert_eq!(dignities(Body::Sun, ZodiacSign::Libra), vec![Dignity::Fall]);
|
||||
assert_eq!(dignities(Body::Venus, ZodiacSign::Virgo), vec![Dignity::Fall]);
|
||||
assert_eq!(dignities(Body::Mars, ZodiacSign::Libra), vec![Dignity::Detriment]);
|
||||
assert!(dignities(Body::Jupiter, ZodiacSign::Leo).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
//! Checks the Rust bindings against reference values produced by the upstream
|
||||
//! `swetest` program (built from the same vendored sources), e.g.
|
||||
//! `swetest -b14.7.1985 -ut12:30 -p0123456789tAD -fPls -house19.0402,47.4979,P`.
|
||||
//!
|
||||
//! Requires the ephemeris files from `scripts/fetch-deps.sh` (data/ephe).
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use astro_engine::chart::{AspectKind, PointId, Sect};
|
||||
use astro_engine::swiss::SwissEphemeris;
|
||||
use astro_engine::{Body, ChartInput, ChartOptions, Ephemeris, Frame, GeoPosition, HouseSystem, calculate_chart};
|
||||
|
||||
/// 1985-07-14 12:30 UT
|
||||
const JD: f64 = 2_446_261.020_833_333_5;
|
||||
const BUDAPEST: GeoPosition = GeoPosition { latitude: 47.4979, longitude: 19.0402, elevation: 0.0 };
|
||||
|
||||
fn engine() -> &'static SwissEphemeris {
|
||||
static ENGINE: OnceLock<SwissEphemeris> = OnceLock::new();
|
||||
ENGINE.get_or_init(|| {
|
||||
let dir = std::env::var_os("ASTRO_EPHE_DIR")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../data/ephe"));
|
||||
SwissEphemeris::new(dir).expect("ephemeris files (run scripts/fetch-deps.sh)")
|
||||
})
|
||||
}
|
||||
|
||||
fn close(actual: f64, expected: f64, tol: f64) -> bool {
|
||||
(actual - expected).abs() <= tol
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn body_positions_match_swetest() {
|
||||
let expected = [
|
||||
(Body::Sun, 112.0007251, 0.9541281),
|
||||
(Body::Moon, 71.1646551, 12.2200994),
|
||||
(Body::Mercury, 138.5356993, 0.9265284),
|
||||
(Body::Venus, 68.8767351, 1.0967944),
|
||||
(Body::Mars, 113.0940242, 0.6506060),
|
||||
(Body::Jupiter, 314.6149088, -0.1098597),
|
||||
(Body::Saturn, 231.5708687, -0.0181844),
|
||||
(Body::Uranus, 254.5844730, -0.0296575),
|
||||
(Body::Neptune, 271.6955376, -0.0248706),
|
||||
(Body::Pluto, 211.9256159, 0.0012526),
|
||||
(Body::TrueNode, 46.1491385, -0.0664496),
|
||||
(Body::MeanLilith, 34.7361561, 0.1108111),
|
||||
(Body::Chiron, 72.1761740, 0.0654425),
|
||||
];
|
||||
for (body, lon, speed) in expected {
|
||||
let s = engine().position(body, JD, &Frame::TROPICAL_GEOCENTRIC).unwrap();
|
||||
assert!(close(s.longitude, lon, 1e-6), "{body:?} longitude {} != {lon}", s.longitude);
|
||||
assert!(close(s.speed_longitude, speed, 1e-6), "{body:?} speed {} != {speed}", s.speed_longitude);
|
||||
assert!(!s.degraded_precision, "{body:?} should come from the data files");
|
||||
}
|
||||
let sun = engine().position(Body::Sun, JD, &Frame::TROPICAL_GEOCENTRIC).unwrap();
|
||||
assert!(close(sun.distance, 1.016507864, 1e-8));
|
||||
assert!(close(sun.declination, 21.6455828, 1e-6));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sun_at_j2000() {
|
||||
// Textbook value: apparent solar longitude at 2000-01-01 12:00 UT = 280.3689°
|
||||
let s = engine().position(Body::Sun, 2_451_545.0, &Frame::TROPICAL_GEOCENTRIC).unwrap();
|
||||
assert!(close(s.longitude, 280.3689187, 1e-6), "{}", s.longitude);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placidus_houses_match_swetest() {
|
||||
let h = engine().houses(JD, &BUDAPEST, HouseSystem::Placidus, &Frame::TROPICAL_GEOCENTRIC).unwrap();
|
||||
let cusps = [
|
||||
215.9678137,
|
||||
244.3181228,
|
||||
278.8086642,
|
||||
316.4009907,
|
||||
349.5231422,
|
||||
15.5954622,
|
||||
35.9678137,
|
||||
64.3181228,
|
||||
98.8086642,
|
||||
136.4009907,
|
||||
169.5231422,
|
||||
195.5954622,
|
||||
];
|
||||
for (i, (a, e)) in h.cusps.iter().zip(cusps).enumerate() {
|
||||
assert!(close(*a, e, 1e-6), "cusp {} {a} != {e}", i + 1);
|
||||
}
|
||||
assert_eq!(h.used, HouseSystem::Placidus);
|
||||
assert!(close(h.ascendant, 215.9678137, 1e-6));
|
||||
assert!(close(h.midheaven, 136.4009907, 1e-6));
|
||||
assert!(close(h.armc, 138.8578266, 1e-6));
|
||||
assert!(close(h.vertex, 72.3891351, 1e-6));
|
||||
assert!(close(h.equatorial_ascendant, 231.2864612, 1e-6));
|
||||
assert!(close(h.ascendant_speed, 264.1614525, 1e-4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placidus_falls_back_to_porphyry_in_polar_regions() {
|
||||
let arctic = GeoPosition { latitude: 75.0, ..BUDAPEST };
|
||||
let h = engine().houses(JD, &arctic, HouseSystem::Placidus, &Frame::TROPICAL_GEOCENTRIC).unwrap();
|
||||
assert_eq!(h.used, HouseSystem::Porphyry);
|
||||
assert!(h.fallback_reason.is_some());
|
||||
// swetest: house 1 = 199°49'46.9801"
|
||||
assert!(close(h.cusps[0], 199.0 + 49.0 / 60.0 + 46.9801 / 3600.0, 1e-6));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delta_t_1985() {
|
||||
// swetest: Delta T 54.6303394 s
|
||||
assert!(close(engine().delta_t(JD) * 86_400.0, 54.6303394, 1e-4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_chart() {
|
||||
let input = ChartInput { jd_ut: JD, observer: BUDAPEST, time_known: true, options: ChartOptions::default() };
|
||||
let chart = calculate_chart(engine(), &input).unwrap();
|
||||
assert!(chart.warnings.is_empty(), "{:?}", chart.warnings);
|
||||
|
||||
// 10 planets + north/south node + Lilith + Chiron + 4 asteroids
|
||||
assert_eq!(chart.points.len(), 18);
|
||||
let get = |id| chart.points.iter().find(|p| p.id == id).unwrap();
|
||||
let sun = get(PointId::Sun);
|
||||
assert_eq!(sun.position.sign, astro_engine::ZodiacSign::Cancer);
|
||||
assert_eq!(sun.house, Some(9)); // 112.0° lies between cusp 9 (98.8°) and 10 (136.4°)
|
||||
let north = get(PointId::NorthNode);
|
||||
let south = get(PointId::SouthNode);
|
||||
assert!(close(south.position.longitude, north.position.longitude + 180.0, 1e-9));
|
||||
|
||||
// Sun 112.0007 and Mars 113.0940: conjunction with orb ~1.09°
|
||||
let conj = chart
|
||||
.aspects
|
||||
.iter()
|
||||
.find(|a| a.point1 == PointId::Sun && a.point2 == PointId::Mars)
|
||||
.expect("sun-mars conjunction");
|
||||
assert_eq!(conj.aspect, AspectKind::Conjunction);
|
||||
assert!(close(conj.orb, 1.0932991, 1e-6));
|
||||
|
||||
// Sun in house 9 is above the horizon -> day chart
|
||||
assert_eq!(chart.summary.sect, Some(Sect::Day));
|
||||
let lots = chart.lots.as_ref().unwrap();
|
||||
let expected_fortune = (215.9678137 + 71.1646551 - 112.0007251f64).rem_euclid(360.0);
|
||||
assert!(close(lots.fortune.position.longitude, expected_fortune, 1e-6));
|
||||
|
||||
let json = serde_json::to_value(&chart).unwrap();
|
||||
assert_eq!(json["points"][0]["id"], "sun");
|
||||
assert_eq!(json["houses"]["system"], "placidus");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_time_omits_houses() {
|
||||
let input = ChartInput { jd_ut: JD, observer: BUDAPEST, time_known: false, options: ChartOptions::default() };
|
||||
let chart = calculate_chart(engine(), &input).unwrap();
|
||||
assert!(chart.houses.is_none() && chart.angles.is_none() && chart.lots.is_none());
|
||||
assert!(chart.points.iter().all(|p| p.house.is_none()));
|
||||
assert!(!chart.warnings.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sidereal_zodiac_subtracts_ayanamsa() {
|
||||
let tropical = engine().position(Body::Sun, JD, &Frame::TROPICAL_GEOCENTRIC).unwrap();
|
||||
let frame = Frame { sidereal: Some(astro_engine::Ayanamsa::Lahiri), topocentric: None };
|
||||
let sidereal = engine().position(Body::Sun, JD, &frame).unwrap();
|
||||
let ayanamsa = engine().ayanamsa(JD, astro_engine::Ayanamsa::Lahiri).unwrap();
|
||||
assert!((23.0..24.5).contains(&ayanamsa), "lahiri ayanamsa {ayanamsa}");
|
||||
assert!(close(tropical.longitude - sidereal.longitude, ayanamsa, 1e-3));
|
||||
}
|
||||
Reference in New Issue
Block a user