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));
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "db"
|
||||
description = "PostgreSQL schema (migrations) and shared data access for the Sorsfonalak services"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
base64.workspace = true
|
||||
rand.workspace = true
|
||||
serde.workspace = true
|
||||
sha2.workspace = true
|
||||
sqlx.workspace = true
|
||||
time.workspace = true
|
||||
uuid.workspace = true
|
||||
@@ -0,0 +1,212 @@
|
||||
-- Users, login, birth charts, synastries, text analyses, credits, sharing.
|
||||
-- Identifiers are UUIDv7 generated by the application (time-ordered).
|
||||
|
||||
-- --- users and login ----------------------------------------------------------
|
||||
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY,
|
||||
-- Always stored lower-case; unique.
|
||||
email text NOT NULL,
|
||||
email_verified_at timestamptz,
|
||||
display_name text,
|
||||
-- UI and analysis language (BCP 47 primary tag, e.g. 'hu', 'en').
|
||||
locale text NOT NULL DEFAULT 'hu',
|
||||
roles text[] NOT NULL DEFAULT ARRAY['user']::text[],
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
last_login_at timestamptz,
|
||||
CONSTRAINT users_email_lower CHECK (email = lower(email)),
|
||||
CONSTRAINT users_roles_valid CHECK (cardinality(roles) > 0 AND roles <@ ARRAY['admin', 'creator', 'user']::text[])
|
||||
);
|
||||
CREATE UNIQUE INDEX users_email_key ON users (email);
|
||||
|
||||
-- One row per login method of a user. 'password' keeps the Argon2id hash;
|
||||
-- external providers keep their stable subject id (Google 'sub').
|
||||
CREATE TABLE auth_identities (
|
||||
id uuid PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
provider text NOT NULL CHECK (provider IN ('password', 'google', 'facebook', 'apple')),
|
||||
subject text NOT NULL,
|
||||
password_hash text,
|
||||
-- E-mail reported by the provider when the identity was linked.
|
||||
email text,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
last_used_at timestamptz,
|
||||
UNIQUE (provider, subject),
|
||||
UNIQUE (user_id, provider),
|
||||
CONSTRAINT auth_identities_password CHECK ((provider = 'password') = (password_hash IS NOT NULL))
|
||||
);
|
||||
|
||||
-- Opaque session tokens; only their SHA-256 hash is stored.
|
||||
CREATE TABLE sessions (
|
||||
id uuid PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
token_hash bytea NOT NULL UNIQUE,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
expires_at timestamptz NOT NULL,
|
||||
user_agent text
|
||||
);
|
||||
CREATE INDEX sessions_user_idx ON sessions (user_id);
|
||||
CREATE INDEX sessions_expiry_idx ON sessions (expires_at);
|
||||
|
||||
-- One-time tokens sent by e-mail (verification, password reset).
|
||||
CREATE TABLE auth_tokens (
|
||||
id uuid PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
purpose text NOT NULL CHECK (purpose IN ('verify_email', 'reset_password')),
|
||||
token_hash bytea NOT NULL UNIQUE,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
expires_at timestamptz NOT NULL,
|
||||
used_at timestamptz
|
||||
);
|
||||
CREATE INDEX auth_tokens_user_idx ON auth_tokens (user_id, purpose);
|
||||
|
||||
-- --- charts and synastries -------------------------------------------------------
|
||||
|
||||
-- A calculated natal chart. `birth_data` is the request sent to the
|
||||
-- horoscope service, `result` its full response.
|
||||
CREATE TABLE charts (
|
||||
id uuid PRIMARY KEY,
|
||||
owner_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
label text NOT NULL,
|
||||
-- The owner's own chart (at most one per user).
|
||||
is_primary boolean NOT NULL DEFAULT false,
|
||||
birth_data jsonb NOT NULL,
|
||||
result jsonb NOT NULL,
|
||||
-- Hash of the resolved birth moment, place and options: same hash, same chart.
|
||||
chart_hash text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE UNIQUE INDEX charts_one_primary ON charts (owner_id) WHERE is_primary;
|
||||
CREATE INDEX charts_owner_idx ON charts (owner_id, created_at DESC);
|
||||
|
||||
-- Comparison of two charts. Visible to `owner_id` and to the owners of both
|
||||
-- charts (an accepted invitation links two users this way).
|
||||
CREATE TABLE synastries (
|
||||
id uuid PRIMARY KEY,
|
||||
owner_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
chart1_id uuid NOT NULL REFERENCES charts (id) ON DELETE CASCADE,
|
||||
chart2_id uuid NOT NULL REFERENCES charts (id) ON DELETE CASCADE,
|
||||
-- Synastry part of the horoscope service response (without the two charts).
|
||||
result jsonb NOT NULL,
|
||||
synastry_hash text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT synastries_distinct CHECK (chart1_id <> chart2_id),
|
||||
UNIQUE (chart1_id, chart2_id)
|
||||
);
|
||||
CREATE INDEX synastries_chart2_idx ON synastries (chart2_id);
|
||||
CREATE INDEX synastries_owner_idx ON synastries (owner_id, created_at DESC);
|
||||
|
||||
-- "How compatible are we?" invitation link.
|
||||
CREATE TABLE synastry_invites (
|
||||
id uuid PRIMARY KEY,
|
||||
inviter_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
inviter_chart_id uuid NOT NULL REFERENCES charts (id) ON DELETE CASCADE,
|
||||
token_hash bytea NOT NULL UNIQUE,
|
||||
message text,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
expires_at timestamptz NOT NULL,
|
||||
accepted_at timestamptz,
|
||||
accepted_by uuid REFERENCES users (id) ON DELETE SET NULL,
|
||||
synastry_id uuid REFERENCES synastries (id) ON DELETE SET NULL
|
||||
);
|
||||
CREATE INDEX synastry_invites_inviter_idx ON synastry_invites (inviter_id, created_at DESC);
|
||||
|
||||
-- --- text analyses (LLM) ---------------------------------------------------------
|
||||
|
||||
CREATE TABLE analyses (
|
||||
id uuid PRIMARY KEY,
|
||||
kind text NOT NULL CHECK (kind IN ('natal', 'synastry')),
|
||||
chart_id uuid REFERENCES charts (id) ON DELETE CASCADE,
|
||||
synastry_id uuid REFERENCES synastries (id) ON DELETE CASCADE,
|
||||
requested_by uuid REFERENCES users (id) ON DELETE SET NULL,
|
||||
language text NOT NULL,
|
||||
model text NOT NULL,
|
||||
prompt_version text NOT NULL,
|
||||
-- sha256(kind | chart/synastry hash | prompt version | model | language):
|
||||
-- a finished analysis with the same key is reused instead of a new LLM call.
|
||||
cache_key text NOT NULL,
|
||||
status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'running', 'done', 'failed')),
|
||||
-- Structured result: {"summary", "strengths": [], "challenges": [], "body"}.
|
||||
content jsonb,
|
||||
error text,
|
||||
input_tokens integer,
|
||||
output_tokens integer,
|
||||
credits_charged integer NOT NULL DEFAULT 0,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
started_at timestamptz,
|
||||
completed_at timestamptz,
|
||||
CONSTRAINT analyses_target CHECK (
|
||||
(kind = 'natal' AND chart_id IS NOT NULL AND synastry_id IS NULL)
|
||||
OR (kind = 'synastry' AND synastry_id IS NOT NULL AND chart_id IS NULL)
|
||||
),
|
||||
CONSTRAINT analyses_done_has_content CHECK (status <> 'done' OR content IS NOT NULL)
|
||||
);
|
||||
CREATE INDEX analyses_chart_idx ON analyses (chart_id, created_at DESC) WHERE chart_id IS NOT NULL;
|
||||
CREATE INDEX analyses_synastry_idx ON analyses (synastry_id, created_at DESC) WHERE synastry_id IS NOT NULL;
|
||||
CREATE INDEX analyses_cache_idx ON analyses (cache_key) WHERE status = 'done';
|
||||
-- Work queue of the worker (SELECT ... FOR UPDATE SKIP LOCKED).
|
||||
CREATE INDEX analyses_pending_idx ON analyses (created_at) WHERE status = 'pending';
|
||||
|
||||
-- --- credits -----------------------------------------------------------------------
|
||||
|
||||
-- Append-only ledger; the balance is SUM(delta).
|
||||
CREATE TABLE credit_ledger (
|
||||
id uuid PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
delta integer NOT NULL CHECK (delta <> 0),
|
||||
reason text NOT NULL CHECK (reason IN ('monthly_grant', 'analysis', 'chat', 'refund', 'admin_adjust', 'purchase')),
|
||||
-- 'YYYY-MM' of a monthly grant.
|
||||
period text,
|
||||
analysis_id uuid REFERENCES analyses (id) ON DELETE SET NULL,
|
||||
note text,
|
||||
created_by uuid REFERENCES users (id) ON DELETE SET NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT credit_ledger_grant_period CHECK ((reason = 'monthly_grant') = (period IS NOT NULL))
|
||||
);
|
||||
CREATE UNIQUE INDEX credit_ledger_monthly_grant_once ON credit_ledger (user_id, period) WHERE reason = 'monthly_grant';
|
||||
CREATE INDEX credit_ledger_user_idx ON credit_ledger (user_id, created_at DESC);
|
||||
|
||||
-- --- public sharing -----------------------------------------------------------------
|
||||
|
||||
-- A public link (and OG card) to a chart, synastry or analysis.
|
||||
CREATE TABLE shares (
|
||||
id uuid PRIMARY KEY,
|
||||
owner_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
-- Unguessable public identifier used in the URL.
|
||||
slug text NOT NULL UNIQUE,
|
||||
kind text NOT NULL CHECK (kind IN ('chart', 'synastry', 'analysis')),
|
||||
chart_id uuid REFERENCES charts (id) ON DELETE CASCADE,
|
||||
synastry_id uuid REFERENCES synastries (id) ON DELETE CASCADE,
|
||||
analysis_id uuid REFERENCES analyses (id) ON DELETE CASCADE,
|
||||
title text,
|
||||
-- Birth date, time and place are hidden unless the owner allows them.
|
||||
show_birth_data boolean NOT NULL DEFAULT false,
|
||||
view_count bigint NOT NULL DEFAULT 0,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
revoked_at timestamptz,
|
||||
CONSTRAINT shares_target CHECK (
|
||||
(kind = 'chart' AND chart_id IS NOT NULL AND synastry_id IS NULL AND analysis_id IS NULL)
|
||||
OR (kind = 'synastry' AND synastry_id IS NOT NULL AND chart_id IS NULL AND analysis_id IS NULL)
|
||||
OR (kind = 'analysis' AND analysis_id IS NOT NULL AND chart_id IS NULL AND synastry_id IS NULL)
|
||||
)
|
||||
);
|
||||
CREATE INDEX shares_owner_idx ON shares (owner_id, created_at DESC);
|
||||
|
||||
-- --- outgoing e-mail -----------------------------------------------------------------
|
||||
|
||||
-- Written by the backend, sent by the worker.
|
||||
CREATE TABLE email_outbox (
|
||||
id uuid PRIMARY KEY,
|
||||
user_id uuid REFERENCES users (id) ON DELETE CASCADE,
|
||||
to_email text NOT NULL,
|
||||
template text NOT NULL,
|
||||
locale text NOT NULL,
|
||||
payload jsonb NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
sent_at timestamptz,
|
||||
attempts integer NOT NULL DEFAULT 0,
|
||||
last_error text
|
||||
);
|
||||
CREATE INDEX email_outbox_unsent_idx ON email_outbox (created_at) WHERE sent_at IS NULL;
|
||||
@@ -0,0 +1,126 @@
|
||||
//! Database schema and the data access shared by several services
|
||||
//! (sessions are validated by the backend and later by the chat engine).
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use rand::RngCore;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use sqlx::postgres::{PgPool, PgPoolOptions};
|
||||
use time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub use sqlx;
|
||||
|
||||
/// All schema migrations, embedded at compile time.
|
||||
pub static MIGRATOR: sqlx::migrate::Migrator = sqlx::migrate!("./migrations");
|
||||
|
||||
pub async fn connect(url: &str) -> Result<PgPool, sqlx::Error> {
|
||||
PgPoolOptions::new().max_connections(20).acquire_timeout(Duration::from_secs(5)).connect(url).await
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Role {
|
||||
Admin,
|
||||
/// May write articles (phase 2).
|
||||
Creator,
|
||||
User,
|
||||
}
|
||||
|
||||
impl Role {
|
||||
pub const ALL: [Role; 3] = [Role::Admin, Role::Creator, Role::User];
|
||||
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Role::Admin => "admin",
|
||||
Role::Creator => "creator",
|
||||
Role::User => "user",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(s: &str) -> Option<Role> {
|
||||
Role::ALL.into_iter().find(|r| r.as_str() == s)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, sqlx::FromRow)]
|
||||
pub struct User {
|
||||
pub id: Uuid,
|
||||
pub email: String,
|
||||
pub email_verified_at: Option<OffsetDateTime>,
|
||||
pub display_name: Option<String>,
|
||||
pub locale: String,
|
||||
pub roles: Vec<String>,
|
||||
pub created_at: OffsetDateTime,
|
||||
pub last_login_at: Option<OffsetDateTime>,
|
||||
}
|
||||
|
||||
impl User {
|
||||
pub fn has_role(&self, role: Role) -> bool {
|
||||
self.roles.iter().any(|r| r == role.as_str())
|
||||
}
|
||||
|
||||
pub fn role_list(&self) -> Vec<Role> {
|
||||
self.roles.iter().filter_map(|r| Role::parse(r)).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Columns selected into [`User`].
|
||||
pub const USER_COLUMNS: &str = "id, email, email_verified_at, display_name, locale, roles, created_at, last_login_at";
|
||||
|
||||
/// A new random secret token (256 bits, URL-safe base64).
|
||||
pub fn new_token() -> String {
|
||||
random_token(32)
|
||||
}
|
||||
|
||||
/// `bytes` random bytes as URL-safe base64.
|
||||
pub fn random_token(bytes: usize) -> String {
|
||||
let mut buf = vec![0u8; bytes];
|
||||
rand::rng().fill_bytes(&mut buf);
|
||||
URL_SAFE_NO_PAD.encode(buf)
|
||||
}
|
||||
|
||||
/// Stored form of a secret token.
|
||||
pub fn token_hash(token: &str) -> Vec<u8> {
|
||||
Sha256::digest(token.as_bytes()).to_vec()
|
||||
}
|
||||
|
||||
/// The session id and user of a valid (unexpired) session token.
|
||||
pub async fn user_by_session(pool: &PgPool, token: &str) -> Result<Option<(Uuid, User)>, sqlx::Error> {
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct Row {
|
||||
session_id: Uuid,
|
||||
#[sqlx(flatten)]
|
||||
user: User,
|
||||
}
|
||||
let row: Option<Row> = sqlx::query_as(
|
||||
"SELECT s.id AS session_id, u.id, u.email, u.email_verified_at, u.display_name, u.locale, u.roles, \
|
||||
u.created_at, u.last_login_at \
|
||||
FROM sessions s JOIN users u ON u.id = s.user_id \
|
||||
WHERE s.token_hash = $1 AND s.expires_at > now()",
|
||||
)
|
||||
.bind(token_hash(token))
|
||||
.fetch_optional(pool)
|
||||
.await?;
|
||||
Ok(row.map(|r| (r.session_id, r.user)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn tokens_are_random_and_hashed() {
|
||||
let a = new_token();
|
||||
let b = new_token();
|
||||
assert_ne!(a, b);
|
||||
assert_eq!(a.len(), 43);
|
||||
assert_eq!(token_hash(&a), token_hash(&a));
|
||||
assert_ne!(token_hash(&a), token_hash(&b));
|
||||
assert_eq!(Role::parse("creator"), Some(Role::Creator));
|
||||
assert_eq!(Role::parse("root"), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "geo-tz"
|
||||
description = "Offline place lookup (GeoNames) and historical time zone resolution (IANA tzdb with backzone)"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
deunicode.workspace = true
|
||||
jiff.workspace = true
|
||||
serde.workspace = true
|
||||
thiserror.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
jiff.workspace = true
|
||||
@@ -0,0 +1,125 @@
|
||||
//! Offline geography and historical civil time.
|
||||
//!
|
||||
//! * [`places`]: country and populated-place lookup from GeoNames dumps.
|
||||
//! * [`tz`]: IANA time zone database (compiled with `backzone`, so every
|
||||
//! country keeps its own pre-1970 daylight saving history) and conversion of
|
||||
//! local civil time to UTC, including DST gaps and folds.
|
||||
//! * [`Atlas`]: both together, plus time zone selection for a birth place.
|
||||
|
||||
pub mod places;
|
||||
pub mod text;
|
||||
pub mod tz;
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
pub use places::{Country, Place, PlaceIndex, PlaceMatch};
|
||||
pub use tz::{AmbiguityPolicy, LocalizedTime, TimeZones, TransitionKind};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum GeoError {
|
||||
#[error("failed to load {what}: {reason}")]
|
||||
Data { what: String, reason: String },
|
||||
#[error("unknown country: {0}")]
|
||||
UnknownCountry(String),
|
||||
#[error("no place named '{query}' found in {country}")]
|
||||
PlaceNotFound { query: String, country: String },
|
||||
#[error("unknown GeoNames id: {0}")]
|
||||
UnknownPlaceId(u64),
|
||||
#[error("place {place} (GeoNames {id}) is in {actual}, not in {expected}")]
|
||||
PlaceCountryMismatch { id: u64, place: String, actual: String, expected: String },
|
||||
#[error("unknown time zone: {0}")]
|
||||
UnknownTimeZone(String),
|
||||
#[error("no time zone could be determined for {0}")]
|
||||
NoTimeZone(String),
|
||||
#[error(
|
||||
"local time {datetime} occurs twice in {zone} (clocks were turned back): \
|
||||
offset {earlier} or {later}; set ambiguous_time to \"earlier\" or \"later\""
|
||||
)]
|
||||
AmbiguousTime { datetime: String, zone: String, earlier: String, later: String },
|
||||
#[error(
|
||||
"local time {datetime} does not exist in {zone} (clocks were turned forward from {earlier} to {later}); \
|
||||
set ambiguous_time to \"earlier\" or \"later\" to interpret it with the offset before or after the change"
|
||||
)]
|
||||
NonexistentTime { datetime: String, zone: String, earlier: String, later: String },
|
||||
#[error("invalid date/time: {0}")]
|
||||
InvalidDateTime(String),
|
||||
}
|
||||
|
||||
/// How the time zone of a chart was chosen.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ZoneSource {
|
||||
/// Given explicitly in the request.
|
||||
Request,
|
||||
/// Time zone of the matched GeoNames place.
|
||||
Place,
|
||||
/// The country has a single time zone.
|
||||
Country,
|
||||
/// Time zone of the nearest populated place in the same country.
|
||||
NearestPlace,
|
||||
/// Nearest reference location of the country's zones in `zone.tab`.
|
||||
ZoneTab,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct ZoneChoice {
|
||||
pub zone: String,
|
||||
pub source: ZoneSource,
|
||||
}
|
||||
|
||||
pub struct Atlas {
|
||||
pub places: PlaceIndex,
|
||||
pub zones: TimeZones,
|
||||
}
|
||||
|
||||
impl Atlas {
|
||||
/// Loads `geonames/` and `zoneinfo/` from the data directory.
|
||||
pub fn load(data_dir: &Path) -> Result<Self, GeoError> {
|
||||
let zones = TimeZones::load(&data_dir.join("zoneinfo"))?;
|
||||
let places = PlaceIndex::load(&data_dir.join("geonames"))?;
|
||||
Ok(Self { places, zones })
|
||||
}
|
||||
|
||||
/// Chooses the time zone for a birth place.
|
||||
///
|
||||
/// Priority: explicit zone > zone of the matched place > the country's only
|
||||
/// zone > zone of the nearest populated place in the country > nearest
|
||||
/// `zone.tab` reference point of the country.
|
||||
pub fn choose_zone(
|
||||
&self,
|
||||
country: &Country,
|
||||
explicit: Option<&str>,
|
||||
place: Option<&Place>,
|
||||
coordinates: (f64, f64),
|
||||
) -> Result<ZoneChoice, GeoError> {
|
||||
if let Some(zone) = explicit {
|
||||
self.zones.get(zone)?;
|
||||
return Ok(ZoneChoice { zone: zone.to_string(), source: ZoneSource::Request });
|
||||
}
|
||||
if let Some(p) = place.filter(|p| self.zones.exists(&p.timezone)) {
|
||||
return Ok(ZoneChoice { zone: p.timezone.clone(), source: ZoneSource::Place });
|
||||
}
|
||||
let country_zones = self.zones.zones_of(&country.iso2);
|
||||
if let [only] = country_zones {
|
||||
return Ok(ZoneChoice { zone: only.name.clone(), source: ZoneSource::Country });
|
||||
}
|
||||
let (lat, lon) = coordinates;
|
||||
if let Some((nearest, _)) = self.places.nearest(&country.iso2, lat, lon, |p| self.zones.exists(&p.timezone)) {
|
||||
return Ok(ZoneChoice { zone: nearest.timezone.clone(), source: ZoneSource::NearestPlace });
|
||||
}
|
||||
country_zones
|
||||
.iter()
|
||||
.min_by(|a, b| {
|
||||
text::distance_km(lat, lon, a.latitude, a.longitude).total_cmp(&text::distance_km(
|
||||
lat,
|
||||
lon,
|
||||
b.latitude,
|
||||
b.longitude,
|
||||
))
|
||||
})
|
||||
.map(|z| ZoneChoice { zone: z.name.clone(), source: ZoneSource::ZoneTab })
|
||||
.ok_or_else(|| GeoError::NoTimeZone(country.name.clone()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
//! Countries and populated places from GeoNames dumps (CC BY 4.0).
|
||||
//!
|
||||
//! Loaded files (see `scripts/fetch-deps.sh`):
|
||||
//! * `countryInfo.txt`, `admin1CodesASCII.txt`
|
||||
//! * `cities*.txt` (worldwide, e.g. cities500) and `full_XX.txt` (every
|
||||
//! populated place of country XX). Duplicates are merged by GeoNames id.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::GeoError;
|
||||
use crate::text::{distance_km, normalize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Country {
|
||||
/// ISO 3166-1 alpha-2 code.
|
||||
pub iso2: String,
|
||||
/// ISO 3166-1 alpha-3 code.
|
||||
pub iso3: String,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Place {
|
||||
pub geonames_id: u64,
|
||||
pub name: String,
|
||||
pub country_code: String,
|
||||
/// First-level administrative division (county, state, ...).
|
||||
pub region: Option<String>,
|
||||
pub latitude: f64,
|
||||
pub longitude: f64,
|
||||
pub elevation: Option<i32>,
|
||||
pub population: u64,
|
||||
/// GeoNames feature code (PPL, PPLA, PPLC, PPLX, PPLH, ...).
|
||||
pub feature_code: String,
|
||||
/// IANA time zone of the place.
|
||||
pub timezone: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct PlaceMatch {
|
||||
#[serde(flatten)]
|
||||
pub place: Place,
|
||||
/// Which name matched the query.
|
||||
pub matched_name: String,
|
||||
/// Ranking score (higher is better).
|
||||
pub score: f64,
|
||||
}
|
||||
|
||||
pub struct PlaceIndex {
|
||||
countries: Vec<Country>,
|
||||
/// normalized ISO2 / ISO3 / name -> index into `countries`
|
||||
country_keys: HashMap<String, usize>,
|
||||
places: Vec<Place>,
|
||||
/// normalized name -> (place index, is primary name)
|
||||
names: HashMap<String, Vec<(u32, bool)>>,
|
||||
by_id: HashMap<u64, u32>,
|
||||
by_country: HashMap<String, Vec<u32>>,
|
||||
pub downloaded: Option<String>,
|
||||
}
|
||||
|
||||
fn data_err(what: &Path, reason: impl ToString) -> GeoError {
|
||||
GeoError::Data { what: what.display().to_string(), reason: reason.to_string() }
|
||||
}
|
||||
|
||||
fn read(path: &Path) -> Result<String, GeoError> {
|
||||
fs::read_to_string(path).map_err(|e| data_err(path, e))
|
||||
}
|
||||
|
||||
impl PlaceIndex {
|
||||
pub fn load(dir: &Path) -> Result<Self, GeoError> {
|
||||
let mut index = PlaceIndex {
|
||||
countries: Vec::new(),
|
||||
country_keys: HashMap::new(),
|
||||
places: Vec::new(),
|
||||
names: HashMap::new(),
|
||||
by_id: HashMap::new(),
|
||||
by_country: HashMap::new(),
|
||||
downloaded: fs::read_to_string(dir.join("DOWNLOADED")).ok().map(|s| s.trim().to_string()),
|
||||
};
|
||||
index.load_countries(&dir.join("countryInfo.txt"))?;
|
||||
let regions = load_regions(&dir.join("admin1CodesASCII.txt"))?;
|
||||
|
||||
let mut files: Vec<_> = fs::read_dir(dir)
|
||||
.map_err(|e| data_err(dir, e))?
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| {
|
||||
let name = p.file_name().and_then(|n| n.to_str()).unwrap_or_default();
|
||||
name.ends_with(".txt") && (name.starts_with("cities") || name.starts_with("full_"))
|
||||
})
|
||||
.collect();
|
||||
// Country files first: they are the most complete for their country.
|
||||
files.sort_by_key(|p| !p.file_name().is_some_and(|n| n.to_string_lossy().starts_with("full_")));
|
||||
if files.is_empty() {
|
||||
return Err(data_err(dir, "no cities*.txt or full_*.txt GeoNames dump found"));
|
||||
}
|
||||
for file in files {
|
||||
index.load_places(&file, ®ions)?;
|
||||
}
|
||||
Ok(index)
|
||||
}
|
||||
|
||||
fn load_countries(&mut self, path: &Path) -> Result<(), GeoError> {
|
||||
for line in read(path)?.lines().filter(|l| !l.starts_with('#') && !l.is_empty()) {
|
||||
let f: Vec<&str> = line.split('\t').collect();
|
||||
if f.len() < 5 {
|
||||
continue;
|
||||
}
|
||||
let idx = self.countries.len();
|
||||
self.countries.push(Country { iso2: f[0].into(), iso3: f[1].into(), name: f[4].into() });
|
||||
for key in [f[0], f[1], f[4]] {
|
||||
self.country_keys.entry(normalize(key)).or_insert(idx);
|
||||
}
|
||||
}
|
||||
if self.countries.is_empty() {
|
||||
return Err(data_err(path, "no countries"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_places(&mut self, path: &Path, regions: &HashMap<String, String>) -> Result<(), GeoError> {
|
||||
let content = read(path)?;
|
||||
for line in content.lines() {
|
||||
let f: Vec<&str> = line.split('\t').collect();
|
||||
// geonameid name asciiname alternatenames lat lon fclass fcode cc cc2
|
||||
// admin1 admin2 admin3 admin4 population elevation dem timezone moddate
|
||||
if f.len() < 19 || f[6] != "P" {
|
||||
continue;
|
||||
}
|
||||
let Ok(id) = f[0].parse::<u64>() else { continue };
|
||||
if self.by_id.contains_key(&id) {
|
||||
continue;
|
||||
}
|
||||
let (Ok(lat), Ok(lon)) = (f[4].parse::<f64>(), f[5].parse::<f64>()) else { continue };
|
||||
let idx = self.places.len() as u32;
|
||||
let country_code = f[8].to_string();
|
||||
let place = Place {
|
||||
geonames_id: id,
|
||||
name: f[1].to_string(),
|
||||
region: regions.get(&format!("{}.{}", f[8], f[10])).cloned(),
|
||||
latitude: lat,
|
||||
longitude: lon,
|
||||
elevation: f[15].parse().ok().or_else(|| f[16].parse().ok().filter(|&d: &i32| d > -9999)),
|
||||
population: f[14].parse().unwrap_or(0),
|
||||
feature_code: f[7].to_string(),
|
||||
timezone: f[17].to_string(),
|
||||
country_code: country_code.clone(),
|
||||
};
|
||||
|
||||
let mut keys: Vec<(String, bool)> = vec![(normalize(f[1]), true), (normalize(f[2]), true)];
|
||||
keys.extend(
|
||||
f[3].split(',')
|
||||
.filter(|n| n.len() > 1 && !n.contains("http") && !n.chars().all(|c| c.is_ascii_digit()))
|
||||
.map(|n| (normalize(n), false)),
|
||||
);
|
||||
keys.sort_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(&a.1)));
|
||||
keys.dedup_by(|a, b| a.0 == b.0);
|
||||
for (key, primary) in keys.into_iter().filter(|(k, _)| !k.is_empty()) {
|
||||
self.names.entry(key).or_default().push((idx, primary));
|
||||
}
|
||||
|
||||
self.by_id.insert(id, idx);
|
||||
self.by_country.entry(country_code).or_default().push(idx);
|
||||
self.places.push(place);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.places.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.places.is_empty()
|
||||
}
|
||||
|
||||
pub fn countries(&self) -> &[Country] {
|
||||
&self.countries
|
||||
}
|
||||
|
||||
/// Looks up a country by ISO alpha-2, alpha-3 or English name.
|
||||
pub fn country(&self, query: &str) -> Result<&Country, GeoError> {
|
||||
self.country_keys
|
||||
.get(&normalize(query))
|
||||
.map(|&i| &self.countries[i])
|
||||
.ok_or_else(|| GeoError::UnknownCountry(query.to_string()))
|
||||
}
|
||||
|
||||
pub fn by_id(&self, id: u64) -> Result<&Place, GeoError> {
|
||||
self.by_id.get(&id).map(|&i| &self.places[i as usize]).ok_or(GeoError::UnknownPlaceId(id))
|
||||
}
|
||||
|
||||
/// Searches populated places of a country by name. Exact (normalized)
|
||||
/// matches on any name come first; if there are none, prefix matches are
|
||||
/// returned. `region` optionally filters by first-level division name.
|
||||
pub fn search(&self, country: &Country, query: &str, region: Option<&str>, limit: usize) -> Vec<PlaceMatch> {
|
||||
let q = normalize(query);
|
||||
if q.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let region = region.map(normalize).filter(|r| !r.is_empty());
|
||||
let region_ok = |p: &Place| match (®ion, &p.region) {
|
||||
(None, _) => true,
|
||||
(Some(r), Some(pr)) => normalize(pr).contains(r.as_str()),
|
||||
(Some(_), None) => false,
|
||||
};
|
||||
|
||||
let mut matches: Vec<PlaceMatch> = self
|
||||
.names
|
||||
.get(&q)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|&(i, primary)| (&self.places[i as usize], primary))
|
||||
.filter(|(p, _)| p.country_code == country.iso2 && region_ok(p))
|
||||
.map(|(p, primary)| PlaceMatch {
|
||||
matched_name: query.trim().to_string(),
|
||||
score: score(p, if primary { 2.0 } else { 1.0 }),
|
||||
place: p.clone(),
|
||||
})
|
||||
.collect();
|
||||
|
||||
if matches.is_empty() {
|
||||
matches = self
|
||||
.by_country
|
||||
.get(&country.iso2)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|&i| &self.places[i as usize])
|
||||
.filter(|p| region_ok(p))
|
||||
.filter(|p| normalize(&p.name).starts_with(&q))
|
||||
.map(|p| PlaceMatch { matched_name: p.name.clone(), score: score(p, 0.0), place: p.clone() })
|
||||
.collect();
|
||||
}
|
||||
|
||||
matches.sort_by(|a, b| b.score.total_cmp(&a.score).then(a.place.geonames_id.cmp(&b.place.geonames_id)));
|
||||
matches.dedup_by_key(|m| m.place.geonames_id);
|
||||
matches.truncate(limit);
|
||||
matches
|
||||
}
|
||||
|
||||
/// Nearest populated place of the country that satisfies `accept`.
|
||||
pub fn nearest(
|
||||
&self,
|
||||
country_iso2: &str,
|
||||
lat: f64,
|
||||
lon: f64,
|
||||
accept: impl Fn(&Place) -> bool,
|
||||
) -> Option<(&Place, f64)> {
|
||||
self.by_country
|
||||
.get(country_iso2)?
|
||||
.iter()
|
||||
.map(|&i| &self.places[i as usize])
|
||||
.filter(|p| accept(p))
|
||||
.map(|p| (p, distance_km(lat, lon, p.latitude, p.longitude)))
|
||||
.min_by(|a, b| a.1.total_cmp(&b.1))
|
||||
}
|
||||
}
|
||||
|
||||
/// Ranking: name quality (primary > alternate > prefix), then administrative
|
||||
/// importance, then population.
|
||||
fn score(p: &Place, name_quality: f64) -> f64 {
|
||||
let importance = match p.feature_code.as_str() {
|
||||
"PPLC" => 6.0,
|
||||
"PPLA" => 5.0,
|
||||
"PPLA2" => 4.0,
|
||||
"PPLA3" | "PPLA4" | "PPLA5" | "PPLG" => 3.0,
|
||||
"PPL" => 2.0,
|
||||
"PPLX" | "PPLL" | "PPLS" | "PPLF" => 1.0,
|
||||
// historical/abandoned places last, but still findable (old birth records)
|
||||
"PPLH" | "PPLQ" | "PPLW" => 0.5,
|
||||
_ => 1.0,
|
||||
};
|
||||
name_quality * 100.0 + importance * 10.0 + (p.population as f64 + 1.0).log10()
|
||||
}
|
||||
|
||||
fn load_regions(path: &Path) -> Result<HashMap<String, String>, GeoError> {
|
||||
Ok(read(path)?
|
||||
.lines()
|
||||
.filter_map(|l| {
|
||||
let mut f = l.split('\t');
|
||||
Some((f.next()?.to_string(), f.next()?.to_string()))
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
//! Name normalization and geodesy helpers.
|
||||
|
||||
/// Normalizes a place or country name for matching: transliterates to ASCII,
|
||||
/// lowercases, and collapses everything that is not a letter or digit into
|
||||
/// single spaces ("Hódmezővásárhely" -> "hodmezovasarhely",
|
||||
/// "Budapest XIII. kerület" -> "budapest xiii kerulet").
|
||||
pub fn normalize(name: &str) -> String {
|
||||
let ascii = deunicode::deunicode(name);
|
||||
let mut out = String::with_capacity(ascii.len());
|
||||
let mut pending_space = false;
|
||||
for c in ascii.chars() {
|
||||
if c.is_ascii_alphanumeric() {
|
||||
if pending_space && !out.is_empty() {
|
||||
out.push(' ');
|
||||
}
|
||||
pending_space = false;
|
||||
out.push(c.to_ascii_lowercase());
|
||||
} else {
|
||||
pending_space = true;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Great-circle distance in kilometers.
|
||||
pub fn distance_km(lat1: f64, lon1: f64, lat2: f64, lon2: f64) -> f64 {
|
||||
const EARTH_RADIUS_KM: f64 = 6371.0;
|
||||
let (p1, p2) = (lat1.to_radians(), lat2.to_radians());
|
||||
let dp = (lat2 - lat1).to_radians();
|
||||
let dl = (lon2 - lon1).to_radians();
|
||||
let a = (dp / 2.0).sin().powi(2) + p1.cos() * p2.cos() * (dl / 2.0).sin().powi(2);
|
||||
2.0 * EARTH_RADIUS_KM * a.sqrt().min(1.0).asin()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn normalizes_names() {
|
||||
assert_eq!(normalize("Hódmezővásárhely"), "hodmezovasarhely");
|
||||
assert_eq!(normalize(" Budapest XIII. kerület "), "budapest xiii kerulet");
|
||||
assert_eq!(normalize("Kolozsvár"), "kolozsvar");
|
||||
assert_eq!(normalize("Москва"), "moskva");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distances() {
|
||||
// Budapest - Szeged ~ 161 km
|
||||
let d = distance_km(47.4979, 19.0402, 46.253, 20.14824);
|
||||
assert!((155.0..170.0).contains(&d), "{d}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
//! IANA time zone database access and local-time resolution.
|
||||
//!
|
||||
//! The zoneinfo directory is compiled by `scripts/fetch-deps.sh` with
|
||||
//! `PACKRATDATA=backzone PACKRATLIST=zone.tab`: every zone listed in
|
||||
//! `zone.tab` keeps its own history before 1970 instead of being linked to
|
||||
//! a zone that merely agrees since 1970 (e.g. Europe/Oslo is not folded into
|
||||
//! Europe/Berlin, so Norway's 1959-1965 summer time is preserved).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use jiff::Timestamp;
|
||||
use jiff::civil::DateTime;
|
||||
use jiff::tz::{AmbiguousOffset, Offset, TimeZone, TimeZoneDatabase};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::GeoError;
|
||||
|
||||
/// What to do when a local time is ambiguous (clocks turned back, the hour
|
||||
/// happens twice) or does not exist (clocks turned forward).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AmbiguityPolicy {
|
||||
/// Return an error that explains both possibilities.
|
||||
#[default]
|
||||
Reject,
|
||||
/// Use the offset in effect before the transition (usually summer time in autumn).
|
||||
Earlier,
|
||||
/// Use the offset in effect after the transition.
|
||||
Later,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum TransitionKind {
|
||||
/// The local time did not exist (clocks turned forward).
|
||||
Gap,
|
||||
/// The local time happened twice (clocks turned back).
|
||||
Fold,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Transition {
|
||||
pub kind: TransitionKind,
|
||||
pub offset_before: String,
|
||||
pub offset_after: String,
|
||||
pub resolved_with: AmbiguityPolicy,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct LocalizedTime {
|
||||
/// IANA zone name; `None` for a fixed offset given in the request.
|
||||
pub zone: Option<String>,
|
||||
/// Local civil time as given.
|
||||
pub local: String,
|
||||
/// The same instant in UTC (RFC 3339).
|
||||
pub utc: String,
|
||||
#[serde(skip)]
|
||||
pub timestamp: Timestamp,
|
||||
pub utc_offset: String,
|
||||
pub utc_offset_seconds: i32,
|
||||
/// Daylight saving (summer) time was in effect.
|
||||
pub dst: bool,
|
||||
/// Zone abbreviation, e.g. CET, CEST, LMT.
|
||||
pub abbreviation: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub transition: Option<Transition>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct ZoneTabEntry {
|
||||
pub name: String,
|
||||
/// Reference location of the zone (its principal city).
|
||||
pub latitude: f64,
|
||||
pub longitude: f64,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub comment: Option<String>,
|
||||
}
|
||||
|
||||
pub struct TimeZones {
|
||||
db: TimeZoneDatabase,
|
||||
pub version: String,
|
||||
zone_tab: HashMap<String, Vec<ZoneTabEntry>>,
|
||||
}
|
||||
|
||||
impl TimeZones {
|
||||
pub fn load(dir: &Path) -> Result<Self, GeoError> {
|
||||
let err = |reason: String| GeoError::Data { what: dir.display().to_string(), reason };
|
||||
let zone_tab_path = dir.join("zone.tab");
|
||||
let content = fs::read_to_string(&zone_tab_path).map_err(|e| err(format!("zone.tab: {e}")))?;
|
||||
let mut zone_tab: HashMap<String, Vec<ZoneTabEntry>> = HashMap::new();
|
||||
for line in content.lines().filter(|l| !l.starts_with('#') && !l.trim().is_empty()) {
|
||||
let f: Vec<&str> = line.split('\t').collect();
|
||||
if f.len() < 3 {
|
||||
continue;
|
||||
}
|
||||
let Some((latitude, longitude)) = parse_iso6709(f[1]) else { continue };
|
||||
zone_tab.entry(f[0].to_string()).or_default().push(ZoneTabEntry {
|
||||
name: f[2].to_string(),
|
||||
latitude,
|
||||
longitude,
|
||||
comment: f.get(3).map(|c| c.to_string()),
|
||||
});
|
||||
}
|
||||
let db = TimeZoneDatabase::from_dir(dir).map_err(|e| err(e.to_string()))?;
|
||||
let version = fs::read_to_string(dir.join("VERSION")).map(|s| s.trim().to_string()).unwrap_or_default();
|
||||
let tz = Self { db, version, zone_tab };
|
||||
// Fail fast on an empty or broken directory.
|
||||
tz.get("Europe/Budapest").map_err(|e| err(e.to_string()))?;
|
||||
Ok(tz)
|
||||
}
|
||||
|
||||
pub fn get(&self, name: &str) -> Result<TimeZone, GeoError> {
|
||||
self.db.get(name).map_err(|_| GeoError::UnknownTimeZone(name.to_string()))
|
||||
}
|
||||
|
||||
pub fn exists(&self, name: &str) -> bool {
|
||||
!name.is_empty() && self.db.get(name).is_ok()
|
||||
}
|
||||
|
||||
/// Zones of a country according to `zone.tab`.
|
||||
pub fn zones_of(&self, iso2: &str) -> &[ZoneTabEntry] {
|
||||
self.zone_tab.get(iso2).map(Vec::as_slice).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Converts local civil time in `zone` to an instant.
|
||||
pub fn localize(&self, zone: &str, local: DateTime, policy: AmbiguityPolicy) -> Result<LocalizedTime, GeoError> {
|
||||
let tz = self.get(zone)?;
|
||||
let ambiguous = tz.to_ambiguous_timestamp(local);
|
||||
let (timestamp, transition) = match ambiguous.offset() {
|
||||
AmbiguousOffset::Unambiguous { offset } => (to_timestamp(local, offset)?, None),
|
||||
AmbiguousOffset::Gap { before, after } | AmbiguousOffset::Fold { before, after } => {
|
||||
let kind = if matches!(ambiguous.offset(), AmbiguousOffset::Gap { .. }) {
|
||||
TransitionKind::Gap
|
||||
} else {
|
||||
TransitionKind::Fold
|
||||
};
|
||||
let offset = match policy {
|
||||
AmbiguityPolicy::Earlier => before,
|
||||
AmbiguityPolicy::Later => after,
|
||||
AmbiguityPolicy::Reject => {
|
||||
let (datetime, zone) = (local.to_string(), zone.to_string());
|
||||
let (earlier, later) = (format_offset(before), format_offset(after));
|
||||
return Err(match kind {
|
||||
TransitionKind::Fold => GeoError::AmbiguousTime { datetime, zone, earlier, later },
|
||||
TransitionKind::Gap => GeoError::NonexistentTime { datetime, zone, earlier, later },
|
||||
});
|
||||
}
|
||||
};
|
||||
let transition = Transition {
|
||||
kind,
|
||||
offset_before: format_offset(before),
|
||||
offset_after: format_offset(after),
|
||||
resolved_with: policy,
|
||||
};
|
||||
(to_timestamp(local, offset)?, Some(transition))
|
||||
}
|
||||
};
|
||||
|
||||
let info = tz.to_offset_info(timestamp);
|
||||
let offset = info.offset();
|
||||
Ok(LocalizedTime {
|
||||
zone: Some(zone.to_string()),
|
||||
local: local.to_string(),
|
||||
utc: timestamp.to_string(),
|
||||
timestamp,
|
||||
utc_offset: format_offset(offset),
|
||||
utc_offset_seconds: offset.seconds(),
|
||||
dst: info.dst().is_dst(),
|
||||
abbreviation: info.abbreviation().to_string(),
|
||||
transition,
|
||||
})
|
||||
}
|
||||
|
||||
/// Converts local civil time with an explicitly given UTC offset.
|
||||
pub fn localize_fixed(&self, local: DateTime, offset_seconds: i32) -> Result<LocalizedTime, GeoError> {
|
||||
let offset = Offset::from_seconds(offset_seconds).map_err(|e| GeoError::InvalidDateTime(e.to_string()))?;
|
||||
let timestamp = to_timestamp(local, offset)?;
|
||||
Ok(LocalizedTime {
|
||||
zone: None,
|
||||
local: local.to_string(),
|
||||
utc: timestamp.to_string(),
|
||||
timestamp,
|
||||
utc_offset: format_offset(offset),
|
||||
utc_offset_seconds: offset_seconds,
|
||||
dst: false,
|
||||
abbreviation: format_offset(offset),
|
||||
transition: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn to_timestamp(local: DateTime, offset: Offset) -> Result<Timestamp, GeoError> {
|
||||
offset.to_timestamp(local).map_err(|e| GeoError::InvalidDateTime(e.to_string()))
|
||||
}
|
||||
|
||||
/// `+02:00`, or `+01:16:20` when the offset has seconds (local mean time).
|
||||
pub fn format_offset(offset: Offset) -> String {
|
||||
let total = offset.seconds();
|
||||
let sign = if total < 0 { '-' } else { '+' };
|
||||
let abs = total.unsigned_abs();
|
||||
let (h, m, s) = (abs / 3600, (abs / 60) % 60, abs % 60);
|
||||
if s == 0 { format!("{sign}{h:02}:{m:02}") } else { format!("{sign}{h:02}:{m:02}:{s:02}") }
|
||||
}
|
||||
|
||||
/// Parses an offset like `+02:00`, `-05:30`, `+01:16:20`, `+0200` or `Z`.
|
||||
pub fn parse_offset(text: &str) -> Option<i32> {
|
||||
let t = text.trim();
|
||||
if t.eq_ignore_ascii_case("z") || t.eq_ignore_ascii_case("utc") {
|
||||
return Some(0);
|
||||
}
|
||||
let (sign, rest) = match t.as_bytes().first()? {
|
||||
b'+' => (1, &t[1..]),
|
||||
b'-' => (-1, &t[1..]),
|
||||
_ => return None,
|
||||
};
|
||||
let parts: Vec<&str> = if rest.contains(':') {
|
||||
rest.split(':').collect()
|
||||
} else if rest.len() == 4 && rest.chars().all(|c| c.is_ascii_digit()) {
|
||||
vec![&rest[..2], &rest[2..]]
|
||||
} else {
|
||||
vec![rest]
|
||||
};
|
||||
let nums: Vec<i32> = parts.iter().map(|p| p.parse::<i32>().ok()).collect::<Option<_>>()?;
|
||||
let (h, m, s) = match nums.as_slice() {
|
||||
[h] => (*h, 0, 0),
|
||||
[h, m] => (*h, *m, 0),
|
||||
[h, m, s] => (*h, *m, *s),
|
||||
_ => return None,
|
||||
};
|
||||
if !(0..=18).contains(&h) || !(0..60).contains(&m) || !(0..60).contains(&s) {
|
||||
return None;
|
||||
}
|
||||
Some(sign * (h * 3600 + m * 60 + s))
|
||||
}
|
||||
|
||||
/// Parses ISO 6709 coordinates as used in zone.tab: `+4730+01905` or
|
||||
/// `+404251-0740023`.
|
||||
fn parse_iso6709(s: &str) -> Option<(f64, f64)> {
|
||||
let split = s[1..].find(['+', '-'])? + 1;
|
||||
let (lat, lon) = s.split_at(split);
|
||||
Some((parse_dms(lat, 2)?, parse_dms(lon, 3)?))
|
||||
}
|
||||
|
||||
fn parse_dms(s: &str, degree_digits: usize) -> Option<f64> {
|
||||
let sign = if s.starts_with('-') { -1.0 } else { 1.0 };
|
||||
let digits = &s[1..];
|
||||
let num = |r: std::ops::Range<usize>| digits.get(r).and_then(|d| d.parse::<f64>().ok());
|
||||
let d = num(0..degree_digits)?;
|
||||
let m = num(degree_digits..degree_digits + 2)?;
|
||||
let sec = if digits.len() > degree_digits + 2 { num(degree_digits + 2..degree_digits + 4)? } else { 0.0 };
|
||||
Some(sign * (d + m / 60.0 + sec / 3600.0))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn iso6709() {
|
||||
let (lat, lon) = parse_iso6709("+4730+01905").unwrap();
|
||||
assert!((lat - 47.5).abs() < 1e-9 && (lon - (19.0 + 5.0 / 60.0)).abs() < 1e-9);
|
||||
let (lat, lon) = parse_iso6709("+404251-0740023").unwrap();
|
||||
assert!((lat - 40.714_166).abs() < 1e-5 && (lon + 74.006_388).abs() < 1e-5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offsets() {
|
||||
assert_eq!(parse_offset("+02:00"), Some(7200));
|
||||
assert_eq!(parse_offset("-05:30"), Some(-19800));
|
||||
assert_eq!(parse_offset("+01:16:20"), Some(4580));
|
||||
assert_eq!(parse_offset("+0100"), Some(3600));
|
||||
assert_eq!(parse_offset("Z"), Some(0));
|
||||
assert_eq!(parse_offset("2"), None);
|
||||
assert_eq!(parse_offset("+25:00"), None);
|
||||
assert_eq!(format_offset(Offset::from_seconds(4580).unwrap()), "+01:16:20");
|
||||
assert_eq!(format_offset(Offset::from_seconds(-12600).unwrap()), "-03:30");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
//! Tests against the real downloaded data (`scripts/fetch-deps.sh`).
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use geo_tz::{AmbiguityPolicy, Atlas, GeoError, TransitionKind, ZoneSource};
|
||||
use jiff::civil::date;
|
||||
|
||||
fn atlas() -> &'static Atlas {
|
||||
static ATLAS: OnceLock<Atlas> = OnceLock::new();
|
||||
ATLAS.get_or_init(|| {
|
||||
let dir = std::env::var_os("ASTRO_DATA_DIR")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../data"));
|
||||
Atlas::load(&dir).expect("data directory (run scripts/fetch-deps.sh)")
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn country_lookup() {
|
||||
let a = atlas();
|
||||
assert_eq!(a.places.country("HU").unwrap().name, "Hungary");
|
||||
assert_eq!(a.places.country("hun").unwrap().iso2, "HU");
|
||||
assert_eq!(a.places.country("hungary").unwrap().iso2, "HU");
|
||||
assert!(matches!(a.places.country("XX"), Err(GeoError::UnknownCountry(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn place_search_handles_accents_villages_and_foreign_names() {
|
||||
let a = atlas();
|
||||
let hu = a.places.country("HU").unwrap();
|
||||
let szeged = &a.places.search(hu, "Szeged", None, 5)[0];
|
||||
assert_eq!(szeged.place.geonames_id, 715429);
|
||||
assert_eq!(szeged.place.timezone, "Europe/Budapest");
|
||||
|
||||
let hmv = a.places.search(hu, "hodmezovasarhely", None, 5);
|
||||
assert_eq!(hmv[0].place.name, "Hódmezővásárhely");
|
||||
|
||||
// a tiny village (population well below 500) from the full HU list
|
||||
let village = a.places.search(hu, "Iborfia", None, 5);
|
||||
assert!(!village.is_empty(), "small villages must be found");
|
||||
|
||||
// Hungarian name of a Romanian city
|
||||
let ro = a.places.country("RO").unwrap();
|
||||
let cluj = &a.places.search(ro, "Kolozsvár", None, 5)[0];
|
||||
assert_eq!(cluj.place.name, "Cluj-Napoca");
|
||||
assert_eq!(cluj.place.timezone, "Europe/Bucharest");
|
||||
|
||||
// prefix fallback
|
||||
assert!(!a.places.search(hu, "Hódmező", None, 5).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zone_choice() {
|
||||
let a = atlas();
|
||||
let hu = a.places.country("HU").unwrap();
|
||||
let z = a.choose_zone(hu, None, None, (47.5, 19.0)).unwrap();
|
||||
assert_eq!((z.zone.as_str(), z.source), ("Europe/Budapest", ZoneSource::Country));
|
||||
|
||||
// multi-zone country resolved from coordinates (Denver)
|
||||
let us = a.places.country("US").unwrap();
|
||||
let z = a.choose_zone(us, None, None, (39.74, -104.99)).unwrap();
|
||||
assert_eq!((z.zone.as_str(), z.source), ("America/Denver", ZoneSource::NearestPlace));
|
||||
|
||||
assert!(a.choose_zone(hu, Some("Mars/Olympus"), None, (0.0, 0.0)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hungarian_dst_history() {
|
||||
let tz = &atlas().zones;
|
||||
// 1985 summer: CEST
|
||||
let t = tz.localize("Europe/Budapest", date(1985, 7, 14).at(14, 30, 0, 0), AmbiguityPolicy::Reject).unwrap();
|
||||
assert_eq!((t.utc_offset.as_str(), t.dst, t.abbreviation.as_str()), ("+02:00", true, "CEST"));
|
||||
assert_eq!(t.utc, "1985-07-14T12:30:00Z");
|
||||
// 1970 summer: Hungary had no DST between 1958 and 1979
|
||||
let t = tz.localize("Europe/Budapest", date(1970, 7, 1).at(12, 0, 0, 0), AmbiguityPolicy::Reject).unwrap();
|
||||
assert_eq!((t.utc_offset.as_str(), t.dst), ("+01:00", false));
|
||||
// 1956 summer: DST was used
|
||||
let t = tz.localize("Europe/Budapest", date(1956, 7, 1).at(12, 0, 0, 0), AmbiguityPolicy::Reject).unwrap();
|
||||
assert_eq!((t.utc_offset.as_str(), t.dst), ("+02:00", true));
|
||||
// before 1890: local mean time of Budapest
|
||||
let t = tz.localize("Europe/Budapest", date(1880, 3, 1).at(12, 0, 0, 0), AmbiguityPolicy::Reject).unwrap();
|
||||
assert_eq!((t.utc_offset.as_str(), t.abbreviation.as_str()), ("+01:16:20", "LMT"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backzone_keeps_national_history() {
|
||||
let tz = &atlas().zones;
|
||||
// Norway had summer time 1959-1965, Germany did not (1950-1979).
|
||||
let oslo = tz.localize("Europe/Oslo", date(1960, 7, 1).at(12, 0, 0, 0), AmbiguityPolicy::Reject).unwrap();
|
||||
let berlin = tz.localize("Europe/Berlin", date(1960, 7, 1).at(12, 0, 0, 0), AmbiguityPolicy::Reject).unwrap();
|
||||
assert!(oslo.dst && !berlin.dst, "oslo {oslo:?} berlin {berlin:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dst_gaps_and_folds() {
|
||||
let tz = &atlas().zones;
|
||||
// 2023-10-29 02:30 happened twice in Budapest
|
||||
let fold = date(2023, 10, 29).at(2, 30, 0, 0);
|
||||
assert!(matches!(
|
||||
tz.localize("Europe/Budapest", fold, AmbiguityPolicy::Reject),
|
||||
Err(GeoError::AmbiguousTime { .. })
|
||||
));
|
||||
let early = tz.localize("Europe/Budapest", fold, AmbiguityPolicy::Earlier).unwrap();
|
||||
let late = tz.localize("Europe/Budapest", fold, AmbiguityPolicy::Later).unwrap();
|
||||
assert_eq!((early.utc_offset.as_str(), late.utc_offset.as_str()), ("+02:00", "+01:00"));
|
||||
assert_eq!(early.transition.as_ref().unwrap().kind, TransitionKind::Fold);
|
||||
|
||||
// 2023-03-26 02:30 did not exist
|
||||
let gap = date(2023, 3, 26).at(2, 30, 0, 0);
|
||||
assert!(matches!(
|
||||
tz.localize("Europe/Budapest", gap, AmbiguityPolicy::Reject),
|
||||
Err(GeoError::NonexistentTime { .. })
|
||||
));
|
||||
let t = tz.localize("Europe/Budapest", gap, AmbiguityPolicy::Earlier).unwrap();
|
||||
assert_eq!(t.transition.unwrap().kind, TransitionKind::Gap);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixed_offset() {
|
||||
let t = atlas().zones.localize_fixed(date(1944, 5, 1).at(10, 0, 0, 0), 7200).unwrap();
|
||||
assert_eq!(t.utc, "1944-05-01T08:00:00Z");
|
||||
assert_eq!(t.zone, None);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "horoscope-client"
|
||||
description = "HTTP client of the horoscope-api service"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
reqwest.workspace = true
|
||||
serde_json.workspace = true
|
||||
thiserror.workspace = true
|
||||
@@ -0,0 +1,64 @@
|
||||
//! Client of the horoscope-api service (`POST /v1/natal`, `POST /v1/synastry`).
|
||||
//!
|
||||
//! Requests and responses are passed as JSON: the horoscope service validates
|
||||
//! the birth data itself, and its error objects are handed back unchanged so
|
||||
//! callers can show them to the user.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum HoroscopeError {
|
||||
/// The service rejected the input (4xx); `body` is its `{"error": {...}}` object.
|
||||
#[error("horoscope service rejected the request ({status})")]
|
||||
Rejected { status: u16, body: Value },
|
||||
/// The service is unreachable or failed (5xx, timeout, invalid response).
|
||||
#[error("horoscope service unavailable: {0}")]
|
||||
Unavailable(String),
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct HoroscopeClient {
|
||||
base_url: String,
|
||||
http: reqwest::Client,
|
||||
}
|
||||
|
||||
impl HoroscopeClient {
|
||||
pub fn new(base_url: impl Into<String>) -> Self {
|
||||
let http = reqwest::Client::builder()
|
||||
.timeout(Duration::from_secs(15))
|
||||
.build()
|
||||
.expect("static reqwest configuration is valid");
|
||||
Self { base_url: base_url.into().trim_end_matches('/').to_string(), http }
|
||||
}
|
||||
|
||||
/// `POST /v1/natal`
|
||||
pub async fn natal(&self, request: &Value) -> Result<Value, HoroscopeError> {
|
||||
self.post("/v1/natal", request).await
|
||||
}
|
||||
|
||||
/// `POST /v1/synastry`
|
||||
pub async fn synastry(&self, request: &Value) -> Result<Value, HoroscopeError> {
|
||||
self.post("/v1/synastry", request).await
|
||||
}
|
||||
|
||||
async fn post(&self, path: &str, body: &Value) -> Result<Value, HoroscopeError> {
|
||||
let response = self
|
||||
.http
|
||||
.post(format!("{}{path}", self.base_url))
|
||||
.json(body)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| HoroscopeError::Unavailable(e.to_string()))?;
|
||||
let status = response.status();
|
||||
let body: Value = response.json().await.map_err(|e| HoroscopeError::Unavailable(e.to_string()))?;
|
||||
if status.is_success() {
|
||||
Ok(body)
|
||||
} else if status.is_client_error() {
|
||||
Err(HoroscopeError::Rejected { status: status.as_u16(), body })
|
||||
} else {
|
||||
Err(HoroscopeError::Unavailable(format!("{status}: {body}")))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
[package]
|
||||
name = "service-kit"
|
||||
description = "Shared plumbing for the HTTP services: logging, listen address, health check, shutdown"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
tokio.workspace = true
|
||||
tracing.workspace = true
|
||||
tracing-subscriber.workspace = true
|
||||
@@ -0,0 +1,64 @@
|
||||
//! Plumbing shared by every HTTP service.
|
||||
//!
|
||||
//! Environment:
|
||||
//! * `BIND_ADDR` listen address (each service has its own default)
|
||||
//! * `LOG_FORMAT` `text` (default) or `json`; `RUST_LOG` sets the level
|
||||
|
||||
use std::net::SocketAddr;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
|
||||
/// Initializes `tracing` from `RUST_LOG` and `LOG_FORMAT`.
|
||||
pub fn init_logging() {
|
||||
use tracing_subscriber::EnvFilter;
|
||||
let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info,tower_http=info"));
|
||||
let builder = tracing_subscriber::fmt().with_env_filter(filter);
|
||||
if std::env::var("LOG_FORMAT").is_ok_and(|f| f.eq_ignore_ascii_case("json")) {
|
||||
builder.json().init();
|
||||
} else {
|
||||
builder.init();
|
||||
}
|
||||
}
|
||||
|
||||
/// Listen address from `BIND_ADDR`, or `default`.
|
||||
pub fn bind_addr(default: &str) -> anyhow::Result<SocketAddr> {
|
||||
let raw = std::env::var("BIND_ADDR").unwrap_or_else(|_| default.into());
|
||||
raw.parse().with_context(|| format!("invalid BIND_ADDR '{raw}'"))
|
||||
}
|
||||
|
||||
/// Minimal HTTP GET against `/healthz` of the local service, so scratch
|
||||
/// images need no curl. Used by the `healthcheck` subcommand.
|
||||
pub fn healthcheck(mut addr: SocketAddr) -> anyhow::Result<()> {
|
||||
use std::io::{Read, Write};
|
||||
if addr.ip().is_unspecified() {
|
||||
addr.set_ip([127, 0, 0, 1].into());
|
||||
}
|
||||
let mut stream = std::net::TcpStream::connect_timeout(&addr, Duration::from_secs(2))?;
|
||||
stream.set_read_timeout(Some(Duration::from_secs(2)))?;
|
||||
stream.write_all(b"GET /healthz HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")?;
|
||||
let mut response = String::new();
|
||||
stream.read_to_string(&mut response)?;
|
||||
anyhow::ensure!(response.starts_with("HTTP/1.1 200"), "unhealthy: {}", response.lines().next().unwrap_or(""));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Resolves on Ctrl+C or SIGTERM (graceful shutdown in Docker).
|
||||
pub async fn shutdown_signal() {
|
||||
let ctrl_c = async {
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
};
|
||||
#[cfg(unix)]
|
||||
let terminate = async {
|
||||
if let Ok(mut s) = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
|
||||
s.recv().await;
|
||||
}
|
||||
};
|
||||
#[cfg(not(unix))]
|
||||
let terminate = std::future::pending::<()>();
|
||||
tokio::select! {
|
||||
_ = ctrl_c => {},
|
||||
_ = terminate => {},
|
||||
}
|
||||
tracing::info!("shutting down");
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
[package]
|
||||
name = "swisseph-sys"
|
||||
description = "Raw FFI bindings to the Swiss Ephemeris C library (sources in vendor/swisseph)"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
links = "swe"
|
||||
|
||||
[build-dependencies]
|
||||
cc = "1"
|
||||
@@ -0,0 +1,44 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Library objects as listed in the upstream Makefile (SWEOBJ).
|
||||
const SOURCES: &[&str] = &[
|
||||
"swedate.c",
|
||||
"swehouse.c",
|
||||
"swejpl.c",
|
||||
"swemmoon.c",
|
||||
"swemplan.c",
|
||||
"sweph.c",
|
||||
"swephlib.c",
|
||||
"swecl.c",
|
||||
"swehel.c",
|
||||
];
|
||||
|
||||
fn main() {
|
||||
let dir = std::env::var_os("SWISSEPH_SRC_DIR")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../vendor/swisseph"));
|
||||
if !dir.join("sweph.c").exists() {
|
||||
panic!(
|
||||
"Swiss Ephemeris sources not found in {}. Run scripts/fetch-deps.sh first \
|
||||
(or set SWISSEPH_SRC_DIR).",
|
||||
dir.display()
|
||||
);
|
||||
}
|
||||
|
||||
let mut build = cc::Build::new();
|
||||
build
|
||||
.include(&dir)
|
||||
// Globals are shared between threads; the Rust side serializes access.
|
||||
.define("TLSOFF", None)
|
||||
.opt_level(2)
|
||||
.warnings(false);
|
||||
for src in SOURCES {
|
||||
let path = dir.join(src);
|
||||
println!("cargo:rerun-if-changed={}", path.display());
|
||||
build.file(path);
|
||||
}
|
||||
build.compile("swe");
|
||||
|
||||
println!("cargo:rerun-if-env-changed=SWISSEPH_SRC_DIR");
|
||||
println!("cargo:rustc-link-lib=m");
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
//! Raw FFI bindings to the subset of the Swiss Ephemeris API used by the
|
||||
//! services. The library keeps global state (ephemeris path, sidereal mode,
|
||||
//! open file handles) and is compiled with `TLSOFF`, so every call must be
|
||||
//! serialized by the caller.
|
||||
#![allow(non_upper_case_globals)]
|
||||
|
||||
use std::os::raw::{c_char, c_double, c_int};
|
||||
|
||||
pub const OK: i32 = 0;
|
||||
pub const ERR: i32 = -1;
|
||||
/// Size of the error string buffers (`AS_MAXCH`).
|
||||
pub const AS_MAXCH: usize = 256;
|
||||
|
||||
pub const SE_JUL_CAL: c_int = 0;
|
||||
pub const SE_GREG_CAL: c_int = 1;
|
||||
|
||||
pub const SE_ECL_NUT: i32 = -1;
|
||||
pub const SE_SUN: i32 = 0;
|
||||
pub const SE_MOON: i32 = 1;
|
||||
pub const SE_MERCURY: i32 = 2;
|
||||
pub const SE_VENUS: i32 = 3;
|
||||
pub const SE_MARS: i32 = 4;
|
||||
pub const SE_JUPITER: i32 = 5;
|
||||
pub const SE_SATURN: i32 = 6;
|
||||
pub const SE_URANUS: i32 = 7;
|
||||
pub const SE_NEPTUNE: i32 = 8;
|
||||
pub const SE_PLUTO: i32 = 9;
|
||||
pub const SE_MEAN_NODE: i32 = 10;
|
||||
pub const SE_TRUE_NODE: i32 = 11;
|
||||
pub const SE_MEAN_APOG: i32 = 12;
|
||||
pub const SE_OSCU_APOG: i32 = 13;
|
||||
pub const SE_CHIRON: i32 = 15;
|
||||
pub const SE_PHOLUS: i32 = 16;
|
||||
pub const SE_CERES: i32 = 17;
|
||||
pub const SE_PALLAS: i32 = 18;
|
||||
pub const SE_JUNO: i32 = 19;
|
||||
pub const SE_VESTA: i32 = 20;
|
||||
|
||||
pub const SEFLG_JPLEPH: i32 = 1;
|
||||
pub const SEFLG_SWIEPH: i32 = 2;
|
||||
pub const SEFLG_MOSEPH: i32 = 4;
|
||||
pub const SEFLG_TRUEPOS: i32 = 16;
|
||||
pub const SEFLG_NONUT: i32 = 64;
|
||||
pub const SEFLG_SPEED: i32 = 256;
|
||||
pub const SEFLG_EQUATORIAL: i32 = 2 * 1024;
|
||||
pub const SEFLG_TOPOCTR: i32 = 32 * 1024;
|
||||
pub const SEFLG_SIDEREAL: i32 = 64 * 1024;
|
||||
|
||||
pub const SE_SIDM_FAGAN_BRADLEY: i32 = 0;
|
||||
pub const SE_SIDM_LAHIRI: i32 = 1;
|
||||
pub const SE_SIDM_DELUCE: i32 = 2;
|
||||
pub const SE_SIDM_RAMAN: i32 = 3;
|
||||
pub const SE_SIDM_KRISHNAMURTI: i32 = 5;
|
||||
pub const SE_SIDM_YUKTESHWAR: i32 = 7;
|
||||
pub const SE_SIDM_GALCENT_0SAG: i32 = 17;
|
||||
pub const SE_SIDM_TRUE_CITRA: i32 = 27;
|
||||
|
||||
unsafe extern "C" {
|
||||
pub fn swe_version(s: *mut c_char) -> *mut c_char;
|
||||
pub fn swe_set_ephe_path(path: *const c_char);
|
||||
pub fn swe_close();
|
||||
pub fn swe_set_sid_mode(sid_mode: i32, t0: c_double, ayan_t0: c_double);
|
||||
pub fn swe_get_ayanamsa_ex_ut(tjd_ut: c_double, iflag: i32, daya: *mut c_double, serr: *mut c_char) -> i32;
|
||||
pub fn swe_set_topo(geolon: c_double, geolat: c_double, geoalt: c_double);
|
||||
|
||||
pub fn swe_calc_ut(tjd_ut: c_double, ipl: i32, iflag: i32, xx: *mut c_double, serr: *mut c_char) -> i32;
|
||||
pub fn swe_pheno_ut(tjd_ut: c_double, ipl: i32, iflag: i32, attr: *mut c_double, serr: *mut c_char) -> i32;
|
||||
|
||||
pub fn swe_houses_ex2(
|
||||
tjd_ut: c_double,
|
||||
iflag: i32,
|
||||
geolat: c_double,
|
||||
geolon: c_double,
|
||||
hsys: c_int,
|
||||
cusps: *mut c_double,
|
||||
ascmc: *mut c_double,
|
||||
cusp_speed: *mut c_double,
|
||||
ascmc_speed: *mut c_double,
|
||||
serr: *mut c_char,
|
||||
) -> c_int;
|
||||
pub fn swe_house_name(hsys: c_int) -> *const c_char;
|
||||
|
||||
pub fn swe_julday(year: c_int, month: c_int, day: c_int, hour: c_double, gregflag: c_int) -> c_double;
|
||||
pub fn swe_revjul(
|
||||
jd: c_double,
|
||||
gregflag: c_int,
|
||||
jyear: *mut c_int,
|
||||
jmon: *mut c_int,
|
||||
jday: *mut c_int,
|
||||
jut: *mut c_double,
|
||||
);
|
||||
pub fn swe_utc_to_jd(
|
||||
iyear: i32,
|
||||
imonth: i32,
|
||||
iday: i32,
|
||||
ihour: i32,
|
||||
imin: i32,
|
||||
dsec: c_double,
|
||||
gregflag: i32,
|
||||
dret: *mut c_double,
|
||||
serr: *mut c_char,
|
||||
) -> i32;
|
||||
pub fn swe_deltat_ex(tjd: c_double, iflag: i32, serr: *mut c_char) -> c_double;
|
||||
pub fn swe_sidtime(tjd_ut: c_double) -> c_double;
|
||||
}
|
||||
Reference in New Issue
Block a user