Moon and retrograde calendars, "today in the sky" on the own chart
CI / test (push) Successful in 2m6s
CI / build (push) Skipped
CI / deploy (push) Skipped

New public pages: /holdnaptar (new and full moons, quarters, eclipses and
the Moon's sign changes, month by month, with the Moon of today) and
/retrograd (the retrograde periods of Mercury to Pluto with their shadows,
and which planets are retrograde now), each with a page per year around
the current one. The own chart gets a "Ma az égen" card: the Moon's sign,
phase and natal house, the tightest transits to the chart in fixed
sentences, and the retrograde planets. No AI, nothing stored.

The events come from astro-engine (sampling and bisection, checked against
swetest and the 2026 eclipses) through horoscope-api GET /v1/sky and
/v1/sky/events; the backend serves them at /v1/public/sky… and keeps them
in memory (the sky now for five minutes, a year's events for good). Links
in the mobile menu, the footer, the sitemap and the free tools on the home
page; the desktop header is unchanged (it is full at 1280 px).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
feco
2026-11-23 17:21:36 +00:00
co-authored by Claude Opus 5.5
parent 3255e939c4
commit 699ce2abbd
30 changed files with 2230 additions and 5 deletions
+3 -1
View File
@@ -6,12 +6,14 @@
//! [`chart`] and is independent of the engine, so the engine can be replaced
//! without touching the chart logic. [`synastry`] compares two charts;
//! [`forecast`] looks at one year of a chart (solar return, transits,
//! progressions, profection, eclipses).
//! progressions, profection, eclipses); [`sky`] is the sky by date, the same
//! for everyone (lunar phases, retrograde periods).
pub mod angle;
pub mod chart;
pub mod engine;
pub mod forecast;
pub mod sky;
pub mod synastry;
pub mod time;
pub mod types;
+265
View File
@@ -0,0 +1,265 @@
//! The sky by date, the same for everyone (tropical, geocentric): the lunar
//! phases, the Moon's sign changes, the stations of the planets and their
//! retrograde periods with the shadows around them. Used by the public moon
//! and retrograde calendars and by the "today in the sky" card.
//!
//! Every event is found by sampling at a step shorter than the shortest gap
//! between two events of its kind, then bisecting to well under a second.
use serde::Serialize;
use crate::angle::normalize;
use crate::chart::{MoonPhaseName, phase_name};
use crate::engine::{EngineError, Ephemeris, Frame};
use crate::types::{Body, ZodiacSign};
type Result<T> = std::result::Result<T, EngineError>;
const FRAME: Frame = Frame::TROPICAL_GEOCENTRIC;
/// The planets that turn retrograde (seen from the Earth, the Sun and the Moon never do).
pub const RETROGRADING: [Body; 8] =
[Body::Mercury, Body::Venus, Body::Mars, Body::Jupiter, Body::Saturn, Body::Uranus, Body::Neptune, Body::Pluto];
/// Days around a window scanned for stations, so that a retrograde period
/// (Pluto's is the longest, about 160 days) overlapping it is found whole.
const STATION_MARGIN: f64 = 200.0;
/// Bisection steps: a day halved 40 times is far below a second.
const BISECT_STEPS: usize = 40;
/// Signed difference `a - b` in `[-180, 180)`.
fn diff(a: f64, b: f64) -> f64 {
(a - b + 180.0).rem_euclid(360.0) - 180.0
}
/// The moment in `[lo, hi]` where `f` turns from negative to non-negative.
fn bisect(mut lo: f64, mut hi: f64, f: impl Fn(f64) -> Result<f64>) -> Result<f64> {
for _ in 0..BISECT_STEPS {
let mid = (lo + hi) / 2.0;
if f(mid)? < 0.0 {
lo = mid;
} else {
hi = mid;
}
}
Ok((lo + hi) / 2.0)
}
fn longitude(engine: &dyn Ephemeris, body: Body, jd: f64) -> Result<f64> {
Ok(engine.position(body, jd, &FRAME)?.longitude)
}
fn speed(engine: &dyn Ephemeris, body: Body, jd: f64) -> Result<f64> {
Ok(engine.position(body, jd, &FRAME)?.speed_longitude)
}
/// Moon minus Sun, `[0, 360)`.
fn elongation(engine: &dyn Ephemeris, jd: f64) -> Result<f64> {
Ok(normalize(longitude(engine, Body::Moon, jd)? - longitude(engine, Body::Sun, jd)?))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum LunationKind {
NewMoon,
FirstQuarter,
FullMoon,
LastQuarter,
}
impl LunationKind {
const ALL: [LunationKind; 4] =
[LunationKind::NewMoon, LunationKind::FirstQuarter, LunationKind::FullMoon, LunationKind::LastQuarter];
}
/// A main lunar phase at its exact moment.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Lunation {
pub kind: LunationKind,
pub jd_ut: f64,
pub moon_longitude: f64,
}
/// The new moons, quarters and full moons between two moments, in time order.
pub fn lunations(engine: &dyn Ephemeris, from: f64, to: f64) -> Result<Vec<Lunation>> {
// The elongation grows 11–15° a day: at half a day no quarter is skipped.
const STEP: f64 = 0.5;
let mut out = Vec::new();
let mut t0 = from;
let mut q0 = (elongation(engine, t0)? / 90.0).floor() as usize % 4;
while t0 < to {
let t1 = (t0 + STEP).min(to);
let q1 = (elongation(engine, t1)? / 90.0).floor() as usize % 4;
if q1 != q0 {
let target = 90.0 * q1 as f64;
let jd = bisect(t0, t1, |t| Ok(diff(elongation(engine, t)?, target)))?;
out.push(Lunation {
kind: LunationKind::ALL[q1],
jd_ut: jd,
moon_longitude: longitude(engine, Body::Moon, jd)?,
});
}
t0 = t1;
q0 = q1;
}
Ok(out)
}
/// The moments the Moon enters a sign, with the sign entered, in time order.
pub fn moon_ingresses(engine: &dyn Ephemeris, from: f64, to: f64) -> Result<Vec<(f64, ZodiacSign)>> {
// The Moon moves 12–15° a day; a sign takes it two days or more.
const STEP: f64 = 0.25;
let mut out = Vec::new();
let mut t0 = from;
let mut s0 = ZodiacSign::from_longitude(longitude(engine, Body::Moon, t0)?);
while t0 < to {
let t1 = (t0 + STEP).min(to);
let s1 = ZodiacSign::from_longitude(longitude(engine, Body::Moon, t1)?);
if s1 != s0 {
let target = 30.0 * s1.index() as f64;
let jd = bisect(t0, t1, |t| Ok(diff(longitude(engine, Body::Moon, t)?, target)))?;
out.push((jd, s1));
}
t0 = t1;
s0 = s1;
}
Ok(out)
}
/// A planet standing still before turning retrograde or direct.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Station {
pub body: Body,
pub jd_ut: f64,
pub longitude: f64,
/// Turns retrograde here (otherwise direct).
pub retrograde: bool,
}
/// The stations of a planet between two moments, in time order.
pub fn stations(engine: &dyn Ephemeris, body: Body, from: f64, to: f64) -> Result<Vec<Station>> {
scan_stations(engine, body, from, to, usize::MAX)
}
/// The first station of a planet after a moment, looking ahead at most `days`.
pub fn next_station(engine: &dyn Ephemeris, body: Body, jd: f64, days: f64) -> Result<Option<Station>> {
Ok(scan_stations(engine, body, jd, jd + days, 1)?.into_iter().next())
}
/// At most `limit` stations, from the first one after `from`.
fn scan_stations(engine: &dyn Ephemeris, body: Body, from: f64, to: f64, limit: usize) -> Result<Vec<Station>> {
// Retrograde and direct runs last three weeks or more: two days skip none.
const STEP: f64 = 2.0;
let mut out = Vec::new();
let mut t0 = from;
let mut v0 = speed(engine, body, t0)?;
while t0 < to {
let t1 = (t0 + STEP).min(to);
let v1 = speed(engine, body, t1)?;
if (v0 < 0.0) != (v1 < 0.0) {
let retrograde = v1 < 0.0;
// Bisect on a function that turns non-negative at the station.
let jd = bisect(t0, t1, |t| {
let v = speed(engine, body, t)?;
Ok(if retrograde { -v } else { v })
})?;
out.push(Station { body, jd_ut: jd, longitude: longitude(engine, body, jd)?, retrograde });
if out.len() >= limit {
break;
}
}
t0 = t1;
v0 = v1;
}
Ok(out)
}
/// A retrograde period and its shadow: the stretch of the zodiac the planet
/// covers three times (forward, backward, forward again).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RetrogradePeriod {
pub body: Body,
pub station_retrograde: Station,
pub station_direct: Station,
/// The planet first reaches the degree where it will turn direct.
pub shadow_start: f64,
/// The planet gets back to the degree where it turned retrograde.
pub shadow_end: f64,
}
/// The moment the planet, moving forward, reaches `target`: searched from
/// `from` backward (`dir` = -1) or forward (`dir` = 1) a day at a time.
fn reaches(engine: &dyn Ephemeris, body: Body, target: f64, from: f64, dir: f64) -> Result<f64> {
// f grows through zero as the planet passes the target moving forward.
let f = |t: f64| Ok(diff(longitude(engine, body, t)?, target));
let mut a = from;
let mut fa = f(a)?;
for _ in 0..400 {
let b = a + dir;
let fb = f(b)?;
// A change of sign near the target (not across the opposite point).
if (fa < 0.0) != (fb < 0.0) && (fa - fb).abs() < 90.0 {
let (lo, hi) = if dir < 0.0 { (b, a) } else { (a, b) };
return bisect(lo, hi, f);
}
(a, fa) = (b, fb);
}
Err(EngineError::Calculation(format!("{body:?} did not reach {target:.2}° in 400 days")))
}
/// The retrograde periods of a planet that overlap `[from, to]`, in time order.
pub fn retrograde_periods(engine: &dyn Ephemeris, body: Body, from: f64, to: f64) -> Result<Vec<RetrogradePeriod>> {
let all = stations(engine, body, from - STATION_MARGIN, to + STATION_MARGIN)?;
let mut out = Vec::new();
for pair in all.windows(2) {
let (r, d) = (pair[0], pair[1]);
if !r.retrograde || d.retrograde || d.jd_ut < from || r.jd_ut > to {
continue;
}
out.push(RetrogradePeriod {
body,
station_retrograde: r,
station_direct: d,
shadow_start: reaches(engine, body, d.longitude, r.jd_ut, -1.0)?,
shadow_end: reaches(engine, body, r.longitude, d.jd_ut, 1.0)?,
});
}
Ok(out)
}
/// The Moon at a moment: phase and sign.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MoonNow {
pub longitude: f64,
pub elongation: f64,
pub phase: MoonPhaseName,
pub illumination: f64,
}
pub fn moon_now(engine: &dyn Ephemeris, jd: f64) -> Result<MoonNow> {
let sun = longitude(engine, Body::Sun, jd)?;
let moon = longitude(engine, Body::Moon, jd)?;
Ok(MoonNow {
longitude: moon,
elongation: normalize(moon - sun),
phase: phase_name(sun, moon),
illumination: engine.illumination(Body::Moon, jd)?,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bisection_finds_the_crossing() {
let t = bisect(0.0, 1.0, |t| Ok(t - 0.3)).unwrap();
assert!((t - 0.3).abs() < 1e-9);
}
#[test]
fn signed_difference_wraps() {
assert_eq!(diff(5.0, 355.0), 10.0);
assert_eq!(diff(355.0, 5.0), -10.0);
}
}
+152
View File
@@ -0,0 +1,152 @@
//! The sky calendar against known 2026 events (stations checked with the
//! upstream `swetest`, eclipses from the published eclipse tables).
//!
//! Requires the ephemeris files from `scripts/fetch-deps.sh` (data/ephe).
use std::path::PathBuf;
use std::sync::OnceLock;
use astro_engine::sky::{LunationKind, lunations, moon_ingresses, next_station, retrograde_periods, stations};
use astro_engine::swiss::SwissEphemeris;
use astro_engine::time::gregorian_from_jdn;
use astro_engine::{Body, Ephemeris, Frame, ZodiacSign};
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)")
})
}
/// 0h UT of a calendar day.
fn jd(y: i32, m: i32, d: i32) -> f64 {
// Fliegel–Van Flandern, valid for Gregorian dates.
let a = (14 - m) / 12;
let (y2, m2) = (y + 4800 - a, m + 12 * a - 3);
let jdn = d + (153 * m2 + 2) / 5 + 365 * y2 + y2 / 4 - y2 / 100 + y2 / 400 - 32045;
f64::from(jdn) - 0.5
}
/// `YYYY-MM-DD` of a moment, UT.
fn day(jd_ut: f64) -> String {
let (y, m, d) = gregorian_from_jdn((jd_ut + 0.5).floor() as i64);
format!("{y:04}-{m:02}-{d:02}")
}
#[test]
fn lunations_of_2026_include_the_eclipses() {
let all = lunations(engine(), jd(2026, 1, 1), jd(2027, 1, 1)).unwrap();
// About 12.4 lunations a year, four phases each.
assert!((48..=51).contains(&all.len()), "{}", all.len());
// The phases follow each other in order, a week or so apart.
for w in all.windows(2) {
let next = |k| match k {
LunationKind::NewMoon => LunationKind::FirstQuarter,
LunationKind::FirstQuarter => LunationKind::FullMoon,
LunationKind::FullMoon => LunationKind::LastQuarter,
LunationKind::LastQuarter => LunationKind::NewMoon,
};
assert_eq!(w[1].kind, next(w[0].kind));
let gap = w[1].jd_ut - w[0].jd_ut;
assert!((6.0..9.0).contains(&gap), "{gap}");
}
let full: Vec<String> = all.iter().filter(|l| l.kind == LunationKind::FullMoon).map(|l| day(l.jd_ut)).collect();
let new: Vec<String> = all.iter().filter(|l| l.kind == LunationKind::NewMoon).map(|l| day(l.jd_ut)).collect();
// Total lunar eclipse on 3 March, total solar eclipse on 12 August, and
// the "blue moon" (second full moon of May) on 31 May.
assert!(full.contains(&"2026-03-03".to_string()), "{full:?}");
assert!(full.contains(&"2026-05-31".to_string()), "{full:?}");
assert!(new.contains(&"2026-08-12".to_string()), "{new:?}");
// At the exact moment the Moon and the Sun are in line.
let e = engine();
for l in &all {
let sun = e.position(Body::Sun, l.jd_ut, &Frame::TROPICAL_GEOCENTRIC).unwrap().longitude;
let target = match l.kind {
LunationKind::NewMoon => 0.0,
LunationKind::FirstQuarter => 90.0,
LunationKind::FullMoon => 180.0,
LunationKind::LastQuarter => 270.0,
};
let off = ((l.moon_longitude - sun - target) + 540.0).rem_euclid(360.0) - 180.0;
assert!(off.abs() < 1e-4, "{off}");
}
// The eclipses fall on these lunations.
for ecl in e.eclipses(jd(2026, 1, 1), jd(2027, 1, 1)).unwrap() {
assert!(all.iter().any(|l| (l.jd_ut - ecl.jd_ut).abs() < 0.5), "{ecl:?}");
}
}
#[test]
fn the_moon_changes_sign_every_two_or_three_days() {
let all = moon_ingresses(engine(), jd(2026, 3, 1), jd(2026, 4, 1)).unwrap();
assert!((13..=15).contains(&all.len()), "{}", all.len());
for w in all.windows(2) {
assert_eq!(w[1].1.index(), (w[0].1.index() + 1) % 12);
let gap = w[1].0 - w[0].0;
assert!((1.9..3.0).contains(&gap), "{gap}");
}
let e = engine();
for &(t, sign) in &all {
let lon = e.position(Body::Moon, t, &Frame::TROPICAL_GEOCENTRIC).unwrap().longitude;
assert_eq!(ZodiacSign::from_longitude(lon + 1e-4), sign);
assert!(((lon - 30.0 * sign.index() as f64 + 540.0).rem_euclid(360.0) - 180.0).abs() < 1e-4);
}
}
#[test]
fn mercury_turns_retrograde_three_times_in_2026() {
let periods = retrograde_periods(engine(), Body::Mercury, jd(2026, 1, 1), jd(2027, 1, 1)).unwrap();
let days: Vec<(String, String)> =
periods.iter().map(|p| (day(p.station_retrograde.jd_ut), day(p.station_direct.jd_ut))).collect();
assert_eq!(
days,
[
("2026-02-26".into(), "2026-03-20".into()),
("2026-06-29".into(), "2026-07-23".into()),
("2026-10-24".into(), "2026-11-13".into()),
]
);
for p in &periods {
// Retrograde between the stations, direct before and after.
let e = engine();
let v = |t| e.position(Body::Mercury, t, &Frame::TROPICAL_GEOCENTRIC).unwrap().speed_longitude;
let mid = (p.station_retrograde.jd_ut + p.station_direct.jd_ut) / 2.0;
assert!(v(mid) < 0.0 && v(p.station_retrograde.jd_ut - 1.0) > 0.0 && v(p.station_direct.jd_ut + 1.0) > 0.0);
// The shadow: about two weeks on each side, at the stations' degrees.
let before = p.station_retrograde.jd_ut - p.shadow_start;
let after = p.shadow_end - p.station_direct.jd_ut;
assert!((8.0..25.0).contains(&before) && (8.0..25.0).contains(&after), "{before} {after}");
let lon = |t| e.position(Body::Mercury, t, &Frame::TROPICAL_GEOCENTRIC).unwrap().longitude;
assert!((lon(p.shadow_start) - p.station_direct.longitude).abs() < 1e-4);
assert!((lon(p.shadow_end) - p.station_retrograde.longitude).abs() < 1e-4);
}
}
#[test]
fn slow_planets_and_overlapping_periods() {
// Every planet turns retrograde at most once or so in a year; Saturn and
// the outer planets once, with a period of four to six months.
for body in [Body::Saturn, Body::Uranus, Body::Neptune, Body::Pluto] {
let periods = retrograde_periods(engine(), body, jd(2026, 1, 1), jd(2027, 1, 1)).unwrap();
assert!(!periods.is_empty(), "{body:?}");
for p in &periods {
let len = p.station_direct.jd_ut - p.station_retrograde.jd_ut;
assert!((120.0..170.0).contains(&len), "{body:?} {len}");
assert!(p.shadow_start < p.station_retrograde.jd_ut && p.shadow_end > p.station_direct.jd_ut);
}
}
// A period that began before the window still counts.
let mercury = retrograde_periods(engine(), Body::Mercury, jd(2026, 3, 10), jd(2026, 3, 11)).unwrap();
assert_eq!(mercury.len(), 1);
assert_eq!(day(mercury[0].station_retrograde.jd_ut), "2026-02-26");
// Stations alternate, and the next one is found from any moment.
let all = stations(engine(), Body::Mercury, jd(2026, 1, 1), jd(2027, 1, 1)).unwrap();
assert_eq!(all.len(), 6);
assert!(all.windows(2).all(|w| w[0].retrograde != w[1].retrograde));
let next = next_station(engine(), Body::Mercury, jd(2026, 3, 1), 200.0).unwrap().unwrap();
assert!(!next.retrograde);
assert_eq!(day(next.jd_ut), "2026-03-20");
}
+11 -1
View File
@@ -1,4 +1,4 @@
//! Client of the horoscope-api service (`POST /v1/natal`, `POST /v1/synastry`).
//! Client of the horoscope-api service (charts, forecasts, the sky by date).
//!
//! Requests and responses are passed as JSON: the horoscope service validates
//! the birth data itself, and its error objects are handed back unchanged so
@@ -48,6 +48,16 @@ impl HoroscopeClient {
self.post("/v1/forecast", request).await
}
/// `GET /v1/sky`: the sky now (planets, retrograde ones, the Moon).
pub async fn sky(&self) -> Result<Value, HoroscopeError> {
self.get("/v1/sky", &[]).await
}
/// `GET /v1/sky/events?year=`: a year's lunar phases, Moon sign changes and retrograde periods.
pub async fn sky_events(&self, year: i32) -> Result<Value, HoroscopeError> {
self.get("/v1/sky/events", &[("year", &year.to_string())]).await
}
/// `GET /v1/countries`
pub async fn countries(&self) -> Result<Value, HoroscopeError> {
self.get("/v1/countries", &[]).await