Files
Jyotisha/scripts/report_render/birth_precision_margins.py
T
ClaudeandClaude Fable 5.2 def4c986bb
Independent Staging Quality Gate / validate-frontend (push) Successful in 5m31s
Independent Staging Quality Gate / validate-python (push) Successful in 7m0s
Independent Staging Quality Gate / publish (push) Successful in 3m34s
fix: plain advice, plain distances and dates, no grade letters in the annual report, named people in synastry analysis (BUG-2034)
Reader-layer leftovers from the round-eight staging retest (astrologer's
2026-11-19 layering rule; owner's no-hedging rule).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
2026-11-19 18:29:42 +08:00

111 lines
4.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Nearest natal varga ascendant sign changes, using the chart's own frame."""
from datetime import datetime
from functools import lru_cache
from ayanamsa_utils import temporary_ayanamsa
from domain_calculation_service import swiss_ephemeris_lock
from jyotish_engine import _birth_hour_decimal, _sidereal_calculation_profile, swe
from varga import calc_varga
from .birth_precision_window import DEFAULT_WINDOW_SOURCE, crosses_birth_window, plain_minutes_zh
_CAP_SECONDS = 240 * 60
_STEP_SECONDS = 30
def _first_change(longitude_at, sign_at, natal_sign, part_width, near, far):
"""Check both halves if a step can cross more than one sign boundary."""
delta = abs((longitude_at(far) - longitude_at(near) + 180) % 360 - 180)
if abs(far - near) > 1 and delta >= part_width:
mid = (near + far) // 2
return _first_change(longitude_at, sign_at, natal_sign, part_width, near, mid) or _first_change(
longitude_at, sign_at, natal_sign, part_width, mid, far,
)
if sign_at(far) == natal_sign:
return None
while abs(far - near) > 1:
mid = (near + far) // 2
if sign_at(mid) == natal_sign:
near = mid
else:
far = mid
return far
def _margin(longitude_at, division, direction, cap_seconds):
def sign_at(seconds):
longitude = longitude_at(seconds)
return int(longitude // 30) if division == 1 else calc_varga(longitude, division)["sign_idx"]
natal_sign = sign_at(0)
for seconds in range(_STEP_SECONDS, cap_seconds + 1, _STEP_SECONDS):
change = _first_change(
longitude_at, sign_at, natal_sign, 30 / division,
direction * (seconds - _STEP_SECONDS), direction * seconds,
)
if change is not None:
return round(abs(change) / 60, 3)
return None
def _margin_summary_zh(before: float | None, after: float | None, cap: float, window: dict) -> str:
# 原值: 「出生时间提前 5.017 分钟上升就换座;推后 8.433 分钟才换座」
# 新值: 「出生时间提前 5 分 1 秒上升就换座;推后 8 分 26 秒才换座」(整分钟写法不变)
# 原因: BUG-2034,这句会被报告正文照抄,读者不该看到带小数的分钟
earlier = (f"出生时间提前 {plain_minutes_zh(before)}上升就换座" if before is not None
else f"出生时间提前 {plain_minutes_zh(cap)}内上升未换座")
later = (f"推后 {plain_minutes_zh(after)}才换座" if after is not None
else f"推后 {plain_minutes_zh(cap)}内未换座")
crosses = crosses_birth_window(before, after, window)
source = window.get("source")
if crosses:
conclusion = "区间内会换座"
elif source == DEFAULT_WINDOW_SOURCE:
conclusion = "按前后 30 分钟试算,没有变化"
elif source == "rectified_range":
conclusion = "在生时纠正选定的区间内没有变化"
elif source in ("user_stated", "shichen", "period"):
conclusion = "在填写的误差范围内没有变化"
else:
conclusion = "区间内不换座"
return f"{earlier};{later}。{conclusion}。"
def ascendant_margins(birth: dict, divisions: set[int], *, window: dict) -> dict:
"""Return distances in minutes, searching strictly past the report window."""
try:
natal = datetime.fromisoformat(f"{birth['date']}T{birth['time']}")
tz = float(str(birth["tz"]).removeprefix("UTC"))
latitude, longitude = float(birth["lat"]), float(birth["lon"])
ayanamsa = birth["ayanamsa_name"]
except (KeyError, TypeError, ValueError):
return {}
hour_ut = _birth_hour_decimal(natal.hour, natal.minute, natal.second) - tz
natal_jd = swe.julday(natal.year, natal.month, natal.day, hour_ut)
# A capped distance is outside the tolerance, including for windows of 240 minutes or more.
search_minutes = max(window["before_minutes"], window["after_minutes"])
cap_seconds = max(_CAP_SECONDS, (int(search_minutes * 60) // _STEP_SECONDS + 1) * _STEP_SECONDS)
@lru_cache(maxsize=None)
def longitude_at(seconds):
jd = natal_jd + seconds / 86_400
# Match compute_chart_data's apparent frame and equal-house Ascendant.
_, _, offset = _sidereal_calculation_profile(jd, "legacy")
cusps, _ = swe.houses(jd, latitude, longitude, b"A")
return (cusps[0] - offset) % 360
with swiss_ephemeris_lock(), temporary_ayanamsa(ayanamsa, swe):
rows = {}
cap = cap_seconds / 60
for division in sorted(divisions):
before = _margin(longitude_at, division, -1, cap_seconds)
after = _margin(longitude_at, division, 1, cap_seconds)
rows[f"D{division}"] = {
"before_minutes": cap if before is None else before,
"after_minutes": cap if after is None else after,
"summary_zh": _margin_summary_zh(before, after, cap, window),
}
return rows