"""Equatorial declination of the natal planets (BUG-2088, astrologer reply B2). The report used to print ``shadbala.kala_bala.declination`` under the heading "Declination". That number is the intermediate angle of the Ayana-bala table (BPHS seven-point interpolation), not a coordinate. This module gives the real one: the declination of each body in the equator of date, read straight from the Swiss Ephemeris with ``FLG_EQUATORIAL``. * unit: degrees, north positive, south negative; * frame: equator and equinox of date, geocentric; ``apparent`` keeps nutation, ``mean`` drops it (the same two frames the natal longitudes use); * declination does not depend on the ayanamsa; * Rahu follows the chart's node mode; Ketu is the opposite point, so its declination is Rahu's with the sign reversed. The upstream skill's ``kranti_producer`` also keeps "declination minus ecliptic latitude" as an observation-only candidate. That value is returned here as ``ecliptic_point_declination`` for comparison and is not printed. Nothing is rounded for display here and nothing is guessed: a missing Julian day or a failed ephemeris call returns ``status: unavailable`` with no rows. """ from __future__ import annotations import logging from typing import Any, Dict, Optional logger = logging.getLogger(__name__) try: import swisseph as swe except ImportError: # pragma: no cover - environments without the ephemeris swe = None try: from ayanamsa_utils import configure_ephemeris_path except ImportError: # pragma: no cover - package import from scripts.ayanamsa_utils import configure_ephemeris_path SCHEMA = "jyotish.equatorial_declination.v1" PLANETS = ("Sun", "Moon", "Mars", "Mercury", "Jupiter", "Venus", "Saturn", "Rahu", "Ketu") POSITION_MODES = ("apparent", "mean") def _unavailable(reason: str) -> Dict[str, Any]: return {"schema": SCHEMA, "status": "unavailable", "reason": reason, "planets": {}} def planet_declinations(jd_ut: Any, *, node_mode: Any = "mean", position_mode: Any = "apparent") -> Dict[str, Any]: """Declination (degrees, north positive) of the nine grahas at ``jd_ut``. Returns ``{"status": "computed", "planets": {name: {"declination": float, "ecliptic_latitude": float, "ecliptic_point_declination": float}}, ...}``. """ if swe is None: return _unavailable("ephemeris_unavailable") if isinstance(jd_ut, bool) or not isinstance(jd_ut, (int, float)): return _unavailable("julian_day_missing") jd = float(jd_ut) node = "true" if str(node_mode or "mean").lower() == "true" else "mean" mode = str(position_mode or "apparent").lower() mode = "mean" if mode == "mean" else "apparent" # ``legacy`` is the apparent frame (BUG-1275) ids = { "Sun": swe.SUN, "Moon": swe.MOON, "Mars": swe.MARS, "Mercury": swe.MERCURY, "Jupiter": swe.JUPITER, "Venus": swe.VENUS, "Saturn": swe.SATURN, "Rahu": swe.TRUE_NODE if node == "true" else swe.MEAN_NODE, } configure_ephemeris_path(swe) flags = swe.FLG_SWIEPH | (swe.FLG_NONUT if mode == "mean" else 0) rows: Dict[str, Dict[str, float]] = {} for name, body in ids.items(): try: equatorial, equatorial_flag = swe.calc_ut(jd, body, flags | swe.FLG_EQUATORIAL) ecliptic, ecliptic_flag = swe.calc_ut(jd, body, flags) except swe.Error as exc: # a date outside the ephemeris range logger.warning("declination of %s unavailable: %s", name, exc) continue if equatorial_flag < 0 or ecliptic_flag < 0: continue declination = float(equatorial[1]) latitude = float(ecliptic[1]) rows[name] = { "declination": declination, "ecliptic_latitude": latitude, "ecliptic_point_declination": declination - latitude, } if "Rahu" in rows: rahu = rows["Rahu"] rows["Ketu"] = {key: -value for key, value in rahu.items()} if not rows: return _unavailable("ephemeris_call_failed") return { "schema": SCHEMA, "status": "computed", "unit": "degrees_north_positive", "frame": "equator_of_date_geocentric", "position_mode": mode, "node_mode": node, "julian_day_ut": jd, "source": "Swiss Ephemeris calc_ut with FLG_EQUATORIAL", "planets": rows, } def _dict(value: Any) -> Dict[str, Any]: return value if isinstance(value, dict) else {} def birth_julian_day(packet: Any) -> Optional[float]: """The birth Julian day (UT) the report packet already carries, or None.""" packet = _dict(packet) for birth in ( _dict(_dict(_dict(packet.get("core_chart")).get("chart")).get("birth_info")), _dict(packet.get("birth_info")), ): value = birth.get("julian_day") if isinstance(value, (int, float)) and not isinstance(value, bool): return float(value) return None def declinations_for_packet(packet: Any) -> Dict[str, Any]: """Declinations for a report packet, from the Julian day it carries. Reads ``core_chart.chart.birth_info.julian_day`` (falls back to ``birth_info.julian_day``), the node mode from ``birth_info`` and the position mode from ``calculation_profile``. No planet longitude is recomputed; only the equatorial coordinate is asked of the ephemeris. """ packet = _dict(packet) jd = birth_julian_day(packet) if jd is None: return _unavailable("julian_day_missing") birth = _dict(packet.get("birth_info")) or _dict(_dict(_dict(packet.get("core_chart")).get("chart")).get("birth_info")) profile = _dict(packet.get("calculation_profile")) settings = _dict(profile.get("effective_settings")) node_mode = birth.get("node_mode") or settings.get("node_mode") or profile.get("node_mode") or "mean" position_mode = settings.get("position_mode") or profile.get("position_mode") or "apparent" return planet_declinations(jd, node_mode=node_mode, position_mode=position_mode) def declination_degrees(packet: Any) -> Dict[str, float]: """``{planet: declination}`` for a packet; empty when it cannot be computed.""" found = declinations_for_packet(packet) return {name: row["declination"] for name, row in _dict(found.get("planets")).items()}