322 lines
16 KiB
Python
322 lines
16 KiB
Python
"""Her Python event engine, run inside the astrologer stage (product 2026-11-07, synced with upstream).
|
|
|
|
Upstream yinduzhanxing@5fb8379c ships two scorers. ``astrologer.py`` ports her
|
|
JS app engine (Dasha 40 / varga 35 / house 15 / nakshatra 10). This module
|
|
ports the second one, ``scripts/active_rectification_event_engine.py``
|
|
(``_score_event`` / ``_candidate_row`` / ``_kp_house_sublords``), so the stage
|
|
carries the layers the JS engine lacks:
|
|
|
|
* Vimshottari MD / AD / PD lord in a domain house, ruling a domain house, or in
|
|
a domain house of the domain varga (2 / 1.5 / 0.75);
|
|
* Narayana MD / AD sign in a domain house (2 / 1);
|
|
* functional benefic / malefic auxiliary of the Dasha lord (+0.2 / -0.1);
|
|
* Arudha auxiliary: Dasha lord in A7 / UL (relationship) or A10 (career), +0.35;
|
|
* the KP layer: the running MD / AD / PD lord against the sub / sub-sub / star
|
|
lord of the domain-house sidereal Placidus cusps (``KP_SUB_WEIGHTS``);
|
|
* SAV auxiliary on the domain houses (+0.2 / -0.1);
|
|
* event-date precision weighting (day 1.0 / month 0.8 / year 0.5);
|
|
* ``adjudicate_candidate_rows``: winning segment, lead margin and confidence.
|
|
|
|
The helpers are this repository's copies of the same upstream functions
|
|
(``active_rectification_event_engine``). Upstream turns KP on with
|
|
``kp_layer=True``; the stage always runs it, because the owner asked for the
|
|
layer, and reports it as its own rule ids so its share stays visible.
|
|
|
|
Two deliberate differences, both stated in the output:
|
|
|
|
* controlled transit (+0.25 Jupiter / Saturn) is not scored -- the astrologer
|
|
stage keeps Gochara ``blocked`` per her technique contract; inside one birth
|
|
window the natal ascendant sign rarely changes, so it would not move a minute;
|
|
* health uses D6 / D8 / D30 as upstream's DOMAIN_CONFIG says. Upstream's
|
|
``calc_all_vargas`` list omits D6 / D8 and silently drops health events
|
|
(``missing_layers``); here they are computed and the event scores.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import json
|
|
from typing import Any, Final
|
|
|
|
import ashtakavarga
|
|
import functional_benefics
|
|
import kp_system
|
|
import varga
|
|
from active_rectification_event_engine import (
|
|
_ashtakavarga_auxiliary,
|
|
_d11_chart,
|
|
_house_lords,
|
|
_leave_one_event_out,
|
|
_planet_house,
|
|
_relative_house,
|
|
_varga_house,
|
|
)
|
|
from active_rectification_events import adjudicate_candidate_rows, precision_weight
|
|
from ayanamsa_utils import DEFAULT_AYANAMSA_NAME, apply_ayanamsa, current_ayanamsa_name, sidereal_ayanamsa_degrees
|
|
|
|
from scripts.domain_calculation_service import swiss_ephemeris_lock
|
|
|
|
UPSTREAM_SOURCE: Final = "yinduzhanxing@5fb8379c scripts/active_rectification_event_engine.py"
|
|
|
|
# upstream active_rectification_event_engine.py lines 49-53.
|
|
KP_SUB_WEIGHTS: Final[dict[str, tuple[float, float]]] = {
|
|
"kp_dba_md": (0.50, 0.25),
|
|
"kp_dba_ad": (0.35, 0.15),
|
|
"kp_dba_pd": (0.20, 0.10),
|
|
}
|
|
KP_MISSING_LAYER: Final = "kp_placidus_cusps"
|
|
|
|
# upstream DOMAIN_CONFIG (lines 56-70): domain -> (domain vargas, domain houses).
|
|
DOMAIN_CONFIG: Final[dict[str, tuple[tuple[str, ...], tuple[int, ...]]]] = {
|
|
"education": (("D24",), (4, 5, 9)),
|
|
"relocation": (("D4",), (4, 12)),
|
|
"relationship": (("D9",), (7,)),
|
|
"career": (("D10",), (10,)),
|
|
"finance": (("D2", "D11"), (2, 11)),
|
|
"health_pressure": (("D6", "D8", "D30"), (6, 8, 12)),
|
|
"family": (("D12",), (4, 9)),
|
|
"sibling_event": (("D3",), (3, 11)),
|
|
}
|
|
|
|
# The stage's event categories (astrologer.EVENT_CATEGORIES) -> upstream domain.
|
|
# ``spiritual`` and ``child`` have no upstream domain; they are listed as not scored.
|
|
CATEGORY_DOMAIN: Final[dict[str, str]] = {
|
|
"marriage": "relationship", "divorce": "relationship", "relationship": "relationship",
|
|
"career": "career", "job_change": "career", "business": "career", "fame": "career",
|
|
"education": "education",
|
|
"travel": "relocation", "property": "relocation",
|
|
"finance_pos": "finance", "finance_neg": "finance",
|
|
"health": "health_pressure", "accident": "health_pressure", "legal": "health_pressure", "loss": "health_pressure",
|
|
"father": "family", "mother": "family", "maternal_relatives": "family", "paternal_relatives": "family",
|
|
"sibling": "sibling_event",
|
|
}
|
|
|
|
CONFIDENCE_CN: Final = {"high": "高", "medium": "中", "low": "低"}
|
|
REASON_CN: Final = {
|
|
"tied_leader": "最高分不止一段",
|
|
"insufficient_events": "事件少于 3 件",
|
|
"insufficient_domains": "事件领域少于 2 个",
|
|
"missing_mandatory_layers": "有必需的层没算出来",
|
|
"unequal_evidence_coverage": "各候选分钟算出的层不一样,总分不能直接比",
|
|
"winning_interval_too_wide": "领先的一段超过 15 分钟",
|
|
"lead_margin_below_medium_threshold": "领先第二名不到 10%",
|
|
"neighbor_stability_not_passed": "和前后几分钟拉不开",
|
|
"leave_one_event_out_not_passed": "去掉任意一件事后领先的分钟会变",
|
|
"no_candidate_rows": "没有候选分钟",
|
|
}
|
|
|
|
|
|
def kp_placidus_cusps(chart: dict[str, Any], lat: float, lon: float, ayanamsa: str) -> dict[int, dict[str, Any]] | None:
|
|
"""upstream ``_kp_house_sublords``: sidereal Placidus cusps (request ayanamsa) -> KP star / sub / sub-sub lords."""
|
|
jd = (chart.get("birth_info") or {}).get("julian_day")
|
|
if not isinstance(jd, int | float) or abs(float(lat)) >= 66.0:
|
|
return None
|
|
try:
|
|
import swisseph as swe
|
|
except ImportError: # pragma: no cover - swisseph is a hard dependency in production
|
|
return None
|
|
previous = current_ayanamsa_name()
|
|
out: dict[int, dict[str, Any]] = {}
|
|
with swiss_ephemeris_lock():
|
|
try:
|
|
apply_ayanamsa(ayanamsa, swe)
|
|
cusps, _ = swe.houses(float(jd), float(lat), float(lon), b"P")
|
|
ayan = sidereal_ayanamsa_degrees(float(jd), swe)
|
|
except Exception: # noqa: BLE001 - recorded as a missing layer, never fatal
|
|
return None
|
|
finally:
|
|
apply_ayanamsa(previous or DEFAULT_AYANAMSA_NAME, swe)
|
|
for house in range(1, 13):
|
|
sidereal = (float(cusps[house - 1]) - ayan) % 360.0
|
|
lords = kp_system.get_kp_lords(sidereal)
|
|
out[house] = {
|
|
"cusp_degree": round(sidereal, 4),
|
|
"nakshatra_lord": str(lords.get("nakshatra_lord") or ""),
|
|
"sub_lord": str(lords.get("sub_lord") or ""),
|
|
"sub_sub_lord": str(lords.get("sub_sub_lord") or ""),
|
|
}
|
|
return out if len(out) == 12 else None
|
|
|
|
|
|
def _varga_charts(planets: dict[str, float], asc_lon: float) -> dict[str, dict[str, Any]]:
|
|
"""Domain varga charts in the ``{"Ascendant": {"sign_idx"}, planet: {"sign_idx"}}`` shape."""
|
|
charts: dict[str, dict[str, Any]] = {}
|
|
for prefix in sorted({p for vargas, _ in DOMAIN_CONFIG.values() for p in vargas}):
|
|
if prefix == "D11":
|
|
charts[prefix] = _d11_chart(planets, asc_lon)
|
|
continue
|
|
d = int(prefix[1:])
|
|
charts[prefix] = {
|
|
"Ascendant": {"sign_idx": int(varga.calc_varga(asc_lon, d)["sign_idx"])},
|
|
**{name: {"sign_idx": int(varga.calc_varga(lon, d)["sign_idx"])} for name, lon in planets.items()},
|
|
}
|
|
return charts
|
|
|
|
|
|
def _score_event(event: dict[str, Any], domain: str, row: dict[str, Any], vim: tuple[str, str, str],
|
|
nar: tuple[int | None, int | None], ctx: dict[str, Any]) -> dict[str, Any]:
|
|
"""Score the upstream event layers and the SAV auxiliary."""
|
|
prefixes, houses = DOMAIN_CONFIG[domain]
|
|
chart = row["chart"]
|
|
asc = row["asc"]
|
|
lords = _house_lords(asc, houses)
|
|
fb, fm = ctx["functional"]
|
|
vargas = [ctx["vargas"][p] for p in prefixes]
|
|
rules: list[str] = []
|
|
points = 0.0
|
|
for lord, weight, label in ((vim[0], 2.0, "vim_md"), (vim[1], 1.5, "vim_ad"), (vim[2], 0.75, "vim_pd")):
|
|
if _planet_house(chart, lord) in houses:
|
|
rules.append(f"{label}_domain_house")
|
|
points += weight
|
|
if lord in lords:
|
|
rules.append(f"{label}_domain_lord")
|
|
points += weight
|
|
for chart_v in vargas:
|
|
if _varga_house(chart_v, lord) in houses:
|
|
rules.append(f"{label}_domain_varga")
|
|
points += weight / (2 * len(vargas))
|
|
if lord in fb:
|
|
rules.append(f"{label}_functional_benefic_auxiliary")
|
|
points += 0.2
|
|
elif lord in fm:
|
|
rules.append(f"{label}_functional_malefic_auxiliary")
|
|
points -= 0.1
|
|
for sign, weight, label in ((nar[0], 2.0, "narayana_md"), (nar[1], 1.0, "narayana_ad")):
|
|
if sign is not None and _relative_house(sign, asc) in houses:
|
|
rules.append(f"{label}_domain_house")
|
|
points += weight
|
|
keys = ("A7", "UL") if domain == "relationship" else ("A10",) if domain == "career" else ()
|
|
arudha = {row["arudha"].get(k) for k in keys} - {None}
|
|
if arudha:
|
|
for lord, label in ((vim[0], "vim_md"), (vim[1], "vim_ad"), (vim[2], "vim_pd")):
|
|
lon = row["planets"].get(lord)
|
|
if isinstance(lon, int | float) and int(lon // 30) in arudha:
|
|
rules.append(f"{label}_arudha_auxiliary")
|
|
points += 0.35
|
|
core_points = points
|
|
kp = ctx["kp"]
|
|
if kp:
|
|
for lord, label in ((vim[0], "kp_dba_md"), (vim[1], "kp_dba_ad"), (vim[2], "kp_dba_pd")):
|
|
sub_w, star_w = KP_SUB_WEIGHTS[label]
|
|
if any(lord in {kp[h]["sub_lord"], kp[h]["sub_sub_lord"]} for h in houses):
|
|
rules.append(f"{label}_domain_cusp_sublord")
|
|
points += sub_w
|
|
if any(kp[h]["nakshatra_lord"] == lord for h in houses):
|
|
rules.append(f"{label}_domain_cusp_starlord")
|
|
points += star_w
|
|
weight = precision_weight(event["precision"])
|
|
weighted = round(points * weight, 4)
|
|
av_rules, av_points = _ashtakavarga_auxiliary(chart, asc, houses, ctx["sav"])
|
|
if av_rules:
|
|
rules.extend(av_rules)
|
|
weighted = round(weighted + av_points * weight, 4)
|
|
# Comparability policy (占星师 2026-11-08 验收清单 §6): per-layer points; KP only when its cusps computed.
|
|
layers = {"dasha_varga_core": core_points * weight, "Ashtakavarga": av_points * weight, "Shadbala": 0.0}
|
|
if kp:
|
|
layers[KP_MISSING_LAYER] = (points - core_points) * weight
|
|
return {"event_id": event["id"], "domain": domain, "candidate_time": row["at"].strftime("%H:%M"),
|
|
"rule_ids": rules or ["no_domain_activation"], "points": weighted, "_layer_points": layers}
|
|
|
|
|
|
def _context(row: dict[str, Any], lat: float, lon: float, ayanamsa: str) -> dict[str, Any]:
|
|
chart = row["chart"]
|
|
planets = chart.get("planets", {})
|
|
# 原值:明确选中 functional_profile=FUNCTIONAL_PROFILE_BPHS(原产品表)。
|
|
# 新值:默认档(PVR 表 30),按产品其他调用方传月亮盈亏。
|
|
# 原因:产品 2026-11-08 批准;占星师第五轮裁定 1、3;与报告/卡口径一致(BUG-1759)。
|
|
functional = functional_benefics.derive_functional_benefic_malefic(
|
|
chart["ascendant"].get("sign"), moon_paksha=functional_benefics.moon_paksha_from_planets(planets))
|
|
sav = ashtakavarga.calc_ashtakavarga(planets, row["asc"])
|
|
return {
|
|
"functional": (set(functional.get("functional_benefics") or []), set(functional.get("functional_malefics") or [])),
|
|
"functional_raw": functional,
|
|
"vargas": _varga_charts(row["planets"], row["asc_lon"]),
|
|
"kp": row["kp_cusps"] if "kp_cusps" in row else kp_placidus_cusps(chart, lat, lon, ayanamsa),
|
|
"sav": sav,
|
|
}
|
|
|
|
|
|
def score_rows(events: list[dict[str, Any]], rows: list[dict[str, Any]], *, lat: float, lon: float, ayanamsa: str,
|
|
active: Any) -> list[dict[str, Any]]:
|
|
"""One ``CandidateScoreRow`` per minute. ``active(event, row)`` returns ((md, ad, pd), (narayana md, ad))."""
|
|
out = []
|
|
profiles = []
|
|
for row in rows:
|
|
ctx = _context(row, lat, lon, ayanamsa)
|
|
profiles.append(ctx["functional_raw"])
|
|
# K3 (占星师 2026-11-08 第五轮逐项答复): one scoring run never mixes functional tables.
|
|
functional_benefics.assert_single_functional_profile(profiles, run="chart_choice")
|
|
evidence = []
|
|
layer_points: dict[str, dict[str, float]] = {}
|
|
missing = [] if ctx["kp"] else [KP_MISSING_LAYER]
|
|
for event in events:
|
|
domain = CATEGORY_DOMAIN.get(event["category"])
|
|
if domain is None:
|
|
continue
|
|
vim, nar = active(event, row)
|
|
if nar[0] is None or nar[1] is None:
|
|
# 原值:来源版 Narayana 定不出时该级按 0 分计入总分,missing_layers 不记。
|
|
# 新值:与 upstream ``_candidate_row`` 相同,该事件不计分并记 Narayana_MD_AD。
|
|
# 原因:占星师 2026-11-08 验收清单 §6(缺层不能变成 0 分)。
|
|
missing.append("Narayana_MD_AD")
|
|
continue
|
|
item = _score_event(event, domain, row, vim, nar, ctx)
|
|
layer_points[item["event_id"]] = item.pop("_layer_points")
|
|
evidence.append(item)
|
|
out.append({
|
|
"time": row["at"].strftime("%H:%M"),
|
|
"score": round(sum(e["points"] for e in evidence), 4),
|
|
"evidence": evidence,
|
|
"layer_points": layer_points,
|
|
"missing_layers": sorted(set(missing)),
|
|
"kp_cusps": {str(h): ctx["kp"][h] for h in (1, 4, 7, 10)} if ctx["kp"] else None,
|
|
"functional": {k: ctx["functional_raw"].get(k) for k in ("functional_benefics", "functional_malefics")},
|
|
})
|
|
return out
|
|
|
|
|
|
def verdict(events: list[dict[str, Any]], rows: list[dict[str, Any]]) -> dict[str, Any]:
|
|
"""``adjudicate_candidate_rows`` on the stage's rows, plus a plain summary of the verdict."""
|
|
scored_events = [{"id": e["id"], "domain": CATEGORY_DOMAIN[e["category"]]} for e in events if e["category"] in CATEGORY_DOMAIN]
|
|
unscored = [e["id"] for e in events if e["category"] not in CATEGORY_DOMAIN]
|
|
fingerprint = hashlib.sha256(json.dumps([[e["id"], e["category"], e["date"]] for e in events]
|
|
+ [r["time"] for r in rows]).encode()).hexdigest()
|
|
loo = _leave_one_event_out(rows, scored_events) if rows else {"status": "blocked", "runs": []}
|
|
adjudicated = adjudicate_candidate_rows(
|
|
rows, event_count=len(scored_events), domain_count=len({e["domain"] for e in scored_events}),
|
|
request_fingerprint=fingerprint, leave_one_event_out=loo,
|
|
)
|
|
segment = adjudicated.get("winning_segment")
|
|
top = adjudicated["top_score"]
|
|
tied = [r["time"] for r in rows if r["score"] == top]
|
|
kp_on = all(r["kp_cusps"] for r in rows) if rows else False
|
|
reasons = list(adjudicated["reasons"])
|
|
return {
|
|
"source": UPSTREAM_SOURCE,
|
|
"layers": ["Vimshottari MD/AD/PD", "Narayana MD/AD", "功能吉凶星", "A7 / UL / A10", "KP Placidus 宫头",
|
|
"SAV", "事件日期精度加权"],
|
|
"kp_layer": "executed" if kp_on else "blocked",
|
|
"kp_weights": {k: list(v) for k, v in KP_SUB_WEIGHTS.items()},
|
|
"transit": "not_scored",
|
|
"precision_weights": {p: precision_weight(p) for p in ("day", "month", "year")},
|
|
"scored_event_ids": [e["id"] for e in scored_events],
|
|
"unscored_event_ids": unscored,
|
|
"confidence": adjudicated["confidence"],
|
|
"confidence_label": CONFIDENCE_CN[adjudicated["confidence"]],
|
|
"can_apply": adjudicated["can_apply"],
|
|
"winning_segment": segment,
|
|
"top_time": segment["representative_time"] if segment else None,
|
|
"tied_top_times": tied if len(tied) > 1 else [],
|
|
"top_score": top,
|
|
"second_score": adjudicated["second_score"],
|
|
"margin_percent": adjudicated["margin_percent"],
|
|
"reasons": reasons,
|
|
"reasons_cn": [REASON_CN.get(r, r) for r in reasons],
|
|
# Raw-total leader vs the leader over the evidence every candidate has (验收清单 §6 / §9 / §10).
|
|
"leader_status": adjudicated["leader_status"],
|
|
"comparable_top_time": (adjudicated["comparable_leader"] or {}).get("representative_time"),
|
|
"missing_layers": adjudicated["missing_layers"],
|
|
"leave_one_event_out": loo.get("status"),
|
|
"ranking": [{"time": r["time"], "score": r["score"]} for r in sorted(rows, key=lambda r: (-r["score"], r["time"]))[:10]],
|
|
"top_evidence": adjudicated.get("evidence", []),
|
|
}
|