"""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, 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 the Vimshottari periods already in the packet; user feedback or life events are never read. """ from __future__ import annotations import json from functools import lru_cache from pathlib import Path 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, ... # 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", ) _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"), "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"), } # 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"), } 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]: """Whether the PD may be used: the current PD is the same across the declared birth-time range. 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``)。 """ 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]: 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) 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"))}) 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]]: 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, 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": 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: """One plain sentence fragment for one hit (no ending punctuation).""" zh = language == "zh" who = _role(hit["lord"], hit["levels"], language) house = hit["house"] 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}" 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, 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 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], *, 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. 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: 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 chain.append({"planet": current, "sign": sign}) seen.append(current) dispositor = SIGN_LORDS.get(sign, "") if dispositor == current: return chain, "own_sign", [] if dispositor in seen: return chain, "loop", seen[seen.index(dispositor):] if len(chain) > cap: return chain, "truncated", [] current = dispositor @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 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() if charts} 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 = _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, loop_members = chain_info hits = [] for hop, step in enumerate(chain[1:], start=1): # 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, "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 = [], [], [] 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: 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 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"]: # 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, "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"]), "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, "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, } 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") 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 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}:{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" 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")) 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}") 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}。", pd_line, "- 方法:相位按 Parashari 整宫行星相位(每颗行星看第 7 宫,火星另看第 4、8 宫,木星另看第 5、9 宫,土星另看第 3、10 宫;罗睺、计都按本规则不投射相位);" "同宫指同一星座,不是精确合相;互换指两星各在对方主管的星座;同一颗星或同一层关系只算一次;" f"定位链从宫主起一直追到终点(行星在自己的星座=自座、回到已出现的行星=循环、下一颗星的位置没有返回=缺失),表里最多显示 {shown} 步;" "定位星只取所在星座的主星,罗睺、计都不作星座主星,所以链不会经过交点;" f"主题分盘按主题选({';'.join(varga_bits)}),第 {without} 宫各含多个事项,不整体指定分盘;" "分盘里只看宫主、落宫、同宫和相位,两星只是都出现在分盘里不算关联,互换和定位链没有在分盘里计算。", "- 这张表只列关联路径,不是激活判定,也不打分;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}.", 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; " "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.", "", "| 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, ""]