Files
Jyotisha/scripts/report_render/indirect_activation.py
T

488 lines
25 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.
"""How each house relates to the current period lords, along five separate paths (BUG-2121).
占星师 2026-11-20 第 1 问: without a direct house-lord relation only this direct path did not
match. The data layer keeps five paths apart and never folds them into one true/false:
1. direct: the period lord is the house lord, or occupies the house;
2. same sign / aspect: the period lord shares a sign with the house lord, or casts a Parashari
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.
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
the Vimshottari periods already in the packet; user feedback or life events are never read.
"""
from __future__ import annotations
from typing import Any
try:
from scripts.aspects import SPECIAL_ASPECTS
from scripts.consultation_native_layers import DRISHTI_CASTERS
from scripts.functional_benefics import SIGN_LORDS
except ModuleNotFoundError: # pragma: no cover - scripts/ on sys.path
from aspects import SPECIAL_ASPECTS
from consultation_native_layers import DRISHTI_CASTERS
from functional_benefics import SIGN_LORDS
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
SIGNS = (
"Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo",
"Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces",
)
_PLANET_ZH = {"Sun": "太阳", "Moon": "月亮", "Mars": "火星", "Mercury": "水星", "Jupiter": "木星",
"Venus": "金星", "Saturn": "土星", "Rahu": "罗睺", "Ketu": "计都"}
_SIGN_ZH = {"Aries": "白羊座", "Taurus": "金牛座", "Gemini": "双子座", "Cancer": "巨蟹座", "Leo": "狮子座",
"Virgo": "处女座", "Libra": "天秤座", "Scorpio": "天蝎座", "Sagittarius": "射手座",
"Capricorn": "摩羯座", "Aquarius": "水瓶座", "Pisces": "双鱼座"}
_LEVEL_ZH = {"md": "大运", "ad": "小运", "pd": "细运"}
_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"),
}
_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"),
}
def _record(value: Any) -> dict:
return value if isinstance(value, dict) else {}
def _rows(value: Any) -> list:
return value if isinstance(value, list) else []
def _planet(name: Any, language: str) -> str:
return _PLANET_ZH.get(str(name), str(name)) if language == "zh" else str(name)
def _sign(name: Any, language: str) -> str:
return _SIGN_ZH.get(str(name), str(name)) if language == "zh" else str(name)
def _day(value: Any) -> str | None:
text = str(value or "")[:10]
return text or None
def _house_of(ascendant: Any, sign: Any) -> int | None:
if ascendant not in SIGNS or sign not in SIGNS:
return None
return (SIGNS.index(sign) - SIGNS.index(ascendant)) % 12 + 1
def _aspected_houses(planet: str, house: Any) -> dict[int, int]:
"""Whole-sign graha drishti, as ``aspects.calc_house_aspects``: target house -> counted distance."""
if planet not in DRISHTI_CASTERS or not isinstance(house, int):
return {}
return {(house - 1 + distance - 1) % 12 + 1: distance for distance in SPECIAL_ASPECTS.get(planet, [7])}
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).
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.
"""
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
def _period_lords(packet: dict) -> tuple[list[dict], dict]:
try:
from scripts.pl9_interpretation_packs import _current_period_rows
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"
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}
def _lord_levels(period_lords: list[dict]) -> dict[str, list[str]]:
levels: dict[str, list[str]] = {}
for item in period_lords:
levels.setdefault(item["lord"], []).append(item["level"])
return levels
def _role(lord: str, levels: list[str], language: str) -> str:
if language == "zh":
return f"{_planet(lord, language)}({'、'.join(_LEVEL_ZH[level] for level in levels)}主星)"
return f"{lord} ({' and '.join(_LEVEL_EN[level] for level in levels)} lord)"
def _aspect_note(distance: int, language: str) -> str:
if language == "zh":
return f"第 {distance} 宫{'特殊' if distance != 7 else ''}相位"
ordinal = f"{distance}{'rd' if distance == 3 else 'th'}"
return f"{ordinal}-house {'special ' if distance != 7 else ''}aspect"
def _chain_text(chain: list[dict], language: str) -> str:
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)
def _fact(kind: str, hit: dict, language: str) -> str:
"""One plain sentence fragment for one hit (no ending punctuation)."""
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 ""
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}"
elif kind == "occupies":
text = f"{who}落在第 {house} 宫" if zh else f"{who} occupies house {house}"
elif kind == "same_sign":
sign = _sign(hit["sign"], language)
text = (f"{who}与第 {house} 宫宫主{lord}同在{sign}(同一星座,不是精确合相)" if zh
else f"{who} shares {sign} with the lord of house {house}, {lord} (same sign, not an exact conjunction)")
elif kind == "aspects_house":
note = _aspect_note(hit["distance"], language)
text = (f"{who}从第 {hit['from_house']} 宫相位第 {house} 宫({note})" if zh
else f"{who} aspects house {house} from house {hit['from_house']} ({note})")
elif kind == "aspects_lord":
note = _aspect_note(hit["distance"], language)
text = (f"{who}从第 {hit['from_house']} 宫相位第 {house} 宫宫主{lord}所在的第 {hit['target_house']} 宫({note})" if zh
else f"{who} aspects the lord of house {house}, {lord}, in house {hit['target_house']} from house {hit['from_house']} ({note})")
elif kind == "exchange":
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)
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
text = ""
return prefix + text
def _relations(
house: int,
house_lord: str,
placements: dict[str, dict],
ascendant: str,
lord_levels: dict[str, list[str]],
*,
chart_label: str | None = None,
) -> dict[str, list[dict]]:
"""Direct, same-sign and aspect hits for one chart (D1 or one varga)."""
found: dict[str, list[dict]] = {"direct": [], "same_sign_or_aspect": []}
lord_place = _record(placements.get(house_lord))
lord_sign = lord_place.get("sign")
lord_house = _house_of(ascendant, lord_sign)
for lord, levels in lord_levels.items():
place = _record(placements.get(lord))
sign = place.get("sign")
own_house = _house_of(ascendant, sign)
base = {"lord": lord, "levels": list(levels), "house": house, "house_lord": house_lord}
if chart_label:
base["chart_label"] = chart_label
if lord == house_lord:
found["direct"].append({**base, "kind": "house_lord"})
if own_house == house:
found["direct"].append({**base, "kind": "occupies"})
if lord != house_lord and sign in SIGNS and sign == lord_sign:
found["same_sign_or_aspect"].append({**base, "kind": "same_sign", "sign": sign})
targets = _aspected_houses(lord, own_house)
if house in targets:
found["same_sign_or_aspect"].append(
{**base, "kind": "aspects_house", "from_house": own_house, "distance": targets[house]})
if lord != house_lord and lord_house in targets and lord_house != house:
found["same_sign_or_aspect"].append({
**base, "kind": "aspects_lord", "from_house": own_house,
"target_house": lord_house, "distance": targets[lord_house],
})
return found
def _path(hits: list[dict]) -> dict:
return {"status": "matched" if hits else "not_matched", "hits": hits}
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.
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``.
"""
chain: list[dict] = []
seen: set[str] = set()
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
chain.append({"planet": current, "sign": sign})
seen.add(current)
dispositor = SIGN_LORDS.get(sign, "")
if dispositor == current:
return chain, "own_sign"
if dispositor in seen:
return chain, "loop"
if len(chain) > DISPOSITOR_MAX_HOPS:
return chain, "depth_cap"
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
mapping: dict[int, list[str]] = {}
for _key, _zh, _en, numbers, charts, _karaka, _arudha in _DOMAINS:
for number in numbers:
for chart in 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)
def build_indirect_activation(packet: dict) -> dict:
"""Per house 1–12, the five paths with the matching period lords, levels and concrete facts."""
try:
from scripts.pl9_interpretation_packs import _house_row, _houses, _planets, _worksheets
except ModuleNotFoundError: # pragma: no cover
from pl9_interpretation_packs import _house_row, _houses, _planets, _worksheets
packet = packet if isinstance(packet, dict) else {}
houses = _houses(packet)
planets = {str(name): _record(row) for name, row in _record(_planets(packet)).items()}
period_lords, pd = _period_lords(packet)
lord_levels = _lord_levels(period_lords)
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()
result_houses: dict[str, dict] = {}
for number in range(1, 13):
house_lord = str(_record(_house_row(houses, number)).get("lord") or "")
row: dict[str, Any] = {"house": number, "lord": house_lord or None}
if not period_lords:
row["paths"] = {path: _blocked("no_current_dasha") for path in PATHS}
result_houses[str(number)] = row
continue
if not house_lord or _record(planets.get(house_lord)).get("sign") not in SIGNS or ascendant not in SIGNS:
row["paths"] = {path: _blocked("house_lord_missing") for path in PATHS}
result_houses[str(number)] = row
continue
d1 = _relations(number, house_lord, planets, ascendant, lord_levels)
lord_sign = planets[house_lord]["sign"]
exchange = []
for lord, levels in lord_levels.items():
sign = _record(planets.get(lord)).get("sign")
if lord != house_lord and SIGN_LORDS.get(str(sign)) == house_lord and SIGN_LORDS.get(lord_sign) == lord:
exchange.append({"lord": lord, "levels": list(levels), "house": number, "house_lord": house_lord,
"kind": "exchange", "lord_sign": sign, "house_lord_sign": lord_sign})
chain_info = _chain(house_lord, planets)
if chain_info is None:
chain_path = _blocked("chain_missing")
else:
chain, end = chain_info
hits = []
for hop, step in enumerate(chain[1:], start=1):
if step["planet"] in lord_levels and step["planet"] != house_lord:
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")
else:
hits, used, missing = [], [], []
for code in charts:
chart = _record(vargas.get(code))
varga_asc = _record(chart.get("Ascendant")).get("sign")
if varga_asc not in SIGNS:
missing.append(code)
continue
varga_lord = SIGN_LORDS[SIGNS[(SIGNS.index(varga_asc) + number - 1) % 12]]
placements = {name: _record(chart.get(name)) for name in _PLANET_ZH}
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]))
for item in found["direct"] + found["same_sign_or_aspect"]:
hits.append({**item, "chart": code})
varga_path = (_blocked("varga_missing") if not used
else {**_path(hits), "charts": used, **({"charts_missing": missing} if missing else {})})
row["paths"] = {
"direct": _path(d1["direct"]),
"same_sign_or_aspect": _path(d1["same_sign_or_aspect"]),
"sign_exchange": _path(exchange),
"dispositor_chain": chain_path,
"topic_varga": varga_path,
}
result_houses[str(number)] = row
return {
"schema": SCHEMA,
"status": "computed" if period_lords else "not_determined",
"period_lords": period_lords,
"levels_used": [item["level"] for item in period_lords],
"pd": pd,
"method": {
"aspect": "parashari_whole_sign_graha_drishti",
"aspect_casters": list(DRISHTI_CASTERS),
"conjunction": "same_sign",
"dispositor_max_hops": DISPOSITOR_MAX_HOPS,
"topic_vargas": {str(number): list(charts) for number, charts in sorted(varga_map.items())},
},
"houses": result_houses,
}
def attach_indirect_activation(packet: dict) -> dict:
"""Store the structure at ``worksheets.advanced_systems.indirect_activation`` (computed once)."""
if not isinstance(packet, dict):
return {}
worksheets = packet.setdefault("worksheets", {})
advanced = worksheets.setdefault("advanced_systems", {}) if isinstance(worksheets, dict) else None
if not isinstance(advanced, dict):
return build_indirect_activation(packet)
stored = advanced.get("indirect_activation")
if not (isinstance(stored, dict) and stored.get("schema") == SCHEMA):
stored = build_indirect_activation(packet)
advanced["indirect_activation"] = stored
return stored
def path_cell(path: dict, language: str) -> str:
zh = language == "zh"
status = _record(path).get("status")
if status == "matched":
if path.get("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 (";" if zh else "; ").join(_fact(hit["kind"], hit, language) for hit in path["hits"])
if status == "not_matched":
return "未对上" if zh else "No match"
reason = _REASON_TEXT.get(str(_record(path).get("reason")))
if reason:
return f"未判定({reason[0]})" if zh else f"Not determined ({reason[1]})"
return "未判定" if zh else "Not determined"
def connection_sentence(structure: Any, house: int, language: str) -> str:
"""One plain sentence naming the first other path that connects; empty when none does."""
row = _record(_record(_record(structure).get("houses")).get(str(house)))
paths = _record(row.get("paths"))
for name in PATHS:
path = _record(paths.get(name))
hits = [hit for hit in _rows(path.get("hits")) if not (name == "direct" and hit.get("kind") == "house_lord")]
if path.get("status") == "matched" and hits:
fact = _fact(hits[0]["kind"], hits[0], language)
if language == "zh":
return f"不过,{fact}。"
return f"However, {'in ' + fact[3:] if fact.startswith('In ') else fact}."
return ""
def table_lines(structure: Any, language: str) -> list[str]:
"""The data-chapter table: houses 1–12 × the five paths, with the method and levels caption."""
structure = _record(structure)
houses = _record(structure.get("houses"))
if not houses:
return []
zh = language == "zh"
lords = _rows(structure.get("period_lords"))
if zh:
period_text = ";".join(
f"{_LEVEL_ZH[item['level']]}主星{_planet(item['lord'], language)}({item.get('start') or '—'} 至 {item.get('end') or '—'})"
for item in lords) or "当前大运没有随报告返回"
else:
period_text = "; ".join(
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")))
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)
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 []),
"- 方法:相位按 Parashari 整宫行星相位(每颗行星看第 7 宫,火星另看第 4、8 宫,木星另看第 5、9 宫,土星另看第 3、10 宫;罗睺、计都按本规则不投射相位);"
"同宫指同一星座,不是精确合相;互换指两星各在对方主管的星座;"
f"定位链从宫主起最多数 {hops} 步,遇到入本宫星座的行星或回到已出现的行星就停;"
f"主题分盘只用本报告给这一宫指定的分盘({';'.join(varga_bits)}),只看该分盘里的宫主、落宫、同宫和相位,两星只是都出现在分盘里不算关联。",
"- 这张表只列关联路径,不是激活判定,也不打分;Yogini、Kalachakra 等其他周期体系另表列出,不并入本表。",
"",
"| 宫位 | 宫主 | 直接(宫主或落宫) | 同宫或相位 | 互换星座 | 定位链 | 主题分盘 |",
"|------|------|------|------|------|------|------|",
]
else:
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 []),
"- 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.",
"- 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.",
"",
"| House | Lord | Direct (lord or occupant) | Same sign or aspect | Sign exchange | Dispositor chain | Topic varga |",
"|-------|------|------|------|------|------|------|",
]
body = []
for number in range(1, 13):
row = _record(houses.get(str(number)))
paths = _record(row.get("paths"))
cells = [str(number), _planet(row.get("lord"), language) if row.get("lord") else ("未判定" if zh else "Not determined")]
cells.extend(path_cell(_record(paths.get(name)), language).replace("|", "/") for name in PATHS)
body.append("| " + " | ".join(cells) + " |")
title = "### 当前周期主星与各宫的关联路径" if zh else "### How the current period lords connect to each house"
return [title, "", *caption, *body, ""]