Files
sorsfonalak/crates/astro-engine/src/swiss.rs
T

404 lines
15 KiB
Rust
Raw Normal View History

//! [`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, EclipseEvent, EclipseKind, EclipseType, 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)
}
fn eclipses(&self, from_jd: f64, to_jd: f64) -> Result<Vec<EclipseEvent>> {
let _guard = lock();
let mut out = Vec::new();
for kind in [EclipseKind::Solar, EclipseKind::Lunar] {
let mut start = from_jd;
loop {
let mut tret = [0.0f64; 10];
let mut serr = [0 as c_char; sys::AS_MAXCH];
// SAFETY: tret has the 10 elements and serr the AS_MAXCH bytes the API requires.
let ret = unsafe {
match kind {
EclipseKind::Solar => sys::swe_sol_eclipse_when_glob(
start,
sys::SEFLG_SWIEPH,
0,
tret.as_mut_ptr(),
0,
serr.as_mut_ptr(),
),
EclipseKind::Lunar => sys::swe_lun_eclipse_when(
start,
sys::SEFLG_SWIEPH,
sys::SE_ECL_TOTAL | sys::SE_ECL_PARTIAL,
tret.as_mut_ptr(),
0,
serr.as_mut_ptr(),
),
}
};
if ret == sys::ERR {
return Err(EngineError::Calculation(c_string(&serr)));
}
let jd = tret[0];
if jd > to_jd {
break;
}
out.push(EclipseEvent { kind, eclipse_type: eclipse_type(ret), jd_ut: jd });
// Eclipses of one kind are at least two weeks apart.
start = jd + 10.0;
}
}
out.sort_by(|a, b| a.jd_ut.total_cmp(&b.jd_ut));
Ok(out)
}
}
fn eclipse_type(flags: i32) -> EclipseType {
if flags & sys::SE_ECL_ANNULAR_TOTAL != 0 {
EclipseType::Hybrid
} else if flags & sys::SE_ECL_TOTAL != 0 {
EclipseType::Total
} else if flags & sys::SE_ECL_ANNULAR != 0 {
EclipseType::Annular
} else if flags & sys::SE_ECL_PARTIAL != 0 {
EclipseType::Partial
} else {
EclipseType::Penumbral
}
}
#[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();
}
}