Files
Jyotisha/scripts/chart_choice/astrologer.py
T
ClaudeandClaude Opus 5.5 b7dd6695a8
Independent Staging Quality Gate / validate-frontend (push) Successful in 6m8s
Independent Staging Quality Gate / validate-python (push) Successful in 7m31s
Independent Staging Quality Gate / publish (push) Successful in 3m29s
fix(rectification): the astrologer-method step states the fact instead of 「只作参考」 (BUG-2102)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXp2U3BH1SxwAGyhhbe1
2026-11-20 21:39:37 +08:00

857 lines
45 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.
"""The astrologer's own birth-time rectification method, run as a stage next to chart choice.
Product order 2026-11-07: birth-time rectification follows the astrologer's
skill (yinduzhanxing 5fb8379c) in full. The chart-choice page stays; this
module adds her method and reports its result with her own confidence rules
beside our backtest caveat. Sources, all upstream:
* ``references/birth-time-rectification-decision-tree.md`` -- layer order
(Dasha + dated events -> D9 -> D10 -> theme vargas -> Nakshatra / Pada /
house shifts -> D30 -> D60), the ">= 5 dated events" gate, theme varga per
event topic, D30 only with health/accident events, D60 last and reference only.
* ``references/birth-time-rectification-advanced.md`` -- the eight methods and
the five-stage automated flow: intake (appearance, constitution, birthmarks,
family events), pre-screen by appearance and birthmarks, event verification
(Dasha per event, match rate >= 80 / 60-80 / < 60 per cent), fine
correction by D9 and D10 ascendant traits, report with 90 / 70 per cent
confidence tiers. Method 1 asks for 10-15 events.
* ``jyotish-app/rectification-engine.js`` -- the scoring she ships: Dasha 40 %,
divisional agreement 35 %, house shifts 15 %, Nakshatra pada 10 %; event
categories with karaka planets, houses and theme varga; match / strong event
counts; the top cluster (within 3 points); her confidence (best >= 65 and
lead >= 15 % -> high, >= 45 and >= 8 % -> medium, >= 25 -> low).
* ``scripts/active_rectification_questions.py`` -- the A/B/C/D questionnaire
(synced into this repository) and its scoring.
* ``scripts/rectification_technique_contract.py`` -- the claim contract.
Local extension, stated as such: her JS reads Vimshottari MD/AD only; the
decision tree and the repository contract require MD/AD/PD + Narayana MD/AD,
so the Dasha part also scores the PD lord (karaka 1, house lord 0.75) and the
Narayana MD / AD sign in a topic house (2 / 1), using the repository's own
calculators. Narayana is the source-version profile the report and the chat
card use (``narayana_rath``, BUG-1759, product 2026-11-08); when a step is
blocked for a minute that layer is unavailable for it (not a miss, no fallback
to the old algorithm). Transit is not scored: the upstream contract keeps Gochara
``blocked_from_verified_timing``.
Product 2026-11-07 (synced with upstream): the stage also runs her Python
event engine (``astrologer_engine.py``: functional benefic / malefic, A7 / UL /
A10, KP Placidus cusp sub-lords, SAV, event-date precision weighting
and the lead-margin verdict of ``adjudicate_candidate_rows``), and scans every
formal varga of her ``candidate_time_sensitivity_scan`` (D2-D12, D16, D20, D24,
D27, D30, D40, D45, D60). D40 / D45 / D60 are reference only, as in her
evidence-domain contract. When the top minutes tie, the match tier says so
instead of 「高度吻合」.
Our own measurement (BUG-1644, 2026-11-06, 77 Rodden-AA cases): inside a
30-minute window, event scoring picked the right segment 0.19 of the time,
uniform random 0.20, the reported time 0.34. Every result carries that caveat.
"""
from __future__ import annotations
import sys
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, Final
_SCRIPTS = Path(__file__).resolve().parents[1]
if str(_SCRIPTS) not in sys.path:
sys.path.insert(0, str(_SCRIPTS))
import dasha_analyzer # noqa: E402
import jaimini # noqa: E402
import kp_system # noqa: E402
import varga # noqa: E402
from active_rectification_event_engine import ( # noqa: E402
_active_narayana, _active_vimshottari, _narayana_antardasha_table, _narayana_periods, _vimshottari_timeline,
)
from rectification_technique_contract import build_rectification_technique_contract # noqa: E402
from scripts.chart_choice import astrologer_engine # noqa: E402
from scripts.chart_choice.boundaries import ChartChoiceInputError, ChartRequest, chart_at # noqa: E402
from scripts.chart_choice.readings import PLANET_CN, SIGN_CN, SIGN_LORD # noqa: E402
ENGINE_VERSION: Final = "astrologer-method-v1"
UPSTREAM_REF: Final = "yinduzhanxing@5fb8379c"
MAX_WINDOW_MINUTES: Final = 241 # her stage 3 allows a +-1-2 hour shift; +-2 h is the widest scan
MAX_EVENTS: Final = 30
MIN_EVENTS: Final = 5 # decision tree step 1
IDEAL_EVENTS: Final = (10, 15) # advanced.md method 1
TOP_CLUSTER_POINTS: Final = 3 # rectification-engine.js buildRectificationAudit
WEIGHTS: Final = {"dasha": 40, "varga": 35, "house": 15, "nakshatra": 10}
# Every divisional chart whose ascendant is tracked minute by minute: her
# candidate_time_sensitivity_scan FORMAL_DIVISIONS (19 vargas). D60 is
# reference only (decision tree section 6); D40 / D45 are research-only in her
# evidence-domain contract. They are reported, never scored.
# 原值 (1, 2, 3, 4, 7, 9, 10, 12, 20, 24, 30, 60) / 新值 加 D5 D6 D8 D11 D16 D27 D40 D45 / 原因 产品 2026-11-07 与占星师上游同步
SCAN_DIVISIONS: Final = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 16, 20, 24, 27, 30, 40, 45, 60)
REFERENCE_ONLY: Final = frozenset({"D40", "D45", "D60", "KP cusps 4/7/10"})
PLANETS: Final = ("Sun", "Moon", "Mars", "Mercury", "Jupiter", "Venus", "Saturn", "Rahu", "Ketu")
NATURAL_MALEFICS: Final = frozenset({"Sun", "Mars", "Saturn", "Rahu", "Ketu"})
# rectification-engine.js EVENT_CATEGORIES, plus the family (六亲) houses of
# advanced.md method 4 (3 siblings, 4 mother, 6 maternal relatives, 7 spouse,
# 9 father, 11 paternal relatives) with D12 / D3 from the decision tree.
EVENT_CATEGORIES: Final[dict[str, dict[str, Any]]] = {
"marriage": {"label": "结婚 / 确定关系", "group": "relationship", "planets": ("Venus", "Jupiter"), "houses": (7,), "varga": "D9"},
"divorce": {"label": "离婚 / 分开", "group": "relationship", "planets": ("Rahu", "Saturn"), "houses": (7, 8), "varga": "D9"},
"relationship": {"label": "重要的感情开始", "group": "relationship", "planets": ("Venus", "Moon"), "houses": (7, 1), "varga": "D9"},
"career": {"label": "入职 / 升职", "group": "career", "planets": ("Sun", "Saturn"), "houses": (10,), "varga": "D10"},
"job_change": {"label": "换工作 / 离职", "group": "career", "planets": ("Saturn", "Sun"), "houses": (10, 6), "varga": "D10"},
"business": {"label": "创业 / 开店", "group": "career", "planets": ("Mercury", "Mars"), "houses": (10, 7), "varga": "D10"},
"fame": {"label": "获奖 / 公开露面", "group": "career", "planets": ("Sun", "Jupiter"), "houses": (1, 10, 9), "varga": "D10"},
"education": {"label": "升学 / 考试 / 毕业", "group": "education", "planets": ("Mercury", "Jupiter"), "houses": (4, 5), "varga": "D24"},
"child": {"label": "生孩子", "group": "family", "planets": ("Jupiter", "Sun"), "houses": (5,), "varga": "D7"},
"father": {"label": "父亲的大事(生病、去世等)", "group": "family", "planets": ("Sun",), "houses": (9,), "varga": "D12"},
"mother": {"label": "母亲的大事(生病、去世等)", "group": "family", "planets": ("Moon",), "houses": (4,), "varga": "D12"},
"sibling": {"label": "兄弟姐妹的大事", "group": "family", "planets": ("Mars",), "houses": (3, 11), "varga": "D3"},
"maternal_relatives": {"label": "外公外婆等母亲那边亲人的大事", "group": "family", "planets": ("Moon",), "houses": (6,), "varga": "D12"},
"paternal_relatives": {"label": "爷爷奶奶等父亲那边亲人的大事", "group": "family", "planets": ("Sun",), "houses": (11,), "varga": "D12"},
"property": {"label": "买房 / 置业", "group": "family", "planets": ("Mars", "Venus"), "houses": (4,), "varga": "D4"},
"travel": {"label": "搬家 / 出国 / 去外地", "group": "mobility", "planets": ("Rahu", "Moon"), "houses": (9, 12, 3), "varga": "D4"},
"finance_pos": {"label": "收入明显变多", "group": "money", "planets": ("Jupiter", "Venus"), "houses": (2, 11), "varga": "D2"},
"finance_neg": {"label": "破财 / 大损失", "group": "stress", "planets": ("Saturn", "Rahu"), "houses": (8, 12), "varga": "D2"},
"health": {"label": "生病 / 手术", "group": "stress", "planets": ("Mars", "Rahu"), "houses": (1, 6, 8, 12), "varga": "D30"},
"accident": {"label": "事故 / 受伤", "group": "stress", "planets": ("Mars", "Saturn"), "houses": (1, 6, 8), "varga": "D30"},
"legal": {"label": "官司 / 纠纷", "group": "stress", "planets": ("Mars", "Saturn"), "houses": (6, 8), "varga": "D30"},
"loss": {"label": "失去重要的人", "group": "stress", "planets": ("Saturn", "Rahu"), "houses": (8, 12), "varga": "D30"},
"spiritual": {"label": "开始修行 / 信仰转变", "group": "inner", "planets": ("Jupiter", "Ketu"), "houses": (9, 12), "varga": "D20"},
}
D30_TOPICS: Final = frozenset({"health", "accident", "legal", "loss"})
# advanced.md method 5 (appearance and constitution), indexed by sign.
APPEARANCE: Final = (
("中等身材、脸部线条分明", "Pitta(火)", "头部、眼睛"),
("结实、脖子粗", "Kapha(水)", "喉咙、颈部"),
("高瘦、手臂长", "Vata(风)", "肺部、神经"),
("圆脸、胸部发达", "Kapha(水)", "胸部、胃部"),
("健壮、背部发达", "Pitta(火)", "心脏、背部"),
("中等身材、肚子敏感", "Vata / Kapha", "腹部、肠道"),
("匀称、举止优雅", "Vata(风)", "肾脏、腰部"),
("结实、眼神深", "Kapha / Pitta", "生殖系统"),
("高大、臀部发达", "Pitta(火)", "臀部、大腿"),
("瘦长、关节突出", "Vata(风)", "骨骼、关节"),
("高瘦、小腿发达", "Vata(风)", "小腿、循环"),
("中等身材、脚容易不舒服", "Kapha(水)", "脚部、淋巴"),
)
# advanced.md method 2 (D9 ascendant -> relationship traits) and method 3 (D10 -> career traits).
D9_TRAITS: Final = (
"主动、热情、来得快;对方独立有活力",
"稳定、务实、在乎安全感;对方稳重、有经济基础",
"爱沟通、多变;对方聪明、能聊",
"重感情、以家为先;对方温柔顾家",
"要面子、有戏剧性;对方有魅力、有地位",
"挑剔、讲细节、愿意照顾人;对方细致、有技能",
"讲和谐、重美感、愿意合作;对方优雅",
"感情深、占有欲强、会经历蜕变;对方有深度",
"要自由、谈理想;对方开放、有学识",
"务实、重责任、来得晚;对方成熟、重事业",
"独立、不走寻常路、像朋友;对方有理想",
"浪漫、愿意付出、重精神;对方有艺术或灵性气质",
)
D10_TRAITS: Final = (
"带头、创业、竞争性强的工作",
"稳定、和钱或艺术有关的工作",
"沟通、写作、教学、销售",
"照顾人、餐饮、住房相关",
"管理、表演、出头露面",
"服务、分析、医疗健康",
"合作、法律、设计、咨询",
"研究、心理、处理危机",
"教育、出版、国际事务",
"管理、政府、工程建设",
"科技、创新、公益",
"艺术、灵性、医疗服务",
)
# advanced.md method 6: body region -> house from the ascendant (Kalapurusha order,
# matching her sign / body table) and the planets her planet table ties to it.
BIRTHMARK_PARTS: Final[dict[str, dict[str, Any]]] = {
"head": {"label": "头部", "house": 1, "planets": ("Mars", "Rahu")},
"face": {"label": "脸、眼睛", "house": 2, "planets": ("Sun", "Moon")},
"neck": {"label": "脖子、喉咙", "house": 2, "planets": ()},
"shoulder_arm": {"label": "肩膀、手臂、手", "house": 3, "planets": ("Mercury", "Moon")},
"chest": {"label": "胸口", "house": 4, "planets": ("Moon",)},
"back": {"label": "后背", "house": 5, "planets": ("Sun",)},
"belly": {"label": "肚子", "house": 6, "planets": ("Ketu",)},
"waist": {"label": "腰", "house": 7, "planets": ("Venus",)},
"private": {"label": "隐私部位", "house": 8, "planets": ("Venus",)},
"thigh_hip": {"label": "臀部、大腿", "house": 9, "planets": ("Jupiter",)},
"knee": {"label": "膝盖", "house": 10, "planets": ("Saturn",)},
"calf": {"label": "小腿、脚踝", "house": 11, "planets": ()},
"foot": {"label": "脚", "house": 12, "planets": ()},
}
QUESTION_CLUSTER_CN: Final = {
"middle_candidate_cluster": "学业变化落在中段候选",
"D4_relocation_cluster": "搬迁信号更强的候选(D4)",
"D9_UL_A7_cluster": "婚恋结构更吻合的候选(D9 / UL / A7)",
"D10_A10_saturn_cluster": "事业责任更吻合的候选(D10 / A10)",
"Mercury_D24_A10_cluster": "学习表达更吻合的候选(D24 / A10)",
"D30_crisis_cluster": "压力窗口更吻合的候选(D30)",
"A10_public_visibility_cluster": "事业外显更吻合的候选(A10)",
"fine_boundary_cluster": "分钟边界候选",
}
# BUG-2102 (负责人 2026-11-20: 用户看得到的地方不写「只作参考」): state the fact only.
# 原值: 「这一步按占星师的方法计算,结果只作参考,不是验证结果。」
CAVEAT: Final = (
"这一步按占星师的方法计算,没有经过实际事件验证。2026-11-06 我们在 77 个出生时间有可靠记录的案例上"
"回测过同类的事件打分:30 分钟范围里头名命中 19%,随机挑也是 20%,直接用报的时间是 34%。"
)
def _at(at: datetime) -> str:
return at.strftime("%Y-%m-%dT%H:%M")
def _hhmm(at: datetime) -> str:
return at.strftime("%H:%M")
def _house(sign: int, asc: int) -> int:
return (sign - asc) % 12 + 1
def _house_lord(asc: int, house: int) -> str:
return SIGN_LORD[(asc + house - 1) % 12]
def _sign_of(longitude: float, division: int) -> int:
if division == 1:
return int(longitude // 30) % 12
return int(varga.calc_varga(longitude, division)["sign_idx"])
# --------------------------------------------------------------------------- scan
def _minute_row(req: ChartRequest, at: datetime) -> dict[str, Any]:
chart = chart_at(req, at)
kp_cusps = astrologer_engine.kp_placidus_cusps(chart, req.lat, req.lon, req.ayanamsa)
planets = {
name: float(data["lon"]) for name, data in chart.get("planets", {}).items()
if isinstance(data, dict) and isinstance(data.get("lon"), int | float)
}
asc_lon = float(chart["ascendant"]["lon"])
asc = int(asc_lon // 30)
vargas = {f"D{d}": _sign_of(asc_lon, d) for d in SCAN_DIVISIONS}
planet_vargas = {
f"D{d}": {name: _sign_of(lon, d) for name, lon in planets.items()} for d in SCAN_DIVISIONS if d != 1
}
arudha = jaimini.calc_arudha_padas(asc, planets)
padas = arudha.get("padas") or {}
arudha_signs = {
"A7": (padas.get("A7") or {}).get("sign_idx"),
"A10": (padas.get("A10") or {}).get("sign_idx"),
"UL": (arudha.get("upapada") or {}).get("sign_idx"),
}
kp = kp_system.get_kp_lords(asc_lon)
asc_nak, _, asc_pada = dasha_analyzer.lon_to_nakshatra(asc_lon)
moon_nak, _moon_progress, moon_pada = dasha_analyzer.lon_to_nakshatra(planets["Moon"])
# BUG-1720: from the candidate birth moment (was the birth date at 00:00), float sub-period splits.
timeline = _vimshottari_timeline(at, planets["Moon"])
# 原值:narayana_dasha.calc_narayana_mahadasha / calc_narayana_antardasha(旧算法:从上升起、一律顺数)。
# 新值:来源版 Narayana(与报告、咨询卡同一个 narayana_rath),从候选出生时刻起算;blocked 时为 None。
# 原因:产品 2026-11-08 批准;占星师第五轮裁定 1、3;与报告/卡口径一致(BUG-1759)。
narayana_periods = _narayana_periods(asc, planets)
narayana_ads = _narayana_antardasha_table(narayana_periods, planets)
return {
"at": at,
"chart": chart,
"asc_lon": asc_lon,
"asc": asc,
"planets": planets,
"planet_houses": {name: _house(int(lon // 30), asc) for name, lon in planets.items()},
"vargas": vargas,
"planet_vargas": planet_vargas,
"arudha": arudha_signs,
"kp_lagna": {"star_lord": kp.get("nakshatra_lord"), "sub_lord": kp.get("sub_lord")},
"kp_cusps": kp_cusps,
"asc_nakshatra": {"name": asc_nak[0], "pada": int(asc_pada)},
"moon_nakshatra": {"index": int(moon_nak[2]), "name": moon_nak[0], "pada": int(moon_pada)},
"timeline": timeline,
"narayana": (narayana_periods, narayana_ads),
}
def _layer_values(row: dict[str, Any]) -> dict[str, Any]:
values: dict[str, Any] = dict(row["vargas"])
values["Nakshatra/Pada"] = (row["asc_nakshatra"]["name"], row["asc_nakshatra"]["pada"])
values["KP sub-lord"] = row["kp_lagna"]["sub_lord"]
cusps = row.get("kp_cusps")
values["KP cusps 4/7/10"] = tuple(cusps[h]["sub_lord"] for h in (4, 7, 10)) if cusps else None
values.update({k: v for k, v in row["arudha"].items()})
return values
def scan(req: ChartRequest, start: datetime, end: datetime) -> list[dict[str, Any]]:
rows = []
at = start
while at <= end:
rows.append(_minute_row(req, at))
at += timedelta(minutes=1)
return rows
def sensitivity_lines(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Minute steps where any tracked layer changes, D60 flagged reference-only."""
lines = []
for prev, cur in zip(rows, rows[1:]):
a, b = _layer_values(prev), _layer_values(cur)
changed = [k for k in a if a[k] != b[k]]
if changed:
lines.append({
"between": [_hhmm(prev["at"]), _hhmm(cur["at"])],
"layers": changed,
"reference_only": all(k in REFERENCE_ONLY for k in changed),
})
return lines
def minute_scan_for_questionnaire(rows: list[dict[str, Any]]) -> dict[str, Any]:
"""The selector's minute-scan shape (candidate_time_sensitivity_scan rows), computed in process."""
out = []
for row in rows:
out.append({
"time": row["at"].strftime("%Y-%m-%d %H:%M"),
"d1_ascendant": SIGN_CN[row["asc"]],
"d1_degree_in_sign": round(row["asc_lon"] % 30, 4),
"d1_longitude": round(row["asc_lon"], 4),
"divisional_ascendants": {k: {"sign_idx": v} for k, v in row["vargas"].items() if k != "D1"},
"arudha": {k: {"sign_idx": v} for k, v in row["arudha"].items()},
"kp_cusps": row["kp_lagna"],
})
transitions = [
{"between": [p["time"], c["time"]], "changed": ["divisional_ascendants"]}
for p, c in zip(out, out[1:]) if p["divisional_ascendants"] != c["divisional_ascendants"] or p["d1_ascendant"] != c["d1_ascendant"]
]
return {"scope": "candidate_time_sensitivity_scan", "status": "local_computed_in_process", "rows": out, "transitions": transitions}
# --------------------------------------------------------------------------- events
def _event_at(date: str) -> tuple[datetime, str]:
parts = date.split("-")
try:
if len(parts) == 1:
return datetime(int(parts[0]), 7, 1), "year"
if len(parts) == 2:
return datetime(int(parts[0]), int(parts[1]), 15), "month"
if len(parts) == 3:
return datetime(int(parts[0]), int(parts[1]), int(parts[2])), "day"
except ValueError:
pass
raise ChartChoiceInputError("event date must be YYYY, YYYY-MM or YYYY-MM-DD")
def parse_events(raw: Any, birth: datetime) -> list[dict[str, Any]]:
if raw in (None, []):
return []
if not isinstance(raw, list) or len(raw) > MAX_EVENTS:
raise ChartChoiceInputError(f"events must be a list of at most {MAX_EVENTS}")
events = []
for index, item in enumerate(raw):
if not isinstance(item, dict) or item.get("category") not in EVENT_CATEGORIES or not isinstance(item.get("date"), str):
raise ChartChoiceInputError("each event needs a known category and a date")
at, precision = _event_at(item["date"].strip())
if at <= birth:
raise ChartChoiceInputError("event date must be after birth")
events.append({"id": str(item.get("id") or f"e{index + 1}"), "category": item["category"],
"date": item["date"].strip(), "at": at, "precision": precision})
return events
def _independent_events(events: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], list[str]]:
"""First event of each (category, date); the ids of the repeats (验收清单 §6)."""
seen: set[tuple[str, str]] = set()
kept, duplicates = [], []
for event in events:
key = (event["category"], event["date"])
if key in seen:
duplicates.append(event["id"])
continue
seen.add(key)
kept.append(event)
return kept, duplicates
def leader_coverage(final_ranked: list[dict[str, Any]]) -> dict[str, Any]:
"""Whether the candidates' match rates rest on the same Dasha levels (验收清单 §6 / §9 / §10).
``score_minute`` divides by each candidate's own available maximum (BUG-1759), so when some
candidates lack a Narayana level that others have, their totals are not directly comparable and the
leader is only provisional. The ranking itself is unchanged (her method).
"""
signatures = {
s["time"]: tuple(sorted((e["id"], level) for e in s["events"] for level in e["chain"].get("unavailable") or ()))
for s in final_ranked
}
distinct = set(signatures.values())
unequal = len(distinct) > 1
return {
"status": "provisional_unequal_coverage" if unequal else "comparable",
"candidates_missing_layers": sum(1 for sig in signatures.values() if sig),
"missing_layers": sorted({level for sig in signatures.values() for _, level in sig}),
}
def _dasha_score(event: dict[str, Any], row: dict[str, Any]) -> tuple[float, dict[str, Any]]:
"""rectification-engine.js scoreDasha (MD / AD), plus PD and Narayana MD / AD (see module doc)."""
cat = event.get("spec") or EVENT_CATEGORIES[event["category"]]
asc = row["asc"]
lords = {_house_lord(asc, h) for h in cat["houses"]}
md, ad, pd = _active_vimshottari(row["at"], row["planets"]["Moon"], event["at"], row["timeline"])
periods, ads = row["narayana"]
n_md, n_ad = _active_narayana(asc, row["planets"], row["at"], event["at"], periods, ads)
score = 0.0
md_ok = md in cat["planets"] or md in lords
ad_ok = ad in cat["planets"] or ad in lords
score += 3 if md in cat["planets"] else 2 if md in lords else 0
score += 2 if ad in cat["planets"] else 1.5 if ad in lords else 0
if md_ok and ad_ok:
score += 2
score += 1 if pd in cat["planets"] else 0.75 if pd in lords else 0
n_md_ok = n_md is not None and _house(n_md, asc) in cat["houses"]
n_ad_ok = n_ad is not None and _house(n_ad, asc) in cat["houses"]
score += (2 if n_md_ok else 0) + (1 if n_ad_ok else 0)
# BUG-1759: a blocked source-version step is an unavailable layer, not a miss.
unavailable = [name for name, value in (("narayana_md", n_md), ("narayana_ad", n_ad)) if value is None]
chain = {
"vimshottari": {"md": md, "ad": ad, "pd": pd},
"narayana": {"md": SIGN_CN[n_md] if n_md is not None else None, "ad": SIGN_CN[n_ad] if n_ad is not None else None},
"activates": {"md": md_ok, "ad": ad_ok, "pd": pd in cat["planets"] or pd in lords,
"narayana_md": n_md_ok, "narayana_ad": n_ad_ok},
}
if unavailable:
chain["unavailable"] = unavailable
return score, chain
def _dasha_max(chain: dict[str, Any]) -> float:
"""Per-event Dasha maximum without the Narayana levels that were unavailable (BUG-1759)."""
missing = set(chain.get("unavailable") or ())
return DASHA_MAX_PER_EVENT - (2 if "narayana_md" in missing else 0) - (1 if "narayana_ad" in missing else 0)
DASHA_MAX_PER_EVENT: Final = 3 + 2 + 2 + 1 + 2 + 1
def _varga_score(event: dict[str, Any], row: dict[str, Any]) -> float:
"""rectification-engine.js scoreVarga: the topic varga's ascendant lord against the event."""
cat = event.get("spec") or EVENT_CATEGORIES[event["category"]]
sign = row["vargas"].get(cat["varga"])
if sign is None:
return 0.0
lord = SIGN_LORD[sign]
score = 0.0
if lord in cat["planets"]:
score += 3
if any(_house_lord(row["asc"], h) == lord for h in cat["houses"]):
score += 2
if _house(sign, row["asc"]) in (1, 4, 5, 7, 9, 10):
score += 1
return score
VARGA_MAX_PER_EVENT: Final = 6
def _nak_score(base: dict[str, Any], row: dict[str, Any]) -> int:
"""rectification-engine.js scoreNak: Moon nakshatra (2) or pada (1) change against the reported minute."""
b, o = base["moon_nakshatra"], row["moon_nakshatra"]
if b["index"] != o["index"]:
return 2
return 1 if b["pada"] != o["pada"] else 0
def score_minute(events: list[dict[str, Any]], row: dict[str, Any], base: dict[str, Any]) -> dict[str, Any]:
n = len(events)
d_raw = v_raw = d_max = 0.0
per_event = []
for event in events:
ds, chain = _dasha_score(event, row)
vs = _varga_score(event, row)
d_raw += ds
d_max += _dasha_max(chain)
v_raw += vs
per_event.append({"id": event["id"], "dasha": ds, "varga": vs, "chain": chain,
"matched": ds > 0 or vs > 0, "strong": ds >= 4 or (ds > 0 and vs > 0)})
house_changes = [p for p in PLANETS if row["planet_houses"].get(p) != base["planet_houses"].get(p)]
d_pct = d_raw / d_max if n and d_max else 0.0
v_pct = v_raw / (n * VARGA_MAX_PER_EVENT) if n else 0.0
h_pct = min(len(house_changes) / max(n, 1), 1.0)
k_pct = _nak_score(base, row) / 2
total = round(d_pct * WEIGHTS["dasha"] + v_pct * WEIGHTS["varga"] + h_pct * WEIGHTS["house"] + k_pct * WEIGHTS["nakshatra"])
matched = sum(1 for e in per_event if e["matched"])
strong = sum(1 for e in per_event if e["strong"])
return {
"time": _hhmm(row["at"]),
"at": _at(row["at"]),
"offset": int((row["at"] - base["at"]).total_seconds() // 60),
"total": total,
"parts": {"dasha": round(d_pct * 100), "varga": round(v_pct * 100), "house": round(h_pct * 100), "nakshatra": round(k_pct * 100)},
"matched": matched,
"strong": strong,
"match_rate": round(matched / n * 100) if n else 0,
"strong_rate": round(strong / n * 100) if n else 0,
"house_changes": house_changes,
"events": per_event,
}
TIED_TIER: Final = {"key": "tied", "label": "分不出前后"}
def match_tier(rate: int, tied_count: int = 0) -> dict[str, str]:
"""advanced.md method 1 / stage 3 verification standard.
原值 只看吻合率,所有分钟并列 100% 时也给「高度吻合」 / 新值 最高分并列时给「分不出前后」
/ 原因 产品 2026-11-07 与占星师上游同步(并列时吻合率不代表验证)。
"""
if tied_count > 1:
return {**TIED_TIER, "meaning": f"{tied_count} 个候选分钟得分并列第一,这些事没有把时间区分开,系统把握:不确定"}
if rate >= 80:
return {"key": "high", "label": "高度吻合", "meaning": "按她的标准,出生时间可以认为是准的"}
if rate >= 60:
return {"key": "medium", "label": "中度吻合", "meaning": "按她的标准需要微调,前后 15 分钟内"}
return {"key": "low", "label": "低度吻合", "meaning": "按她的标准需要大幅调整,前后 1 到 2 小时,当前范围可能不够"}
def report_confidence(rate: int) -> dict[str, str]:
"""advanced.md stage 5: high >= 90 %, medium 70-90 %, low < 70 %."""
if rate >= 90:
return {"key": "high", "label": "高"}
if rate >= 70:
return {"key": "medium", "label": "中"}
return {"key": "low", "label": "低"}
def engine_confidence(ranked: list[dict[str, Any]], coverage_thin: bool, exact_tie: bool) -> dict[str, Any]:
"""rectification-engine.js calcConf."""
if not ranked:
return {"key": "none", "label": "不确定", "lead_percent": 0}
best = ranked[0]["total"]
second = ranked[1]["total"] if len(ranked) > 1 else 0
gap = best - second
gap_pct = round(gap / second * 100) if second > 0 else 100
if best >= 65 and gap_pct >= 15 and not coverage_thin and not exact_tie:
key, label = "high", "高"
elif best >= 45 and gap_pct >= 8 and not exact_tie:
key, label = "medium", "中"
elif best >= 25:
key, label = "low", "低"
else:
key, label = "none", "不确定"
return {"key": key, "label": label, "lead_percent": gap_pct, "best_score": best, "second_score": second}
def coverage(events: list[dict[str, Any]]) -> dict[str, Any]:
"""rectification-engine.js summarizeEventCoverage."""
groups = sorted({EVENT_CATEGORIES[e["category"]]["group"] for e in events})
categories = sorted({e["category"] for e in events})
years = [e["at"].year for e in events]
span = max(years) - min(years) if years else 0
n = len(events)
level = "strong" if n >= 8 and len(groups) >= 3 and (span >= 7 or n >= 8) else "usable" if n >= 5 and len(groups) >= 3 else "thin"
return {"event_count": n, "category_count": len(categories), "group_count": len(groups),
"groups": groups, "year_span": span, "level": level}
def decision_plan(events: list[dict[str, Any]]) -> dict[str, Any]:
"""rectification-engine.js buildRectificationDecisionPlan / decision tree section 7."""
theme = []
for e in events:
v = EVENT_CATEGORIES[e["category"]]["varga"]
if v not in theme:
theme.append(v)
use_d30 = any(e["category"] in D30_TOPICS for e in events)
use_d60 = len(events) >= 8 and len(theme) >= 2
warnings = []
if len(events) < MIN_EVENTS:
warnings.append("事件少于 5 件时,不急着看高敏分盘,先补事件。")
if not use_d30:
warnings.append("没有健康、事故、官司或失去亲人的事件,D30 不参与。")
warnings.append("D60 只在高度收敛后作最后参考,不参与打分。" if use_d60 else "D60 默认后置,不参与打分。")
return {
"principle": "Dasha 定框,D9 / D10 定核心,按事件主题补分盘,D30 / D60 最后谨慎使用。",
"ordered_layers": [
"Dasha + 有日期的事件", "D9", "D10", " / ".join(v for v in theme if v not in ("D9", "D10", "D30")) or "按事件主题的分盘",
"Nakshatra / Pada / 宫位变化", "D30(仅有健康类事件时)", "D60(仅作最后参考)",
],
"theme_vargas": theme,
"d30_used": use_d30,
"d60_reference": use_d60,
"warnings": warnings,
}
# --------------------------------------------------------------------------- intake screens
def appearance_options(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
signs = sorted({r["asc"] for r in rows}, key=lambda s: next(i for i, r in enumerate(rows) if r["asc"] == s))
return [{"sign": s, "label": f"{SIGN_CN[s]}上升", "features": APPEARANCE[s][0], "constitution": APPEARANCE[s][1],
"health": APPEARANCE[s][2]} for s in signs]
def trait_options(rows: list[dict[str, Any]], key: str, table: tuple[str, ...]) -> list[dict[str, Any]]:
seen: list[int] = []
for r in rows:
if r["vargas"][key] not in seen:
seen.append(r["vargas"][key])
return [{"sign": s, "label": f"{key} {SIGN_CN[s]}", "traits": table[s]} for s in seen]
def _birthmark_supported(part: str, row: dict[str, Any]) -> bool:
spec = BIRTHMARK_PARTS[part]
occupants = {p for p, h in row["planet_houses"].items() if h == spec["house"]}
return bool(occupants & (set(spec["planets"]) | NATURAL_MALEFICS))
def _sign_pick(body: dict[str, Any], key: str) -> int | None:
value = body.get(key)
if value is None or value == "unsure":
return None
if isinstance(value, int) and 0 <= value <= 11:
return value
raise ChartChoiceInputError(f"{key} must be a sign index 0-11 or 'unsure'")
def _narrow(candidates: list[dict[str, Any]], keep: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], str]:
if not keep:
return candidates, "no_match_kept_all"
if len(keep) == len(candidates):
return candidates, "not_discriminating"
return keep, "narrowed"
NARROW_TEXT: Final = {
"narrowed": ":有行星落在对应宫位的分钟保留了下来。",
"not_discriminating": ":范围里每个分钟都对得上,分不出前后。",
"no_match_kept_all": ":范围里没有一个分钟对得上,全部保留。",
}
def _span(rows: list[dict[str, Any]]) -> dict[str, str] | None:
if not rows:
return None
return {"from": _hhmm(rows[0]["at"]), "to": _hhmm(rows[-1]["at"]), "minutes": len(rows)}
# --------------------------------------------------------------------------- questionnaire
def _questionnaire(rows: list[dict[str, Any]], req: ChartRequest, answers: dict[str, str]) -> dict[str, Any]:
from active_rectification_questions import build_questionnaire, score_answers
start, end = rows[0]["at"], rows[-1]["at"]
half = max(int((end - start).total_seconds() // 120), 1)
center = start + timedelta(minutes=half)
questionnaire = build_questionnaire(
center.strftime("%Y-%m-%d %H:%M"), half, 1,
ayanamsa=req.ayanamsa, node_mode=req.node_mode,
minute_scan=minute_scan_for_questionnaire(rows),
)
bank = {q["id"]: q for q in questionnaire["question_bank"]}
clean = {k: v for k, v in answers.items() if k in bank and v in ("A", "B", "C", "D")}
scored = score_answers(questionnaire, clean) if clean else None
nxt = (scored["next_round_questions"] if scored else questionnaire["questions"]) or []
question = None
if nxt:
q = bank.get(nxt[0]["id"], nxt[0])
question = {"id": q["id"], "prompt": q["prompt"], "why": (q.get("why_this_question") or [""])[0],
"options": [{"key": o["key"], "label": o["label"]} for o in q["options"]],
"primary_varga": (q.get("audit_binding") or {}).get("primary_varga")}
rankings = [
{"cluster": r["cluster"], "label": QUESTION_CLUSTER_CN.get(r["cluster"], r["cluster"]), "score": r["score"]}
for r in (scored or {}).get("candidate_cluster_rankings", []) if r["score"] > 0
]
return {
"source": f"{UPSTREAM_REF} scripts/active_rectification_questions.py",
"answered": len(clean),
"answers": clean,
"next_question": question,
"leaning": rankings[:3],
"workflow_status": (scored or {}).get("workflow_status", "question_rounds_active"),
"required_next_evidence": (scored or {}).get("required_next_evidence"),
"boundary": "问卷只给倾向,不定分钟;分钟要靠有日期的事件。",
}
# --------------------------------------------------------------------------- main entry
def _report_summary(result: dict[str, Any]) -> str:
best, py = result["best"], result["python_engine"]
if result["tied_count"] > 1:
head = f"{result['tied_count']} 个分钟得分并列第一(吻合 {best['match_rate']}%),分不出前后,把握:不确定。"
else:
head = f"最靠前 {best['time']},事件吻合 {best['match_rate']}%。"
if py["top_time"]:
tail = f"她的 Python 事件引擎(含 KP 宫头)最靠前 {py['top_time']},领先 {py['margin_percent']}%,把握{py['confidence_label']}。"
elif py["tied_top_times"]:
tail = f"她的 Python 事件引擎(含 KP 宫头)有 {len(py['tied_top_times'])} 个分钟并列,把握{py['confidence_label']}。"
else:
tail = ""
return head + tail
def _clean_answers(raw: Any) -> dict[str, str]:
if raw is None:
return {}
if not isinstance(raw, dict):
raise ChartChoiceInputError("question_answers must be an object")
return {str(k): str(v).upper() for k, v in raw.items()}
def evaluate(body: dict[str, Any]) -> dict[str, Any]:
"""Run the legacy five-stage flow. The merged multi-round flow reuses the scoring and question helpers in this module."""
from scripts.chart_choice.service import _request
req, start, end, reported, reported_known = _request(body)
if (end - start) > timedelta(minutes=MAX_WINDOW_MINUTES):
raise ChartChoiceInputError(f"window longer than {MAX_WINDOW_MINUTES} minutes")
rows = scan(req, start, end)
base = min(rows, key=lambda r: abs((r["at"] - reported).total_seconds()))
events = parse_events(body.get("events"), start)
# 原值:同类别同日期的事件重复录入时各算一件。
# 新值:只算第一件,其余记入 duplicate_event_ids(同类别同日期的打分输入完全相同,是同一次检验)。
# 原因:占星师 2026-11-08 验收清单 §6(重复事实不得当独立支持)。
events, duplicate_event_ids = _independent_events(events)
marks = body.get("birthmarks") or []
if not isinstance(marks, list) or any(m not in BIRTHMARK_PARTS for m in marks):
raise ChartChoiceInputError("birthmarks must be a list of known body parts")
appearance_pick = _sign_pick(body, "appearance_sign")
d9_pick = _sign_pick(body, "d9_sign")
d10_pick = _sign_pick(body, "d10_sign")
answers = _clean_answers(body.get("question_answers"))
stages: list[dict[str, Any]] = []
# Stage 1: intake (questionnaire, appearance, birthmarks, family events).
questionnaire = _questionnaire(rows, req, answers)
stages.append({"id": "intake", "label": "信息收集", "status": "done",
"summary": f"答了 {questionnaire['answered']} 道选择题,录了 {len(events)} 件有日期的事。"})
# Stage 2: pre-screen by appearance, then birthmarks (advanced.md methods 5 and 6).
pool = rows
if appearance_pick is None:
stages.append({"id": "appearance", "label": "外表体质", "status": "skipped" if len({r['asc'] for r in rows}) > 1 else "not_applicable",
"summary": "范围里上升星座没有变化,外表分不出前后。" if len({r['asc'] for r in rows}) == 1 else "没有选。"})
else:
pool, how = _narrow(pool, [r for r in pool if r["asc"] == appearance_pick])
stages.append({"id": "appearance", "label": "外表体质", "status": how,
"summary": f"选了{SIGN_CN[appearance_pick]}上升的描述,剩 {_span(pool)['from']}–{_span(pool)['to']}。"})
if marks:
keep = [r for r in pool if all(_birthmark_supported(m, r) for m in marks)]
pool, how = _narrow(pool, keep)
stages.append({"id": "birthmarks", "label": "胎记伤疤", "status": how,
"summary": "、".join(BIRTHMARK_PARTS[m]["label"] for m in marks) + NARROW_TEXT[how]})
else:
stages.append({"id": "birthmarks", "label": "胎记伤疤", "status": "skipped", "summary": "没有填。"})
# Stage 3: event verification (decision tree step 1 gate, method 1 tiers).
cov = coverage(events)
plan = decision_plan(events)
contract = build_rectification_technique_contract(event_count=len(events), domain_count=cov["group_count"])
ranked: list[dict[str, Any]] = []
py_rows: list[dict[str, Any]] = []
if len(events) < MIN_EVENTS:
stages.append({"id": "events", "label": "事件验证", "status": "needs_events",
"summary": f"她的方法要求至少 {MIN_EVENTS} 件有年份的事(最好 {IDEAL_EVENTS[0]}–{IDEAL_EVENTS[1]} 件),现在 {len(events)} 件。"})
else:
scored = [score_minute(events, r, base) for r in pool]
py_rows = astrologer_engine.score_rows(
events, pool, lat=req.lat, lon=req.lon, ayanamsa=req.ayanamsa,
active=lambda ev, r: (
_active_vimshottari(r["at"], r["planets"]["Moon"], ev["at"], r["timeline"]),
_active_narayana(r["asc"], r["planets"], r["at"], ev["at"], *r["narayana"]),
),
)
ranked = sorted(scored, key=lambda s: (-s["total"], abs(s["offset"]), s["offset"]))
same_rate = len({s["match_rate"] for s in scored}) == 1
stages.append({"id": "events", "label": "事件验证", "status": "done",
"summary": f"在 {len(pool)} 个候选分钟上逐件对 Vimshottari 大运 / 小运 / 细运与 Narayana 大运 / 小运。"
+ ("每个候选分钟的吻合率都一样,事件分不出这些分钟。" if same_rate else "")})
# Stage 4: fine correction by D9 / D10 traits (methods 2 and 3).
final_pool = pool
for key, pick, label in (("D9", d9_pick, "婚恋特质(D9)"), ("D10", d10_pick, "事业特质(D10)")):
if pick is None:
stages.append({"id": key.lower(), "label": label, "status": "skipped" if len({r['vargas'][key] for r in rows}) > 1 else "not_applicable",
"summary": f"范围里 {key} 上升没有变化。" if len({r['vargas'][key] for r in rows}) == 1 else "没有选。"})
continue
final_pool, how = _narrow(final_pool, [r for r in final_pool if r["vargas"][key] == pick])
stages.append({"id": key.lower(), "label": label, "status": how,
"summary": f"选了 {key} {SIGN_CN[pick]} 的描述。"})
# Stage 5: report.
final_ranked = [s for s in ranked if any(s["at"] == _at(r["at"]) for r in final_pool)] if ranked else []
result: dict[str, Any] | None = None
if final_ranked:
top = final_ranked[0]
cluster = [s for s in final_ranked if top["total"] - s["total"] <= TOP_CLUSTER_POINTS][:8]
exact_tie = len(final_ranked) > 1 and final_ranked[1]["total"] == top["total"]
tied_count = sum(1 for s in final_ranked if s["total"] == top["total"])
final_times = {s["time"] for s in final_ranked}
python_engine = astrologer_engine.verdict(events, [r for r in py_rows if r["time"] in final_times])
offsets = [s["offset"] for s in cluster]
best_row = next(r for r in rows if _at(r["at"]) == top["at"])
result = {
"best": {k: top[k] for k in ("time", "at", "offset", "total", "parts", "matched", "strong", "match_rate", "strong_rate")},
"best_charts": {"D1": SIGN_CN[best_row["asc"]], "D9": SIGN_CN[best_row["vargas"]["D9"]],
"D10": SIGN_CN[best_row["vargas"]["D10"]], "D60_reference": SIGN_CN[best_row["vargas"]["D60"]]},
"events": [
{"id": e["id"], "category": next(ev["category"] for ev in events if ev["id"] == e["id"]),
"matched": e["matched"], "strong": e["strong"],
"vimshottari": e["chain"]["vimshottari"], "narayana": e["chain"]["narayana"],
"vimshottari_cn": "–".join(PLANET_CN.get(x, x) for x in e["chain"]["vimshottari"].values())}
for e in top["events"]
],
"match_tier": match_tier(top["match_rate"], tied_count),
"confidence": {"key": "none", "label": "不确定"} if tied_count > 1 else report_confidence(top["match_rate"]),
"tied_count": tied_count,
"engine_confidence": engine_confidence(final_ranked, cov["level"] == "thin", exact_tie),
"top_cluster": {"from_offset": min(offsets), "to_offset": max(offsets), "count": len(cluster)},
"exact_tie": exact_tie,
"stay_near_reported": exact_tie or len(cluster) >= 4 or top["total"] < 45,
"match_rate_same_for_all_candidates": len({s["match_rate"] for s in ranked}) == 1,
"ranking": [{k: s[k] for k in ("time", "offset", "total", "match_rate")} for s in final_ranked[:10]],
"python_engine": python_engine,
"leader_coverage": leader_coverage(final_ranked),
}
stages.append({"id": "report", "label": "结果", "status": "done" if result else "waiting",
"summary": (_report_summary(result) if result else "事件够了才出结果。")})
lines = sensitivity_lines(rows)
return {
"engine_version": ENGINE_VERSION,
"upstream": UPSTREAM_REF,
"window": {"start_at": _at(start), "end_at": _at(end)},
"reported_at": _at(reported),
"reported_known": reported_known,
"ayanamsa": req.ayanamsa,
"node_mode": req.node_mode,
"status": "evaluated" if result else "needs_events" if len(events) < MIN_EVENTS else "no_candidates",
"scan": {
"minutes": len(rows),
"layers": [f"D{d}" for d in SCAN_DIVISIONS] + ["Nakshatra/Pada", "KP sub-lord", "A7", "UL", "A10", "KP cusps 4/7/10"],
"reference_only": sorted(REFERENCE_ONLY),
"lines": lines,
"line_count": sum(1 for line in lines if not line["reference_only"]),
"remaining": _span(final_pool),
},
"intake": {
"appearance": appearance_options(rows),
"d9": trait_options(rows, "D9", D9_TRAITS),
"d10": trait_options(rows, "D10", D10_TRAITS),
"birthmark_parts": [{"key": k, "label": v["label"]} for k, v in BIRTHMARK_PARTS.items()],
"event_categories": [{"key": k, "label": v["label"], "group": v["group"], "varga": v["varga"]} for k, v in EVENT_CATEGORIES.items()],
"min_events": MIN_EVENTS,
"ideal_events": list(IDEAL_EVENTS),
},
"questionnaire": questionnaire,
"stages": stages,
"coverage": cov,
"decision_plan": plan,
"result": result,
"duplicate_event_ids": duplicate_event_ids,
"technique_contract": contract,
"transit": {"status": "blocked", "reason": "上游合同:行运(Gochara)没有独立的反例验证,不参与打分。"},
"caveat": CAVEAT,
}