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:
feco
2026-11-15 10:25:35 +00:00
co-authored by Claude Opus 5.5
parent 0b5416df45
commit 3a84110565
148 changed files with 95803 additions and 0 deletions
+921
View File
@@ -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);
}
}