Files
sorsfonalak/crates/astro-engine/src/synastry.rs
T
fecoandClaude Opus 5.5 3a84110565 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
2026-11-15 10:25:35 +00:00

329 lines
11 KiB
Rust

//! 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));
}
}