Files
Jyotisha/scripts/kp_monthly_vimshottari.py
ClaudeandClaude Opus 5.5 aadba9dc61 feat(chat): the astrologer's KP monthly packet with the multi-system window in chat timing — KP sub-chain in the KP profile, packet segments as strip cut points, per-period domain activations instead of K1 / K2, KP windows on the KP periods said as 「前后」 (BUG-2333)
Ports her yinduzhanxing 17a135457ec16b621f86dd57ba3926612ce1b9b8 (docs ee34700357): timing_evidence_packets.py
(new), kp_monthly_report_packet / theme_support / vimshottari / transits, kp_system, with her tests. The report path
(frozen engine, no timing systems supplied) keeps its earlier packet byte for byte; her profile and window run when
the caller supplies the periods it already computed (engine tool kp_timing_packet, cached per chart and window).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXp2Vp62Ur3C7yRWQdSq
2026-11-24 21:07:35 +08:00

129 lines
6.6 KiB
Python
Executable File

#!/usr/bin/env python3
"""Monthly five-level Vimshottari snapshots for the KP monthly report."""
from __future__ import annotations
from datetime import datetime
try: # pragma: no cover - import path differs under CLI vs pytest
from dasha_calculator_enhanced import calculate_five_level_dasha
from chart_dasha.birth_moment import compute_vimshottari_timeline # issue #137: same start as the report
from chart_dasha.birth_moment import mahadashas as birth_moment_mahadashas
except ImportError: # pragma: no cover
from scripts.dasha_calculator_enhanced import calculate_five_level_dasha
from scripts.chart_dasha.birth_moment import compute_vimshottari_timeline
from scripts.chart_dasha.birth_moment import mahadashas as birth_moment_mahadashas
def _current_period(timeline: dict, anchor_dt: datetime) -> dict:
"""The mahadasha running at ``anchor_dt``.
The birth-moment timeline (issue #137) returns ``periods`` only, without the
``current_dasha`` the old service returned; without this every month fell
back to the birth-balance lord with zero elapsed years.
"""
anchor = anchor_dt.strftime("%Y-%m-%d")
for row in timeline.get("periods") or []:
if isinstance(row, dict) and str(row.get("start") or "") <= anchor < str(row.get("end") or ""):
return row
return {}
def _cmd_dasha_snapshot(*, birth_dt: datetime, moon_lon: float, anchor_dt: datetime) -> dict:
"""The astrologer's 17a135457ec16b621f86dd57ba3926612ce1b9b8 (BUG-2333): MD / AD / PD are the native cmd_dasha rows
at the anchor, not a reconstructed sequence; Sookshma / Prana only when the five-level helper agrees with them."""
from types import SimpleNamespace
from datetime import timedelta
from scripts.jyotish_engine import cmd_dasha
timeline = cmd_dasha(SimpleNamespace(
year=birth_dt.year, month=birth_dt.month, day=birth_dt.day,
hour=birth_dt.hour, minute=birth_dt.minute, second=birth_dt.second,
birthdate=None, moon_lon=moon_lon, nakshatra=None, pada=None,
today=anchor_dt.date().isoformat(), dasha_year_days=365.25))
def at(rows):
matches = [row for row in rows if datetime.fromisoformat(row['start_datetime']) <= anchor_dt < datetime.fromisoformat(row['end_datetime'])]
if len(matches) != 1:
raise ValueError('KP monthly reference outside unique native Dasha interval')
return matches[0]
current = at(timeline.get('timeline', []))
ad = at(current['antardasha_timeline'])
pd = at(ad['pratyantar_dasha_timeline'])
# Reuse the native full MD extent, including pre-birth elapsed time.
# No day truncation and no independently reconstructed MD/AD/PD sequence.
year_days = timeline['year_days']
current_start = datetime.fromisoformat(current['end_datetime']) - timedelta(days=current['full_years'] * year_days)
elapsed_years = (anchor_dt - current_start).total_seconds() / (year_days * 86400)
md_lord = current['lord']
levels = calculate_five_level_dasha(md_lord, elapsed_years)
deeper_agrees = levels['bhukti']['lord'] == ad['lord'] and levels['pratyantar']['lord'] == pd['lord']
return {
"anchor_date": anchor_dt.strftime("%Y-%m-%d"),
"timeline": {
"current_dasha": current,
"birth_balance": timeline['timeline'][0],
"source": "jyotish_engine.cmd_dasha", "year_days": year_days,
},
"levels": {
"mahadasha": {k: current[k] for k in ('lord', 'start_datetime', 'end_datetime')},
"antardasha": {k: ad[k] for k in ('lord', 'start_datetime', 'end_datetime')},
"pratyantardasha": {k: pd[k] for k in ('lord', 'start_datetime', 'end_datetime')},
"sookshma": levels.get("sookshma") if deeper_agrees else None,
"prana": levels.get("prana") if deeper_agrees else None,
},
"deep_levels_status": "parent_path_agrees" if deeper_agrees else "blocked_parent_path_disagreement",
"birth_time_stability": "not_evaluated",
"status": "parameter_sensitive",
"must_not_claim": ["exact_event_timing", "specific_event_prediction"],
}
def build_monthly_vimshottari_snapshot(
*, birth_dt: datetime, moon_lon: float, anchor_dt: datetime, source: str = "birth_moment"
) -> dict:
"""``source="birth_moment"`` (default): the product's snapshot that the report and the annual pages read (issue
#137, BUG-1719), unchanged. ``source="cmd_dasha"``: the astrologer's native-boundary snapshot (BUG-2333), used by the
dedicated KP packet."""
if source == "cmd_dasha":
return _cmd_dasha_snapshot(birth_dt=birth_dt, moon_lon=moon_lon, anchor_dt=anchor_dt)
if source != "birth_moment":
raise ValueError(f"unknown Vimshottari snapshot source: {source}")
timeline = compute_vimshottari_timeline(
birth_dt=birth_dt,
moon_lon=moon_lon,
current_date=anchor_dt,
)
current = timeline.get("current_dasha") or _current_period(timeline, anchor_dt)
# BUG-1719: 原值 elapsed = (anchor - 日期粒度的大运起点).days / 365.25(起点丢出生时刻、
# 跨度取整数天,五级里 Sookshma / Prana 在边界附近会换主星);新值用出生时刻起算的
# 完整精度大运起点与 total_seconds。
precise_rows, *_ = birth_moment_mahadashas(birth_dt, moon_lon, through=anchor_dt)
precise = next((row for row in precise_rows if row["start"] <= anchor_dt < row["end"]), None)
if precise is not None:
elapsed_years = max((anchor_dt - precise["start"]).total_seconds() / 86400.0 / 365.25, 0.0)
md_lord = precise["lord"]
else:
start_text = current.get("start")
if start_text:
current_start = datetime.strptime(start_text, "%Y-%m-%d")
elapsed_years = max((anchor_dt - current_start).total_seconds() / 86400.0 / 365.25, 0.0)
else:
elapsed_years = 0.0
md_lord = current.get("lord") or timeline.get("birth_balance", {}).get("lord")
levels = calculate_five_level_dasha(md_lord, elapsed_years)
return {
"anchor_date": anchor_dt.strftime("%Y-%m-%d"),
"timeline": {
"current_dasha": current,
"birth_balance": timeline.get("birth_balance"),
},
"levels": {
"mahadasha": levels.get("mahadasha"),
"antardasha": levels.get("bhukti"),
"pratyantardasha": levels.get("pratyantar"),
"sookshma": levels.get("sookshma"),
"prana": levels.get("prana"),
},
"status": "parameter_sensitive",
"must_not_claim": ["exact_event_timing", "specific_event_prediction"],
}