Files
Jyotisha/scripts/report_render/annual_motion_appendix.py
T
ClaudeandClaude Opus 5.5 0ff2d1d395 feat(report): annual appendix chapter per year — range and method, the year's exact contacts, sign changes and stations in time order, and each named yoga's own contacts; Chinese and English (BUG-2317)
Lists in full the events of the year's named-yoga pairs and of the year lord
and Muntha lord; the Moon's and all other events are counted by kind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXp2U3BH1SxwAGyhhbe1
2026-11-24 15:44:32 +08:00

319 lines
18 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.
"""BUG-2317 (占星师 2026-11-23 信息密度交接 §4、验收第 5、7 条): the annual continuous-motion appendix chapter.
Per report year: the range and the method, a chronological table of exact contacts, sign changes and stations,
then each annual named-yoga row's motion evidence. A year has about 900 events, most of them the Moon's, so the
table lists in full the events the year's own rows, year lord and Muntha lord point to, and counts the rest by
kind; the chapter says so in one sentence. Chinese and English are written separately (no translation layer).
"""
from __future__ import annotations
from collections import Counter
from datetime import datetime, timedelta, timezone
from typing import Any
from zoneinfo import ZoneInfo
try:
from scripts.report_render.text import SIGNS, SIGNS_CN
except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path
from report_render.text import SIGNS, SIGNS_CN
HEADING = {"zh": "年度连续运动与具名 Yoga 运动记录", "en": "Annual Continuous Motion and Named-Yoga Motion Records"}
PLANET_ZH = {"Sun": "太阳", "Moon": "月亮", "Mars": "火星", "Mercury": "水星", "Jupiter": "木星",
"Venus": "金星", "Saturn": "土星"}
ROLE_WORDS = {
"mediator": {"zh": "中介星", "en": "Mediator"},
"helper_planet": {"zh": "援助星", "en": "Assisting planet"},
"interfering_planet": {"zh": "阻碍星", "en": "Interfering planet"},
"afflicted_planet": {"zh": "受损星", "en": "Affected planet"},
}
KIND_WORDS = {"exact_contact": {"zh": "精确成相", "en": "Exact contact"},
"ingress": {"zh": "换座", "en": "Sign change"},
"station": {"zh": "停滞", "en": "Station"}}
AYANAMSA_WORDS = {"raman": "Raman", "lahiri": "Lahiri", "kp": "KP", "krishnamurti": "KP"}
# Reader words for the recorded reasons a year has no motion. Never "no change".
REASON_WORDS = {
"time_budget_exceeded": {"zh": "这次生成报告的时间内没有算完这一年,下次生成会补上",
"en": "this year did not fit in this report's computing time; the next report fills it in"},
"next_solar_return_epoch_unavailable": {"zh": "找不到下一次太阳返照的时刻,无法确定这一年的终点",
"en": "the next solar return could not be found, so the year has no end point"},
"annual_chart_utc_epoch_required": {"zh": "这一年的返照时刻没有算出来", "en": "this year's return moment was not computed"},
"complete_annual_motion_planets_required": {"zh": "年盘缺少完整的七星位置", "en": "the annual chart lacks complete positions for the seven planets"},
"motion_request_missing": {"zh": "这一年没有连续运动的计算请求", "en": "no continuous-motion request was made for this year"},
"annual_year_blocked": {"zh": "这一年的年盘没有算出来", "en": "this year's annual chart was not computed"},
}
FULL_LIST_RULE = {
"zh": ("表中完整列出本年具名 Yoga 各行星对自己的精确成相、年主星与 Muntha 主星之间的精确成相,以及年主星、Muntha 主星的换座和停滞;"
"月亮约两天半换一个星座,它的事件和其余事件只按种类计数(月亮那几对的第一次精确成相见后面的 Yoga 表)。"),
"en": ("The table lists in full each named-yoga pair's own exact contacts this year, the exact contacts between the year lord "
"and the Muntha lord, and the year lord's and Muntha lord's sign changes and stations; the Moon changes sign about every "
"two and a half days, so its events and all other events are only counted by kind (the first exact contact of each "
"Moon pair is in the yoga table below)."),
}
BOUNDARY = {
"zh": "精确成相的时刻是算出的行星运行,不是人生事件的日期;Yoga 表里的成相记录也不表示这条 Yoga 已按传统完成兑现。",
"en": ("An exact contact is computed planetary motion, not the date of a life event; the contacts in the yoga table do not "
"mean that the yoga has been fulfilled in the traditional sense."),
}
def _dict(value: Any) -> dict:
return value if isinstance(value, dict) else {}
def _list(value: Any) -> list:
return value if isinstance(value, list) else []
def _planet(name: Any, language: str) -> str:
return PLANET_ZH.get(str(name), str(name)) if language == "zh" else str(name)
def _planets(names: Any, language: str) -> str:
return ("、" if language == "zh" else ", ").join(_planet(name, language) for name in _list(names))
def _sign(index: Any, language: str) -> str:
if not isinstance(index, int) or isinstance(index, bool) or not 0 <= index < 12:
return "—"
return SIGNS_CN[SIGNS[index]] if language == "zh" else SIGNS[index]
def _cell(text: Any) -> str:
return str(text).replace("|", "/").replace("\n", " ")
def _table(header: tuple[str, ...], rows: list[tuple]) -> list[str]:
lines = ["| " + " | ".join(header) + " |", "| " + " | ".join("---" for _ in header) + " |"]
lines.extend("| " + " | ".join(_cell(value) for value in row) + " |" for row in rows)
return lines
class _Clock:
"""UTC event stamps to the annual chart's local clock (the return instant's zone or offset)."""
def __init__(self, location: dict):
self.zone = None
zone_id = location.get("timezone_id")
if isinstance(zone_id, str) and zone_id:
try:
self.zone = ZoneInfo(zone_id)
except (KeyError, ValueError):
self.zone = None
offset = location.get("utc_offset")
hours = float(offset) if isinstance(offset, (int, float)) and not isinstance(offset, bool) else 0.0
self.fixed = timezone(timedelta(hours=hours))
self.zone_id = zone_id if self.zone is not None else None
self.hours = hours
def local(self, stamp: Any) -> str:
try:
moment = datetime.fromisoformat(str(stamp)).replace(tzinfo=timezone.utc)
except ValueError:
return str(stamp)
return moment.astimezone(self.zone or self.fixed).strftime("%Y-%m-%d %H:%M")
def label(self, language: str) -> str:
sign = "+" if self.hours >= 0 else "−"
whole = abs(self.hours)
offset = f"UTC{sign}{int(whole):02d}:{int(round((whole % 1) * 60)):02d}"
if language == "zh":
return f"年盘所在地当地时间,{self.zone_id}" if self.zone_id else f"年盘所在地当地时间,{offset}"
return f"local time at the annual chart's place, {self.zone_id}" if self.zone_id else f"local time at the annual chart's place, {offset}"
def _folded(angle: Any) -> int | None:
if not isinstance(angle, (int, float)) or isinstance(angle, bool):
return None
directed = float(angle) % 360
return int(round(min(directed, 360 - directed)))
def _change_text(event: dict, language: str) -> str:
kind = event.get("kind")
if kind == "exact_contact":
angle = _folded(event.get("directed_angle"))
return f"{angle}°" if angle is not None else "—"
if kind == "ingress":
arrow = " → "
return _sign(event.get("from_sign_idx"), language) + arrow + _sign(event.get("to_sign_idx"), language)
if kind == "station":
after = event.get("direction_after")
if language == "zh":
return "转逆行" if after == "retrograde" else "转顺行" if after == "direct" else "停滞"
return "turns retrograde" if after == "retrograde" else "turns direct" if after == "direct" else "station"
return "—"
def _lords(pack: dict) -> tuple[str | None, str | None]:
year_lord = _dict(_dict(pack.get("year_lord")).get("data")).get("year_lord")
muntha_lord = _dict(_dict(pack.get("muntha")).get("data")).get("muntha_lord")
return (year_lord if isinstance(year_lord, str) else None, muntha_lord if isinstance(muntha_lord, str) else None)
def _shown_rows(condition: dict) -> list[dict]:
"""Rows with planets (present or candidate), identical display rows merged."""
seen, rows = set(), []
for row in _list(condition.get("rows")):
if not isinstance(row, dict) or not _list(row.get("planets")):
continue
key = (row.get("yoga"), tuple(row.get("planets")), *(row.get(role) for role in ROLE_WORDS))
if key in seen:
continue
seen.add(key)
rows.append(row)
return rows
def select_events(pack: dict, condition: dict) -> tuple[list[tuple[int, list[str]]], Counter]:
"""(shown events as (index, reasons), counts of the rest by kind) under FULL_LIST_RULE."""
events = _list(_dict(condition.get("motion_timeline")).get("events"))
year_lord, muntha_lord = _lords(pack)
reasons: dict[int, list[str]] = {}
for row in _shown_rows(condition):
for index in _list(_dict(row.get("motion_evidence")).get("contact_refs")):
if isinstance(index, int) and 0 <= index < len(events) and "Moon" not in events[index].get("planets", []):
reasons.setdefault(index, [])
if row.get("yoga") not in reasons[index]:
reasons[index].append(str(row.get("yoga")))
lords = {name for name in (year_lord, muntha_lord) if name and name != "Moon"}
for index, event in enumerate(events):
planets = set(event.get("planets") or [])
if event.get("kind") == "exact_contact" and year_lord and muntha_lord and year_lord != muntha_lord \
and planets == {year_lord, muntha_lord} and "Moon" not in planets:
reasons.setdefault(index, []).append("lords")
elif event.get("kind") in ("ingress", "station") and planets & lords:
reasons.setdefault(index, []).append("lords")
rest = Counter(event.get("kind") for index, event in enumerate(events) if index not in reasons)
return sorted(reasons.items()), rest
def _related(tags: list[str], event: dict, pack: dict, language: str) -> str:
year_lord, muntha_lord = _lords(pack)
words = [tag for tag in tags if tag != "lords"]
if "lords" in tags:
planets = set(event.get("planets") or [])
if year_lord in planets:
words.append("年主星" if language == "zh" else "Year lord")
if muntha_lord in planets:
words.append("Muntha 主星" if language == "zh" else "Muntha lord")
return (";" if language == "zh" else "; ").join(dict.fromkeys(words)) or "—"
def _count_line(rest: Counter, language: str) -> str:
order = ("exact_contact", "ingress", "station")
if language == "zh":
parts = [f"{KIND_WORDS[kind]['zh']} {rest.get(kind, 0)} 次" for kind in order]
return "其余事件:" + "、".join(parts) + "。"
parts = [f"{rest.get(kind, 0)} {KIND_WORDS[kind]['en'].lower()}{'s' if rest.get(kind, 0) != 1 else ''}" for kind in order]
return "Other events: " + ", ".join(parts) + "."
def _row_evidence_cells(row: dict, events: list, clock: _Clock, language: str) -> tuple[str, str, str]:
evidence = _dict(row.get("motion_evidence"))
status = evidence.get("execution_status")
zh = language == "zh"
if status != "executed":
if evidence.get("reason") == "multi_body_chain_requires_separate_contact_order_adjudication":
text = "三颗星以上的链,接触先后不在这里判断" if zh else "Chain of three or more planets; contact order is not judged here"
else:
text = "本年没有连续运动记录" if zh else "No continuous-motion record this year"
return text, "—", "—"
count = evidence.get("contact_count")
if count is None:
count = len(_list(evidence.get("contacts")))
aspect = evidence.get("aspect_filter")
only = (f"(只计 {_folded(aspect)}°)" if zh else f" ({_folded(aspect)}° only)") if isinstance(aspect, (int, float)) else ""
if not count:
contacts = ("本年窗口内没有" if zh else "None within this year's window") + only
first = "—"
else:
contacts = (f"{count} 次" if zh else f"{count}") + only
first_contact = _dict(evidence.get("first_contact"))
first = f"{clock.local(first_contact.get('timestamp_local'))},{_change_text(first_contact, language)}" if zh else \
f"{clock.local(first_contact.get('timestamp_local'))}, {_change_text(first_contact, language)}"
changes = evidence.get("motion_change_count")
changes_text = (f"{changes} 次" if zh else str(changes)) if isinstance(changes, int) else "—"
return contacts, first, changes_text
def _year_lines(year: str, pack: dict, language: str) -> list[str]:
zh = language == "zh"
condition = _dict(pack.get("tajika_condition_status_pack"))
timeline = _dict(condition.get("motion_timeline"))
location = _dict(_dict(_dict(pack.get("solar_return")).get("data")).get("annual_location"))
clock = _Clock(location)
lines = [f"### {year} 年" if zh else f"### {year}", ""]
if timeline.get("execution_status") != "executed":
reason = REASON_WORDS.get(str(timeline.get("reason")), {}).get(language)
if reason is None:
reason = "计算没有完成" if zh else "the computation did not complete"
lines.append(f"本年连续运动没有算出:{reason}。不能据此认为这一年没有变化。" if zh else
f"This year's continuous motion was not computed: {reason}. This does not mean the year has no changes.")
lines.append("")
return lines
span = _dict(timeline.get("range"))
profile = _dict(timeline.get("profile"))
ayanamsa = AYANAMSA_WORDS.get(str(profile.get("ayanamsa")).lower(), str(profile.get("ayanamsa") or "—"))
mean = profile.get("position_mode") == "mean"
if zh:
lines.append(f"- 范围:{clock.local(span.get('start'))} 至 {clock.local(span.get('end_exclusive'))}({clock.label('zh')};"
"本次太阳返照到下一次太阳返照,终点不含)。")
lines.append(f"- 方法:七颗行星从年盘同一时刻起连续计算,每六小时取样后求到精确时刻;岁差 {ayanamsa},"
f"{'平位置' if mean else '视位置'};不含罗睺、计都。")
else:
lines.append(f"- Range: {clock.local(span.get('start'))} to {clock.local(span.get('end_exclusive'))} ({clock.label('en')}; "
"this solar return to the next, end excluded).")
lines.append(f"- Method: the seven planets computed continuously from the annual chart's moment, sampled every six hours "
f"and refined to the exact moment; ayanamsa {ayanamsa}, {'mean' if mean else 'apparent'} positions; Rahu and Ketu not included.")
events = _list(timeline.get("events"))
totals = Counter(event.get("kind") for event in events)
lines.append((f"- 本年共 {len(events)} 个事件:精确成相 {totals.get('exact_contact', 0)} 次、换座 {totals.get('ingress', 0)} 次、"
f"停滞 {totals.get('station', 0)} 次。") if zh else
(f"- {len(events)} events this year: {totals.get('exact_contact', 0)} exact contacts, "
f"{totals.get('ingress', 0)} sign changes, {totals.get('station', 0)} stations."))
lines.append("")
shown, rest = select_events(pack, condition)
if shown:
header = ("时间", "类型", "行星", "角度或换座", "相关") if zh else ("Time", "Kind", "Planets", "Angle or sign change", "Related")
rows = [(clock.local(events[index].get("timestamp_local")), KIND_WORDS.get(events[index].get("kind"), {}).get(language, "—"),
_planets(events[index].get("planets"), language), _change_text(events[index], language),
_related(tags, events[index], pack, language)) for index, tags in shown]
lines.extend(_table(header, rows))
lines.append("")
lines.extend([_count_line(rest, language), ""])
yoga_rows = _shown_rows(condition)
if yoga_rows:
header = (("具名 Yoga", "行星", "其他参与星", "本年精确成相", "第一次精确成相", "两星换座与停滞") if zh else
("Named yoga", "Planets", "Other planets", "Exact contacts this year", "First exact contact", "Sign changes and stations of the two"))
body = []
for row in yoga_rows:
others = [f"{ROLE_WORDS[role][language]} {_planet(row[role], language)}" for role in ROLE_WORDS
if isinstance(row.get(role), str)]
body.append((row.get("yoga"), _planets(row.get("planets"), language),
("、" if zh else ", ").join(others) or "—", *_row_evidence_cells(row, events, clock, language)))
lines.extend(_table(header, body))
lines.append("")
return lines
def render_annual_motion_chapter(packet: dict, language: str) -> list[str]:
"""The chapter's lines, or [] when no report year carries a condition pack."""
language = "en" if language == "en" else "zh"
timing = _dict(_dict(packet.get("worksheets")).get("timing_and_predictive_systems"))
years = _dict(_dict(timing.get("annual_tajika_series")).get("years"))
packs = [(str(year), pack) for year, pack in sorted(years.items(), key=lambda item: str(item[0]))
if isinstance(pack, dict) and isinstance(pack.get("tajika_condition_status_pack"), dict)]
if not packs:
return []
zh = language == "zh"
lines = [f"## {HEADING[language]}", "",
("每一年从当年太阳返照的时刻算到下一次太阳返照,列出七颗行星两两精确成相(0°、60°、90°、120°、180°)、换座和停滞的时刻,"
"以及本年每条具名 Yoga 的那一对星在这一年里的实际接触。" if zh else
"Each year runs from that year's solar return to the next. It lists the moments when two of the seven planets reach an "
"exact aspect (0°, 60°, 90°, 120°, 180°), when a planet changes sign, and when it stations, then the actual contacts "
"of each named yoga's pair during the year."),
"", FULL_LIST_RULE[language], "", BOUNDARY[language], ""]
for year, pack in packs:
lines.extend(_year_lines(year, pack, language))
return lines