Files
Jyotisha/scripts/report_render/sade_sati_intervals.py
T
ClaudeandClaude Opus 5.5 50fd5710a4
Independent Staging Quality Gate / validate-frontend (push) Successful in 6m21s
Independent Staging Quality Gate / validate-python (push) Successful in 7m34s
Independent Staging Quality Gate / publish (push) Successful in 3m9s
fix(report): no library names or source lines in front of the reader; owner-verified rectification items resolved (BUG-2115)
The annual method data shows only its numbers and clock facts; the research
chapter says "reference algorithm"; KP and Sade Sati describe the ephemeris
without naming Swiss Ephemeris. Reader leak checks now cover the whole report.
BUG-2055/2058/2063/2064/2074/2079/2090/2102 marked resolved after the owner's
staging walkthrough.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXp2U3BH1SxwAGyhhbe1
2026-11-21 10:27:53 +08:00

257 lines
13 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.
"""Dated Sade Sati intervals for the personal report (BUG-2089, 占星师 2026-11-20 B9).
The report printed only the three sign phases and said there were no dates. The dated
segments were computed for chat only (``sade_sati.build_saturn_cycle_timeline``:
Saturn's sidereal sign scanned day by day, each sign change bisected to the minute,
so a retrograde return gives its own segment). This module carries those segments into
the report packet under ``yogas_doshas.sade_sati.dated_intervals`` and prints them with
every boundary and the calculation settings. Nothing is copied from another report.
"""
from __future__ import annotations
import re
from datetime import date, datetime
from typing import Any
SIGNS = ("Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo",
"Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces")
PHASES = {"rising": ("上升期(月亮前一座)", "Rising (sign before the Moon)"),
"peak": ("高峰期(月亮所在座)", "Peak (the Moon's sign)"),
"setting": ("下降期(月亮后一座)", "Setting (sign after the Moon)")}
ENTRY = {"first": ("本轮首次进入", "First entry in this round"),
"re_entry": ("逆行回返后再次进入", "Re-entry after a retrograde return")}
# A new round starts when Saturn comes back to the three signs after this long away.
ROUND_GAP_DAYS = 3 * 365
SCAN_YEARS_BEFORE_BIRTH = 4
SCAN_YEARS_AFTER_BIRTH = 100
_POSITION_USED = "apparent_geocentric"
def _record(value: Any) -> dict:
return value if isinstance(value, dict) else {}
def _sign(value: Any) -> str | None:
text = str(value or "").strip()
return text if text in SIGNS else None
def _offset_hours(value: Any) -> float | None:
if isinstance(value, (int, float)) and not isinstance(value, bool):
return float(value)
match = re.fullmatch(r"(?:UTC)?\s*([+-]?)(\d{1,2})(?::(\d{2})|(\.\d+))?", str(value or "").strip())
if not match:
return None
hours = float(match.group(2)) + (int(match.group(3)) / 60 if match.group(3) else float(match.group(4) or 0))
return -hours if match.group(1) == "-" else hours
def _moment(value: Any) -> datetime | None:
try:
return datetime.strptime(str(value), "%Y-%m-%dT%H:%M")
except (TypeError, ValueError):
return None
def _edge(value: Any) -> date | None:
try:
return datetime.strptime(str(value), "%m-%d-%Y").date()
except (TypeError, ValueError):
return None
def sade_sati_segments(rows: Any, moon_sign: str) -> list[dict]:
"""Phase, round and entry kind for each Saturn sign segment of the timeline.
``rows`` are ``sadhesati_rows`` of ``build_saturn_cycle_timeline`` in time order.
A boundary that is the edge of the scanned years, not a sign change, is flagged.
"""
moon = SIGNS.index(moon_sign)
phase_of = {SIGNS[(moon - 1) % 12]: "rising", moon_sign: "peak", SIGNS[(moon + 1) % 12]: "setting"}
out: list[dict] = []
round_number = 0
seen: set[str] = set()
previous_end: datetime | None = None
for row in rows or []:
row = _record(row)
phase = phase_of.get(str(row.get("transit_sign")))
if phase is None:
continue
start, end = _moment(row.get("beginning_moment_local")), _moment(row.get("ending_moment_local"))
start_day = start.date() if start else _edge(row.get("beginning_date"))
end_day = end.date() if end else _edge(row.get("ending_date"))
if start_day is None or end_day is None:
continue
begins = start or datetime(start_day.year, start_day.month, start_day.day)
if previous_end is None or (begins - previous_end).days > ROUND_GAP_DAYS:
round_number += 1
seen = set()
out.append({
"round": round_number,
"phase": phase,
"sign": row.get("transit_sign"),
"start": start.strftime("%Y-%m-%d %H:%M") if start else start_day.isoformat(),
"end": end.strftime("%Y-%m-%d %H:%M") if end else end_day.isoformat(),
"start_is_scan_edge": start is None,
"end_is_scan_edge": end is None,
"entry": "re_entry" if phase in seen else "first",
})
seen.add(phase)
previous_end = end or datetime(end_day.year, end_day.month, end_day.day)
return out
def build_sade_sati_intervals(packet: dict) -> dict:
"""Compute the dated segments from the packet's own birth data and settings."""
packet = _record(packet)
worksheets = _record(packet.get("worksheets"))
d1 = _record(worksheets.get("d1_rasi_bhava")) or _record(packet.get("core_chart"))
sade = _record(_record(_record(worksheets.get("advanced_systems")).get("yogas_doshas")).get("sade_sati"))
birth = _record(packet.get("birth_info"))
profile = _record(packet.get("calculation_profile"))
moon_sign = _sign(_record(_record(d1.get("planets")).get("Moon")).get("sign")) or _sign(sade.get("moon_sign"))
ascendant = _record(d1.get("ascendant"))
asc_sign = _sign(ascendant.get("sign") or ascendant.get("sign_name"))
offset = _offset_hours(birth.get("tz"))
ayanamsa = profile.get("ayanamsa") or birth.get("ayanamsa_name")
try:
born = date.fromisoformat(str(birth.get("date")))
except ValueError:
born = None
missing = [name for name, value in (("moon_sign", moon_sign), ("timezone_offset", offset),
("ayanamsa", ayanamsa), ("birth_date", born)) if value in (None, "")]
if missing:
return {"status": "blocked", "missing": missing, "segments": []}
try:
from scripts.ayanamsa_utils import configure_ephemeris_path
from scripts.sade_sati import build_saturn_cycle_timeline
except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path
from ayanamsa_utils import configure_ephemeris_path
from sade_sati import build_saturn_cycle_timeline
# The ephemeris path is process-wide. Set it here so both editions get the same minute
# (without the files swisseph falls back to Moshier and boundaries move by a minute or two).
try:
import swisseph as swe
ephemeris = "swiss_ephemeris_files" if configure_ephemeris_path(swe) else "moshier_built_in"
except ImportError:
return {"status": "blocked", "missing": ["saturn_positions"], "segments": []}
timeline = build_saturn_cycle_timeline(
moon_sign,
# The ascendant only feeds the Kantaka rows, which this table does not use.
asc_sign or moon_sign,
start_year=born.year - SCAN_YEARS_BEFORE_BIRTH,
end_year=born.year + SCAN_YEARS_AFTER_BIRTH,
tz=offset,
ayanamsa=str(ayanamsa),
birth_date=born,
)
if timeline.get("status") == "blocked":
return {"status": "blocked", "missing": ["saturn_positions"], "segments": []}
return {
"status": "computed",
"moon_sign": moon_sign,
"segments": sade_sati_segments(timeline.get("sadhesati_rows"), moon_sign),
"parameters": {
"ayanamsa": str(ayanamsa),
"saturn_position": _POSITION_USED,
"ephemeris": ephemeris,
"chart_position_mode": profile.get("position_mode"),
"chart_node_mode": profile.get("node_mode") or birth.get("node_mode"),
"clock_utc_offset_hours": offset,
"boundary": "sign_change_bisected_to_minute",
"scan_years": list(timeline.get("year_range") or []),
},
}
def attach_sade_sati_intervals(packet: dict) -> dict | None:
"""Add ``dated_intervals`` beside the phase frame; existing keys keep their meaning."""
doshas = _record(_record(_record(_record(packet).get("worksheets")).get("advanced_systems")).get("yogas_doshas"))
sade = doshas.get("sade_sati")
if not isinstance(sade, dict):
return None
if not isinstance(sade.get("dated_intervals"), dict):
sade["dated_intervals"] = build_sade_sati_intervals(packet)
return sade["dated_intervals"]
def _offset_text(hours: Any) -> str:
if not isinstance(hours, (int, float)):
return ""
minutes = round(abs(hours) * 60)
return f"UTC{'-' if hours < 0 else '+'}{minutes // 60}" + (f":{minutes % 60:02d}" if minutes % 60 else "")
def sade_sati_parameter_text(intervals: dict, language: str) -> str:
"""One caption with the method, the unit and the settings actually used."""
params = _record(_record(intervals).get("parameters"))
zh = language == "zh"
try:
from scripts.report_render.appendix_language import sign_name
except ModuleNotFoundError: # pragma: no cover
from report_render.appendix_language import sign_name
ayanamsa = str(params.get("ayanamsa") or "").replace("_", " ").title()
offset = _offset_text(params.get("clock_utc_offset_hours"))
years = params.get("scan_years") or []
span = f"{years[0]}–{years[1]}" if len(years) == 2 else ""
node = {"mean": ("平交点", "mean node"), "true": ("真交点", "true node")}.get(str(params.get("chart_node_mode")))
mode = {"apparent": ("视位置", "apparent"), "true": ("真位置", "true"), "mean": ("平位置", "mean")}.get(str(params.get("chart_position_mode")))
moon = sign_name(intervals.get("moon_sign"), language)
# BUG-2115 (负责人 2026-11-21): the reader sees what kind of ephemeris, never the library's name.
ephemeris = {"swiss_ephemeris_files": ("高精度星历文件", "high-precision ephemeris files"),
"moshier_built_in": ("内置近似星历(未找到星历文件,换座时刻可能差一两分钟)",
"the built-in approximate ephemeris (no ephemeris files found; a boundary may differ by a minute or two)")}.get(
str(params.get("ephemeris")), ("未注明", "not stated"))
if zh:
text = (f"算法:逐日计算土星的恒星黄道星座,换座时刻用二分法收到分钟;月亮在{moon}。"
f"时间按出生地的固定时差({offset},不含夏令时)写成年-月-日 时:分。"
f"岁差:{ayanamsa};土星取地心视位置")
if mode:
text += f"(星盘的位置设置为{mode[0]})"
if node:
text += f";星盘的交点设置为{node[0]},不影响土星位置"
text += f"。星历:{ephemeris[0]}。扫描范围:{span} 年;范围两端不是换座时刻的,表里另行标明。"
return text
text = (f"Method: Saturn's sidereal sign is computed day by day and each sign change is bisected to the minute; the Moon is in {moon}. "
f"Times are year-month-day hour:minute on the birth place's fixed offset ({offset}, no daylight saving). "
f"Ayanamsa: {ayanamsa}; Saturn is the geocentric apparent position")
if mode:
text += f" (the chart's position setting is {mode[1]})"
if node:
text += f"; the chart's node setting is {node[1]}, which does not affect Saturn"
text += f". Ephemeris: {ephemeris[1]}. Scanned years: {span}; a boundary that is the edge of the scan rather than a sign change is marked."
return text
def sade_sati_interval_lines(intervals: Any, language: str) -> list[str]:
"""Markdown for the reader body: caption, then one row per segment."""
intervals = _record(intervals)
zh = language == "zh"
try:
from scripts.report_render.appendix_language import sign_name
except ModuleNotFoundError: # pragma: no cover
from report_render.appendix_language import sign_name
heading = "#### Sade Sati 各段起止日期" if zh else "#### Sade Sati dated intervals"
if intervals.get("status") != "computed":
return [heading, "", "本次没有算出各段起止日期,缺少出生日期、时区、岁差或月亮星座中的一项;这里不估算。" if zh
else "The dated intervals were not computed this time: the birth date, time zone, ayanamsa or Moon sign is missing. Nothing is estimated here.", ""]
segments = [item for item in intervals.get("segments") or [] if isinstance(item, dict)]
if not segments:
return [heading, "", "扫描范围内土星没有进入月亮前后三座。" if zh else "Saturn does not enter the three signs around the Moon in the scanned years.", ""]
edge = "(扫描范围边界,不是换座时刻)" if zh else " (edge of the scan, not a sign change)"
lines = [heading, "", sade_sati_parameter_text(intervals, language), ""]
lines.append("| 轮次 | 阶段 | 土星所在星座 | 开始 | 结束 | 进入方式 |" if zh
else "| Round | Phase | Saturn's sign | Start | End | Entry |")
lines.append("|------|------|------|------|------|------|")
for item in segments:
phase = PHASES.get(str(item.get("phase")))
entry = ENTRY.get(str(item.get("entry")))
lines.append(
f"| {('第 ' + str(item.get('round')) + ' 轮') if zh else item.get('round')} | {phase[0 if zh else 1] if phase else '-'} | "
f"{sign_name(item.get('sign'), language)} | {item.get('start')}{edge if item.get('start_is_scan_edge') else ''} | "
f"{item.get('end')}{edge if item.get('end_is_scan_edge') else ''} | {entry[0 if zh else 1] if entry else '-'} |"
)
lines.append("")
return lines