Files
Jyotisha/scripts/report_render/range_boundary_scan.py
T
ClaudeandClaude Opus 5.5 6b026fe5b7
Independent Staging Quality Gate / validate-frontend (push) Successful in 6m26s
Independent Staging Quality Gate / validate-python (push) Successful in 7m58s
Independent Staging Quality Gate / publish (push) Successful in 4m19s
feat(report): scan the declared birth-time range for every layer's change to the second, with rectification's own boundary function (BUG-2123)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXp2Vp62Ur3C7yRWQdSq
2026-11-21 15:40:27 +08:00

257 lines
13 KiB
Python

"""Boundary scan across the birth-time range the user declared (BUG-2123, 占星师 2026-11-20 第 9 问).
For every layer of the report's birth-time sensitivity matrix, find whether and where inside the
declared range the value changes, to the second, and keep the value on each side.
* Varga ascendants (``Dn.ascendant``) use the rectification flow's own function,
``chart_choice.boundaries.find_lines`` (minute steps, bisection to the second). No second
ascendant-crossing algorithm lives here.
* UL / A7 / A10 and the KP cusps 1/4/7/10 have no rectification function; ``find_value_changes``
below scans them with the same shape (minute steps, bisection to the second, value on each side)
so rectification can reuse it later.
The scan only runs on a declared range. A fixed time without a range, or the product's ±30 minute
trial for an unknown margin, is never widened: the result says the scan was not run and why.
The values never depend on user life events or feedback.
"""
from __future__ import annotations
from collections.abc import Callable, Hashable
from datetime import datetime, timedelta
from typing import Any, Final
try:
from scripts.chart_choice import boundaries as _boundaries
except ModuleNotFoundError: # pragma: no cover - direct scripts/ execution
from chart_choice import boundaries as _boundaries
import jaimini # noqa: E402 (scripts/ is on sys.path once chart_choice.boundaries is imported)
import kp_system # noqa: E402
SCHEMA: Final = "jyotish.birth_range_boundary_scan.v1"
# The charts scanned for the birth range. One constant shared by the report's three-point sample,
# this scan and (later) rectification; the astrologer's answer on which charts rectification should
# compare will change it here only.
RANGE_SCAN_LAYERS: Final = (
"D1.ascendant", "D3.ascendant", "D4.ascendant", "D6.ascendant", "D7.ascendant", "D9.ascendant",
"D10.ascendant", "D11.ascendant", "D12.ascendant", "D16.ascendant", "D24.ascendant", "D30.ascendant",
"D40.ascendant", "D45.ascendant", "D60.ascendant", "arudha.UL", "arudha.A7", "arudha.A10", "KP.cusp_observation",
)
KP_CUSPS: Final = ("house_1", "house_4", "house_7", "house_10")
STEP_SECONDS: Final = 60
RESOLUTION_SECONDS: Final = 1
# report_birth_window sources that are a range the user declared or chose. The ±30 minute trial for an
# unknown margin (default_unknown_30) and a confirmed minute without a chosen interval are not.
DECLARED_SOURCES: Final = frozenset({"user_stated", "shichen", "period", "rectified_range"})
_PLANETS: Final = frozenset({"Sun", "Moon", "Mars", "Mercury", "Jupiter", "Venus", "Saturn", "Rahu", "Ketu"})
def find_value_changes(
value_at: Callable[[datetime], Hashable], start: datetime, end: datetime,
*, step_seconds: int = STEP_SECONDS,
) -> list[dict[str, Any]]:
"""Every change of ``value_at`` in (start, end], to the second: ``[{at, before, after}]``.
The value is read every ``step_seconds``. When a step ends on a different value, the first
second that differs is found by bisection (``value_at(at - 1 s) == before``,
``value_at(at) == after``); the scan then restarts from that second, so two different changes
inside one step are both found. A value that changes and changes back inside one step is not
seen: finding no change is not proof that none exists.
"""
if end <= start:
raise ValueError("range end must be after start")
changes: list[dict[str, Any]] = []
t, value = start, value_at(start)
step = timedelta(seconds=step_seconds)
while t < end:
t_next = min(t + step, end)
while (next_value := value_at(t_next)) != value:
lo, hi = t, t_next
while (hi - lo).total_seconds() > RESOLUTION_SECONDS:
mid = (lo + (hi - lo) / 2).replace(microsecond=0)
if mid <= lo:
break
if value_at(mid) == value:
lo = mid
else:
hi = mid
after = value_at(hi)
changes.append({"at": hi, "before": value, "after": after})
t, value = hi, after
if hi == t_next:
break
t, value = t_next, next_value
return changes
def _chart_cache(req: Any) -> Callable[[datetime], dict]:
cache: dict[datetime, dict] = {}
def chart(at: datetime) -> dict:
if at not in cache:
cache[at] = _boundaries.chart_at(req, at)
return cache[at]
return chart
def _arudha_signs(chart: dict) -> dict[str, str | None]:
"""UL / A7 / A10 sign, the same call the three-point sample makes (flexible_birth_time_profile)."""
planets = {name: row["lon"] for name, row in (chart.get("planets") or {}).items() if name in _PLANETS}
arudha = jaimini.calc_arudha_padas(int(float(chart["ascendant"]["lon"]) // 30), planets)
padas = arudha.get("padas") or {}
return {"UL": (arudha.get("upapada") or {}).get("sign"),
"A7": (padas.get("A7") or {}).get("sign"), "A10": (padas.get("A10") or {}).get("sign")}
def _kp_cusp(chart: dict, house: str) -> tuple[str | None, str | None, str | None] | None:
degree = ((chart.get("houses") or {}).get(house) or {}).get("cusp_degree")
if degree is None:
return None
lords = kp_system.get_kp_lords(float(degree))
return lords.get("sign"), lords.get("nakshatra_lord"), lords.get("sub_lord")
def _cusp_dict(value: tuple | None) -> dict | None:
return None if value is None else {"sign": value[0], "nakshatra_lord": value[1], "sub_lord": value[2]}
def _iso(at: datetime) -> str:
return at.isoformat(timespec="seconds")
def scan_birth_range(
req: Any, start: datetime, end: datetime,
layers: tuple[str, ...] = RANGE_SCAN_LAYERS,
) -> dict[str, dict]:
"""Per layer: the value at ``start`` and every change in (start, end].
Output per layer key::
{"value_at_start": <sign name | {house: cusp dict}>,
"changes": [{"at": "YYYY-MM-DDTHH:MM:SS", "before": ..., "after": ...}, ...]}
KP changes also carry ``"cusp": "house_7"``; their values are ``{sign, nakshatra_lord, sub_lord}``.
``at`` is the first second on the new side.
"""
chart = _chart_cache(req)
result: dict[str, dict] = {}
divisions = tuple(sorted({int(key.split(".")[0][1:]) for key in layers if key.endswith(".ascendant")}))
if divisions:
lines = _boundaries.find_lines(req, start, end, divisions,
longitude_at=lambda at: float(chart(at)["ascendant"]["lon"]))
start_lon = float(chart(start)["ascendant"]["lon"])
for division in divisions:
key = f"D{division}.ascendant"
if key not in layers:
continue
result[key] = {
"value_at_start": _boundaries.varga.SIGNS[_boundaries.varga_sign(start_lon, division)],
"changes": [{"at": _iso(line.at), "before": _boundaries.varga.SIGNS[line.flips[f"D{division}"][0]],
"after": _boundaries.varga.SIGNS[line.flips[f"D{division}"][1]]}
for line in lines if f"D{division}" in line.flips],
}
for name in ("UL", "A7", "A10"):
key = f"arudha.{name}"
if key in layers:
changes = find_value_changes(lambda at, name=name: _arudha_signs(chart(at))[name], start, end)
result[key] = {"value_at_start": _arudha_signs(chart(start))[name],
"changes": [{**change, "at": _iso(change["at"])} for change in changes]}
if "KP.cusp_observation" in layers:
changes = []
for house in KP_CUSPS:
for change in find_value_changes(lambda at, house=house: _kp_cusp(chart(at), house), start, end):
changes.append({"at": _iso(change["at"]), "cusp": house,
"before": _cusp_dict(change["before"]), "after": _cusp_dict(change["after"])})
changes.sort(key=lambda change: (change["at"], KP_CUSPS.index(change["cusp"])))
result["KP.cusp_observation"] = {
"value_at_start": {house: _cusp_dict(_kp_cusp(chart(start), house)) for house in KP_CUSPS},
"changes": changes,
}
return result
def _center(info: dict) -> datetime | None:
"""Reported birth moment with its seconds (BUG-2067)."""
try:
day = datetime.strptime(str(info["date"])[:10], "%Y-%m-%d") if info.get("date") else \
datetime(int(info["year"]), int(info["month"]), int(info["day"]))
if info.get("hour") is None and info.get("time"):
parts = [int(part) for part in str(info["time"]).split(":")]
hour, minute, second = (parts + [0, 0])[:3]
else:
hour, minute = int(info.get("hour") or 0), int(info.get("minute") or 0)
second = int(info.get("second") or 0)
return day.replace(hour=hour, minute=minute, second=second)
except (KeyError, TypeError, ValueError):
return None
def _windows(window: dict, center: datetime) -> list[tuple[datetime, datetime]] | None:
"""The declared range as civil intervals, or None when no range was declared."""
intervals = window.get("intervals")
if isinstance(intervals, list) and intervals:
parts = [(datetime.fromisoformat(part["start_at"]), datetime.fromisoformat(part["end_at"])) for part in intervals]
elif window.get("start_at") and window.get("end_at"):
parts = [(datetime.fromisoformat(window["start_at"]), datetime.fromisoformat(window["end_at"]))]
elif window.get("source") not in DECLARED_SOURCES:
return None
else:
before, after = float(window.get("before_minutes") or 0), float(window.get("after_minutes") or 0)
if not before and not after:
return None
parts = [(center - timedelta(minutes=before), center + timedelta(minutes=after))]
# Whole seconds, widened outwards so the declared edges stay inside.
parts = [(lo.replace(microsecond=0), hi if not hi.microsecond else hi.replace(microsecond=0) + timedelta(seconds=1))
for lo, hi in parts]
return [(lo, hi) for lo, hi in parts if hi > lo] or None
def birth_range_boundary_scan(packet: dict, tz_hours: Callable[[dict], float]) -> dict:
"""The scan for this report, read from ``packet["report_birth_window"]`` (computed once, then cached).
``status`` is ``scanned`` or ``not_run``; ``reason`` (not_run only) is ``no_declared_range``,
``fixed_time``, ``input_missing`` or ``calculation_failed``.
"""
cached = packet.get("birth_range_boundary_scan")
if isinstance(cached, dict) and cached.get("schema") == SCHEMA:
return cached
window = packet.get("report_birth_window") if isinstance(packet.get("report_birth_window"), dict) else {}
base = {"schema": SCHEMA, "status": "not_run", "layers_scanned": list(RANGE_SCAN_LAYERS)}
info = packet.get("birth_info") if isinstance(packet.get("birth_info"), dict) else {}
center = _center(info)
if not window:
return {**base, "reason": "no_declared_range"}
if center is None:
return {**base, "reason": "input_missing"}
try:
windows = _windows(window, center)
except (KeyError, TypeError, ValueError):
return {**base, "reason": "input_missing"}
if windows is None:
return {**base, "reason": "fixed_time" if window.get("source") == "confirmed_minute" else "no_declared_range"}
settings = (packet.get("calculation_profile") or {}).get("effective_settings") or {}
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 {**base, "reason": "input_missing"}
try:
req = _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)
parts = [{"start": _iso(lo), "end": _iso(hi), "layers": scan_birth_range(req, lo, hi)}
for lo, hi in windows]
except Exception: # noqa: BLE001 - shown as "not computed", never as "no change"
return {**base, "reason": "calculation_failed"}
return {
**base,
"status": "scanned",
"window": {"center": _iso(center), "source": window.get("source"),
"before_minutes": window.get("before_minutes"), "after_minutes": window.get("after_minutes")},
"intervals": parts,
"search": {"step_seconds": STEP_SECONDS, "resolution_seconds": RESOLUTION_SECONDS,
"varga_ascendants": "chart_choice.boundaries.find_lines",
"arudha_and_kp": "range_boundary_scan.find_value_changes"},
"settings": {"ayanamsa": ayanamsa, "node_mode": node_mode, "tz_hours": req.tz},
}