Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DbBXp2U3BH1SxwAGyhhbe1
280 lines
14 KiB
Python
280 lines
14 KiB
Python
"""Transit Saturn / Jupiter against the natal chart, for the report reading (BUG-2021).
|
||
|
||
Position facts only. The same comparison the chat card carries as
|
||
``transit_natal_sign`` (BUG-1995, frontend/src/lib/consultation-transit-natal-sign.ts):
|
||
the natal sign and the transit sign are copied, ``same_sign`` is an equality, and
|
||
the dates of the current visit come from ingress records that already exist.
|
||
|
||
The report packet has no ingress records, so the dates are read from the scan the
|
||
chat uses (``consultation_native_layers.build_slow_transits`` → ``key_dates``),
|
||
called on the report's own chart, reference date, time zone, ayanamsa and node
|
||
mode. No date is computed here; a side without a record is ``not_available``.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
from datetime import datetime, timedelta
|
||
from typing import Any
|
||
|
||
try:
|
||
from scripts.consult_facts.evidence_ids import transit_id
|
||
except ModuleNotFoundError: # pragma: no cover - direct scripts/ execution path
|
||
from consult_facts.evidence_ids import transit_id
|
||
|
||
SIGNS = (
|
||
"Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo",
|
||
"Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces",
|
||
)
|
||
RETURN_PLANETS = ("Saturn", "Jupiter")
|
||
NOT_AVAILABLE = "not_available"
|
||
DATE_SOURCE = "consultation_native_layers.build_slow_transits key_dates (ingress records, the chat card's scan)"
|
||
# 占星师 2026-11-16 裁定(BUG-1946,与 frontend/src/lib/consultation-evidence-card.ts 的
|
||
# KANTAKA_HOUSES_FROM_MOON / ASHTAMA_HOUSE_FROM_MOON 同值):Kantaka 只从月亮起第 4、7、10 宫;
|
||
# 月亮起第 8 宫单列为 Ashtama Shani;上升参照不并入。
|
||
KANTAKA_HOUSES_FROM_MOON = (4, 7, 10)
|
||
ASHTAMA_HOUSE_FROM_MOON = 8
|
||
KANTAKA_RULING_ZH = "占星师 2026-11-16 裁定:Kantaka 只从月亮起第 4、7、10 宫;月亮起第 8 宫单列为 Ashtama Shani"
|
||
# BUG-2024: fact text only. The earlier wording (「……这一条里一并列出」) read as an instruction and the
|
||
# reading copied it (「同一句要并读」); what to write lives in the rules block, not in the facts.
|
||
SADE_SATI_SCOPE_ZH = "Sade Sati 指行运土星在本命月亮所在星座及其前后各一座(月亮起第 12、1、2 宫)。"
|
||
_DAY = re.compile(r"\d{4}-\d{2}-\d{2}\Z")
|
||
_OFFSET = re.compile(r"(?:UTC)?\s*([+-])\s*(\d{1,2})(?::(\d{2})|\.(\d+))?\Z")
|
||
|
||
|
||
def _record(value: Any) -> dict:
|
||
return value if isinstance(value, dict) else {}
|
||
|
||
|
||
def _sign(value: Any) -> bool:
|
||
return isinstance(value, str) and value in SIGNS
|
||
|
||
|
||
def _day(value: Any) -> bool:
|
||
return isinstance(value, str) and bool(_DAY.match(value))
|
||
|
||
|
||
def transit_natal_sign_facts(natal_planets: Any, transit_planets: Any, key_dates: Any, reference_date: Any) -> list[dict]:
|
||
"""One row per planet whose natal and transit signs are both known.
|
||
|
||
The nearest ingress on each side of the reference date must belong to this
|
||
visit of the sign; a retrograde re-entry is a separate visit and is not
|
||
merged with the one before it.
|
||
"""
|
||
natal = _record(natal_planets)
|
||
transit = _record(transit_planets)
|
||
rows = [_record(row) for row in key_dates] if isinstance(key_dates, list) else []
|
||
facts: list[dict] = []
|
||
for planet in RETURN_PLANETS:
|
||
natal_sign = _record(natal.get(planet)).get("sign")
|
||
transit_sign = _record(transit.get(planet)).get("sign")
|
||
# A missing position cannot establish either true or false.
|
||
if not _sign(natal_sign) or not _sign(transit_sign):
|
||
continue
|
||
fact: dict[str, Any] = {
|
||
"planet": planet, "natal_sign": natal_sign, "transit_sign": transit_sign,
|
||
"same_sign": natal_sign == transit_sign, "evidence_id": transit_id(planet),
|
||
}
|
||
if fact["same_sign"]:
|
||
fact["start"] = NOT_AVAILABLE
|
||
fact["end"] = NOT_AVAILABLE
|
||
if _day(reference_date):
|
||
ingress = sorted(
|
||
(row for row in rows
|
||
if row.get("kind") == "ingress" and isinstance(row.get("body"), str)
|
||
and row["body"].lower() == planet.lower() and _day(row.get("date"))
|
||
and _sign(row.get("from_sign")) and _sign(row.get("to_sign"))
|
||
and row["from_sign"] != row["to_sign"]),
|
||
key=lambda row: row["date"],
|
||
)
|
||
previous = [row for row in ingress if row["date"] <= reference_date][-1:]
|
||
following = [row for row in ingress
|
||
if row["date"] > reference_date
|
||
or (row["date"] == reference_date and row["from_sign"] == transit_sign)][:1]
|
||
if previous and previous[0]["to_sign"] == transit_sign:
|
||
fact["start"] = previous[0]["date"]
|
||
if following and following[0]["from_sign"] == transit_sign:
|
||
fact["end"] = following[0]["date"]
|
||
fact["date_source"] = DATE_SOURCE
|
||
facts.append(fact)
|
||
return facts
|
||
|
||
|
||
def saturn_from_moon(house: Any, saturn_row: dict | None) -> dict[str, Any] | None:
|
||
"""Saturn's house counted from the natal Moon, named next to the Sade Sati state.
|
||
|
||
``house`` is the packet's own count (transit_multi_reference, Chandra Lagna).
|
||
Kantaka and Ashtama Shani are read off that house with the astrologer's
|
||
2026-11-16 ruling; nothing else is judged here.
|
||
"""
|
||
if type(house) is not int or not 1 <= house <= 12:
|
||
return None
|
||
out: dict[str, Any] = {
|
||
"house": house,
|
||
"kantaka": house in KANTAKA_HOUSES_FROM_MOON,
|
||
"ashtama_shani": house == ASHTAMA_HOUSE_FROM_MOON,
|
||
"rule": KANTAKA_RULING_ZH,
|
||
}
|
||
end = _record(saturn_row).get("end")
|
||
if _day(end):
|
||
# Saturn leaves this sign, and so this house from the Moon, on the same ingress record.
|
||
out["until"] = end
|
||
return out
|
||
|
||
|
||
def saturn_sign_returns(segments: Any, until: Any) -> list[dict]:
|
||
"""Retrograde returns into the sign Saturn leaves on ``until``, from the dated Sade Sati segments.
|
||
|
||
BUG-2205 (占星师 2026-11-22 一楠报告审核第 01 条): the reading only had the first leave date, so the
|
||
health section wrote 「2027 年 5 月离开……到那时会缓解」 while the appendix table listed a return from
|
||
2027-11-08 to 2028-02-07. The segments are the appendix's own rows (``dated_intervals``); a return is a
|
||
later segment of the same sign and round that starts within three years of the first leave.
|
||
"""
|
||
if not _day(until):
|
||
return []
|
||
rows = [_record(row) for row in (segments or []) if isinstance(row, dict)]
|
||
leaving = next((row for row in rows if str(row.get("end", ""))[:10] == until), None)
|
||
if leaving is None:
|
||
return []
|
||
out: list[dict] = []
|
||
limit = int(until[:4]) + 3
|
||
for row in rows:
|
||
start, end = str(row.get("start", ""))[:10], str(row.get("end", ""))[:10]
|
||
if (row.get("sign") == leaving.get("sign") and row.get("round") == leaving.get("round")
|
||
and _day(start) and _day(end) and start > until and int(start[:4]) <= limit
|
||
and row.get("end_is_scan_edge") is not True):
|
||
out.append({"back": start, "leaves": end})
|
||
return out
|
||
|
||
|
||
def saturn_sign_returns_by_scan(sign: Any, until: Any, tz: Any, ayanamsa: Any, years: int = 3) -> list[dict]:
|
||
"""BUG-2232: retrograde returns into ``sign`` after Saturn leaves it on ``until``, from the ephemeris.
|
||
|
||
BUG-2205 read the returns from the dated Sade Sati segments only, so a Saturn in a sign that is not one
|
||
of the three Sade Sati signs (the staging acceptance report of 2026-11-23: back in its natal Pisces,
|
||
「2027 年 5 月才离开」) still had no return. This scans Saturn's sidereal sign day by day for ``years``
|
||
years after the leave date, with the same functions as the Saturn cycle table. [] on any failure.
|
||
"""
|
||
if not _day(until) or not _sign(sign) or not isinstance(tz, (int, float)) or not isinstance(ayanamsa, str):
|
||
return []
|
||
try:
|
||
try:
|
||
from scripts.sade_sati import SIGNS as SADE_SIGNS, _refine_saturn_sign_boundary, _saturn_sign_on_day
|
||
except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path
|
||
from sade_sati import SIGNS as SADE_SIGNS, _refine_saturn_sign_boundary, _saturn_sign_on_day
|
||
target = SADE_SIGNS.index(sign)
|
||
start = datetime.strptime(until, "%Y-%m-%d").date() + timedelta(days=1)
|
||
end = start + timedelta(days=365 * years)
|
||
out: list[dict] = []
|
||
previous = _saturn_sign_on_day(start, float(tz), ayanamsa)
|
||
back: str | None = None
|
||
day = start + timedelta(days=1)
|
||
while day <= end:
|
||
current = _saturn_sign_on_day(day, float(tz), ayanamsa)
|
||
if current != previous:
|
||
moment = _refine_saturn_sign_boundary(day - timedelta(days=1), day, previous, float(tz), ayanamsa)
|
||
stamp = moment.strftime("%Y-%m-%d")
|
||
if current == target:
|
||
back = stamp
|
||
elif previous == target and back:
|
||
out.append({"back": back, "leaves": stamp})
|
||
back = None
|
||
previous = current
|
||
day += timedelta(days=1)
|
||
return out
|
||
except Exception: # noqa: BLE001 - the dates are optional, the facts are not
|
||
return []
|
||
|
||
|
||
def _reader_day_zh(day: str) -> str:
|
||
year, month, date = day.split("-")
|
||
return f"{int(year)} 年 {int(month)} 月 {int(date)} 日"
|
||
|
||
|
||
def sade_sati_summary_zh(is_active: Any, from_moon: dict | None) -> str | None:
|
||
"""One plain sentence pair for the reading: the Sade Sati state, then Saturn's house from the Moon.
|
||
|
||
BUG-2024: the reading gets the finished fact sentence, so no rule has to tell it how to join the
|
||
two (that rule wording leaked into the report). Nothing is judged here beyond `saturn_from_moon`.
|
||
"""
|
||
parts: list[str] = []
|
||
if is_active is True:
|
||
parts.append("Sade Sati 进行中。")
|
||
elif is_active is False:
|
||
parts.append("Sade Sati 未启动。")
|
||
row = _record(from_moon)
|
||
house = row.get("house")
|
||
if type(house) is int and 1 <= house <= 12:
|
||
if row.get("kantaka") is True:
|
||
kind = "属于 Kantaka"
|
||
elif row.get("ashtama_shani") is True:
|
||
kind = "属于 Ashtama Shani"
|
||
else:
|
||
kind = "不属于 Kantaka,也不属于 Ashtama Shani"
|
||
until = row.get("until")
|
||
# 原值: 「,2027-05-20 离开这个星座」;新值: 「,2027 年 5 月 20 日离开这个星座」
|
||
# 原因: BUG-2034,这句会进报告正文,日期写法要和正文其他句子一致;`until` 字段仍是 ISO 日期
|
||
tail = f",{_reader_day_zh(until)}离开这个星座" if _day(until) else ""
|
||
# BUG-2205: a retrograde return is part of the same visit; the last date is when it really leaves.
|
||
for visit in row.get("returns") or []:
|
||
tail += f",{_reader_day_zh(visit['back'])}退回这个星座,{_reader_day_zh(visit['leaves'])}再次离开"
|
||
parts.append(f"行运土星在本命月亮起第 {house} 宫,{kind}{tail}。")
|
||
return "".join(parts) or None
|
||
|
||
|
||
def _offset_hours(packet: dict) -> float | None:
|
||
profile = _record(packet.get("calculation_profile"))
|
||
for raw in (_record(profile.get("effective_settings")).get("timezone_offset"),
|
||
_record(packet.get("birth_info")).get("tz")):
|
||
if isinstance(raw, (int, float)) and not isinstance(raw, bool):
|
||
return float(raw)
|
||
match = _OFFSET.match(raw.strip()) if isinstance(raw, str) else None
|
||
if match:
|
||
hours = int(match.group(2))
|
||
if match.group(3):
|
||
hours += int(match.group(3)) / 60
|
||
elif match.group(4):
|
||
hours += float(f"0.{match.group(4)}")
|
||
return hours if match.group(1) == "+" else -hours
|
||
return None
|
||
|
||
|
||
def slow_transit_key_dates(packet: dict, full_reading: dict, reference_day: Any) -> list[dict]:
|
||
"""Ingress / station records of the twelve months after the reference date, or [].
|
||
|
||
Never fails the facts: without the engine, the chart or the settings the
|
||
report simply has no dates for the visit.
|
||
"""
|
||
if not _day(reference_day):
|
||
return []
|
||
chart = _record(_record(full_reading).get("chart"))
|
||
modules = _record(_record(full_reading).get("modules"))
|
||
birth = _record(packet.get("birth_info"))
|
||
profile = _record(packet.get("calculation_profile"))
|
||
ayanamsa = profile.get("ayanamsa") or birth.get("ayanamsa_name")
|
||
node_mode = profile.get("node_mode") or birth.get("node_mode")
|
||
tz = _offset_hours(packet)
|
||
if not _record(chart.get("planets")) or not _record(chart.get("ascendant")):
|
||
return []
|
||
if not isinstance(ayanamsa, str) or not isinstance(node_mode, str) or tz is None:
|
||
return []
|
||
try:
|
||
try:
|
||
from scripts import consultation_native_layers as layers
|
||
except ModuleNotFoundError: # pragma: no cover - direct scripts/ execution path
|
||
import consultation_native_layers as layers
|
||
engine = layers._load_engine()
|
||
layers._scripts_on_path()
|
||
from ayanamsa_utils import temporary_ayanamsa
|
||
from domain_calculation_service import swiss_ephemeris_lock
|
||
reference = datetime.strptime(reference_day, "%Y-%m-%d").replace(hour=12)
|
||
with swiss_ephemeris_lock(), temporary_ayanamsa(ayanamsa, engine.swe):
|
||
scan = layers.build_slow_transits(
|
||
engine, chart, modules, reference=reference, tz=tz, ayanamsa=ayanamsa, node_mode=node_mode,
|
||
)
|
||
except Exception: # noqa: BLE001 - the dates are optional, the facts are not
|
||
return []
|
||
if _record(scan).get("status") != "executed" or not isinstance(scan.get("key_dates"), list):
|
||
return []
|
||
return [row for row in scan["key_dates"] if isinstance(row, dict)]
|