- Functional default = PVR Table 30 (functional_profile=pvr_table_30); the former product table is bphs_exception_profile, scored only when named (rectification names it, scores unchanged). profile_divergence shows both roles side by side; movable-lagna Moon by the table's paksha note; dual-lordship note; prior rulings BUG-1570/1590/#166 Q4 checked against Table 30. - Shadbala: six open items labelled parameter_sensitive; every option combination computed; only planets whose pass/fail flips get minimum_check=parameter_sensitive. - Vimshottari AD/PD rows carry parent_period_start / visible_period_start; the consult card cuts the balance MD from its full parent and clips at birth. - KP DBA: full first parent, clipped at birth (no balance rescale). - Mudda: balance fields + balance_method (angle default, time comparison apart), nominal_year_days, her crossing wording; Harsha combined blocked reason lists items. - D30 _meta describes the unequal parts (as her r40). - Golden recaptured with TTL=0. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
626 lines
29 KiB
Python
626 lines
29 KiB
Python
#!/usr/bin/env python3
|
|
"""Personal transit calendar: one natal chart, one date range, one row per day.
|
|
|
|
The 星历 month view reads this. Every day carries the layers below. Each layer
|
|
comes from a calculator that already exists in this repository; this module
|
|
only joins them on one date axis.
|
|
|
|
- Panchanga five limbs, in the subject's own ayanamsa (BUG-703 / BUG-1667),
|
|
from ``muhurta.panchanga_range_report``.
|
|
- Tara bala and Chandra bala against the natal Moon, from
|
|
``muhurta.calc_tarabala`` / ``muhurta.calc_chandrabala`` (Raman Muhurtha).
|
|
- The Moon's transit house from the natal Lagna and from the natal Moon.
|
|
- Ashtakavarga: SAV of the sign the Moon transits and the Moon's own BAV
|
|
there, from ``ashtakavarga.calc_ashtakavarga``.
|
|
- Transit conjunctions with natal points (Lagna, the nine grahas): the day
|
|
of closest approach, within 1° for the fast grahas and on the day the Moon
|
|
crosses the natal degree.
|
|
- Functional benefic / malefic for the natal Lagna, from
|
|
``functional_layer.functional_layer_for_ascendant``. It decides the sign of
|
|
a contact on the Moon or the Lagna.
|
|
- Activity verdicts (marriage, business, travel, medical, education) with the
|
|
native's Tara / Chandra bala and Lagna, from ``muhurta.check_activity_muhurta``.
|
|
- Events: ingress and station (``ephemeris_events``), combustion start / end,
|
|
solar and lunar eclipses, Vimshottari antardasha and pratyantardasha
|
|
boundaries.
|
|
- Month backdrop: running Vimshottari MD / AD / PD and Narayana MD / AD
|
|
(product Rath view), Sade Sati / Kantaka Shani, slow-graha contacts
|
|
(Jupiter, Saturn, Rahu, Ketu) and Jupiter + Saturn double transit houses.
|
|
|
|
Day level and day themes are rule codes (``CALENDAR_RULES_VERSION``). The
|
|
product writes the words. Nothing here is a model call.
|
|
|
|
Not wired, on purpose: KP sub-lord transits (parameter sensitive), Tajika
|
|
(yearly), Kakshya (the transit helper has no caller and the registry keeps it
|
|
as supporting evidence only), VedAstro range scan (external, case-bound).
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from datetime import datetime, timedelta
|
|
from pathlib import Path
|
|
import logging
|
|
import sys
|
|
from typing import Any
|
|
|
|
SCRIPT_DIR = Path(__file__).resolve().parent
|
|
if str(SCRIPT_DIR) not in sys.path:
|
|
sys.path.insert(0, str(SCRIPT_DIR))
|
|
|
|
import swisseph as swe # noqa: E402
|
|
|
|
from ayanamsa_utils import normalize_ayanamsa_name, temporary_ayanamsa # noqa: E402
|
|
from chart_dasha.birth_moment import antardashas, mahadashas # noqa: E402
|
|
from dasha_common import VIMSHOTTARI_ORDER, VIMSHOTTARI_YEARS # noqa: E402
|
|
from domain_calculation_service import compute_chart # noqa: E402
|
|
import muhurta # noqa: E402
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
CALENDAR_RULES_VERSION = "personal_calendar_v1"
|
|
MAX_RANGE_DAYS = 45
|
|
|
|
SIGNS = (
|
|
"Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo",
|
|
"Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces",
|
|
)
|
|
GRAHAS = ("Sun", "Moon", "Mars", "Mercury", "Jupiter", "Venus", "Saturn", "Rahu", "Ketu")
|
|
FAST = ("Sun", "Mercury", "Venus", "Mars")
|
|
SLOW = ("Jupiter", "Saturn", "Rahu", "Ketu")
|
|
NATAL_POINTS = ("Lagna",) + GRAHAS
|
|
CONTACT_ORB = 1.0
|
|
SLOW_CONTACT_ORB = 1.0
|
|
COMBUST_BODIES = ("Mercury", "Venus", "Mars", "Jupiter", "Saturn")
|
|
NATURAL_MALEFICS = {"Sun", "Mars", "Saturn", "Rahu", "Ketu"}
|
|
NATURAL_BENEFICS = {"Jupiter", "Venus", "Mercury", "Moon"}
|
|
|
|
# Moon's transit house from the Lagna -> theme code.
|
|
HOUSE_THEME = {
|
|
1: "self", 2: "money", 3: "talk", 4: "home", 5: "romance", 6: "health",
|
|
7: "partner", 8: "upheaval", 9: "travel", 10: "career", 11: "gain", 12: "rest",
|
|
}
|
|
# A transiting graha on a natal point -> theme code.
|
|
TRANSIT_THEME = {
|
|
"Sun": "career", "Mercury": "talk", "Venus": "romance", "Mars": "clash",
|
|
"Jupiter": "help", "Saturn": "pressure", "Rahu": "mood", "Ketu": "mood",
|
|
}
|
|
# The Moon crossing a natal graha -> theme code (it crosses every natal point once a month).
|
|
MOON_ON_THEME = {
|
|
"Lagna": "self", "Sun": "self", "Moon": "mood", "Mars": "clash", "Mercury": "talk",
|
|
"Jupiter": "help", "Venus": "romance", "Saturn": "pressure", "Rahu": "mood", "Ketu": "mood",
|
|
}
|
|
TRIGGER_PRIORITY = {
|
|
"eclipse": 10, "station": 8, "dasha": 7, "ingress": 6, "contact": 5,
|
|
"combust": 3, "moon_contact": 4,
|
|
}
|
|
ACTIVITIES = ("marriage", "business", "travel", "medical", "education")
|
|
_SWE_IDS = {
|
|
"Sun": swe.SUN, "Moon": swe.MOON, "Mars": swe.MARS, "Mercury": swe.MERCURY,
|
|
"Jupiter": swe.JUPITER, "Venus": swe.VENUS, "Saturn": swe.SATURN,
|
|
}
|
|
|
|
|
|
class PersonalCalendarError(ValueError):
|
|
"""Bad request input."""
|
|
|
|
|
|
def _sep(a: float, b: float) -> float:
|
|
return abs((a - b + 180.0) % 360.0 - 180.0)
|
|
|
|
|
|
def _house(from_sign: int, to_sign: int) -> int:
|
|
return (to_sign - from_sign) % 12 + 1
|
|
|
|
|
|
def _parse_day(value: Any, key: str) -> datetime:
|
|
if not isinstance(value, str):
|
|
raise PersonalCalendarError(f"{key} must be YYYY-MM-DD")
|
|
try:
|
|
return datetime.strptime(value[:10], "%Y-%m-%d")
|
|
except ValueError as exc:
|
|
raise PersonalCalendarError(f"{key} must be YYYY-MM-DD") from exc
|
|
|
|
|
|
def _float(body: dict[str, Any], key: str, low: float, high: float) -> float:
|
|
try:
|
|
value = float(body[key])
|
|
except (KeyError, TypeError, ValueError) as exc:
|
|
raise PersonalCalendarError(f"{key} is required") from exc
|
|
if not low <= value <= high:
|
|
raise PersonalCalendarError(f"{key} out of range")
|
|
return value
|
|
|
|
|
|
class _Sky:
|
|
"""Sidereal positions in one ayanamsa, cached per Julian day."""
|
|
|
|
def __init__(self, ayanamsa: str, node_mode: str):
|
|
self.ayanamsa = ayanamsa
|
|
self.node_id = swe.TRUE_NODE if node_mode == "true" else swe.MEAN_NODE
|
|
self.flags = swe.FLG_SWIEPH | swe.FLG_SPEED | swe.FLG_SIDEREAL
|
|
self._cache: dict[float, dict[str, tuple[float, float]]] = {}
|
|
|
|
def at(self, jd: float) -> dict[str, tuple[float, float]]:
|
|
hit = self._cache.get(jd)
|
|
if hit is not None:
|
|
return hit
|
|
out: dict[str, tuple[float, float]] = {}
|
|
with temporary_ayanamsa(self.ayanamsa, swe):
|
|
for name, pid in _SWE_IDS.items():
|
|
pos, _ = swe.calc_ut(jd, pid, self.flags)
|
|
out[name] = (pos[0] % 360.0, pos[3])
|
|
node, _ = swe.calc_ut(jd, self.node_id, self.flags)
|
|
out["Rahu"] = (node[0] % 360.0, node[3])
|
|
out["Ketu"] = ((node[0] + 180.0) % 360.0, node[3])
|
|
self._cache[jd] = out
|
|
return out
|
|
|
|
|
|
def _local_jd(day: datetime, local_hour: float, tz: float) -> float:
|
|
return swe.julday(day.year, day.month, day.day, local_hour - tz)
|
|
|
|
|
|
def _natal_points(chart: dict[str, Any]) -> dict[str, float]:
|
|
planets = chart.get("planets") or {}
|
|
points = {"Lagna": float((chart.get("ascendant") or {})["lon"])}
|
|
for name in GRAHAS:
|
|
row = planets.get(name)
|
|
if isinstance(row, dict) and row.get("lon") is not None:
|
|
points[name] = float(row["lon"]) % 360.0
|
|
if "Ketu" not in points and "Rahu" in points:
|
|
points["Ketu"] = (points["Rahu"] + 180.0) % 360.0
|
|
return points
|
|
|
|
|
|
def _functional(chart: dict[str, Any]) -> dict[str, Any]:
|
|
try:
|
|
from functional_layer import functional_layer_for_ascendant
|
|
except ModuleNotFoundError: # pragma: no cover
|
|
from scripts.functional_layer import functional_layer_for_ascendant
|
|
layer = functional_layer_for_ascendant(chart.get("ascendant"), chart.get("planets"))
|
|
return {
|
|
"status": layer.get("status"),
|
|
"benefics": list(layer.get("functional_benefics") or []),
|
|
"malefics": list(layer.get("functional_malefics") or []),
|
|
"yogakarakas": list(layer.get("yogakarakas") or []),
|
|
}
|
|
|
|
|
|
def _contact_sign(graha: str, functional: dict[str, Any]) -> tuple[int, str | None]:
|
|
"""+1 / -1 / 0 for a transit on the natal Moon or Lagna, and the conflict note."""
|
|
fb = graha in functional["benefics"] or graha in functional["yogakarakas"]
|
|
fm = graha in functional["malefics"]
|
|
natural_good = graha in NATURAL_BENEFICS
|
|
natural_bad = graha in NATURAL_MALEFICS
|
|
if natural_good and fm:
|
|
return 0, "natural_benefic_functional_malefic"
|
|
if natural_bad and fb:
|
|
return 0, "natural_malefic_functional_benefic"
|
|
if natural_good or fb:
|
|
return 1, None
|
|
if natural_bad or fm:
|
|
return -1, None
|
|
return 0, None
|
|
|
|
|
|
def _ashtakavarga(chart: dict[str, Any]) -> dict[str, Any] | None:
|
|
try:
|
|
from ashtakavarga import calc_ashtakavarga
|
|
asc_idx = SIGNS.index((chart.get("ascendant") or {}).get("sign"))
|
|
result = calc_ashtakavarga(chart.get("planets") or {}, asc_idx)
|
|
except Exception as exc: # the rest of the day still has meaning
|
|
logger.warning("personal_calendar ashtakavarga degraded: %s", type(exc).__name__)
|
|
return None
|
|
sav = (result.get("sav") or {}).get("scores") or {}
|
|
bindus = ((result.get("bav") or {}).get("Moon") or {}).get("bindus") or []
|
|
return {
|
|
"sav": {sign: int(sav.get(sign, 0)) for sign in SIGNS},
|
|
"moon_bav": {sign: int(bindus[i]) for i, sign in enumerate(SIGNS)} if len(bindus) == 12 else {},
|
|
}
|
|
|
|
|
|
def _subperiods(parent: dict[str, Any]) -> list[dict[str, Any]]:
|
|
"""Pratyantardashas of one antardasha: the parent's own length split by years/120."""
|
|
total = parent["end"] - parent["start"]
|
|
first = VIMSHOTTARI_ORDER.index(parent["lord"])
|
|
rows, start = [], parent["start"]
|
|
for offset in range(9):
|
|
lord = VIMSHOTTARI_ORDER[(first + offset) % 9]
|
|
end = parent["end"] if offset == 8 else start + total * (VIMSHOTTARI_YEARS[lord] / 120.0)
|
|
rows.append({"lord": lord, "start": start, "end": end})
|
|
start = end
|
|
return rows
|
|
|
|
|
|
def _vimshottari(birth_dt: datetime, moon_lon: float, start: datetime, end: datetime) -> dict[str, Any]:
|
|
timeline, *_rest = mahadashas(birth_dt, moon_lon, through=end)
|
|
running: dict[str, Any] = {}
|
|
boundaries: list[dict[str, Any]] = []
|
|
for md in timeline:
|
|
if md["end"] < start or md["start"] > end + timedelta(days=1):
|
|
continue
|
|
for ad in antardashas(md):
|
|
if ad["end"] < start or ad["start"] > end + timedelta(days=1):
|
|
continue
|
|
if start <= ad["start"] <= end:
|
|
boundaries.append({"date": ad["start"].strftime("%Y-%m-%d"), "level": "antardasha", "md": md["lord"], "lord": ad["lord"]})
|
|
for pd in _subperiods(ad):
|
|
if pd["end"] < start or pd["start"] > end + timedelta(days=1):
|
|
continue
|
|
if start <= pd["start"] <= end:
|
|
boundaries.append({"date": pd["start"].strftime("%Y-%m-%d"), "level": "pratyantardasha", "md": md["lord"], "ad": ad["lord"], "lord": pd["lord"]})
|
|
if pd["start"] <= start < pd["end"]:
|
|
running = {
|
|
"md": md["lord"], "ad": ad["lord"], "pd": pd["lord"],
|
|
"md_end": md["end"].strftime("%Y-%m-%d"),
|
|
"ad_end": ad["end"].strftime("%Y-%m-%d"),
|
|
"pd_end": pd["end"].strftime("%Y-%m-%d"),
|
|
}
|
|
return {"running": running, "boundaries": boundaries}
|
|
|
|
|
|
def _narayana(chart: dict[str, Any], birth_dt: datetime, reference: datetime) -> dict[str, Any]:
|
|
try:
|
|
import narayana_dasha
|
|
from narayana_legacy_label import narayana_age, product_narayana
|
|
asc_idx = SIGNS.index((chart.get("ascendant") or {}).get("sign"))
|
|
lons = {name: float(row["lon"]) for name, row in (chart.get("planets") or {}).items()
|
|
if isinstance(row, dict) and row.get("lon") is not None}
|
|
age = narayana_age(birth_dt, reference)
|
|
legacy = narayana_dasha.narayana_dasha_full_report(lagna_sign_idx=asc_idx, planet_lons=lons, current_age=age, birth_year=birth_dt.year)
|
|
product = product_narayana(legacy, asc_idx, lons, current_age=age, birth_year=birth_dt.year,
|
|
birth_datetime=birth_dt)
|
|
except Exception as exc:
|
|
logger.warning("personal_calendar narayana degraded: %s", type(exc).__name__)
|
|
return {"status": "blocked", "reason": type(exc).__name__}
|
|
current = product.get("current_dasha") or {}
|
|
if product.get("status") == "blocked" or not current.get("md"):
|
|
return {"status": "blocked", "reason": str(product.get("reason") or "no_current_period")}
|
|
|
|
def _row(period: Any) -> dict[str, Any] | None:
|
|
if not isinstance(period, dict) or period.get("sign") not in SIGNS:
|
|
return None
|
|
sign_idx = SIGNS.index(period["sign"])
|
|
return {"sign": period["sign"], "house": _house(asc_idx, sign_idx)}
|
|
|
|
return {"status": "used", "md": _row(current.get("md")), "ad": _row(current.get("ad"))}
|
|
|
|
|
|
def _sade_sati(chart: dict[str, Any], saturn_lon: float, reference: datetime) -> dict[str, Any]:
|
|
try:
|
|
from sade_sati import calc_sade_sati_complete
|
|
result = calc_sade_sati_complete(
|
|
float(chart["planets"]["Moon"]["lon"]), float(chart["ascendant"]["lon"]), saturn_lon, reference,
|
|
)
|
|
except Exception as exc:
|
|
logger.warning("personal_calendar sade_sati degraded: %s", type(exc).__name__)
|
|
return {"status": "blocked"}
|
|
sade = result.get("sade_sati") or {}
|
|
kantaka = result.get("kantaka_shani") or {}
|
|
return {
|
|
"status": "used",
|
|
"sade_sati_active": bool(sade.get("active") or sade.get("is_active")),
|
|
"phase": sade.get("phase") or sade.get("current_phase"),
|
|
"kantaka_active": bool(kantaka.get("active") or kantaka.get("is_active")),
|
|
"saturn_house_from_moon": _house(int(float(chart["planets"]["Moon"]["lon"]) // 30), int(saturn_lon // 30)),
|
|
}
|
|
|
|
|
|
def _double_transit(body: dict[str, Any], reference: datetime) -> dict[str, Any]:
|
|
try:
|
|
import jyotish_engine as engine
|
|
from consultation_native_layers import _double_transit_args
|
|
except Exception as exc: # pragma: no cover
|
|
return {"status": "blocked", "reason": type(exc).__name__}
|
|
houses: list[int] = []
|
|
for house in range(1, 13):
|
|
try:
|
|
result = engine.cmd_double_transit_pac(_double_transit_args(body, reference, house))
|
|
except Exception as exc:
|
|
logger.warning("personal_calendar double_transit degraded: %s", type(exc).__name__)
|
|
return {"status": "blocked", "reason": type(exc).__name__}
|
|
if isinstance(result, dict) and result.get("error"):
|
|
return {"status": "blocked", "reason": "double_transit_unavailable"}
|
|
rows = result.get("double_transit") if isinstance(result, dict) else None
|
|
if any(isinstance(row, dict) and row.get("layer") in (None, "D1") for row in rows or []):
|
|
houses.append(house)
|
|
return {"status": "used", "date": reference.strftime("%Y-%m-%d"), "houses": houses}
|
|
|
|
|
|
def _eclipses(start: datetime, end: datetime, sky: _Sky, natal: dict[str, float], lagna_sign: int) -> list[dict[str, Any]]:
|
|
out: list[dict[str, Any]] = []
|
|
jd_start = swe.julday(start.year, start.month, start.day, 0.0)
|
|
jd_end = swe.julday(end.year, end.month, end.day, 24.0)
|
|
for kind, finder in (("solar", lambda jd: swe.sol_eclipse_when_glob(jd, swe.FLG_SWIEPH, 0)),
|
|
("lunar", lambda jd: swe.lun_eclipse_when(jd, swe.FLG_SWIEPH, 0))):
|
|
try:
|
|
_flag, times = finder(jd_start - 1)
|
|
except Exception as exc: # pragma: no cover
|
|
logger.warning("personal_calendar eclipse degraded: %s", type(exc).__name__)
|
|
continue
|
|
peak = times[0]
|
|
if not jd_start <= peak <= jd_end:
|
|
continue
|
|
positions = sky.at(peak)
|
|
lon = positions["Sun"][0] if kind == "solar" else positions["Moon"][0]
|
|
y, m, d, _h = swe.revjul(peak)
|
|
hits = [name for name, natal_lon in natal.items() if _sep(lon, natal_lon) <= 3.0]
|
|
out.append({
|
|
"kind": "eclipse", "eclipse": kind, "date_ut": f"{y:04d}-{m:02d}-{d:02d}",
|
|
"sign": SIGNS[int(lon // 30)], "house": _house(lagna_sign, int(lon // 30)), "natal_hits": hits,
|
|
})
|
|
return out
|
|
|
|
|
|
def _activity(panchanga: dict[str, Any], natal_nak0: int, natal_moon_sign0: int, lagna_sign0: int) -> dict[str, Any]:
|
|
out: dict[str, Any] = {}
|
|
for activity in ACTIVITIES:
|
|
row = muhurta.check_activity_muhurta(
|
|
panchanga, activity, lagna=lagna_sign0,
|
|
birth_nakshatra=natal_nak0, birth_moon_sign=natal_moon_sign0,
|
|
)
|
|
out[activity] = {
|
|
"verdict": muhurta.activity_verdict_code(row.get("verdict")),
|
|
"blocks": list(row.get("blocking_doshas") or []),
|
|
}
|
|
return out
|
|
|
|
|
|
def _panchanga_factors(panchanga: dict[str, Any]) -> dict[str, Any]:
|
|
return {
|
|
"vara": {"name": panchanga["vara"]["vara"], "quality": panchanga["vara"]["quality"]},
|
|
"tithi": {"name": panchanga["tithi"]["full_name"], "number": panchanga["tithi"]["tithi_num"], "quality": panchanga["tithi"]["quality"]},
|
|
"nakshatra": {"name": panchanga["nakshatra"]["nakshatra"], "index": panchanga["nakshatra"]["nakshatra_idx"], "pada": panchanga["nakshatra"].get("pada"), "quality": panchanga["nakshatra"]["quality"]},
|
|
"yoga": {"name": panchanga["yoga"]["yoga"], "quality": panchanga["yoga"]["quality"]},
|
|
"karana": {"name": panchanga["karana"]["karana"], "quality": panchanga["karana"]["quality"], "vishti": bool(panchanga["karana"].get("is_vishti"))},
|
|
}
|
|
|
|
|
|
def score_day(day: dict[str, Any]) -> tuple[str, list[dict[str, Any]]]:
|
|
"""Level and the signed reasons behind it (``personal_calendar_v1``)."""
|
|
reasons: list[dict[str, Any]] = []
|
|
tara = day["tara"]
|
|
if tara["quality"] == "good":
|
|
reasons.append({"code": "tara_good", "weight": 1, "tara": tara["name"]})
|
|
elif tara["quality"] == "bad":
|
|
reasons.append({"code": "tara_bad", "weight": -1, "tara": tara["name"]})
|
|
chandra = day["chandrabala"]
|
|
if chandra["distance"] == 8:
|
|
reasons.append({"code": "chandrashtama", "weight": -2})
|
|
elif chandra["avoided"]:
|
|
reasons.append({"code": "chandrabala_bad", "weight": -1, "distance": chandra["distance"]})
|
|
sav = day.get("ashtakavarga")
|
|
if sav:
|
|
if sav["sav"] >= 30:
|
|
reasons.append({"code": "sav_strong", "weight": 1, "bindus": sav["sav"]})
|
|
elif sav["sav"] <= 24:
|
|
reasons.append({"code": "sav_weak", "weight": -1, "bindus": sav["sav"]})
|
|
good = sum(1 for factor in day["panchanga"].values() if factor["quality"] == "subha")
|
|
panch = 1 if good >= 4 else (-1 if good <= 1 else 0)
|
|
if day["panchanga"]["karana"]["vishti"]:
|
|
panch = min(panch, 0) - 1
|
|
if panch:
|
|
reasons.append({"code": "panchanga_good" if panch > 0 else "panchanga_bad", "weight": max(-1, panch), "subha": good, "vishti": day["panchanga"]["karana"]["vishti"]})
|
|
for contact in day["contacts"]:
|
|
if contact["natal"] in ("Moon", "Lagna") and contact.get("sign"):
|
|
reasons.append({"code": "contact_" + ("good" if contact["sign"] > 0 else "bad"), "weight": contact["sign"], "transit": contact["transit"], "natal": contact["natal"]})
|
|
total = sum(r["weight"] for r in reasons)
|
|
if chandra["distance"] == 8 or total <= -2:
|
|
level = "bad"
|
|
elif total >= 2:
|
|
level = "good"
|
|
else:
|
|
level = "mid"
|
|
return level, reasons
|
|
|
|
|
|
def day_themes(day: dict[str, Any], dasha_lords: set[str], limit: int = 3) -> list[dict[str, Any]]:
|
|
"""The Moon's house first, then the strongest triggers, at most ``limit`` themes."""
|
|
themes: list[dict[str, Any]] = [{
|
|
"theme": HOUSE_THEME[day["moon"]["house_from_lagna"]],
|
|
"sources": [{"kind": "moon_house", "house": day["moon"]["house_from_lagna"]}],
|
|
}]
|
|
triggers: list[tuple[int, str, dict[str, Any]]] = []
|
|
for contact in day["contacts"]:
|
|
if contact["transit"] == "Moon":
|
|
theme = MOON_ON_THEME.get(contact["natal"], "mood")
|
|
weight = TRIGGER_PRIORITY["moon_contact"] + (2 if contact["natal"] in dasha_lords else 0)
|
|
triggers.append((weight, theme, {"kind": "moon_contact", **contact}))
|
|
else:
|
|
theme = TRANSIT_THEME[contact["transit"]]
|
|
weight = TRIGGER_PRIORITY["contact"] + (2 if contact["transit"] in dasha_lords or contact["natal"] in dasha_lords else 0)
|
|
triggers.append((weight, theme, {"kind": "contact", **contact}))
|
|
for event in day["events"]:
|
|
kind = event["kind"]
|
|
if kind == "ingress":
|
|
theme = HOUSE_THEME[event["house"]]
|
|
elif kind == "combust":
|
|
theme = TRANSIT_THEME.get(event["body"], "mood")
|
|
elif kind in ("station", "eclipse", "dasha"):
|
|
theme = "upheaval" if kind != "station" else TRANSIT_THEME.get(event["body"], "upheaval")
|
|
else:
|
|
continue
|
|
triggers.append((TRIGGER_PRIORITY.get(kind, 1), theme, event))
|
|
triggers.sort(key=lambda row: -row[0])
|
|
for _weight, theme, source in triggers:
|
|
existing = next((row for row in themes if row["theme"] == theme), None)
|
|
if existing:
|
|
existing["sources"].append(source)
|
|
elif len(themes) < limit:
|
|
themes.append({"theme": theme, "sources": [source]})
|
|
return themes
|
|
|
|
|
|
def build_personal_calendar(body: dict[str, Any] | None) -> dict[str, Any]:
|
|
if not isinstance(body, dict):
|
|
raise PersonalCalendarError("JSON body must be an object")
|
|
start = _parse_day(body.get("start_date"), "start_date")
|
|
end = _parse_day(body.get("end_date"), "end_date")
|
|
if end < start:
|
|
raise PersonalCalendarError("end_date must be on or after start_date")
|
|
if (end - start).days + 1 > MAX_RANGE_DAYS:
|
|
raise PersonalCalendarError(f"range must be <= {MAX_RANGE_DAYS} days")
|
|
for key in ("year", "month", "day", "hour", "minute"):
|
|
if body.get(key) is None:
|
|
raise PersonalCalendarError(f"{key} is required")
|
|
tz = _float(body, "tz", -14, 14)
|
|
lat = _float(body, "lat", -90, 90)
|
|
lon = _float(body, "lon", -180, 180)
|
|
ayanamsa = normalize_ayanamsa_name(body.get("ayanamsa"))
|
|
node_mode = "true" if str(body.get("node_mode") or "mean").lower() == "true" else "mean"
|
|
here_lat = float(body.get("current_lat", lat))
|
|
here_lon = float(body.get("current_lon", lon))
|
|
here_tz = float(body.get("current_tz", tz))
|
|
|
|
chart = compute_chart({**body, "ayanamsa": ayanamsa, "node_mode": node_mode})
|
|
natal = _natal_points(chart)
|
|
lagna_sign = int(natal["Lagna"] // 30)
|
|
natal_moon = natal["Moon"]
|
|
natal_moon_sign = int(natal_moon // 30)
|
|
natal_nak = int(natal_moon // (360.0 / 27.0))
|
|
functional = _functional(chart)
|
|
av = _ashtakavarga(chart)
|
|
birth_dt = datetime(int(body["year"]), int(body["month"]), int(body["day"]), int(body["hour"]), int(body["minute"]))
|
|
vim = _vimshottari(birth_dt, natal_moon, start, end)
|
|
dasha_lords = {lord for lord in (vim["running"].get("md"), vim["running"].get("ad"), vim["running"].get("pd")) if lord}
|
|
|
|
sky = _Sky(ayanamsa, node_mode)
|
|
report = muhurta.panchanga_range_report(
|
|
start.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d"),
|
|
lat=here_lat, lon=here_lon, tz=here_tz, ayanamsa_name=ayanamsa,
|
|
)
|
|
rows = {row["query_date"]: row for row in report.get("days") or []}
|
|
|
|
try:
|
|
import ephemeris_events
|
|
ingress = ephemeris_events.build_ephemeris_events({
|
|
"start_date": (start - timedelta(days=1)).strftime("%Y-%m-%d"),
|
|
"end_date": end.strftime("%Y-%m-%d"),
|
|
"ayanamsa": ayanamsa, "node_mode": node_mode,
|
|
}).get("events") or []
|
|
except Exception as exc:
|
|
logger.warning("personal_calendar ephemeris_events degraded: %s", type(exc).__name__)
|
|
ingress = []
|
|
eclipses = _eclipses(start, end, sky, natal, lagna_sign)
|
|
|
|
from jyotish_engine import is_combust # heavy module, imported once per request
|
|
|
|
events_by_day: dict[str, list[dict[str, Any]]] = {}
|
|
for event in ingress:
|
|
row = {"kind": event["kind"], "body": event["body"].capitalize()}
|
|
if event["kind"] == "ingress":
|
|
row.update({"sign": event["to_sign"], "house": _house(lagna_sign, SIGNS.index(event["to_sign"]))})
|
|
else:
|
|
row["motion"] = event["motion"]
|
|
events_by_day.setdefault(event["date"], []).append(row)
|
|
for eclipse in eclipses:
|
|
events_by_day.setdefault(eclipse["date_ut"], []).append(eclipse)
|
|
for boundary in vim["boundaries"]:
|
|
events_by_day.setdefault(boundary["date"], []).append({"kind": "dasha", **boundary})
|
|
|
|
days: list[dict[str, Any]] = []
|
|
previous_combust: dict[str, bool] | None = None
|
|
cursor = start - timedelta(days=1)
|
|
noon = {}
|
|
while cursor <= end + timedelta(days=1):
|
|
noon[cursor.strftime("%Y-%m-%d")] = sky.at(_local_jd(cursor, 12.0, here_tz))
|
|
cursor += timedelta(days=1)
|
|
|
|
cursor = start - timedelta(days=1)
|
|
while cursor <= end:
|
|
iso = cursor.strftime("%Y-%m-%d")
|
|
pos = noon[iso]
|
|
combust = {name: is_combust(name, pos[name][0], pos["Sun"][0], pos[name][1] < 0) for name in COMBUST_BODIES}
|
|
if cursor < start:
|
|
previous_combust = combust
|
|
cursor += timedelta(days=1)
|
|
continue
|
|
if previous_combust is not None:
|
|
for name in COMBUST_BODIES:
|
|
if combust[name] != previous_combust[name]:
|
|
events_by_day.setdefault(iso, []).append({"kind": "combust", "body": name, "state": "start" if combust[name] else "end"})
|
|
previous_combust = combust
|
|
|
|
row = rows.get(iso)
|
|
if row is None:
|
|
raise RuntimeError(f"panchanga row missing for {iso}")
|
|
panchanga = row["panchanga"]
|
|
moon_lon = float(panchanga["nakshatra"]["moon_lon"]) % 360.0
|
|
moon_sign = int(moon_lon // 30)
|
|
nak0 = int(panchanga["nakshatra"]["nakshatra_idx"])
|
|
tara = muhurta.calc_tarabala(natal_nak, nak0)
|
|
chandra = muhurta.calc_chandrabala(natal_moon_sign, moon_sign)
|
|
|
|
contacts: list[dict[str, Any]] = []
|
|
before = noon[(cursor - timedelta(days=1)).strftime("%Y-%m-%d")]
|
|
after = noon[(cursor + timedelta(days=1)).strftime("%Y-%m-%d")]
|
|
for graha in FAST:
|
|
for point, natal_lon in natal.items():
|
|
today_sep = _sep(pos[graha][0], natal_lon)
|
|
if today_sep <= CONTACT_ORB and today_sep <= _sep(before[graha][0], natal_lon) and today_sep < _sep(after[graha][0], natal_lon):
|
|
sign, conflict = _contact_sign(graha, functional) if point in ("Moon", "Lagna") else (0, None)
|
|
contacts.append({"transit": graha, "natal": point, "orb": round(today_sep, 2), "sign": sign, "functional_conflict": conflict})
|
|
moon_start = sky.at(_local_jd(cursor, 0.0, here_tz))["Moon"][0]
|
|
moon_end = sky.at(_local_jd(cursor, 24.0, here_tz))["Moon"][0]
|
|
arc = (moon_end - moon_start) % 360.0
|
|
for point, natal_lon in natal.items():
|
|
if point == "Moon":
|
|
continue # the Moon's return is the Janma Tara / Chandra bala row already
|
|
if (natal_lon - moon_start) % 360.0 <= arc:
|
|
contacts.append({"transit": "Moon", "natal": point, "orb": 0.0, "sign": 0, "functional_conflict": None})
|
|
|
|
day: dict[str, Any] = {
|
|
"date": iso,
|
|
"panchanga": _panchanga_factors(panchanga),
|
|
"moon": {
|
|
"sign": SIGNS[moon_sign], "nakshatra_index": nak0,
|
|
"house_from_lagna": _house(lagna_sign, moon_sign),
|
|
"house_from_moon": _house(natal_moon_sign, moon_sign),
|
|
},
|
|
"tara": {"distance": tara["distance_inclusive"], "name": tara["tara"], "quality": "good" if tara["quality"] in ("good", "activity_exception_usable") else ("bad" if tara["quality"] == "bad" else "mild")},
|
|
"chandrabala": {"distance": chandra["distance_inclusive"], "avoided": bool(chandra["avoided"])},
|
|
"ashtakavarga": ({"sav": av["sav"][SIGNS[moon_sign]], "moon_bav": av["moon_bav"].get(SIGNS[moon_sign])} if av else None),
|
|
"contacts": contacts,
|
|
"events": events_by_day.get(iso, []),
|
|
"activities": _activity(panchanga, natal_nak, natal_moon_sign, lagna_sign),
|
|
}
|
|
level, reasons = score_day(day)
|
|
day["level"] = level
|
|
day["reasons"] = reasons
|
|
day["themes"] = day_themes(day, dasha_lords)
|
|
days.append(day)
|
|
cursor += timedelta(days=1)
|
|
|
|
middle = start + (end - start) / 2
|
|
middle_pos = sky.at(_local_jd(middle, 12.0, here_tz))
|
|
slow_contacts = []
|
|
for graha in SLOW:
|
|
for point, natal_lon in natal.items():
|
|
separation = _sep(middle_pos[graha][0], natal_lon)
|
|
if separation <= SLOW_CONTACT_ORB:
|
|
slow_contacts.append({"transit": graha, "natal": point, "orb": round(separation, 2)})
|
|
|
|
return {
|
|
"success": True,
|
|
"endpoint": "personal_calendar",
|
|
"rules_version": CALENDAR_RULES_VERSION,
|
|
"calculation": {
|
|
"ayanamsa": ayanamsa, "node_mode": node_mode,
|
|
"start_date": start.strftime("%Y-%m-%d"), "end_date": end.strftime("%Y-%m-%d"),
|
|
"panchanga_reference": "sunrise + 6h, local", "positions_reference": "12:00 local",
|
|
"contact_orb_deg": CONTACT_ORB,
|
|
},
|
|
"natal": {
|
|
"lagna_sign": SIGNS[lagna_sign], "moon_sign": SIGNS[natal_moon_sign],
|
|
"moon_nakshatra_index": natal_nak, "functional": functional,
|
|
},
|
|
"backdrop": {
|
|
"vimshottari": vim["running"],
|
|
"narayana": _narayana(chart, birth_dt, middle),
|
|
"sade_sati": _sade_sati(chart, middle_pos["Saturn"][0], middle),
|
|
"slow_contacts": slow_contacts,
|
|
"double_transit": _double_transit({**body, "ayanamsa": ayanamsa, "node_mode": node_mode}, middle),
|
|
},
|
|
"days": days,
|
|
"not_wired": ["kp_sub_lord_transit", "tajika", "kakshya", "vedastro_range_scan"],
|
|
}
|