"""Whether the current Vimshottari PD holds across the birth-time range (BUG-2157, G1). 占星师 2026-11-22 §6.2: a "confirmed to the minute" label does not certify the PD. The PD may be used only when the current PD is the same period at both ends of the declared birth-time range (and so, the Vimshottari position being monotonic in birth time, everywhere inside it). When the candidates fall in different PDs the branches are listed side by side and none is picked. Without a definable range the PD's stability is not assessed (never assume ±1 minute); MD and AD stay in use. Inputs: ``packet["report_birth_window"]`` (BUG-2013 / BUG-2123), the birth moment and settings the range scan uses, the Vimshottari reference date and year length on the packet. The Moon's longitude at each candidate moment comes from the same chart call the range scan makes (``chart_choice.boundaries.chart_at``); boundaries inside the range are found with the scan's own ``range_boundary_scan.find_value_changes`` (minute steps, bisection to the second). Before trusting the arithmetic, the MD/AD/PD it gives at the reported moment are compared with the engine's current periods on the packet; a mismatch leaves the PD unassessed. User feedback and life events are never read. """ from __future__ import annotations from datetime import datetime from typing import Any try: from scripts.dasha_common import NAKSHATRA_SPAN, VIMSHOTTARI_ORDER, VIMSHOTTARI_YEARS except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path from dasha_common import NAKSHATRA_SPAN, VIMSHOTTARI_ORDER, VIMSHOTTARI_YEARS SCHEMA = "jyotish.pd_range_stability.v1" CYCLE_YEARS = 120.0 # Branches listed by name; a wider range keeps the count and the first ones only. MAX_BRANCHES_LISTED = 9 _CUMULATIVE = {} _total = 0.0 for _lord in VIMSHOTTARI_ORDER: _CUMULATIVE[_lord] = _total _total += VIMSHOTTARI_YEARS[_lord] def _record(value: Any) -> dict: return value if isinstance(value, dict) else {} def cycle_position(moon_longitude: float) -> float: """Years from the start of Ashwini's Ketu period to the birth, continuous over all 27 nakshatras.""" moon = float(moon_longitude) % 360.0 index = int(moon // NAKSHATRA_SPAN) lord = VIMSHOTTARI_ORDER[index % 9] fraction = (moon - index * NAKSHATRA_SPAN) / NAKSHATRA_SPAN return (index // 9) * CYCLE_YEARS + _CUMULATIVE[lord] + fraction * VIMSHOTTARI_YEARS[lord] def _split(position: float, lord: str, length: float) -> tuple[str, float, float, int]: """Inside a period of ``lord`` lasting ``length`` years, the sub-period at ``position`` (0 ≤ p < length).""" start = VIMSHOTTARI_ORDER.index(lord) offset = 0.0 for step in range(9): sub = VIMSHOTTARI_ORDER[(start + step) % 9] sub_length = length * VIMSHOTTARI_YEARS[sub] / CYCLE_YEARS if position < offset + sub_length or step == 8: return sub, position - offset, sub_length, step offset += sub_length raise AssertionError("unreachable") # pragma: no cover def periods_at(moon_longitude: float, birth: datetime, reference: datetime, year_days: float) -> dict: """MD / AD / PD lords at ``reference`` for a birth at ``birth`` with this Moon, plus the PD instance key.""" absolute = cycle_position(moon_longitude) + (reference - birth).total_seconds() / 86400.0 / float(year_days) cycle, inside = divmod(absolute, CYCLE_YEARS) md = next(lord for lord in reversed(VIMSHOTTARI_ORDER) if inside >= _CUMULATIVE[lord]) ad, in_ad, ad_length, ad_step = _split(inside - _CUMULATIVE[md], md, VIMSHOTTARI_YEARS[md]) pd, _in_pd, _pd_length, pd_step = _split(in_ad, ad, ad_length) return {"md": md, "ad": ad, "pd": pd, "ad_key": (int(cycle), md, ad_step), "pd_key": (int(cycle), md, ad_step, pd_step)} def _moon_at(req: Any) -> Any: try: from scripts.report_render import range_boundary_scan as scan except ModuleNotFoundError: # pragma: no cover from report_render import range_boundary_scan as scan chart = scan._chart_cache(req) def moon(at: datetime) -> float: return float(_record(_record(chart(at).get("planets")).get("Moon"))["lon"]) return moon def _iso(at: datetime) -> str: return at.strftime("%Y-%m-%dT%H:%M:%S") def _not_assessed(reason: str, **extra: Any) -> dict: return {"schema": SCHEMA, "status": "not_assessed", "pd_used": False, "reason": reason, **extra} def pd_range_stability(packet: dict, *, moon_at: Any = None) -> dict: """``status``: ``stable`` (PD used), ``split`` (branches, PD not used) or ``not_assessed`` (PD not used). ``moon_at`` (a callable ``datetime -> sidereal Moon longitude``) is for tests; by default the range scan's chart call is used with the report's ayanamsa and node settings. """ try: from scripts.report_render import range_boundary_scan as scan from scripts.pl9_interpretation_packs import _current_period_rows from scripts.report_render.upstream_sync_chapters import _tz_hours except ModuleNotFoundError: # pragma: no cover from report_render import range_boundary_scan as scan from pl9_interpretation_packs import _current_period_rows from report_render.upstream_sync_chapters import _tz_hours window = _record(packet.get("report_birth_window")) if not window: return _not_assessed("no_birth_window") source = window.get("source") if source == "confirmed_minute" and not (window.get("intervals") or window.get("start_at")): return _not_assessed("minute_without_range", window_source=source) if source == "default_unknown_30": return _not_assessed("trial_range_only", window_source=source) info = _record(packet.get("birth_info")) center = scan._center(info) if center is None: return _not_assessed("input_missing", window_source=source) try: windows = scan._windows(window, center) except (KeyError, TypeError, ValueError): windows = None if not windows: return _not_assessed("no_declared_range", window_source=source) timing = _record(_record(packet.get("worksheets")).get("timing_and_predictive_systems")) or _record(packet.get("timing_and_predictive_systems")) dasha = _record(timing.get("dasha")) try: reference = datetime.fromisoformat(str(dasha.get("reference_date"))[:10]) year_days = float(dasha.get("year_days") or 365.25) except (TypeError, ValueError): return _not_assessed("input_missing", window_source=source) current = _current_period_rows(packet) engine = {level: str(_record(current.get(level)).get("lord") or "") for level in ("md", "ad", "pd")} if not engine["pd"]: return _not_assessed("no_current_pd", window_source=source) if moon_at is None: settings = _record(_record(packet.get("calculation_profile")).get("effective_settings")) ayanamsa = str(settings.get("ayanamsa") or info.get("ayanamsa_name") or "").strip().lower() node_mode = str(settings.get("node_mode") or info.get("node_mode") or "").strip().lower() if not ayanamsa or node_mode not in ("mean", "true"): return _not_assessed("input_missing", window_source=source) try: req = scan._boundaries.ChartRequest(birth_date=center.date().isoformat(), lat=float(info["lat"]), lon=float(info["lon"]), tz=float(_tz_hours(packet)), ayanamsa=ayanamsa, node_mode=node_mode) except (KeyError, TypeError, ValueError): return _not_assessed("input_missing", window_source=source) moon_at = _moon_at(req) def at(moment: datetime) -> dict: return periods_at(moon_at(moment), moment, reference, year_days) try: here = at(center) if (here["md"], here["ad"], here["pd"]) != (engine["md"], engine["ad"], engine["pd"]): return _not_assessed("engine_mismatch", window_source=source, recomputed={k: here[k] for k in ("md", "ad", "pd")}, engine=engine) branches: list[dict] = [] ad_changes = 0 for lo, hi in windows: changes = scan.find_value_changes(lambda moment: at(moment)["pd_key"], lo, hi) ad_changes += len(scan.find_value_changes(lambda moment: at(moment)["ad_key"], lo, hi)) edges = [lo, *[change["at"] for change in changes], hi] for start, end in zip(edges, edges[1:]): period = at(start) branches.append({"from": _iso(start), "to": _iso(end), "md": period["md"], "ad": period["ad"], "pd": period["pd"]}) except Exception: # noqa: BLE001 - shown as not assessed, never as stable return _not_assessed("calculation_failed", window_source=source) keys = {at(datetime.fromisoformat(branch["from"]))["pd_key"] for branch in branches} checked = [{"from": _iso(lo), "to": _iso(hi)} for lo, hi in windows] base = {"schema": SCHEMA, "window_source": source, "checked_ranges": checked, "reference_date": reference.date().isoformat(), "ad_boundary_inside_range": bool(ad_changes), "method": "vimshottari_cycle_position; moon from chart_choice.boundaries.chart_at; " "boundaries by range_boundary_scan.find_value_changes"} if len(keys) == 1: return {**base, "status": "stable", "pd_used": True, "pd_lord": engine["pd"]} return {**base, "status": "split", "pd_used": False, "branches": branches, "branch_count": len(branches)} def attach_pd_range_stability(packet: dict) -> dict: """Computed once per packet (``packet["pd_range_stability"]``).""" cached = packet.get("pd_range_stability") if isinstance(packet, dict) else None if isinstance(cached, dict) and cached.get("schema") == SCHEMA: return cached result = pd_range_stability(packet if isinstance(packet, dict) else {}) if isinstance(packet, dict): packet["pd_range_stability"] = result return result def caption_line(result: dict, language: str, *, level_name: tuple[str, str] = ("细运", "PD")) -> str: """One caption line for a table that uses (or leaves out) the PD.""" zh = language == "zh" status = _record(result).get("status") ranges = ";".join(f"{item['from'][11:19]}–{item['to'][11:19]}" for item in _record(result).get("checked_ranges") or []) if zh else \ "; ".join(f"{item['from'][11:19]}–{item['to'][11:19]}" for item in _record(result).get("checked_ranges") or []) if status == "stable": lord = _planet(result.get("pd_lord"), language) return (f"- 细运:在出生时间范围 {ranges} 的两端当前细运都是{lord}细运,范围内没有细运交界,本表使用细运。" if zh else f"- PD: at both ends of the birth-time range {ranges} the current PD is {lord}'s, with no PD boundary inside; this table uses the PD.") if status == "split": branches = result.get("branches") or [] shown = branches[:MAX_BRANCHES_LISTED] if zh: parts = ";".join(f"{b['from'][11:19]}–{b['to'][11:19]} 为{_planet(b['pd'], language)}细运" for b in shown) more = f";另有 {len(branches) - len(shown)} 段未列" if len(branches) > len(shown) else "" return (f"- 细运按出生时间分支:{parts}{more}。本表不在其中选一个,细运不参加下列关联;大运和小运照常使用。" + ("小运在这个范围内也有交界。" if result.get("ad_boundary_inside_range") else "")) parts = "; ".join(f"{b['from'][11:19]}–{b['to'][11:19]}: {b['pd']} PD" for b in shown) more = f"; {len(branches) - len(shown)} more not listed" if len(branches) > len(shown) else "" return (f"- The PD branches with the birth time: {parts}{more}. This table does not pick one, and the PD takes no part in " "the connections below; MD and AD are used as usual." + (" The AD also changes inside this range." if result.get("ad_boundary_inside_range") else "")) reason = str(_record(result).get("reason") or "") why = _NOT_ASSESSED_TEXT.get(reason, _NOT_ASSESSED_TEXT["input_missing"]) return (f"- 细运稳定性未评估:{why[0]}。细运不参加下列关联;大运和小运照常使用。" if zh else f"- PD stability not assessed: {why[1]}. The PD takes no part in the connections below; MD and AD are used as usual.") _NOT_ASSESSED_TEXT = { "no_birth_window": ("没有出生时间的误差范围", "no birth-time margin is available"), "minute_without_range": ("出生时间只填写到分钟,没有误差范围,不按前后 1 分钟假定", "the birth time is given to the minute with no margin, and ±1 minute is not assumed"), "trial_range_only": ("没有填写误差,前后 30 分钟只是试算,不作为出生时间范围", "no margin was given; the ±30 minute trial is not a birth-time range"), "no_declared_range": ("没有可用的出生时间范围", "no usable birth-time range"), "no_current_pd": ("当前细运没有随报告返回", "the current PD was not returned"), "engine_mismatch": ("细运复核与报告的周期表不一致", "the PD re-check does not match the report's period table"), "calculation_failed": ("范围两端的细运没有算出", "the PD at the range ends could not be computed"), "input_missing": ("出生资料或计算设置不全", "the birth data or settings are incomplete"), } _PLANET_ZH = {"Sun": "太阳", "Moon": "月亮", "Mars": "火星", "Mercury": "水星", "Jupiter": "木星", "Venus": "金星", "Saturn": "土星", "Rahu": "罗睺", "Ketu": "计都"} def _planet(name: Any, language: str) -> str: return _PLANET_ZH.get(str(name), str(name)) if language == "zh" else str(name)