fix(report): one canonical Mars marriage screen; short debilitation cells by verified state; natal Saham steps shown; PD by declared range, full dispositor chains, topic varga routes (BUG-2154, BUG-2155, BUG-2156, BUG-2157)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXp2Vp62Ur3C7yRWQdSq
This commit is contained in:
2026-11-22 12:03:46 +08:00
co-authored by Claude Opus 5.5
parent 9206f23c3e
commit c1957e3164
26 changed files with 1807 additions and 191 deletions
+3 -1
View File
@@ -12,7 +12,9 @@ from typing import Any
# _saham(p1, p2) = Asc + p2 - p1.
_LOCAL = (
("karya_saham", ("Moon", "Mars"), ("Mars", "Moon")),
("vivah_saham", ("Mars", "Venus"), None),
# BUG-2156: was ("Mars", "Venus"), None — Asc + Venus - Mars, not Vivaha. Table 74:
# day Venus - Saturn + Asc, night Saturn - Venus + Asc. Only used when the formula metadata is missing.
("vivah_saham", ("Saturn", "Venus"), ("Venus", "Saturn")),
("rajya_saham", ("Jupiter", "Sun"), None),
("shatru_saham", ("Saturn", "Mars"), None),
("labha_saham", ("Moon", "Jupiter"), None),
+23 -4
View File
@@ -1744,10 +1744,18 @@ def _render_pl9_ai_density_raw_data_markdown_en(packet: dict, language: str = "e
"Lagna", asc.get("sign"), asc.get("degree_in_sign"), asc.get("degree_raw") or asc.get("lon"), 1,
asc_fields.get("nakshatra") or "-", asc_fields.get("pada") or "-", "-", "-",
])
try:
from scripts.report_render.neecha_witness import neecha_states, neecha_table_notes
except ModuleNotFoundError: # pragma: no cover
from report_render.neecha_witness import neecha_states, neecha_table_notes
# BUG-2155: the dignity cells name the real Neecha Bhanga state; notes go under the table.
nb_states = neecha_states(packet)
raw_statuses: dict = {}
if isinstance(planets, dict):
for planet in ["Sun", "Moon", "Mars", "Mercury", "Jupiter", "Venus", "Saturn", "Rahu", "Ketu"]:
item = planets.get(planet, {})
if isinstance(item, dict):
raw_statuses[planet] = item.get("status")
rows.append([
planet,
item.get("sign"),
@@ -1757,10 +1765,13 @@ def _render_pl9_ai_density_raw_data_markdown_en(packet: dict, language: str = "e
item.get("nakshatra"),
item.get("pada"),
# BUG-2065:引擎的尊贵标签是双语的(入旺(Exalted)),和正文一样只写一个名字。
_dignity_label(item.get("status"), language),
_dignity_label(item.get("status"), language, planet, nb_states),
item.get("speed"),
])
lines.extend(["## Core Chart Raw Positions", "", table(["Object", "Sign", "Degree in sign", "Longitude", "House", "Nakshatra", "Pada", "Status", "Speed"], rows), ""])
raw_notes = neecha_table_notes(list(raw_statuses), raw_statuses, nb_states, language)
if raw_notes:
lines.extend([*raw_notes, ""])
if isinstance(asc, dict) and isinstance(planets, dict):
try:
@@ -1855,6 +1866,7 @@ def _render_pl9_ai_density_raw_data_markdown_en(packet: dict, language: str = "e
}
summary_rows = []
narrative_rows: list[str] = []
lord_statuses: dict = {}
for house_index in range(1, 13):
house = d1_houses.get(f"house_{house_index}") or d1_houses.get(str(house_index)) or {}
if not isinstance(house, dict):
@@ -1866,7 +1878,11 @@ def _render_pl9_ai_density_raw_data_markdown_en(packet: dict, language: str = "e
sign = house.get("cusp_sign") or house.get("sign")
lord_sign = lord_row.get("sign")
lord_house = lord_row.get("house")
dignity = _dignity_label(lord_row.get("status") or lord_row.get("dignity"), language)
lord_status = lord_row.get("status") or lord_row.get("dignity")
lord_statuses.setdefault(str(lord), lord_status)
# BUG-2155: the table cell carries ¹ (note under the table); the sentence says 「见格局说明」.
dignity = _dignity_label(lord_status, language, str(lord), nb_states)
dignity_sentence = _dignity_label(lord_status, language, str(lord), nb_states, footnote=False)
activation_active = str(lord) in active_lords
if language == "zh":
try:
@@ -1887,7 +1903,7 @@ def _render_pl9_ai_density_raw_data_markdown_en(packet: dict, language: str = "e
lord_dasha_cell(activation_active, bool(active_lords), "zh"), # BUG-2110 (was: activation)
])
narrative_rows.extend(house_lord_narrative_zh(
house_index, sign, lord, lord_sign, lord_house, dignity, activation_active,
house_index, sign, lord, lord_sign, lord_house, dignity_sentence, activation_active,
))
else:
activation = "active Dasha layer" if activation_active else "not a current Dasha lord" # BUG-2076
@@ -1905,7 +1921,7 @@ def _render_pl9_ai_density_raw_data_markdown_en(packet: dict, language: str = "e
"",
f"House {house_index} covers {topic}. Its sign is {clean(sign)}, and its lord is {clean(lord)}.",
"",
f"The lord is placed in {placement}, with dignity/status {clean(dignity)}. This carries the house-{house_index} agenda into {destination}.",
f"The lord is placed in {placement}, with dignity/status {clean(dignity_sentence)}. This carries the house-{house_index} agenda into {destination}.",
"",
f"This placement is read with dignity, conjunctions, aspects, Shadbala, divisional repetition and Dasha timing. Current timing layer: {activation}.",
"",
@@ -1916,6 +1932,9 @@ def _render_pl9_ai_density_raw_data_markdown_en(packet: dict, language: str = "e
except ModuleNotFoundError: # pragma: no cover
from report_render.appendix_language import LORD_DASHA_HEADER
lines.extend(["## Bhavesh House-Lord Interpretations", "", table(["House", "Sign", "Lord", "Lord placement", "Lord dignity", LORD_DASHA_HEADER["zh" if language == "zh" else "en"]], summary_rows), ""])
lord_notes = neecha_table_notes(list(lord_statuses), lord_statuses, nb_states, language)
if lord_notes:
lines.extend([*lord_notes, ""])
lines.extend(narrative_rows)
moon_chart = dict_get(("divisional_and_special_charts", "moon_chart"), {})
+72 -8
View File
@@ -214,10 +214,20 @@ def _role(raw: Any, language: str) -> str:
return "未单独列出" if language == "zh" else "not listed separately"
def _dignity(value: Any, language: str) -> str:
def _dignity(value: Any, language: str, *, neecha_clause: bool = False) -> str:
text = str(value or "").strip()
if not text:
return "未列出" if language == "zh" else "not listed"
if neecha_clause:
# BUG-2155 (占星师 2026-11-22 §4): a body page keeps the original 落陷 and points to the yoga notes;
# the full explanation is on the Neecha Bhanga page. Was: 「尊贵为落陷取消」 (the 落陷 itself lost).
try:
from scripts.report_render.neecha_witness import neecha_bhanga_dignity_cell
except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path
from report_render.neecha_witness import neecha_bhanga_dignity_cell
cell = neecha_bhanga_dignity_cell(text, language, footnote=False)
if cell is not None:
return cell
match = re.fullmatch(r"([^()()]+?)\s*[((]([A-Za-z][A-Za-z \-]*)[))]", text)
if not match:
if language == "en" and re.search(r"[\u4e00-\u9fff]", text):
@@ -605,7 +615,7 @@ def _natal_zh(lord: str, facts: dict, trigger: dict, functional_profile: str | N
owned = facts.get("ownership") if isinstance(facts.get("ownership"), list) else []
bits = [f"{_planet(lord, 'zh')}在本命盘位于第{house}宫" if isinstance(house, int) else f"{_planet(lord, 'zh')}的落宫未列出"]
bits.append(_ruled_houses_clause(lord, owned, "zh"))
bits.append(f"尊贵为{_dignity(facts.get('dignity'), 'zh')}")
bits.append(f"尊贵为{_dignity(facts.get('dignity'), 'zh', neecha_clause=True)}")
bits.append(f"星宿为{facts.get('nakshatra') or '未列出'}")
bits.append(f"功能吉凶为{_role(trigger.get('functional_classification'), 'zh')}")
return "盘内依据:" + ";".join(bits) + f"。功能吉凶口径为{_functional_profile_note(functional_profile)}。"
@@ -620,7 +630,7 @@ def _natal_en(lord: str, facts: dict, trigger: dict) -> str:
nakshatra = "not listed separately"
return (
f"Natal basis: {lord} is in house {house}, {ownership}, "
f"dignity {_dignity(facts.get('dignity'), 'en')}, nakshatra {nakshatra}, "
f"dignity {_dignity(facts.get('dignity'), 'en', neecha_clause=True)}, nakshatra {nakshatra}, "
f"functional nature {_role(trigger.get('functional_classification'), 'en')}. "
"Functional nature comes from this site's functional benefic/malefic layer."
)
@@ -648,7 +658,7 @@ def _sub_paragraph(parent: str, lord: str, row: dict, facts: dict, language: str
return (
f"{_planet(parent, language)} / {_planet(lord, language)}({level}):{start} 至 {end}。"
f"这段时间可能突出{_planet(lord, language)}的第{house_text}宫、{ruled}、"
f"尊贵{_dignity(facts.get('dignity'), language)}与星宿{facts.get('nakshatra') or '未列出'}。"
f"尊贵{_dignity(facts.get('dignity'), language, neecha_clause=True)}与星宿{facts.get('nakshatra') or '未列出'}。"
+ _period_beats(lord, language)
)
house_text = str(house) if house is not None else "not listed"
@@ -658,7 +668,7 @@ def _sub_paragraph(parent: str, lord: str, row: dict, facts: dict, language: str
return (
f"{parent} / {lord} ({level}): {start} to {end}. "
f"This period may bring forward {lord}'s house {house_text}, {ruled}, "
f"dignity {_dignity(facts.get('dignity'), language)}, and nakshatra {nakshatra}. "
f"dignity {_dignity(facts.get('dignity'), language, neecha_clause=True)}, and nakshatra {nakshatra}. "
+ _period_beats(lord, language)
)
@@ -875,7 +885,7 @@ def build_graha_interpretation_pack(
sign = row.get("sign")
owned = owned_houses.get(planet) if isinstance(owned_houses.get(planet), list) else []
role = _role(functional_classification.get(planet), language)
dignity = _dignity(row.get("status") or row.get("dignity"), language)
dignity = _dignity(row.get("status") or row.get("dignity"), language, neecha_clause=True)
nakshatra = row.get("nakshatra") or ("未列出" if language == "zh" else "not listed")
if language == "en" and re.search(r"[\u4e00-\u9fff]", str(nakshatra)):
nakshatra = "not listed separately"
@@ -968,10 +978,17 @@ def build_yoga_interpretation_pack(
entries: list[dict] = []
by_key: dict[tuple, dict] = {}
by_name: dict[tuple, dict] = {}
try:
from scripts.report_render.yoga_rule_aliases import reader_explanation, resolve_row
except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path
from report_render.yoga_rule_aliases import reader_explanation, resolve_row
for rows in groups:
for raw in _list(rows):
if not isinstance(raw, dict):
continue
# BUG-2154: an archived alias id (old packets' kalatra_dosha_mars_7) resolves to its
# canonical rule, so the two ids share one page under the canonical name.
raw = resolve_row(raw)
neecha_page = _is_neecha_bhanga(raw)
name = _yoga_name(raw, language)
planets = _page_planets(raw)
@@ -999,7 +1016,9 @@ def build_yoga_interpretation_pack(
if entry is None:
entry = {"name": name, "planets": planets, "neecha": neecha_page, "combinations": [], "roles": None,
"rule": key[:-1], "source": _yoga_source_text(raw, language), "key": key,
"planets_key": key[-1], "profile": profile, "position": ""}
"planets_key": key[-1], "profile": profile, "position": "",
"explanation": reader_explanation(rule_id, language) if rule_id else "",
"evidence_identity": raw.get("evidence_identity") or ""}
by_key[key] = entry
by_name.setdefault((name, key[-1]), entry)
entries.append(entry)
@@ -1049,6 +1068,12 @@ def build_yoga_interpretation_pack(
else "The current three Dasha levels do not directly overlap the planets in this combination."
),
}
if entry.get("explanation"):
# BUG-2154 (占星师 2026-11-22 §3): the rule's own explanation replaces the generic result
# line; the page never states a fixed verdict (婚姻延迟 / 需要匹配化解).
sections["result"] = entry["explanation"]
if entry.get("evidence_identity") and _mangal_detected(yogas_doshas_snapshot):
sections["same_fact"] = MARS_SAME_FACT_NOTE["zh" if zh else "en"]["yoga"]
if neecha_page:
# BUG-2110 (占星师 2026-11-21 B): the page lists the original debilitation position, then
# each satisfied condition with its own witness, then the overall meaning and limits; the
@@ -1102,6 +1127,37 @@ def build_yoga_interpretation_pack(
return {"schema": "pl9.yoga_interpretation_pack.v1", "status": "partial_verified" if pages else "blocked", "pages": pages}
# BUG-2154 (占星师 2026-11-22 §3): the dosha table's 火星婚姻煞 and the yoga page of
# kalatra_dosha_mars_1_4_7_8_12 read the same Mars fact (evidence identity
# ev:mars_marriage_screen@D1:lagna); each keeps its own summary, neither is a further adverse item.
MARS_SAME_FACT_NOTE = {
"zh": {
"yoga": "这与 Dosha 表里的「火星婚姻煞」是同一项火星位置事实,只算一项,不是另一个不利因素。",
"dosha": "这与格局表里的「火星婚姻相关配置(1/4/7/8/12宫筛查)」是同一项火星位置事实,只算一项,不是另一个不利因素。",
},
"en": {
"yoga": "This is the same Mars placement fact as Mangala / Kuja Dosha in the dosha table; it counts once, not as a further adverse factor.",
"dosha": ("This is the same Mars placement fact as the Mars Marriage-Related Placement (1/4/7/8/12 House Screen) in the yoga "
"table; it counts once, not as a further adverse factor."),
},
}
def _mangal_detected(yogas_doshas_snapshot: Any) -> bool:
raw = _dict(_dict(yogas_doshas_snapshot).get("mangal_dosha"))
return raw.get("has_dosha") is True and _house_number(raw.get("mars_house")) is not None
def _mars_screen_hit(house: int | None) -> bool:
"""Mars sits in a house the canonical 1/4/7/8/12 screen lists (the dosha table also lists the 2nd)."""
try:
from scripts.report_render.yoga_rule_aliases import MARS_MARRIAGE_RULE_ID, canonical_rule
except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path
from report_render.yoga_rule_aliases import MARS_MARRIAGE_RULE_ID, canonical_rule
logic = _dict(_dict(canonical_rule(MARS_MARRIAGE_RULE_ID)).get("logic"))
return house is not None and house in (logic.get("houses") or [])
# BUG-2110 (占星师 2026-11-21 B): the closing paragraph of a Neecha Bhanga page.
NEECHA_SUMMARY = {
"zh": (
@@ -1335,7 +1391,7 @@ def build_bhavesh_interpretation_pack(
continue
lord_house = lord_row.get("house")
role = _role(functional_classification.get(str(lord)), language)
dignity = _dignity(lord_row.get("status") or lord_row.get("dignity"), language)
dignity = _dignity(lord_row.get("status") or lord_row.get("dignity"), language, neecha_clause=True)
sign = lord_row.get("sign") or ("未列出" if language == "zh" else "not listed")
if language == "en" and re.search(r"[\u4e00-\u9fff]", str(sign)):
sign = "not listed separately"
@@ -1566,6 +1622,7 @@ def _dosha_sections(key: str, raw: dict, state: str, title: str, language: str)
"result": "在所选参考点和宫位规则下出现了火星相关结构。传统上,它可以作为亲密关系中行动节奏、急躁或摩擦的一个观察因素;"
"需要结合第七宫、金星、九分盘(D9)和缓解或抵消条件一起看,不等于婚姻失败。",
"cancellation": "取消条件以检测器返回的说明为准,这里不新判。",
**({"same_fact": MARS_SAME_FACT_NOTE["zh"]["dosha"]} if _mars_screen_hit(house) else {}),
}
return {
"detected": f"{title}: Detected by this rule.",
@@ -1574,6 +1631,7 @@ def _dosha_sections(key: str, raw: dict, state: str, title: str, language: str)
"factor to watch for pace of action, impatience or friction in close relationships. It has to be read together with the "
"seventh house, Venus, D9 and any mitigating or cancelling conditions, and it does not mean a failed marriage.",
"cancellation": "Cancellation notes stay with the detector. This page does not add a new judgment.",
**({"same_fact": MARS_SAME_FACT_NOTE["en"]["dosha"]} if _mars_screen_hit(house) else {}),
}
if kaal:
rahu, ketu = _house_number(raw.get("rahu_house")), _house_number(raw.get("ketu_house"))
@@ -1730,8 +1788,14 @@ def build_dosha_remedy_pack(
title = zh_label if language == "zh" else en_label
state = _dosha_state(key, raw, chart_planets)
states[key] = state
try:
from scripts.report_render.yoga_rule_aliases import dosha_evidence_identity
except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path
from report_render.yoga_rule_aliases import dosha_evidence_identity
identity = dosha_evidence_identity(key)
rows.append({
"id": key,
**({"evidence_identity": identity} if identity else {}),
"title": title,
# None = not assessed; an unknown is never reported as "no". BUG-2110: a screening
# candidate (Kaal Sarp) is neither formed nor absent, so it is None as well; `state` says which.
+22 -8
View File
@@ -35,13 +35,13 @@ try: # scripts/ on sys.path
from report_render.english_gaps import english_effects, first_clean_english
from report_render.karaka_domains import KARAKA_DOMAIN_EN
from report_render.reader_keys import aspect_type_en, reader_key, reader_point_name, yoga_category_name
from report_render.neecha_witness import neecha_bhanga_dignity_cell
from report_render.neecha_witness import neecha_bhanga_dignity_cell, neecha_states, neecha_table_notes
except ImportError: # pragma: no cover - package import
from scripts.report_render.audit_chapters import STATUS
from scripts.report_render.english_gaps import english_effects, first_clean_english
from scripts.report_render.karaka_domains import KARAKA_DOMAIN_EN
from scripts.report_render.reader_keys import aspect_type_en, reader_key, reader_point_name, yoga_category_name
from scripts.report_render.neecha_witness import neecha_bhanga_dignity_cell
from scripts.report_render.neecha_witness import neecha_bhanga_dignity_cell, neecha_states, neecha_table_notes
import re
from datetime import datetime
@@ -118,7 +118,7 @@ def _pl9_english_report_title(packet: dict) -> str:
return f"{name}'s Vedic Astrology Chart Report" if name else "Vedic Astrology Chart Report"
def _dignity_label(value, language: str = 'zh') -> str:
def _dignity_label(value, language: str = 'zh', planet=None, states=None, footnote=True) -> str:
"""Engine dignity labels are bilingual (``入旺(Exalted)``); the reader shows one name.
The glossary pass would otherwise translate the English half too and print
@@ -127,7 +127,9 @@ def _dignity_label(value, language: str = 'zh') -> str:
"""
text = str(value or '').strip()
# BUG-2105: the Neecha Bhanga status keeps the original dignity, with the cancellation as a clause.
if (cancelled := neecha_bhanga_dignity_cell(text, language)) is not None:
# BUG-2155: the clause is the short state (落陷;另有缓解条件¹ / 落陷;缓解条件待核); with `planet`
# and `states` a plain 落陷 that is a candidate says so too. The table prints neecha_table_notes.
if (cancelled := neecha_bhanga_dignity_cell(text, language, planet, states, footnote=footnote)) is not None:
return cancelled
match = re.fullmatch(r'([^()()]+?)\s*[((]([A-Za-z][A-Za-z \-]*)[))]', text)
if not match:
@@ -1593,15 +1595,21 @@ def render_pl9_parity_markdown(packet: dict) -> str:
f"| {_cell(asc_label)} | {_cell(_token(info['sign_lord']))} | {_cell(_token(info['nakshatra_lord']))} | "
f"{asc_not_applicable} | - | {_cell('/')} | {asc_not_applicable} |"
)
_neecha = neecha_states(packet)
_status_seen = {}
for planet in ('Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn', 'Rahu', 'Ketu'):
row = _dict(planets.get(planet))
if not row:
continue
_status_seen[planet] = row.get('status')
lines.append(
f"| {_cell(_token(planet))} | {_cell(_token(row.get('rasi_lord')))} | "
f"{_cell(_token(row.get('nakshatra_lord')))} | {_cell(_token(row.get('sub_lord')))} | "
f"{_cell(_token(row.get('sub_sub_lord')))} | {_cell(_dignity_label(row.get('status'), _lang))} | {_cell(_num(row.get('sb'), 2))} |"
f"{_cell(_token(row.get('sub_sub_lord')))} | {_cell(_dignity_label(row.get('status'), _lang, planet, _neecha))} | {_cell(_num(row.get('sb'), 2))} |"
)
_notes = neecha_table_notes(list(_status_seen), _status_seen, _neecha, _lang)
if _notes:
lines.extend(['', *_notes])
lines.extend([
'',
*(
@@ -3902,6 +3910,8 @@ def render_pl9_parity_markdown(packet: dict) -> str:
for pd in _list(ad.get('pratyantar_dasha_timeline')):
if isinstance(pd, dict) and pd.get('is_current') and pd.get('lord'):
active_lords.add(str(pd.get('lord')))
_neecha = neecha_states(packet)
_lord_status = {}
for index in range(1, 13):
house = _dict(d1_houses.get(f'house_{index}') or d1_houses.get(str(index)))
lord = house.get('lord')
@@ -3909,10 +3919,14 @@ def render_pl9_parity_markdown(packet: dict) -> str:
placement = '-'
if lord_row:
placement = f"{_token(lord_row.get('sign'))} H{lord_row.get('house') or '-'} {_degree(lord_row.get('degree_in_sign'))}"
_lord_status.setdefault(str(lord), lord_row.get('status') or lord_row.get('dignity'))
lines.append(
f"| {index} | {_cell(_token(house.get('cusp_sign') or house.get('sign')))} | {_cell(_token(lord))} | "
f"{_cell(placement)} | {_cell(_dignity_label(lord_row.get('status') or lord_row.get('dignity'), _lang))} | {_cell(lord_dasha_cell(str(lord) in active_lords, bool(active_lords), _lang))} |"
f"{_cell(placement)} | {_cell(_dignity_label(lord_row.get('status') or lord_row.get('dignity'), _lang, str(lord), _neecha))} | {_cell(lord_dasha_cell(str(lord) in active_lords, bool(active_lords), _lang))} |"
)
_notes = neecha_table_notes(list(_lord_status), _lord_status, _neecha, _lang)
if _notes:
lines.extend(['', *_notes])
lines.append('')
# BUG-2121 (占星师 2026-11-20 问题 1): five separate paths between each house and the current
# period lords, next to the house-lord table; an index, not an activation verdict.
@@ -3985,7 +3999,7 @@ def render_pl9_parity_markdown(packet: dict) -> str:
if not title:
continue
lines.extend([f'#### {title}', ''])
for key in ('detected', 'consideration', 'facts', 'result', 'cancellation'):
for key in ('detected', 'consideration', 'facts', 'result', 'cancellation', 'same_fact'):
value = str(sections.get(key) or '').strip()
if value:
lines.extend([_public_report_text(value), ''])
@@ -4152,7 +4166,7 @@ def render_pl9_parity_markdown(packet: dict) -> str:
if not name:
continue
lines.extend([f'#### {name}', ''])
for key in _list(row.get('section_order')) or ('detected', 'roles', 'theme', 'result', 'activation'):
for key in _list(row.get('section_order')) or ('detected', 'roles', 'theme', 'result', 'same_fact', 'activation'):
value = str(sections.get(key) or '').strip()
if value:
lines.extend([_public_report_text(value), ''])
+202 -75
View File
@@ -8,11 +8,17 @@ match. The data layer keeps five paths apart and never folds them into one true/
whole-sign graha drishti on the house or on the house lord (same sign is not an exact
conjunction and is kept apart from the aspects);
3. sign exchange: the period lord and the house lord sit in each other's signs;
4. dispositor chain: the house lord's dispositor chain reaches the period lord within
``DISPOSITOR_MAX_HOPS`` hops; the chain stops at a planet in its own sign or at a loop;
5. topic varga: the same kinds of relation inside the house's topic varga, using the report's
own domain mapping (``opening_guide._DOMAINS``). Two planets that merely both appear in that
varga are not a relation.
4. dispositor chain: the house lord's dispositor chain, followed to its end (BUG-2157 G2): a planet
in its own sign (自座), a loop (循环), a missing position (缺失), or the safety cap (截断, never
shown as "not connected"). ``DISPOSITOR_DISPLAY_STEPS`` steps are shown; every hop is computed;
5. topic varga: the same kinds of relation inside the topic vargas that
``references/topic_varga_routes.json`` routes to the house (BUG-2157 G3, 占星师 2026-11-22 §6.4).
Two planets that merely both appear in that varga are not a relation. Exchanges and dispositor
chains inside vargas are not computed.
PD (BUG-2157 G1): used only when ``pd_range_stability`` finds the same PD at both ends of the declared
birth-time range; split ranges list the branches and leave the PD out; no definable range = PD
stability not assessed, PD left out, MD/AD kept. A "confirmed minute" label never certifies it.
This is an evidence index, not an activation verdict, a score, or a vote. Yogini, Kalachakra and
the other period systems stay in their own tables. It reads only the natal chart, the vargas and
@@ -21,6 +27,9 @@ the Vimshottari periods already in the packet; user feedback or life events are
from __future__ import annotations
import json
from functools import lru_cache
from pathlib import Path
from typing import Any
try:
@@ -36,8 +45,20 @@ SCHEMA = "jyotish.report_indirect_activation.v1"
PATHS = ("direct", "same_sign_or_aspect", "sign_exchange", "dispositor_chain", "topic_varga")
LEVELS = ("md", "ad", "pd")
# Hops counted from the house lord: 1 = its dispositor, 2 = that planet's dispositor, ...
# Capped so that a long chain cannot make every house "connected" (her ruling, path 4).
DISPOSITOR_MAX_HOPS = 3
# BUG-2157 (占星师 2026-11-22 §6.3): three steps is the display length, not a cut-off of the computation.
# 原值:DISPOSITOR_MAX_HOPS = 3,第 4 步起不再追,链停在 depth_cap,没有命中时表上写「未对上」
# 新值:链追到终点(自座 own_sign / 循环 loop / 缺失 sign_missing);首屏显示 3 步;只有超过安全上限才记
# 「截断」(truncated),截断且没有命中时是「未判定」,不写未关联
# 原因:她要求区分「未算到」与「已查明没有」,三步只是展示长度
DISPOSITOR_DISPLAY_STEPS = 3
# Safety cap only: with nine planets every chain reaches its own sign or a loop by step 9.
DISPOSITOR_SAFETY_CAP = 12
DISPOSITOR_MAX_HOPS = DISPOSITOR_DISPLAY_STEPS # kept for older readers of `max_hops`
# Node convention (fixed, not chosen per chart): a planet's dispositor is the classical lord of the sign it
# occupies (functional_benefics.SIGN_LORDS). Rahu and Ketu are never sign lords here (no Aquarius /
# Scorpio co-lordship), so a chain never passes through a node; a node's own dispositor is its sign lord.
NODE_DISPOSITOR_CONVENTION = "sign_lord_only_no_node_co_lordship"
TOPIC_ROUTES_PATH = Path(__file__).resolve().parents[2] / "references" / "topic_varga_routes.json"
SIGNS = (
"Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo",
"Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces",
@@ -52,13 +73,17 @@ _LEVEL_EN = {"md": "MD", "ad": "AD", "pd": "PD"}
_REASON_TEXT = {
"no_current_dasha": ("当前大运没有随报告返回", "the current Dasha was not returned"),
"house_lord_missing": ("宫主或宫主位置没有随报告返回", "the house lord or its placement was not returned"),
"no_topic_varga": ("本报告没有给这一宫指定主题分盘", "the report assigns no topic varga to this house"),
"varga_missing": ("主题分盘没有随报告返回", "the topic varga was not returned"),
"chain_missing": ("定位链没有随报告返回", "the dispositor chain was not returned"),
"chain_truncated": ("定位链超过计算上限被截断,没有算完", "the dispositor chain hit the safety cap and was not finished"),
}
_PD_REASON_TEXT = {
"birth_time_not_minute_confirmed": ("出生时间没有确认到分钟", "the birth time is not confirmed to the minute"),
"no_current_pd": ("当前细运没有随报告返回", "the current PD was not returned"),
# BUG-2157 (占星师 2026-11-22 §6.4): 原值「未判定(本报告没有给这一宫指定主题分盘)」; 新值见下(不带「未判定」).
NO_TOPIC_VARGA_TEXT = ("这项主题的分盘关联尚未评估", "The divisional link for this topic has not been assessed")
_CHAIN_END_TEXT = {
"own_sign": ("自座", "own sign"),
"loop": ("循环", "loop"),
"sign_missing": ("缺失", "missing position"),
"truncated": ("截断", "truncated"),
}
@@ -97,20 +122,21 @@ def _aspected_houses(planet: str, house: Any) -> dict[int, int]:
def pd_precision(packet: dict) -> tuple[bool, str | None]:
"""PD only for a birth time confirmed to the minute (the report's BUG-2013 precision record).
"""Whether the PD may be used: the current PD is the same across the declared birth-time range.
The rendered report carries ``report_birth_window`` (``source == "confirmed_minute"`` for a confirmed
minute); without it the engine's ``birth_time_sensitivity.accuracy`` is read.
BUG-2157 (占星师 2026-11-22 §6.2). 原值:``report_birth_window.source == "confirmed_minute"`` 即可用细运
(「确认到分钟」当作开关),否则 reason ``birth_time_not_minute_confirmed``。新值:读
``pd_range_stability``:两端同一细运且范围内无交界才用(``None``);分支 → ``pd_range_split``;
无可定义范围或算不出 → ``pd_stability_not_assessed``(细节在 ``stability.reason``)。
"""
window = _record(packet.get("report_birth_window"))
if window:
if window.get("source") != "confirmed_minute":
return False, "birth_time_not_minute_confirmed"
else:
accuracy = _record(packet.get("birth_time_sensitivity")).get("accuracy")
if accuracy not in (None, "confirmed"):
return False, "birth_time_not_minute_confirmed"
return True, None
try:
from scripts.report_render.pd_range_stability import attach_pd_range_stability
except ModuleNotFoundError: # pragma: no cover
from report_render.pd_range_stability import attach_pd_range_stability
result = attach_pd_range_stability(packet)
if result.get("status") == "stable":
return True, None
return False, "pd_range_split" if result.get("status") == "split" else "pd_stability_not_assessed"
def _period_lords(packet: dict) -> tuple[list[dict], dict]:
@@ -119,16 +145,21 @@ def _period_lords(packet: dict) -> tuple[list[dict], dict]:
except ModuleNotFoundError: # pragma: no cover
from pl9_interpretation_packs import _current_period_rows
rows = _current_period_rows(packet)
allowed, reason = pd_precision(packet)
if not _record(rows.get("pd")).get("lord"):
allowed, reason = False, "no_current_pd"
else:
allowed, reason = pd_precision(packet)
lords = []
for level in LEVELS:
row = _record(rows.get(level))
if not row.get("lord") or (level == "pd" and not allowed):
continue
lords.append({"level": level, "lord": str(row["lord"]), "start": _day(row.get("start")), "end": _day(row.get("end"))})
return lords, {"used": allowed, "reason": None if allowed else reason}
stability = _record(packet.get("pd_range_stability"))
pd = {"used": allowed, "reason": None if allowed else reason}
if stability:
pd["stability"] = stability
return lords, pd
def _lord_levels(period_lords: list[dict]) -> dict[str, list[str]]:
@@ -151,10 +182,24 @@ def _aspect_note(distance: int, language: str) -> str:
return f"{ordinal}-house {'special ' if distance != 7 else ''}aspect"
def _chain_text(chain: list[dict], language: str) -> str:
def _chain_text(chain: list[dict], language: str, end: str | None = None, limit: int | None = None,
loop_members: list[str] | None = None) -> str:
"""The chain as shown: at most ``limit`` steps after the house lord, then 「…(共 N 步,止于自座)」."""
shown = chain if limit is None else chain[:limit + 1]
if language == "zh":
return "→".join(f"{_planet(step['planet'], language)}在{_sign(step['sign'], language)}" for step in chain)
return " → ".join(f"{step['planet']} in {step['sign']}" for step in chain)
text = "→".join(f"{_planet(step['planet'], language)}在{_sign(step['sign'], language)}" for step in shown)
else:
text = " → ".join(f"{step['planet']} in {step['sign']}" for step in shown)
if end is None:
return text
label = _CHAIN_END_TEXT.get(end, (end, end))
if end == "loop" and loop_members:
label = (label[0] + ":" + "、".join(_planet(name, "zh") for name in loop_members),
label[1] + ": " + ", ".join(loop_members))
hidden = len(chain) - len(shown)
if language == "zh":
return text + (f"→…(共 {len(chain) - 1} 步,止于{label[0]})" if hidden else f"(止于{label[0]})")
return text + (f" → … ({len(chain) - 1} steps, ends: {label[1]})" if hidden else f" (ends: {label[1]})")
def _fact(kind: str, hit: dict, language: str) -> str:
@@ -162,7 +207,11 @@ def _fact(kind: str, hit: dict, language: str) -> str:
zh = language == "zh"
who = _role(hit["lord"], hit["levels"], language)
house = hit["house"]
prefix = (f"{hit['chart_label']} 中" if zh else f"In {hit['chart_label']}, ") if hit.get("chart_label") else ""
label = hit.get("chart_label")
topic = hit.get("topic_label_zh" if zh else "topic_label_en")
if label and topic:
label = f"{label}({topic})" if zh else f"{label} ({topic})"
prefix = (f"{label}{'中' if topic else ' 中'}" if zh else f"In {label}, ") if label else ""
lord = _planet(hit.get("house_lord"), language)
if kind == "house_lord":
text = f"{who}是第 {house} 宫宫主" if zh else f"{who} is the lord of house {house}"
@@ -184,7 +233,9 @@ def _fact(kind: str, hit: dict, language: str) -> str:
text = (f"{who}在{_sign(hit['lord_sign'], language)},第 {house} 宫宫主{lord}在{_sign(hit['house_lord_sign'], language)},两星互入对方星座" if zh
else f"{who} is in {hit['lord_sign']} and the lord of house {house}, {lord}, is in {hit['house_lord_sign']}: a sign exchange")
elif kind == "chain":
steps = _chain_text(hit["chain"], language)
steps = _chain_text(hit["chain"], language, limit=DISPOSITOR_DISPLAY_STEPS)
if len(hit["chain"]) > DISPOSITOR_DISPLAY_STEPS + 1:
steps += "→…" if zh else " → …"
text = (f"第 {house} 宫宫主的定位链({steps})第 {hit['hop']} 步到{who}" if zh
else f"the dispositor chain of the lord of house {house} ({steps}) reaches {who} at step {hit['hop']}")
else: # pragma: no cover - every kind above is handled
@@ -239,43 +290,71 @@ def _blocked(reason: str) -> dict:
return {"status": "not_determined", "hits": [], "reason": reason}
def _chain(house_lord: str, planets: dict[str, dict]) -> tuple[list[dict], str] | None:
"""The house lord's dispositor chain (``jyotish_engine.calc_dispositor_chain``'s method), capped.
def _chain(house_lord: str, planets: dict[str, dict], *, cap: int | None = None) -> tuple[list[dict], str, list[str]] | None:
"""The house lord's dispositor chain (``jyotish_engine.calc_dispositor_chain``'s method), to its end.
Ends: ``own_sign`` (a planet in its own sign), ``loop`` (the next dispositor is already in the chain),
``depth_cap`` (``DISPOSITOR_MAX_HOPS`` steps reached), ``sign_missing``.
Returns ``(chain, end, loop_members)``. Ends: ``own_sign`` (a planet in its own sign), ``loop`` (the
next dispositor is already in the chain; ``loop_members`` lists the planets of the cycle once each),
``sign_missing`` (the next planet's position was not returned), ``truncated`` (``cap`` hops reached;
a safety cap only). None when the house lord itself has no position.
"""
cap = DISPOSITOR_SAFETY_CAP if cap is None else cap
chain: list[dict] = []
seen: set[str] = set()
seen: list[str] = []
current = house_lord
while True:
sign = _record(planets.get(current)).get("sign")
if sign not in SIGNS:
return (chain, "sign_missing") if chain else None
return (chain, "sign_missing", []) if chain else None
chain.append({"planet": current, "sign": sign})
seen.add(current)
seen.append(current)
dispositor = SIGN_LORDS.get(sign, "")
if dispositor == current:
return chain, "own_sign"
return chain, "own_sign", []
if dispositor in seen:
return chain, "loop"
if len(chain) > DISPOSITOR_MAX_HOPS:
return chain, "depth_cap"
return chain, "loop", seen[seen.index(dispositor):]
if len(chain) > cap:
return chain, "truncated", []
current = dispositor
def _varga_map() -> tuple[dict[int, tuple[str, ...]], dict[str, str]]:
try:
from scripts.report_render.opening_guide import _CHART_LABELS, _DOMAINS
except ModuleNotFoundError: # pragma: no cover
from report_render.opening_guide import _CHART_LABELS, _DOMAINS
@lru_cache(maxsize=1)
def topic_varga_routes() -> dict:
"""``references/topic_varga_routes.json`` (BUG-2157 G3; shape documented in its ``_comment``)."""
return json.loads(TOPIC_ROUTES_PATH.read_text(encoding="utf-8"))
def _varga_key(prefix: str, vargas: dict) -> str | None:
"""``D10`` -> the ``varga_full`` key (``D10_Dasamsa``); None when the packet has no such chart."""
return next((key for key in vargas if key.split("_")[0] == prefix), None)
def house_routes(number: int) -> list[dict]:
"""The topic routes that give house ``number`` a varga, in file order; [] for houses 1/6/8/9/12.
``D1`` (the natal chart itself) is left out: its relations are the report's D1 paths already.
"""
routes = topic_varga_routes()
if number in (routes.get("houses_without_whole_house_chart") or []):
return []
out = []
for topic in routes.get("topics") or []:
if number in (topic.get("houses") or []):
charts = [chart for chart in topic.get("charts") or [] if chart != "D1"]
if charts:
out.append({**topic, "charts": charts})
return out
def _varga_map() -> dict[int, tuple[str, ...]]:
"""House -> chart prefixes (``D10``), from the topic routes; kept for the method caption."""
mapping: dict[int, list[str]] = {}
for _key, _zh, _en, numbers, charts, _karaka, _arudha in _DOMAINS:
for number in numbers:
for chart in charts:
for number in range(1, 13):
for topic in house_routes(number):
for chart in topic["charts"]:
if chart not in mapping.setdefault(number, []):
mapping[number].append(chart)
return {number: tuple(charts) for number, charts in mapping.items()}, dict(_CHART_LABELS)
return {number: tuple(charts) for number, charts in mapping.items() if charts}
def build_indirect_activation(packet: dict) -> dict:
@@ -292,7 +371,7 @@ def build_indirect_activation(packet: dict) -> dict:
first = _record(_house_row(houses, 1))
ascendant = str(first.get("cusp_sign") or first.get("sign") or "")
vargas = _record(_record(_worksheets(packet).get("divisional_and_special_charts")).get("varga_full"))
varga_map, chart_labels = _varga_map()
varga_map = _varga_map()
result_houses: dict[str, dict] = {}
for number in range(1, 13):
house_lord = str(_record(_house_row(houses, number)).get("lord") or "")
@@ -317,19 +396,30 @@ def build_indirect_activation(packet: dict) -> dict:
if chain_info is None:
chain_path = _blocked("chain_missing")
else:
chain, end = chain_info
chain, end, loop_members = chain_info
hits = []
for hop, step in enumerate(chain[1:], start=1):
if step["planet"] in lord_levels and step["planet"] != house_lord:
# A planet already counted in this chain (a loop's repeat) is never a second hit.
if step["planet"] in lord_levels and step["planet"] != house_lord \
and all(hit["lord"] != step["planet"] for hit in hits):
hits.append({"lord": step["planet"], "levels": list(lord_levels[step["planet"]]), "house": number,
"house_lord": house_lord, "kind": "chain", "hop": hop, "chain": chain[:hop + 1]})
chain_path = {**_path(hits), "chain": chain, "chain_end": end, "max_hops": DISPOSITOR_MAX_HOPS}
charts = varga_map.get(number, ())
if not charts:
varga_path = _blocked("no_topic_varga")
chain_path = {**_path(hits), "chain": chain, "chain_end": end, "start": house_lord,
"loop_members": loop_members, "reference_chart": "D1",
"display_steps": DISPOSITOR_DISPLAY_STEPS, "max_hops": DISPOSITOR_MAX_HOPS,
"safety_cap": DISPOSITOR_SAFETY_CAP}
# Display steps never cut the computation; hops past the display are still hits.
if end == "truncated" and not hits:
# Not computed to the end is never "not connected".
chain_path.update(status="not_determined", reason="chain_truncated")
routes = house_routes(number)
if not routes:
varga_path = {"status": "not_assessed", "hits": [], "reason": "no_topic_route"}
else:
hits, used, missing = [], [], []
for code in charts:
pairs = [(topic, prefix) for topic in routes for prefix in topic["charts"]]
for topic, prefix in pairs:
code = _varga_key(prefix, vargas) or prefix
chart = _record(vargas.get(code))
varga_asc = _record(chart.get("Ascendant")).get("sign")
if varga_asc not in SIGNS:
@@ -340,13 +430,20 @@ def build_indirect_activation(packet: dict) -> dict:
if _record(placements.get(varga_lord)).get("sign") not in SIGNS:
missing.append(code)
continue
used.append(code)
found = _relations(number, varga_lord, placements, varga_asc, lord_levels,
chart_label=chart_labels.get(code, code.split("_")[0]))
if code not in used:
used.append(code)
found = _relations(number, varga_lord, placements, varga_asc, lord_levels, chart_label=prefix)
seen_hits = {(hit["chart"], hit["kind"], hit["lord"]) for hit in hits}
for item in found["direct"] + found["same_sign_or_aspect"]:
hits.append({**item, "chart": code})
# One chart read for two topics (none today) is still one relation.
if (code, item["kind"], item["lord"]) not in seen_hits:
extra = ({"topic_label_zh": topic.get("label_zh"), "topic_label_en": topic.get("label_en")}
if len(routes) > 1 else {})
hits.append({**item, "chart": code, "topic": topic["topic"], **extra})
varga_path = (_blocked("varga_missing") if not used
else {**_path(hits), "charts": used, **({"charts_missing": missing} if missing else {})})
else {**_path(hits), "charts": used, "topics": [topic["topic"] for topic in routes],
"not_computed_in_vargas": ["sign_exchange", "dispositor_chain"],
**({"charts_missing": missing} if missing else {})})
row["paths"] = {
"direct": _path(d1["direct"]),
"same_sign_or_aspect": _path(d1["same_sign_or_aspect"]),
@@ -366,7 +463,12 @@ def build_indirect_activation(packet: dict) -> dict:
"aspect_casters": list(DRISHTI_CASTERS),
"conjunction": "same_sign",
"dispositor_max_hops": DISPOSITOR_MAX_HOPS,
"dispositor_display_steps": DISPOSITOR_DISPLAY_STEPS,
"dispositor_safety_cap": DISPOSITOR_SAFETY_CAP,
"node_dispositor": NODE_DISPOSITOR_CONVENTION,
"topic_vargas": {str(number): list(charts) for number, charts in sorted(varga_map.items())},
"topic_routes": "references/topic_varga_routes.json",
"not_computed_in_vargas": ["sign_exchange", "dispositor_chain"],
},
"houses": result_houses,
}
@@ -390,17 +492,28 @@ def attach_indirect_activation(packet: dict) -> dict:
def path_cell(path: dict, language: str) -> str:
zh = language == "zh"
status = _record(path).get("status")
chain = _record(path).get("chain")
chain_text = (_chain_text(chain, language, path.get("chain_end"), path.get("display_steps", DISPOSITOR_DISPLAY_STEPS),
path.get("loop_members"))
if chain else "")
if status == "matched":
if path.get("chain"):
if chain:
reached = ("," if zh else ", ").join(
f"第 {hit['hop']} 步到{_role(hit['lord'], hit['levels'], language)}" if zh
else f"step {hit['hop']} reaches {_role(hit['lord'], hit['levels'], language)}"
for hit in path["hits"])
return f"{_chain_text(path['chain'], language)}:{reached}" if zh else f"{_chain_text(path['chain'], language)}: {reached}"
return f"{chain_text}:{reached}" if zh else f"{chain_text}: {reached}"
return (";" if zh else "; ").join(_fact(hit["kind"], hit, language) for hit in path["hits"])
if status == "not_matched":
if chain:
# Computed to its end and no current period lord on it: 已查明没有, with the chain shown.
return f"未对上({chain_text})" if zh else f"No match ({chain_text})"
return "未对上" if zh else "No match"
if status == "not_assessed":
return NO_TOPIC_VARGA_TEXT[0 if zh else 1]
reason = _REASON_TEXT.get(str(_record(path).get("reason")))
if chain and reason:
return f"未判定({reason[0]}:{chain_text})" if zh else f"Not determined ({reason[1]}: {chain_text})"
if reason:
return f"未判定({reason[0]})" if zh else f"Not determined ({reason[1]})"
return "未判定" if zh else "Not determined"
@@ -438,22 +551,32 @@ def table_lines(structure: Any, language: str) -> list[str]:
f"{_LEVEL_EN[item['level']]} lord {item['lord']} ({item.get('start') or '—'} to {item.get('end') or '—'})"
for item in lords) or "the current Dasha was not returned"
pd = _record(structure.get("pd"))
pd_reason = _PD_REASON_TEXT.get(str(pd.get("reason")))
try:
from scripts.report_render.pd_range_stability import caption_line as pd_caption
except ModuleNotFoundError: # pragma: no cover
from report_render.pd_range_stability import caption_line as pd_caption
if pd.get("reason") == "no_current_pd":
pd_line = "- 细运没有使用:当前细运没有随报告返回。" if zh else "- PD not used: the current PD was not returned."
else:
pd_line = pd_caption(_record(pd.get("stability")) or {"status": "not_assessed", "reason": "no_birth_window"}, language)
method = _record(structure.get("method"))
varga_bits = []
for number, charts in _record(method.get("topic_vargas")).items():
labels = "、".join(code.split("_")[0] for code in charts) if zh else ", ".join(code.split("_")[0] for code in charts)
varga_bits.append(f"第 {number} 宫 {labels}" if zh else f"house {number}: {labels}")
hops = method.get("dispositor_max_hops", DISPOSITOR_MAX_HOPS)
shown = method.get("dispositor_display_steps", DISPOSITOR_DISPLAY_STEPS)
without = "、".join(str(n) for n in topic_varga_routes().get("houses_without_whole_house_chart") or [])
if zh:
levels = "、".join(_LEVEL_ZH[level] for level in _rows(structure.get("levels_used"))) or "无"
caption = [
f"- 所用周期层级:Vimshottari {levels}。{period_text}。",
*([f"- 细运没有使用:{pd_reason[0]}。"] if not pd.get("used") and pd_reason else []),
pd_line,
"- 方法:相位按 Parashari 整宫行星相位(每颗行星看第 7 宫,火星另看第 4、8 宫,木星另看第 5、9 宫,土星另看第 3、10 宫;罗睺、计都按本规则不投射相位);"
"同宫指同一星座,不是精确合相;互换指两星各在对方主管的星座;"
f"定位链从宫主起最多数 {hops} 步,遇到入本宫星座的行星或回到已出现的行星就停;"
f"主题分盘只用本报告给这一宫指定的分盘({';'.join(varga_bits)}),只看该分盘里的宫主、落宫、同宫和相位,两星只是都出现在分盘里不算关联。",
"同宫指同一星座,不是精确合相;互换指两星各在对方主管的星座;同一颗星或同一层关系只算一次;"
f"定位链从宫主起一直追到终点(行星在自己的星座=自座、回到已出现的行星=循环、下一颗星的位置没有返回=缺失),表里最多显示 {shown} 步;"
"定位星只取所在星座的主星,罗睺、计都不作星座主星,所以链不会经过交点;"
f"主题分盘按主题选({';'.join(varga_bits)}),第 {without} 宫各含多个事项,不整体指定分盘;"
"分盘里只看宫主、落宫、同宫和相位,两星只是都出现在分盘里不算关联,互换和定位链没有在分盘里计算。",
"- 这张表只列关联路径,不是激活判定,也不打分;Yogini、Kalachakra 等其他周期体系另表列出,不并入本表。",
"",
"| 宫位 | 宫主 | 直接(宫主或落宫) | 同宫或相位 | 互换星座 | 定位链 | 主题分盘 |",
@@ -463,13 +586,17 @@ def table_lines(structure: Any, language: str) -> list[str]:
levels = ", ".join(_LEVEL_EN[level] for level in _rows(structure.get("levels_used"))) or "none"
caption = [
f"- Period levels used: Vimshottari {levels}. {period_text}.",
*([f"- PD not used: {pd_reason[1]}."] if not pd.get("used") and pd_reason else []),
pd_line,
"- Method: aspects are Parashari whole-sign graha drishti (every planet the 7th house; Mars also the 4th and 8th, "
"Jupiter also the 5th and 9th, Saturn also the 3rd and 10th; Rahu and Ketu cast none under this rule); "
"same sign means the same sign, not an exact conjunction; a sign exchange means each planet is in a sign the other rules; "
f"the dispositor chain is followed at most {hops} steps from the house lord and stops at a planet in its own sign or a repeat; "
f"the topic varga is the one the report assigns to the house ({'; '.join(varga_bits)}), using only the house lord, occupants, "
"same sign and aspects inside that varga; two planets that merely both appear in it are not a connection.",
"one planet or one relation counts once; "
"the dispositor chain is followed from the house lord to its end (a planet in its own sign, a loop back to a planet "
f"already in it, or a missing position), and the table shows at most {shown} steps; a dispositor is the lord of the "
"sign only, Rahu and Ketu rule no sign here, so a chain never passes through a node; "
f"topic vargas are chosen by topic ({'; '.join(varga_bits)}); houses {without.replace('、', ', ')} each hold several "
"matters and get no chart as a whole; inside a varga only the house lord, occupants, same sign and aspects are read, "
"two planets that merely both appear in it are not a connection, and exchanges and dispositor chains are not computed in vargas.",
"- This table lists connection paths only. It is not an activation verdict and gives no score. Yogini, Kalachakra and "
"the other period systems have their own tables and are not merged here.",
"",
+127 -4
View File
@@ -37,12 +37,135 @@ NEECHA_BHANGA_DIGNITY_CELL = {
}
def neecha_bhanga_dignity_cell(value: Any, language: str) -> str | None:
"""The dignity cell for an engine Neecha Bhanga status; None for any other value."""
# BUG-2155 (占星师 2026-11-22 §4, E): the long BUG-2030 sentence above left the tables. A table cell
# names the real state in a short form; the full explanation is written once, on the planet's
# Neecha Bhanga page (pl9_interpretation_packs.NEECHA_SUMMARY). Mitigation is not a new dignity: the
# original 落陷 always stays. States (``neecha_state``):
# verified the named default rule's conditions hold (nicha_bhanga_raj.yogas)
# candidate only another named reading's condition holds (nicha_bhanga_raj.variant_only)
# self_reference_only only the literal self-reference condition holds (nicha_bhanga_raj.literal_only);
# product policy neecha_bhanga_policy_v1 keeps the label 落陷 and adds its own note
# not_met computed, no condition holds
# not_computed the cancellation check did not run or its inputs were missing
# Was: every NEECHA_BHANGA status printed NEECHA_BHANGA_DIGNITY_CELL; a candidate or an
# uncomputed check printed 落陷 with nothing to tell them apart.
NEECHA_STATES = ("verified", "candidate", "self_reference_only", "not_met", "not_computed")
NEECHA_FOOTNOTE_MARK = "¹"
NEECHA_SHORT_CELL = {
"verified": {"zh": "落陷;另有缓解条件", "en": "Debilitated; mitigating conditions present"},
"candidate": {"zh": "落陷;缓解条件待核", "en": "Debilitated; mitigating conditions to be checked"},
"self_reference_only": {"zh": "落陷", "en": "Debilitated"},
"not_met": {"zh": "落陷", "en": "Debilitated"},
"not_computed": {"zh": "落陷", "en": "Debilitated"},
}
# Where the cell has no footnote line under it (a sentence, not a table).
NEECHA_SEE_PAGE = {"zh": "(见格局说明)", "en": " (see the yoga notes)"}
DEBILITATED_LABELS = frozenset({"落陷(Debilitated)", "落陷", "DEBILITATED", "Debilitated"})
def _nb_snapshot(source: Any) -> dict | None:
"""``nicha_bhanga_raj`` from a packet, a yogas_doshas dict, or the snapshot itself; None when absent."""
record = _record(source)
if any(key in record for key in ("yogas", "variant_only", "literal_only")):
return record
if isinstance(record.get("nicha_bhanga_raj"), dict):
return record["nicha_bhanga_raj"]
for holder in (_record(record.get("advanced_systems")), _record(_record(record.get("worksheets")).get("advanced_systems"))):
found = _record(holder.get("yogas_doshas")).get("nicha_bhanga_raj")
if isinstance(found, dict):
return found
return None
def neecha_state(planet: Any, source: Any) -> str:
"""One of NEECHA_STATES for ``planet`` (see the note above)."""
snapshot = _nb_snapshot(source)
if snapshot is None:
return "not_computed"
for key, state in (("yogas", "verified"), ("variant_only", "candidate"), ("literal_only", "self_reference_only")):
if any(isinstance(row, dict) and row.get("planet") == planet for row in snapshot.get(key) or []):
return state
return "not_met"
def neecha_states(source: Any) -> dict[str, str]:
"""Planet -> state for the seven planets that can be debilitated."""
return {planet: neecha_state(planet, source) for planet in PLANETS[:7]}
def neecha_page_title(planet: Any, language: str) -> str:
"""The title of the planet's Neecha Bhanga page (pl9_interpretation_packs page titles)."""
if language == "en":
return f"Neecha Bhanga ({planet})"
return f"落陷取消({_planet(planet, 'zh')})"
def neecha_bhanga_dignity_cell(value: Any, language: str, planet: Any = None, states: dict | None = None,
*, footnote: bool = True) -> str | None:
"""The short dignity cell for a debilitated planet; None for any other value.
An engine Neecha Bhanga status is the verified state unless ``states`` says otherwise. A plain
落陷 status takes the candidate wording only when ``planet`` and ``states`` show a candidate.
``footnote`` marks the verified cell with ¹ (the table then prints ``neecha_table_notes``);
without it the cell ends with 「(见格局说明)」.
"""
text = str(value or "").strip()
if text not in NEECHA_BHANGA_DIGNITY_LABELS:
lang = "en" if language == "en" else "zh"
if text in NEECHA_BHANGA_DIGNITY_LABELS:
state = (states or {}).get(planet) if planet else None
state = state if state in ("verified", "candidate") else "verified"
elif text in DEBILITATED_LABELS and planet and states:
state = states.get(planet) or "not_computed"
else:
return None
return NEECHA_BHANGA_DIGNITY_CELL["en" if language == "en" else "zh"]
cell = NEECHA_SHORT_CELL[state][lang]
if state == "verified":
cell += NEECHA_FOOTNOTE_MARK if footnote else NEECHA_SEE_PAGE[lang]
return cell
NEECHA_NOTE = {
"verified": {
"zh": "¹ 缓解条件和见证星见「瑜伽解释」里的「{title}」;缓解不是新的尊贵等级,原始的落陷不变。",
"en": "¹ The mitigating conditions and their witnesses are on the \"{title}\" page under Yoga interpretation; mitigation is not a new dignity and the original debilitation stands.",
},
"candidate": {
"zh": "{planet}「缓解条件待核」:只有另一种读法下的化解条件成立,默认规则没有成立,这里不按已缓解处理。",
"en": "{planet}, \"mitigating conditions to be checked\": only a condition of another reading holds and the default rule does not, so this is not treated as mitigated.",
},
"not_computed": {
"zh": "{planet}的落陷取消条件这次没有计算,这不表示没有缓解条件。",
"en": "The cancellation conditions for {planet}'s debilitation were not computed this time; this does not mean there are none.",
},
}
def neecha_table_notes(planets_in_table: Any, statuses: dict, states: dict | None, language: str) -> list[str]:
"""Lines printed under a table whose dignity cells came from ``neecha_bhanga_dignity_cell``.
``statuses`` maps each listed planet to the raw status the table printed; a note is written
only for a planet that is debilitated in that table. Verified planets get the ¹ footnote.
"""
lang = "en" if language == "en" else "zh"
lines: list[str] = []
seen: set = set()
for planet in planets_in_table or []:
if planet in seen:
continue
seen.add(planet)
raw = str(statuses.get(planet) or "").strip()
if raw not in NEECHA_BHANGA_DIGNITY_LABELS and raw not in DEBILITATED_LABELS:
continue
if raw in NEECHA_BHANGA_DIGNITY_LABELS:
state = (states or {}).get(planet)
state = state if state in ("verified", "candidate") else "verified"
else:
state = (states or {}).get(planet) if states else None
if state not in NEECHA_NOTE:
continue
template = NEECHA_NOTE[state][lang]
lines.append(template.format(title=neecha_page_title(planet, lang), planet=_planet(planet, lang)))
return lines
def _record(value: Any) -> dict:
+146 -6
View File
@@ -3403,14 +3403,154 @@ def _chalit_convention(packet: dict, language: str) -> str:
# BUG-2156 (占星师 2026-11-22 §5.4): the natal Vivaha Saham chapter shows every step under the named
# profile, from the natal Saham set only (advanced_systems.sahams, chart_kind natal); the annual
# Tajika value is never read here. The method name may appear in this data chapter; no book title.
VIVAH_CAPTION = {
"zh": "本命婚姻Saham,采用PVR Saham计算口径;本命书例数值对照待完成。",
"en": "Natal Vivaha Saham, calculated under the PVR Saham convention; the comparison with the natal textbook example is still to be done.",
}
_VIVAH_OPERAND_ZH = {"Venus": "金星", "Saturn": "土星", "Ascendant": "上升"}
def _jd_local_text(jd: Any, offset_hours: float | None) -> str | None:
if not _plain_number(jd) or offset_hours is None:
return None
from datetime import datetime, timedelta, timezone
moment = datetime(2000, 1, 1, 12, tzinfo=timezone.utc) + timedelta(days=float(jd) - 2451545.0)
local = moment + timedelta(hours=offset_hours)
return local.strftime("%Y-%m-%d %H:%M")
def _profile_offset_hours(packet: dict) -> float | None:
profile = packet.get("calculation_profile") if isinstance(packet.get("calculation_profile"), dict) else {}
settings = profile.get("effective_settings") if isinstance(profile.get("effective_settings"), dict) else {}
timezone = profile.get("timezone") if isinstance(profile.get("timezone"), dict) else {}
raw = str(settings.get("timezone_offset") or timezone.get("utc_offset") or "")
match = re.fullmatch(r"([+-])(\d{1,2}):(\d{2})", raw.strip())
if not match:
return None
hours = int(match.group(2)) + int(match.group(3)) / 60
return hours if match.group(1) == "+" else -hours
def _vivah_degree(value: Any, language: str) -> str:
if not _plain_number(value):
return undetermined(language)
lon = float(value) % 360
return f"{lon:.4f}°({sign_name(SIGNS[int(lon // 30) % 12], language)} {lon % 30:.4f}°)" if language == "zh" else \
f"{lon:.4f}° ({sign_name(SIGNS[int(lon // 30) % 12], language)} {lon % 30:.4f}°)"
def _vivah_name(operand: Any, language: str) -> str:
text = str(operand or "")
if language == "zh":
return _VIVAH_OPERAND_ZH.get(text) or planet_name(text, language)
return text
def vivah_saham_steps(packet: dict, language: str) -> list[list[str]] | None:
"""[item, value] rows for the natal Vivaha Saham, or None when the natal Saham set is missing."""
zh = language == "zh"
sahams = _first(packet, ("advanced_systems", "sahams"))
if not isinstance(sahams, dict) or str(sahams.get("chart_kind") or "natal") != "natal":
return None
row = sahams.get("vivah_saham")
if not isinstance(row, dict) or not _plain_number(row.get("longitude")):
return None
operands = list(row.get("formula_operands") or [])
values = row.get("operand_longitudes") if isinstance(row.get("operand_longitudes"), dict) else {}
names = dict(zip(("A", "B", "C"), operands)) if len(operands) == 3 else {}
daynight = sahams.get("daynight_evidence") if isinstance(sahams.get("daynight_evidence"), dict) else {}
birth = packet.get("birth_info") if isinstance(packet.get("birth_info"), dict) else {}
profile = packet.get("calculation_profile") if isinstance(packet.get("calculation_profile"), dict) else {}
offset = _profile_offset_hours(packet)
is_day = daynight.get("is_daytime")
variant = row.get("formula_variant")
rows: list[list[str]] = []
rows.append(["盘种", "本命盘"] if zh else ["Chart", "Natal chart"])
moment = " ".join(str(birth.get(key) or "") for key in ("date", "time")).strip() or str(sahams.get("moment") or "")
tz = str(birth.get("tz") or "").strip()
rows.append(["时刻", (f"出生时刻 {moment}" + (f"({tz})" if tz else "")) if moment else undetermined(language)] if zh
else ["Moment", (f"Birth moment {moment}" + (f" ({tz})" if tz else "")) if moment else undetermined(language)])
settings = profile.get("effective_settings") if isinstance(profile.get("effective_settings"), dict) else {}
ayanamsa = birth.get("ayanamsa_display") or settings.get("ayanamsa") or profile.get("ayanamsa") or birth.get("ayanamsa_name")
node = str(settings.get("node_mode") or profile.get("node_mode") or birth.get("node_mode") or "")
position = str(settings.get("position_mode") or profile.get("position_mode") or "")
node_words = {"mean": ("平均交点", "mean nodes"), "true": ("真交点", "true nodes")}.get(node)
position_words = {"apparent": ("视位置", "apparent positions"), "true": ("真位置", "true positions")}.get(position)
parts = [
(f"岁差 {str(ayanamsa).title()}" if zh else f"ayanamsa {str(ayanamsa).title()}") if ayanamsa else "",
node_words[0 if zh else 1] if node_words else "",
position_words[0 if zh else 1] if position_words else "",
]
setting_text = ("," if zh else ", ").join(part for part in parts if part)
rows.append(["位置参数", setting_text or undetermined(language)] if zh else ["Settings", setting_text or undetermined(language)])
if isinstance(is_day, bool):
sunrise = _jd_local_text(daynight.get("sunrise_jd_ut"), offset)
sunset = _jd_local_text(daynight.get("sunset_jd_ut"), offset)
nxt = _jd_local_text(daynight.get("next_sunrise_jd_ut"), offset)
if zh:
basis = "白天出生" if is_day else "夜间出生"
times = ";".join(part for part in (f"日出 {sunrise}" if sunrise else "", f"日落 {sunset}" if sunset else "",
f"次日日出 {nxt}" if nxt and not is_day else "") if part)
basis += f"({times};按太阳中心过地平线、不计折射)" if times else "(按太阳中心过地平线、不计折射)"
else:
basis = "Day birth" if is_day else "Night birth"
times = "; ".join(part for part in (f"sunrise {sunrise}" if sunrise else "", f"sunset {sunset}" if sunset else "",
f"next sunrise {nxt}" if nxt and not is_day else "") if part)
basis += f" ({times}; Sun's centre on the horizon, no refraction)" if times else " (Sun's centre on the horizon, no refraction)"
else:
basis = undetermined(language)
rows.append(["昼夜依据", basis] if zh else ["Day/night basis", basis])
if names:
formula = f"{_vivah_name(names['A'], language)} − {_vivah_name(names['B'], language)} + {_vivah_name(names['C'], language)}"
rows.append(["公式(A − B + C)", formula] if zh else ["Formula (A − B + C)", formula])
for key in ("A", "B", "C"):
label = f"{key}:{_vivah_name(names[key], language)}" if zh else f"{key}: {names[key]}"
rows.append([label, _vivah_degree(values.get(key), language)])
swaps = row.get("swaps_by_day_night")
if isinstance(swaps, bool):
if zh:
swap_text = ("这个 Saham 按昼夜交换:白天用金星 − 土星 + 上升,夜间用土星 − 金星 + 上升;"
+ ("本盘是夜间,A 与 B 已交换。" if variant == "night" else "本盘是白天,未交换。")) if swaps else "这个 Saham 不按昼夜交换。"
else:
swap_text = ("This Saham swaps by day and night: Venus − Saturn + Ascendant by day, Saturn − Venus + Ascendant by night; "
+ ("this is a night birth, so A and B are swapped." if variant == "night" else "this is a day birth, so they are not swapped.")) if swaps else "This Saham does not swap by day and night."
rows.append(["是否昼夜交换", swap_text] if zh else ["Swapped by day/night?", swap_text])
passes = row.get("arc_passes_c")
if isinstance(passes, bool) and names:
arc, c_from_b = row.get("arc_b_to_a"), row.get("c_from_b")
a, b, c = (_vivah_name(names[key], language) for key in ("A", "B", "C"))
if zh:
arc_text = (f"从 B({b})顺黄道走到 A({a})共 {float(arc):.4f}°;C({c})在 B 之后 {float(c_from_b):.4f}°,"
+ ("在这段弧内(经过 C)。" if passes else "不在这段弧内(不经过 C)。"))
else:
arc_text = (f"From B ({b}) forward to A ({a}) is {float(arc):.4f}°; C ({c}) is {float(c_from_b):.4f}° past B, "
+ ("inside that arc (passes C)." if passes else "outside that arc (does not pass C)."))
rows.append(["弧段判断", arc_text] if zh else ["Arc check", arc_text])
rows.append(["未修正值", _vivah_degree(row.get("base_longitude_before_exception"), language)] if zh
else ["Unadjusted value", _vivah_degree(row.get("base_longitude_before_exception"), language)])
applied = row.get("zodiacal_order_exception_applied")
if isinstance(applied, bool):
applied_text = ("是:弧段不经过 C,按本口径加 30°" if applied else "否:弧段经过 C,不加 30°") if zh else \
("Yes: the arc does not pass C, so 30° is added under this convention" if applied else "No: the arc passes C, so nothing is added")
else:
applied_text = undetermined(language)
rows.append(["是否加 30°", applied_text] if zh else ["30° added?", applied_text])
rows.append(["最终值(归一到 0–360°)", _vivah_degree(row.get("longitude"), language)] if zh
else ["Final value (normalised to 0–360°)", _vivah_degree(row.get("longitude"), language)])
return rows
def _vivah(packet: dict, language: str) -> str:
module = _first(packet, ("advanced_systems", "vivah_saham"))
if not isinstance(module, dict):
sahams = _first(packet, ("advanced_systems", "sahams")) or {}
module = sahams.get("vivah_saham") if isinstance(sahams, dict) else {}
if not isinstance(module, dict):
steps = vivah_saham_steps(packet, language)
if steps is None:
return _blank(language, ["sign", "degree", "longitude"])
return _rows_from([module], language, [("sign", "sign"), ("degree_in_sign", "text"), ("longitude", "text"), ("degree", "text")])
zh = language == "zh"
table = _md_table(["项目", "值"] if zh else ["Item", "Value"], steps)
return VIVAH_CAPTION["zh" if zh else "en"] + "\n\n" + table
def _pair(table: dict, key: Any, language: str) -> str | None:
+242
View File
@@ -0,0 +1,242 @@
"""Whether the current Vimshottari PD holds across the birth-time range (BUG-2157, G1).
占星师 2026-11-22 §6.2: a "confirmed to the minute" label does not certify the PD. The PD may be used
only when the current PD is the same period at both ends of the declared birth-time range (and so,
the Vimshottari position being monotonic in birth time, everywhere inside it). When the candidates
fall in different PDs the branches are listed side by side and none is picked. Without a definable
range the PD's stability is not assessed (never assume ±1 minute); MD and AD stay in use.
Inputs: ``packet["report_birth_window"]`` (BUG-2013 / BUG-2123), the birth moment and settings the
range scan uses, the Vimshottari reference date and year length on the packet. The Moon's longitude at
each candidate moment comes from the same chart call the range scan makes
(``chart_choice.boundaries.chart_at``); boundaries inside the range are found with the scan's own
``range_boundary_scan.find_value_changes`` (minute steps, bisection to the second).
Before trusting the arithmetic, the MD/AD/PD it gives at the reported moment are compared with the
engine's current periods on the packet; a mismatch leaves the PD unassessed. User feedback and life
events are never read.
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
try:
from scripts.dasha_common import NAKSHATRA_SPAN, VIMSHOTTARI_ORDER, VIMSHOTTARI_YEARS
except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path
from dasha_common import NAKSHATRA_SPAN, VIMSHOTTARI_ORDER, VIMSHOTTARI_YEARS
SCHEMA = "jyotish.pd_range_stability.v1"
CYCLE_YEARS = 120.0
# Branches listed by name; a wider range keeps the count and the first ones only.
MAX_BRANCHES_LISTED = 9
_CUMULATIVE = {}
_total = 0.0
for _lord in VIMSHOTTARI_ORDER:
_CUMULATIVE[_lord] = _total
_total += VIMSHOTTARI_YEARS[_lord]
def _record(value: Any) -> dict:
return value if isinstance(value, dict) else {}
def cycle_position(moon_longitude: float) -> float:
"""Years from the start of Ashwini's Ketu period to the birth, continuous over all 27 nakshatras."""
moon = float(moon_longitude) % 360.0
index = int(moon // NAKSHATRA_SPAN)
lord = VIMSHOTTARI_ORDER[index % 9]
fraction = (moon - index * NAKSHATRA_SPAN) / NAKSHATRA_SPAN
return (index // 9) * CYCLE_YEARS + _CUMULATIVE[lord] + fraction * VIMSHOTTARI_YEARS[lord]
def _split(position: float, lord: str, length: float) -> tuple[str, float, float, int]:
"""Inside a period of ``lord`` lasting ``length`` years, the sub-period at ``position`` (0 ≤ p < length)."""
start = VIMSHOTTARI_ORDER.index(lord)
offset = 0.0
for step in range(9):
sub = VIMSHOTTARI_ORDER[(start + step) % 9]
sub_length = length * VIMSHOTTARI_YEARS[sub] / CYCLE_YEARS
if position < offset + sub_length or step == 8:
return sub, position - offset, sub_length, step
offset += sub_length
raise AssertionError("unreachable") # pragma: no cover
def periods_at(moon_longitude: float, birth: datetime, reference: datetime, year_days: float) -> dict:
"""MD / AD / PD lords at ``reference`` for a birth at ``birth`` with this Moon, plus the PD instance key."""
absolute = cycle_position(moon_longitude) + (reference - birth).total_seconds() / 86400.0 / float(year_days)
cycle, inside = divmod(absolute, CYCLE_YEARS)
md = next(lord for lord in reversed(VIMSHOTTARI_ORDER) if inside >= _CUMULATIVE[lord])
ad, in_ad, ad_length, ad_step = _split(inside - _CUMULATIVE[md], md, VIMSHOTTARI_YEARS[md])
pd, _in_pd, _pd_length, pd_step = _split(in_ad, ad, ad_length)
return {"md": md, "ad": ad, "pd": pd,
"ad_key": (int(cycle), md, ad_step), "pd_key": (int(cycle), md, ad_step, pd_step)}
def _moon_at(req: Any) -> Any:
try:
from scripts.report_render import range_boundary_scan as scan
except ModuleNotFoundError: # pragma: no cover
from report_render import range_boundary_scan as scan
chart = scan._chart_cache(req)
def moon(at: datetime) -> float:
return float(_record(_record(chart(at).get("planets")).get("Moon"))["lon"])
return moon
def _iso(at: datetime) -> str:
return at.strftime("%Y-%m-%dT%H:%M:%S")
def _not_assessed(reason: str, **extra: Any) -> dict:
return {"schema": SCHEMA, "status": "not_assessed", "pd_used": False, "reason": reason, **extra}
def pd_range_stability(packet: dict, *, moon_at: Any = None) -> dict:
"""``status``: ``stable`` (PD used), ``split`` (branches, PD not used) or ``not_assessed`` (PD not used).
``moon_at`` (a callable ``datetime -> sidereal Moon longitude``) is for tests; by default the
range scan's chart call is used with the report's ayanamsa and node settings.
"""
try:
from scripts.report_render import range_boundary_scan as scan
from scripts.pl9_interpretation_packs import _current_period_rows
from scripts.report_render.upstream_sync_chapters import _tz_hours
except ModuleNotFoundError: # pragma: no cover
from report_render import range_boundary_scan as scan
from pl9_interpretation_packs import _current_period_rows
from report_render.upstream_sync_chapters import _tz_hours
window = _record(packet.get("report_birth_window"))
if not window:
return _not_assessed("no_birth_window")
source = window.get("source")
if source == "confirmed_minute" and not (window.get("intervals") or window.get("start_at")):
return _not_assessed("minute_without_range", window_source=source)
if source == "default_unknown_30":
return _not_assessed("trial_range_only", window_source=source)
info = _record(packet.get("birth_info"))
center = scan._center(info)
if center is None:
return _not_assessed("input_missing", window_source=source)
try:
windows = scan._windows(window, center)
except (KeyError, TypeError, ValueError):
windows = None
if not windows:
return _not_assessed("no_declared_range", window_source=source)
timing = _record(_record(packet.get("worksheets")).get("timing_and_predictive_systems")) or _record(packet.get("timing_and_predictive_systems"))
dasha = _record(timing.get("dasha"))
try:
reference = datetime.fromisoformat(str(dasha.get("reference_date"))[:10])
year_days = float(dasha.get("year_days") or 365.25)
except (TypeError, ValueError):
return _not_assessed("input_missing", window_source=source)
current = _current_period_rows(packet)
engine = {level: str(_record(current.get(level)).get("lord") or "") for level in ("md", "ad", "pd")}
if not engine["pd"]:
return _not_assessed("no_current_pd", window_source=source)
if moon_at is None:
settings = _record(_record(packet.get("calculation_profile")).get("effective_settings"))
ayanamsa = str(settings.get("ayanamsa") or info.get("ayanamsa_name") or "").strip().lower()
node_mode = str(settings.get("node_mode") or info.get("node_mode") or "").strip().lower()
if not ayanamsa or node_mode not in ("mean", "true"):
return _not_assessed("input_missing", window_source=source)
try:
req = scan._boundaries.ChartRequest(birth_date=center.date().isoformat(), lat=float(info["lat"]),
lon=float(info["lon"]), tz=float(_tz_hours(packet)),
ayanamsa=ayanamsa, node_mode=node_mode)
except (KeyError, TypeError, ValueError):
return _not_assessed("input_missing", window_source=source)
moon_at = _moon_at(req)
def at(moment: datetime) -> dict:
return periods_at(moon_at(moment), moment, reference, year_days)
try:
here = at(center)
if (here["md"], here["ad"], here["pd"]) != (engine["md"], engine["ad"], engine["pd"]):
return _not_assessed("engine_mismatch", window_source=source,
recomputed={k: here[k] for k in ("md", "ad", "pd")}, engine=engine)
branches: list[dict] = []
ad_changes = 0
for lo, hi in windows:
changes = scan.find_value_changes(lambda moment: at(moment)["pd_key"], lo, hi)
ad_changes += len(scan.find_value_changes(lambda moment: at(moment)["ad_key"], lo, hi))
edges = [lo, *[change["at"] for change in changes], hi]
for start, end in zip(edges, edges[1:]):
period = at(start)
branches.append({"from": _iso(start), "to": _iso(end), "md": period["md"], "ad": period["ad"], "pd": period["pd"]})
except Exception: # noqa: BLE001 - shown as not assessed, never as stable
return _not_assessed("calculation_failed", window_source=source)
keys = {at(datetime.fromisoformat(branch["from"]))["pd_key"] for branch in branches}
checked = [{"from": _iso(lo), "to": _iso(hi)} for lo, hi in windows]
base = {"schema": SCHEMA, "window_source": source, "checked_ranges": checked,
"reference_date": reference.date().isoformat(), "ad_boundary_inside_range": bool(ad_changes),
"method": "vimshottari_cycle_position; moon from chart_choice.boundaries.chart_at; "
"boundaries by range_boundary_scan.find_value_changes"}
if len(keys) == 1:
return {**base, "status": "stable", "pd_used": True, "pd_lord": engine["pd"]}
return {**base, "status": "split", "pd_used": False, "branches": branches,
"branch_count": len(branches)}
def attach_pd_range_stability(packet: dict) -> dict:
"""Computed once per packet (``packet["pd_range_stability"]``)."""
cached = packet.get("pd_range_stability") if isinstance(packet, dict) else None
if isinstance(cached, dict) and cached.get("schema") == SCHEMA:
return cached
result = pd_range_stability(packet if isinstance(packet, dict) else {})
if isinstance(packet, dict):
packet["pd_range_stability"] = result
return result
def caption_line(result: dict, language: str, *, level_name: tuple[str, str] = ("细运", "PD")) -> str:
"""One caption line for a table that uses (or leaves out) the PD."""
zh = language == "zh"
status = _record(result).get("status")
ranges = ";".join(f"{item['from'][11:19]}–{item['to'][11:19]}" for item in _record(result).get("checked_ranges") or []) if zh else \
"; ".join(f"{item['from'][11:19]}–{item['to'][11:19]}" for item in _record(result).get("checked_ranges") or [])
if status == "stable":
lord = _planet(result.get("pd_lord"), language)
return (f"- 细运:在出生时间范围 {ranges} 的两端当前细运都是{lord}细运,范围内没有细运交界,本表使用细运。" if zh
else f"- PD: at both ends of the birth-time range {ranges} the current PD is {lord}'s, with no PD boundary inside; this table uses the PD.")
if status == "split":
branches = result.get("branches") or []
shown = branches[:MAX_BRANCHES_LISTED]
if zh:
parts = ";".join(f"{b['from'][11:19]}–{b['to'][11:19]} 为{_planet(b['pd'], language)}细运" for b in shown)
more = f";另有 {len(branches) - len(shown)} 段未列" if len(branches) > len(shown) else ""
return (f"- 细运按出生时间分支:{parts}{more}。本表不在其中选一个,细运不参加下列关联;大运和小运照常使用。"
+ ("小运在这个范围内也有交界。" if result.get("ad_boundary_inside_range") else ""))
parts = "; ".join(f"{b['from'][11:19]}–{b['to'][11:19]}: {b['pd']} PD" for b in shown)
more = f"; {len(branches) - len(shown)} more not listed" if len(branches) > len(shown) else ""
return (f"- The PD branches with the birth time: {parts}{more}. This table does not pick one, and the PD takes no part in "
"the connections below; MD and AD are used as usual." + (" The AD also changes inside this range." if result.get("ad_boundary_inside_range") else ""))
reason = str(_record(result).get("reason") or "")
why = _NOT_ASSESSED_TEXT.get(reason, _NOT_ASSESSED_TEXT["input_missing"])
return (f"- 细运稳定性未评估:{why[0]}。细运不参加下列关联;大运和小运照常使用。" if zh
else f"- PD stability not assessed: {why[1]}. The PD takes no part in the connections below; MD and AD are used as usual.")
_NOT_ASSESSED_TEXT = {
"no_birth_window": ("没有出生时间的误差范围", "no birth-time margin is available"),
"minute_without_range": ("出生时间只填写到分钟,没有误差范围,不按前后 1 分钟假定",
"the birth time is given to the minute with no margin, and ±1 minute is not assumed"),
"trial_range_only": ("没有填写误差,前后 30 分钟只是试算,不作为出生时间范围",
"no margin was given; the ±30 minute trial is not a birth-time range"),
"no_declared_range": ("没有可用的出生时间范围", "no usable birth-time range"),
"no_current_pd": ("当前细运没有随报告返回", "the current PD was not returned"),
"engine_mismatch": ("细运复核与报告的周期表不一致", "the PD re-check does not match the report's period table"),
"calculation_failed": ("范围两端的细运没有算出", "the PD at the range ends could not be computed"),
"input_missing": ("出生资料或计算设置不全", "the birth data or settings are incomplete"),
}
_PLANET_ZH = {"Sun": "太阳", "Moon": "月亮", "Mars": "火星", "Mercury": "水星", "Jupiter": "木星",
"Venus": "金星", "Saturn": "土星", "Rahu": "罗睺", "Ketu": "计都"}
def _planet(name: Any, language: str) -> str:
return _PLANET_ZH.get(str(name), str(name)) if language == "zh" else str(name)
@@ -35,14 +35,14 @@ try:
from scripts.report_render.audit_chapters import _clean, _status
from scripts.report_render.audit_chapters import _table as _audit_table
from scripts.report_render.text import _md_cell
from scripts.report_render.neecha_witness import neecha_bhanga_dignity_cell
from scripts.report_render.neecha_witness import neecha_bhanga_dignity_cell, neecha_states, neecha_table_notes
except ModuleNotFoundError: # pragma: no cover - direct scripts/ execution
from report_render.appendix_language import planet_name as _planet_name
from report_render.appendix_language import sign_name
from report_render.audit_chapters import _clean, _status
from report_render.audit_chapters import _table as _audit_table
from report_render.text import _md_cell
from report_render.neecha_witness import neecha_bhanga_dignity_cell
from report_render.neecha_witness import neecha_bhanga_dignity_cell, neecha_states, neecha_table_notes
KP_HEADING = {"zh": "KP 宫位显著星、Cuspal Promise 与分盘尊贵", "en": "KP House Significators, Cuspal Promise and Varga Dignity"}
MONTHLY_HEADING = {"zh": "三年流月、星历重点月份与年度附加点", "en": "Three-Year Monthly Support, Ephemeris Key Months and Annual Extra Points"}
@@ -333,12 +333,13 @@ def _kp_section(packet: dict, language: str) -> list[str]:
return lines
def _dignity_word(value: Any, language: str) -> str:
def _dignity_word(value: Any, language: str, planet: Any = None, states: dict | None = None) -> str:
text = str(value or "").strip()
if not text:
return "—"
# BUG-2105: keep the original dignity; the cancellation is a separate clause.
if (cancelled := neecha_bhanga_dignity_cell(text, language)) is not None:
# BUG-2155: the clause is the short state; the D1 row passes the Neecha Bhanga states.
if (cancelled := neecha_bhanga_dignity_cell(text, language, planet, states)) is not None:
return cancelled
if "(" in text and text.endswith(")"):
chinese, english = text[:-1].split("(", 1)
@@ -351,9 +352,11 @@ def _dignity_section(packet: dict, language: str) -> list[str]:
varga_full = _dict(_sheet(packet, "divisional_and_special_charts").get("varga_full"))
d1 = _dict(_sheet(packet, "d1_rasi_bhava").get("planets"))
rows = []
states = neecha_states(packet)
d1_statuses = {planet: _dict(d1.get(planet)).get("status") for planet in PLANETS}
for label, key in DIGNITY_VARGAS:
if key is None:
values = [_dignity_word(_dict(d1.get(planet)).get("status"), language) for planet in PLANETS]
values = [_dignity_word(d1_statuses[planet], language, planet, states) for planet in PLANETS]
if all(value == "—" for value in values):
continue
else:
@@ -374,6 +377,7 @@ def _dignity_section(packet: dict, language: str) -> list[str]:
*_table(("Varga", *(planet_name(planet, language) for planet in PLANETS), "Status") if en
else ("分盘", *(planet_name(planet, language) for planet in PLANETS), "状态"), rows),
"",
*[line for note in neecha_table_notes(PLANETS, d1_statuses, states, language) for line in (note, "")],
]
+124
View File
@@ -0,0 +1,124 @@
"""BUG-2154: archived yoga rule ids, their canonical entry, and the shared evidence identity.
Astrologer ruling 2026-11-22 §3 (D): ``kalatra_dosha_mars_1_4_7_8_12`` is the canonical entry for
the Mars 1/4/7/8/12 screen; ``kalatra_dosha_mars_7`` (same condition) no longer executes or counts
on its own and stays in ``references/yoga_rules.json`` as an archived alias (``enabled: false``,
``duplicate_of``). Old report packets that still carry the archived id resolve to the canonical
entry here, so one fact gives one page, one table row and one adverse item.
Evidence identity (shared by the yoga row and the dosha table row ``mangal_dosha``)::
ev:mars_marriage_screen@<chart>:<reference_point> e.g. ev:mars_marriage_screen@D1:lagna
The report dedup key is ``(dedup_key, reference_point, chart, source_profile)``, so a later Moon-
or Venus-based version, another chart, or another source profile is never merged into this one.
"""
from __future__ import annotations
import json
from functools import lru_cache
from pathlib import Path
from typing import Any
RULES_PATH = Path(__file__).resolve().parents[2] / "references" / "yoga_rules.json"
# The dosha table key and the canonical yoga rule that read the same Mars fact.
MARS_MARRIAGE_RULE_ID = "kalatra_dosha_mars_1_4_7_8_12"
MARS_MARRIAGE_DOSHA_KEY = "mangal_dosha"
MARS_MARRIAGE_EVIDENCE = "mars_marriage_screen"
SHARED_EVIDENCE_GROUPS = {MARS_MARRIAGE_RULE_ID: MARS_MARRIAGE_EVIDENCE}
DEFAULT_REFERENCE_POINT = "lagna"
DEFAULT_CHART = "D1"
@lru_cache(maxsize=1)
def _rules() -> dict[str, dict]:
data = json.loads(RULES_PATH.read_text(encoding="utf-8"))
return {str(rule["id"]): rule for rule in data.get("rules") or [] if isinstance(rule, dict) and rule.get("id")}
def canonical_rule_id(rule_id: Any) -> str:
"""The canonical id for ``rule_id`` (itself when it is not an archived alias)."""
current = str(rule_id or "").strip()
seen = set()
while current and current not in seen:
seen.add(current)
target = str((_rules().get(current) or {}).get("duplicate_of") or "").strip()
if not target or target not in _rules():
return current
current = target
return current
def canonical_rule(rule_id: Any) -> dict | None:
return _rules().get(canonical_rule_id(rule_id))
def is_archived_alias(rule_id: Any) -> bool:
return canonical_rule_id(rule_id) != str(rule_id or "").strip()
def evidence_identity(rule_id: Any, chart: Any = None, reference_point: Any = None) -> str | None:
"""``ev:mars_marriage_screen@D1:lagna`` for the Mars screen; None for rules without a shared identity."""
canonical = canonical_rule_id(rule_id)
group = SHARED_EVIDENCE_GROUPS.get(canonical)
if not group:
return None
rule = _rules().get(canonical) or {}
point = str(reference_point or rule.get("reference_point") or DEFAULT_REFERENCE_POINT)
return f"ev:{group}@{chart or DEFAULT_CHART}:{point}"
def dosha_evidence_identity(dosha_key: str, chart: Any = None, reference_point: Any = None) -> str | None:
"""The same identity for the dosha table row that reads the same fact (``mangal_dosha`` only)."""
if dosha_key != MARS_MARRIAGE_DOSHA_KEY:
return None
return evidence_identity(MARS_MARRIAGE_RULE_ID, chart, reference_point)
def report_dedup_key(rule_id: Any, chart: Any = None) -> tuple | None:
"""``(dedup_key, reference_point, chart, source_profile)`` for a rule with a dedup group, else None."""
rule = canonical_rule(rule_id) or {}
group = rule.get("dedup_key")
if not group:
return None
return (
str(group),
str(rule.get("reference_point") or DEFAULT_REFERENCE_POINT),
str(chart or DEFAULT_CHART),
str(rule.get("source_profile") or ""),
)
def resolve_row(row: dict) -> dict:
"""A copy of an engine row with an archived id moved to its canonical entry (names, effects).
Rows of a canonical rule are returned unchanged except for the ``evidence_identity`` field.
The copy keeps ``legacy_rule_id`` so an old report's id stays traceable.
"""
if not isinstance(row, dict):
return row
rule_id = str(row.get("rule_id") or "").strip()
canonical = canonical_rule_id(rule_id) if rule_id else ""
out = dict(row)
if canonical and canonical != rule_id:
rule = _rules().get(canonical) or {}
out["legacy_rule_id"] = rule_id
out["rule_id"] = canonical
for key in ("name", "name_cn", "effects", "effects_en", "strength", "strength_en", "category"):
if key in rule:
out[key] = rule[key]
evidence = out.get("condition_evidence")
if isinstance(evidence, dict) and evidence.get("rule_id") == rule_id:
out["condition_evidence"] = {**evidence, "rule_id": canonical}
identity = evidence_identity(out.get("rule_id"), out.get("chart") or out.get("chart_type"))
if identity:
out["evidence_identity"] = identity
return out
def reader_explanation(rule_id: Any, language: str) -> str:
"""The rule's own reader explanation (``reader_explanation`` / ``reader_explanation_en``), or ''."""
rule = canonical_rule(rule_id) or {}
return str(rule.get("reader_explanation_en" if language == "en" else "reader_explanation") or "").strip()
+33 -14
View File
@@ -2,13 +2,11 @@
from __future__ import annotations
import json
from datetime import date, time
from functools import lru_cache
from pathlib import Path
from types import SimpleNamespace
from .english_gaps import HAN
from .yoga_rule_aliases import evidence_identity, report_dedup_key, resolve_row
YOGA_STATUS_MAPPING = {
"candidate": {"evidence": ["candidate", "support_only_candidate"], "text": "命中候选规则,尚未完整确认"},
@@ -140,21 +138,17 @@ def _yoga_instance_key(row):
return row.get("name"), names
@lru_cache(maxsize=1)
def _rule_dedup_groups():
path = Path(__file__).resolve().parents[2] / "references" / "yoga_rules.json"
rules = json.loads(path.read_text(encoding="utf-8")).get("rules") or []
return {rule["id"]: rule["dedup_key"] for rule in rules if isinstance(rule, dict) and rule.get("id") and rule.get("dedup_key")}
def _engine_variant_keys(engine_rows):
"""BUG-2075:规则引擎不再按规则组加组合文字并行(上游 19cfd9c0),各规则的行都留在引擎输出里。
报告候选表照旧:同一规则组、同样的参与行星、同一句组合文字的几条变体只列第一条。"""
# 原值:规则组 = 规则表的 dedup_key("mangal_dosha" 等)
# 新值:规则组 = (dedup_key, 参考点, 盘种, 来源口径),归档别名先解析到规范规则
# 原因:BUG-2154(占星师 2026-11-22 §3):日后上升/月亮/金星或不同盘种、口径的版本不能被误合并
keys = {}
for row in engine_rows or []:
if not isinstance(row, dict):
continue
group = _rule_dedup_groups().get(row.get("rule_id"))
group = report_dedup_key(row.get("rule_id"), row.get("chart") or row.get("chart_type"))
if group and row.get("combination"):
keys.setdefault((row["rule_id"], _yoga_instance_key(row)[1]), (group, _yoga_instance_key(row)[1], str(row["combination"])))
return keys
@@ -169,9 +163,20 @@ def _report_yoga_rows(rows, cap=REPORT_YOGA_ROW_CAP, variant_keys=None, merged=N
seen = set()
unique = []
by_variant = {}
seen_rules = set()
for row in rows or []:
if not isinstance(row, dict) or _yoga_instance_key(row) in seen:
if not isinstance(row, dict):
continue
# BUG-2154: an archived alias row (an old packet's kalatra_dosha_mars_7) resolves to its
# canonical rule; the same rule on the same planets is one row, not a same-fact merge.
row = resolve_row(row)
rule_key = (row.get("rule_id"), _yoga_instance_key(row)[1]) if row.get("rule_id") else None
if rule_key is not None and rule_key in seen_rules:
continue
if _yoga_instance_key(row) in seen:
continue
if rule_key is not None:
seen_rules.add(rule_key)
variant = (variant_keys or {}).get((row.get("rule_id"), _yoga_instance_key(row)[1]))
if variant in seen:
if merged is not None and variant in by_variant:
@@ -232,10 +237,16 @@ def report_yoga_conditions(packet, *, gender=None):
merged = []
kept = _report_yoga_rows(layer.get("rows"), variant_keys=_engine_variant_keys(_legacy_yoga_rows(packet)), merged=merged)
position = {id(row): index for index, row in enumerate(kept)}
projected = _project_rows(kept, YOGA_FIELDS)
# BUG-2154: rule_id -> evidence identity shared with the dosha table's mangal_dosha. Kept beside the
# rows so the rows stay the exact projection of the card's field list.
identities = {row["rule_id"]: evidence_identity(row["rule_id"]) for row in projected
if row.get("rule_id") and evidence_identity(row["rule_id"])}
result = {
"status": layer.get("status") or "blocked",
"reference_date": body["reference_date"],
"rows": _project_rows(kept, YOGA_FIELDS),
"rows": projected,
**({"evidence_identities": identities} if identities else {}),
"not_evaluated": _project_rows(layer.get("not_evaluated"), UNEVALUATED_FIELDS),
}
# BUG-2089: rules that hit the same fact as a listed row; `into` is that row's index in `rows`.
@@ -253,7 +264,8 @@ def report_yoga_conditions(packet, *, gender=None):
def report_yoga_table(packet):
layer = report_yoga_conditions(packet)
old_rows = _legacy_yoga_rows(packet)
# BUG-2154: archived alias ids in an old packet resolve to the canonical rule (one row per rule).
old_rows = [resolve_row(row) if isinstance(row, dict) else row for row in _legacy_yoga_rows(packet)]
by_name = {row["name"]: row for row in old_rows if isinstance(row, dict) and row.get("name")}
# BUG-2065:同名多行(每颗落陷星一条)按名字加参与行星对应,各取各的组合说明。
by_instance = {_yoga_instance_key(row): row for row in old_rows if isinstance(row, dict) and row.get("name")}
@@ -283,7 +295,14 @@ def report_yoga_table(packet):
for item in layer.get("same_fact_rows") or []:
if isinstance(item, dict) and isinstance(item.get("row"), dict):
same_fact.setdefault(item.get("into"), []).append(item["row"])
seen_rules = set()
for index, row in enumerate(layer["rows"]):
row = resolve_row(row)
rule_key = (row.get("rule_id"), _yoga_instance_key(row)[1]) if row.get("rule_id") else None
if rule_key is not None and rule_key in seen_rules:
continue
if rule_key is not None:
seen_rules.add(rule_key)
if is_structural_observation(row):
observations += 1
continue
+31 -1
View File
@@ -138,9 +138,22 @@ def _formula_saham_trace(
first = _resolve_saham_operand(formula[0], planet_lons, asc_lon, computed)
second = _resolve_saham_operand(formula[1], planet_lons, asc_lon, computed)
third = _resolve_saham_operand(formula[2], planet_lons, asc_lon, computed)
# BUG-2156 (占星师 2026-11-22 §5): the order of steps for A - B + C (PVR named profile).
# 1. Day/night only picks the formula: a Saham whose rule lists a different night formula
# swaps A and B at night (`swaps_by_day_night`); night birth is never itself the +30 trigger.
# 2. Arc check: walk from B to A in zodiacal order; does that arc pass C?
# 3. If it does NOT pass C, add 30 degrees; the result is normalised to 0-360.
# Edge cases the source does not spell out (our choice, tested, not a ruling):
# - crossing 0 degrees: all distances are taken mod 360, so the arc may wrap through 0 Aries;
# - C exactly at B or exactly at A counts as on the arc (inclusive ends): no +30;
# - A == B: the arc has length 0, so it passes C only when C == B as well; otherwise +30.
arc_b_to_a = (first - second) % 360
c_from_b = (third - second) % 360
base_longitude = (third + (first - second)) % 360
third_between_points = (third - second) % 360 <= (first - second) % 360
third_between_points = c_from_b <= arc_b_to_a
exception_applied = not third_between_points
rule = _SAHAM_RULES['sahams'].get(rule_name) or {}
day_formula, night_formula = rule.get('formula_day'), rule.get('formula_night')
trace = {
'longitude': (base_longitude + 30.0) % 360 if exception_applied else base_longitude,
'base_longitude': base_longitude,
@@ -149,6 +162,11 @@ def _formula_saham_trace(
'formula_variant': 'day' if is_day else 'night',
'zodiacal_order_exception_applied': exception_applied,
'rule_source': 'references/saham_rules.json',
'swaps_by_day_night': bool(day_formula and night_formula and list(day_formula) != list(night_formula)),
'operand_longitudes': {'A': first, 'B': second, 'C': third},
'arc_b_to_a': arc_b_to_a,
'c_from_b': c_from_b,
'arc_passes_c': third_between_points,
}
if any(str(operand).startswith('House') for operand in formula):
trace['house_operand_profile'] = _SAHAM_RULES['house_operand_profile']
@@ -1913,6 +1931,9 @@ def calc_all_sahams(planet_lons: Dict[str, float],
results = {
'status': 'partial',
# BUG-2156: which chart and moment these Sahams belong to, so a natal value is never read as an annual one.
'chart_kind': chart_type,
'moment': birth_dt.isoformat() if hasattr(birth_dt, 'isoformat') else str(birth_dt),
'daynight_evidence': daynight,
'formula_rule_source': 'references/saham_rules.json',
'formula_rule_boundary': (
@@ -2069,6 +2090,15 @@ def _saham_dict(lon: float, name: str, interp: str, *, trace: Optional[Dict] = N
'base_longitude_before_exception': round(trace['base_longitude'], 4),
'formula_source': trace['rule_source'],
})
# BUG-2156: the steps behind the value (data chapter only).
if 'operand_longitudes' in trace:
result.update({
'swaps_by_day_night': trace['swaps_by_day_night'],
'operand_longitudes': {key: round(value, 4) for key, value in trace['operand_longitudes'].items()},
'arc_b_to_a': round(trace['arc_b_to_a'], 4),
'c_from_b': round(trace['c_from_b'], 4),
'arc_passes_c': trace['arc_passes_c'],
})
if 'house_operand_profile' in trace:
result['house_operand_profile'] = trace['house_operand_profile']
else:
+6 -1
View File
@@ -707,7 +707,12 @@ def calc_mangal_dosha(planets_data: Dict, mars_house: int) -> Dict:
- 第七宫/第七宫主有吉星→ 部分缓和
- 双鱼/巨蟹上升 → 更麻烦(Mars在这些星座更凶)
"""
results = {'has_dosha': False, 'severity': 'none', 'remedies': []}
# BUG-2154 (占星师 2026-11-22 §3): the dosha table row and the canonical yoga rule
# kalatra_dosha_mars_1_4_7_8_12 read one Mars fact; both carry this identity so a consumer
# counts it once. Reference point = Lagna, chart = D1 (mars_house is counted from the Lagna).
results = {'has_dosha': False, 'severity': 'none', 'remedies': [],
'evidence_identity': 'ev:mars_marriage_screen@D1:lagna',
'canonical_rule_id': 'kalatra_dosha_mars_1_4_7_8_12'}
bad_houses = [1, 2, 4, 7, 8, 12]
if mars_house not in bad_houses: