99 lines
4.6 KiB
Python
99 lines
4.6 KiB
Python
"""Natal KP cusps and minute-resolution birth-window observations for the appendix."""
|
|
from __future__ import annotations
|
|
|
|
from datetime import timedelta, timezone
|
|
from math import isfinite
|
|
|
|
from . import package as ap
|
|
|
|
PRODUCER = "kp_system.calc_kp_analysis"
|
|
METHOD_NOTE = "KP 宫头制,与正文的整宫制是不同方法"
|
|
UNKNOWN_NOTE = "出生时间误差未知,子主是否稳定无法判断"
|
|
NO_CUSPS = "出生地的 Placidus 宫头无法计算。"
|
|
|
|
|
|
def _cusps(calculator, ctx, jd):
|
|
# The rectification KP helper uses the same Swiss Ephemeris Placidus
|
|
# calculation and sidereal offset, but rounds the returned longitude.
|
|
values = calculator.calculate_cusps(0.0, 0.0, "placidus", jd, ctx.birth["lat"], ctx.birth["lon"])
|
|
if len(values) != 12 or not all(isfinite(value) and 0 <= value < 360 for value in values):
|
|
raise ValueError("invalid Placidus cusps")
|
|
return values
|
|
|
|
|
|
def _runs(samples, birth_utc, zone):
|
|
intervals = []
|
|
for offset, lord in samples:
|
|
at = ap.instant(birth_utc + timedelta(minutes=offset), zone)
|
|
if intervals and intervals[-1]["sub_lord"] == lord:
|
|
intervals[-1]["last_sample"] = at
|
|
else:
|
|
intervals.append({"sub_lord": lord, "first_sample": at, "last_sample": at})
|
|
return intervals
|
|
|
|
|
|
def _calculate(ctx, natal, window, domains):
|
|
if abs(ctx.birth["lat"]) >= 66:
|
|
return ap.block("blocked", PRODUCER, reason=NO_CUSPS)
|
|
lons = natal.get("longitudes") or {}
|
|
planets = ap.NATAL_POINTS[1:]
|
|
if natal.get("status") != "computed" or any(name not in lons or not isfinite(lons[name]) for name in planets):
|
|
return ap.block("blocked", PRODUCER, reason="缺少本命行星经度,无法计算 KP 宫位的代表星。")
|
|
|
|
kp = ap._module("kp_system")
|
|
ayanamsa = ap._module("ayanamsa_utils")
|
|
lock = ap._module("domain_calculation_service").swiss_ephemeris_lock
|
|
calculator = ap._module("bhava_chalit").BhavaChalitCalculator()
|
|
houses = tuple(dict.fromkeys(house for group in domains.values() for house in group))
|
|
known = window is not None and window["known"]
|
|
before, after = (window["before_minutes"], window["after_minutes"]) if known else (30, 30)
|
|
zone = timezone(timedelta(hours=ctx.tz_hours))
|
|
samples = {house: [] for house in houses}
|
|
birth_jd = ap._jd_from_utc(ctx.birth_utc)
|
|
with lock(), ayanamsa.temporary_ayanamsa(ctx.ayanamsa):
|
|
natal_cusps = _cusps(calculator, ctx, birth_jd)
|
|
for offset in range(-before, after + 1):
|
|
moment = ctx.birth_utc + timedelta(minutes=offset)
|
|
cusps = _cusps(calculator, ctx, ap._jd_from_utc(moment)) if offset else natal_cusps
|
|
for house in houses:
|
|
samples[house].append((offset, kp.get_kp_lords(cusps[house - 1])["sub_lord"]))
|
|
|
|
positions = {
|
|
name: {"sign": ap.SIGNS[ap._sign_idx(lons[name])], "degree": lons[name] % 30,
|
|
"house": calculator._planet_bhava_from_cusps(lons[name], natal_cusps)}
|
|
for name in planets
|
|
}
|
|
result = kp.calc_kp_analysis(
|
|
positions, ap.SIGNS[ap._sign_idx(natal_cusps[0])], house_cusps=natal_cusps, house_occupancy_basis="cusp_to_cusp",
|
|
)
|
|
if result.get("house_basis") != "explicit_cusps":
|
|
return ap.block("blocked", PRODUCER, reason=NO_CUSPS)
|
|
rows = {}
|
|
changed = []
|
|
for house in houses:
|
|
intervals = _runs(samples[house], ctx.birth_utc, zone)
|
|
if len(intervals) > 1:
|
|
changed.append(house)
|
|
stability = "range_unknown"
|
|
if known:
|
|
stability = "boundary_sensitive" if len(intervals) > 1 else "stable_in_window"
|
|
rows[house] = {"house": house, **result["houses"][house], "stability": stability, "branches": intervals}
|
|
|
|
return ap.block(
|
|
"computed", PRODUCER, profile="sidereal_placidus_cusp_to_cusp",
|
|
house_basis=result["house_basis"], house_occupancy_basis=result["house_occupancy_basis"],
|
|
house_system="placidus", ayanamsa=ctx.ayanamsa, node_mode=ctx.node_mode, method_note=METHOD_NOTE,
|
|
precision={"source": "declared" if known else "reference",
|
|
"before_minutes": before, "after_minutes": after, "resolution_minutes": 1,
|
|
"status": "checked" if known else "range_unknown",
|
|
"note": None if known else UNKNOWN_NOTE, "changing_houses": sorted(changed)},
|
|
domains={domain: [rows[house] for house in group] for domain, group in domains.items()},
|
|
)
|
|
|
|
|
|
def build(ctx, natal, window, domains):
|
|
try:
|
|
return _calculate(ctx, natal, window, domains)
|
|
except Exception: # noqa: BLE001 - a failed cusp sample blocks the appendix and no proxy can replace it.
|
|
return ap.block("blocked", PRODUCER, reason=NO_CUSPS)
|