Files
ClaudeandClaude Opus 5.5 3aae50940e
Independent Staging Quality Gate / publish (push) Canceled after 0s
Independent Staging Quality Gate / validate-frontend (push) Canceled after 31s
Independent Staging Quality Gate / validate-python (push) Canceled after 37s
fix(report): render-only items from the astrologer's 11-25 comparison (BUG-2377–2386)
- 2377 appendix yoga table: kind, formation, also-needs, condition and meaning source (book title only)
- 2378 Saham trace: A, B, C, A − B + C, arc test, +30°, final value
- 2379 daridra_2 「第二宫主落陷…」 no longer classified as Neecha Bhanga
- 2380 Neecha variant names on page titles; Raja add-on line
- 2381 Pancha Mahapurusha page agrees with its basis; degree, Moolatrikona, same-fact line
- 2382 no book/page "Source:" lines in the body Yoga Expression chapter
- 2383 yoga pages state participants' combustion, Shadbala, functional role
- 2384 unresolved-rule records stay backstage (packet only)
- 2385 Neecha verified state matches the row's own fallen planet
- 2386 no hedge line for uncomputed Neecha notes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXp3RzgZVEpT1PXxkwHj
2026-11-25 18:04:38 +08:00

588 lines
32 KiB
Python
Raw Permalink 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.
"""Two roles in a Neecha Bhanga row: the fallen planet and the cancellation witnesses (BUG-2089).
占星师 2026-11-20(问题 4、A6、C 第 4 行): the witness planets may take part in the
"current dasha lord overlap" check, as their own role. A witness that is the current lord
is a link to that cancellation condition, not a cancellation that is "activated" or
"delivered". A self-reference witness is shown but is not independent support, and one
planet that satisfies several conditions is one planet.
The witnesses are read from the detector's structured conditions
(``yogas_doshas.neecha_bhanga_assessment`` → ``cancellation_conditions`` /
``formation_evidence.cancellation_reasons``), never from the combination sentence.
"""
from __future__ import annotations
from typing import Any
PLANETS = ("Sun", "Moon", "Mars", "Mercury", "Jupiter", "Venus", "Saturn", "Rahu", "Ketu")
_PLANET_ZH = {"Sun": "太阳", "Moon": "月亮", "Mars": "火星", "Mercury": "水星", "Jupiter": "木星",
"Venus": "金星", "Saturn": "土星", "Rahu": "罗睺", "Ketu": "计都"}
_ROLE_OF_CONDITION = {
"dispositor": ("落陷星座的主星", "lord of the debilitation sign"),
"exaltation_sign_lord": ("落陷星入旺星座的主星", "lord of the fallen planet's exaltation sign"),
"planet_exalted_in_debility_sign": ("在落陷星座入旺的行星", "planet exalted in the debilitation sign"),
}
# BUG-2105: the engine writes the Neecha Bhanga status into the dignity field
# (jyotish_engine.DIGNITY_LABELS['NEECHA_BHANGA']). A dignity cell keeps the original dignity and
# names the cancellation as a separate clause, as the Tithi-lord table does.
NEECHA_BHANGA_DIGNITY_LABELS = frozenset({"落陷取消(Neecha Bhanga)", "落陷取消", "NEECHA_BHANGA", "Neecha Bhanga"})
# The astrologer's user-facing wording for this status (BUG-2030, 2026-11-19), the same sentence the
# reading facts and the chat card use, so the data tables do not say it a third way.
NEECHA_BHANGA_DIGNITY_CELL = {
"zh": "落陷;这一配置的不利影响有缓解因素,但不能据此认为困难全部消失",
"en": "Debilitated; the adverse effect of this placement has mitigating factors, but this does not mean the difficulties are gone",
}
# 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 = {
# BUG-2280 (负责人 2026-11-23,占星师建议): 原值 verified「落陷;另有缓解条件」、candidate「落陷;缓解条件待核」/
# 新值:检测到缓解条件就一律写「落陷;有缓解」/ 原因:流派多,给出有缓解这一特质即可,不给用户模棱两可的「待核」。
# 核实与否只留在后台数据(neecha_states),用户只看到一种写法。
"verified": {"zh": "落陷;有缓解", "en": "Debilitated; mitigated"},
"candidate": {"zh": "落陷;有缓解", "en": "Debilitated; mitigated"},
"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
# BUG-2165 (占星师 2026-11-22 §4): 「已核实」 only when the named source's conditions are verified. The
# yoga table shows that verification per row (yoga_status_words.yoga_status): ``formed_under_source``
# is verified; ``computed`` (「检测器检出,待核实」), candidate and blocked are not. A planet in the
# detector's default-rule list is therefore verified only when its Neecha Bhanga row in the same yoga
# layer the table prints has ``formed_under_source``; otherwise it is a candidate (detector only).
# Was: the detector's default-rule list alone gave "verified", so the dignity cells said
# 「落陷;另有缓解条件」 while the yoga table said 「检测器检出,待核实」 for the same row.
# With today's rule library no Neecha Bhanga row reaches formed_under_source: the Neecha Bhanga JSON
# rules are reference_only and run on the main detector (row main_detector:neecha_bhanga, status
# computed), and yoga_engine.yoga_formation_contract has no contract for that row.
NEECHA_REASONS = ("source_verified", "detector_only", "variant_only", "self_reference_only", "not_met", "not_computed")
_STATE_OF_REASON = {"source_verified": "verified", "detector_only": "candidate", "variant_only": "candidate",
"self_reference_only": "self_reference_only", "not_met": "not_met", "not_computed": "not_computed"}
def _yoga_layer(source: Any) -> dict:
"""The yoga layer the report's yoga table prints (yoga_status_words.report_yoga_conditions).
A cached layer on the packet is read as is; a full packet without one computes it once (cached on
the packet, so the yoga table later prints the same rows). Anything else has no layer.
"""
record = _record(source)
if isinstance(record.get("rows"), list) and "status" in record:
return record
cached = record.get("report_yoga_conditions")
if isinstance(cached, dict):
return cached
if not isinstance(record.get("birth_info"), dict) or not isinstance(record.get("worksheets"), dict):
return {}
try:
from .yoga_status_words import report_yoga_conditions, report_yoga_inputs
except ImportError: # pragma: no cover - report_render imported as a top-level package
from report_render.yoga_status_words import report_yoga_conditions, report_yoga_inputs
if report_yoga_inputs(record) is None:
return {}
return _record(report_yoga_conditions(record))
def _neecha_row_verified(planet: Any, layer: dict) -> bool:
"""True when a Neecha Bhanga row for ``planet`` in the yoga layer has the table's verified status."""
try:
from .yoga_status_words import yoga_status
except ImportError: # pragma: no cover
from report_render.yoga_status_words import yoga_status
rows = [row for row in layer.get("rows") or [] if isinstance(row, dict)]
rows += [_record(item.get("row")) for item in layer.get("same_fact_rows") or [] if isinstance(item, dict)]
for row in rows:
if is_neecha_bhanga_row(row) and _row_fallen(row) == planet and yoga_status(row)[0] == "formed_under_source":
return True
return False
def _row_fallen(row: dict) -> Any:
"""BUG-2385: the row's own fallen planet. A witness listed in ``planets`` (even a debilitated one) is not
the planet this row mitigates; a row without a named fallen planet counts only when it lists one planet."""
fallen = _record(row.get("formation_evidence")).get("planet") or row.get("planet")
if fallen in PLANETS:
return fallen
listed = row.get("planets")
planets = [name for name in listed if name in PLANETS] if isinstance(listed, (list, tuple, dict)) else []
return planets[0] if len(planets) == 1 else None
def _her_neecha_rows(planet: Any, layer: dict) -> list[dict]:
"""BUG-2303: the yoga layer's rows of her Neecha Bhanga rules for the debilitated ``planet``."""
rows = [row for row in layer.get("rows") or [] if isinstance(row, dict)]
rows += [_record(item.get("row")) for item in layer.get("same_fact_rows") or [] if isinstance(item, dict)]
return [row for row in rows if str(row.get("rule_id") or "").startswith("neechabhanga_")
and _record(row.get("formation_evidence")).get("planet") == planet]
def neecha_reason(planet: Any, source: Any, yoga_layer: Any = None) -> str:
"""One of NEECHA_REASONS for ``planet``; ``yoga_layer`` overrides the layer read from ``source``.
BUG-2303 (负责人 2026-11-24 同意): her rules decide. A row of her Neecha Bhanga rules for the planet
whose formation check is ``formed_under_source`` is verified (「已核定」 is then her named rule's result);
a row whose only witness is the Moon measured from itself is self_reference_only; any other row of
hers is a candidate; an executed layer without her row for the planet is not_met. Was: the site's own
detector list (nicha_bhanga_raj) decided whether there was a mitigation, and no row could reach
formed_under_source. The snapshot is read only when there is no executed layer, or the layer is an
older packet's (retired main-detector rows).
"""
layer = _record(yoga_layer) if yoga_layer is not None else _yoga_layer(source)
hers = _her_neecha_rows(planet, layer)
if hers:
try:
from .yoga_status_words import yoga_status
except ImportError: # pragma: no cover
from report_render.yoga_status_words import yoga_status
if all(_record(row.get("formation_evidence")).get("self_reference_only") for row in hers):
return "self_reference_only"
if any(yoga_status(row)[0] == "formed_under_source"
and not _record(row.get("formation_evidence")).get("self_reference_only") for row in hers):
return "source_verified"
return "detector_only"
layer_rows = [row for row in layer.get("rows") or [] if isinstance(row, dict)]
layer_rows += [_record(item.get("row")) for item in layer.get("same_fact_rows") or [] if isinstance(item, dict)]
legacy = any(is_neecha_bhanga_row(row) and not str(row.get("rule_id") or "").startswith("neechabhanga_")
for row in layer_rows)
if layer.get("status") == "executed" and not legacy:
return "not_met"
snapshot = _nb_snapshot(source)
if snapshot is None:
return "not_computed"
if any(isinstance(row, dict) and row.get("planet") == planet for row in snapshot.get("yogas") or []):
layer = _record(yoga_layer) if yoga_layer is not None else _yoga_layer(source)
return "source_verified" if _neecha_row_verified(planet, layer) else "detector_only"
for key, reason in (("variant_only", "variant_only"), ("literal_only", "self_reference_only")):
if any(isinstance(row, dict) and row.get("planet") == planet for row in snapshot.get(key) or []):
return reason
return "not_met"
def neecha_state(planet: Any, source: Any, yoga_layer: Any = None) -> str:
"""One of NEECHA_STATES for ``planet`` (see the notes above)."""
return _STATE_OF_REASON[neecha_reason(planet, source, yoga_layer)]
def neecha_reasons(source: Any, yoga_layer: Any = None) -> dict[str, str]:
"""Planet -> reason for the seven planets that can be debilitated (the layer is read once)."""
# BUG-2303: her rows in the layer decide, so the layer is read once for every chart.
layer = _record(yoga_layer) if yoga_layer is not None else _yoga_layer(source)
return {planet: neecha_reason(planet, source, layer) for planet in PLANETS[:7]}
def neecha_states(source: Any, yoga_layer: Any = None) -> dict[str, str]:
"""Planet -> state for the seven planets that can be debilitated."""
return {planet: _STATE_OF_REASON[reason] for planet, reason in neecha_reasons(source, yoga_layer).items()}
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 takes the state ``states`` gives the planet; without one it is a
candidate (BUG-2165: never 「已核实」 without the yoga row's verification). 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 a verified or candidate cell ends with 「(见格局说明)」.
"""
text = str(value or "").strip()
lang = "en" if language == "en" else "zh"
if text in NEECHA_BHANGA_DIGNITY_LABELS:
state = (states or {}).get(planet) if planet else None
# 原值:没有 states 时按 verified;新值:按 candidate;原因:BUG-2165(已核只看格局表的核实状态)
state = state if state in ("verified", "candidate") else "candidate"
elif text in DEBILITATED_LABELS and planet and states:
state = states.get(planet) or "not_computed"
else:
return None
cell = NEECHA_SHORT_CELL[state][lang]
# BUG-2303 (负责人 BUG-2280 裁定): 原值 verified 的格子加 ¹ 脚注 / 新值:verified 与 candidate 对读者完全一样
# (「落陷;有缓解」,同一句说明)/ 原因:她的规则现在真的能核定(formed_under_source),核定与否只留在后台。
if state in ("verified", "candidate") and not footnote:
# BUG-2165: a sentence with the candidate state points to the notes too (the table form has the
# note line under the table). Was: 「尊贵为落陷;缓解条件待核。」 with no pointer.
cell += 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": {
# BUG-2280 原值「{planet}「缓解条件待核」:…这里不按已缓解处理。」/ 新值见下 / 原因:负责人 11-23,有缓解就写有缓解。
"zh": "{planet}有缓解:按另一种读法,化解条件成立;原始的落陷不变。",
"en": "{planet} is mitigated: the cancellation condition holds under another reading; the original debilitation stands.",
},
# BUG-2165: the default rule's detector found the conditions, the named source's check has not run
# (the yoga table's 「检测器检出,待核实」).
"detector_only": {
# BUG-2280 原值「{planet}「缓解条件待核」:检测器找到了化解条件,还没有按所选规则逐项核实…不按已缓解处理…」/ 新值见下 / 原因:同上
"zh": "{planet}有缓解:化解条件和见证星见「瑜伽解释」里的「{title}」;原始的落陷不变。",
"en": "{planet} is mitigated: the conditions and witnesses are on the \"{title}\" page under Yoga interpretation, and the original debilitation stands.",
},
"not_computed": {
# BUG-2386 原值「…这次没有计算,这不表示没有缓解条件。」/ 新值:只写落陷 / 原因:负责人不加两可说法(BUG-2280 同一规则)。
"zh": "{planet}落陷。",
"en": "{planet} is debilitated.",
},
}
def neecha_table_notes(planets_in_table: Any, statuses: dict, states: dict | None, language: str,
reasons: dict | None = None) -> 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.
``reasons`` (``neecha_reasons``) tells a detector-only candidate from a variant-only one; without
it the raw status does (``_candidate_reason``).
"""
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 == "candidate" and _candidate_reason(planet, raw, reasons) == "detector_only":
state = "detector_only"
# BUG-2303: a verified planet reads exactly as a detected one (BUG-2280); no ¹ line of its own.
if state == "verified":
state = "detector_only"
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
# BUG-2165 (占星师 2026-11-22 §4 「避免九次复制同一句」): in a long list where the same planet repeats
# period after period (the AD / PD paragraphs of a Dasha page), each mention is a short marker
# 「落陷¹」 and ONE footnote under that list gives the state and points to the planet's Neecha Bhanga
# page. The planet / dignity summary tables keep the short sentence (neecha_bhanga_dignity_cell).
# Was: every AD / PD paragraph printed 「落陷;另有缓解条件(见格局说明)」 (72 PD + 9 AD times for
# Obama's Jupiter).
NEECHA_MARKER = {"zh": "落陷" + NEECHA_FOOTNOTE_MARK, "en": "Debilitated" + NEECHA_FOOTNOTE_MARK}
NEECHA_MARKER_NOTE = {
"zh": "¹ {planet}:{cell}。缓解条件和见证星见「瑜伽解释」里的「{title}」;缓解不是新的尊贵等级,原始的落陷不变。",
"en": "¹ {planet}: {cell}. 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.",
}
NEECHA_MARKER_NOTE_VARIANT = {
# BUG-2280 原值「…只有另一种读法下的化解条件成立,默认规则没有成立,这里不按已缓解处理;…」/ 新值见下 / 原因:负责人 11-23。
"zh": "¹ {planet}:{cell}。按另一种读法,化解条件成立;原始的落陷不变。",
"en": "¹ {planet}: {cell}. The cancellation condition holds under another reading; the original debilitation stands.",
}
def _candidate_reason(planet: Any, raw: Any, reasons: dict | None) -> str:
"""detector_only / variant_only for a candidate. The engine writes the Neecha Bhanga status only
when the default rule's detector holds, so without ``reasons`` that status is detector-only and a
plain 落陷 candidate is variant-only."""
reason = (reasons or {}).get(planet)
if reason in ("detector_only", "variant_only"):
return reason
return "detector_only" if str(raw or "").strip() in NEECHA_BHANGA_DIGNITY_LABELS else "variant_only"
def _marked_state(value: Any, planet: Any, states: dict | None) -> str | None:
text = str(value or "").strip()
if text in NEECHA_BHANGA_DIGNITY_LABELS:
state = (states or {}).get(planet) if planet else None
return state if state in ("verified", "candidate") else "candidate"
if text in DEBILITATED_LABELS and planet and states and states.get(planet) in ("verified", "candidate"):
return states[planet]
return None
def neecha_marker_cell(value: Any, language: str, planet: Any = None, states: dict | None = None) -> str | None:
"""「落陷¹」 / "Debilitated¹" for a debilitated planet with mitigation (verified or to be checked).
None for anything else (plain 落陷 without a candidate, other dignities): the caller prints its
usual text, and no footnote is owed.
"""
if _marked_state(value, planet, states) is None:
return None
return NEECHA_MARKER["en" if language == "en" else "zh"]
def neecha_marker_note(planet: Any, value: Any, language: str, states: dict | None = None,
reasons: dict | None = None) -> str | None:
"""The one footnote under a list that printed ``neecha_marker_cell`` for ``planet``."""
state = _marked_state(value, planet, states)
if state is None:
return None
lang = "en" if language == "en" else "zh"
cell = NEECHA_SHORT_CELL[state][lang]
variant = state == "candidate" and _candidate_reason(planet, value, reasons) == "variant_only"
template = (NEECHA_MARKER_NOTE_VARIANT if variant else NEECHA_MARKER_NOTE)[lang]
return template.format(planet=_planet(planet, lang), cell=cell, title=neecha_page_title(planet, lang))
def _record(value: Any) -> dict:
return value if isinstance(value, dict) else {}
def _planet(name: Any, language: str) -> str:
return _PLANET_ZH.get(str(name), str(name)) if language == "zh" else str(name)
def is_neecha_bhanga_row(row: Any) -> bool:
row = _record(row)
blob = " ".join(str(row.get(key) or "") for key in ("name", "name_cn", "type", "category", "subtype", "rule_id")).lower()
# BUG-2379: the bare word 「落陷」 also names other rules (daridra_2 「第二宫主落陷且在第6、8或12宫」), which were
# then shown as a Neecha Bhanga with "witnesses not returned". Only the cancellation itself counts.
return ("neecha" in blob or "nicha" in blob or "落陷取消" in blob or "落陷化解" in blob
or "neecha_bhanga" in blob or "nicha_bhanga" in blob)
def row_object_planets(row: Any) -> list[str]:
"""BUG-2303: the planets a yoga row is about — for a Neecha Bhanga row of her rule, the fallen planet only."""
row = _record(row)
if is_neecha_bhanga_row(row) and _record(row.get("formation_evidence")).get("planet") in PLANETS:
return [_record(row.get("formation_evidence"))["planet"]]
planets = row.get("planets")
return [name for name in planets if name in PLANETS] if isinstance(planets, (list, tuple, dict)) else []
def _row_planets(row: dict) -> list[str]:
# BUG-2303: her Neecha Bhanga rows list the debilitated planet and its witnesses as participants;
# the fallen planet is her formation_evidence.planet.
fallen = _record(row.get("formation_evidence")).get("planet")
if fallen in PLANETS:
return [fallen]
planets = row.get("planets")
names = [name for name in planets if name in PLANETS] if isinstance(planets, (list, tuple, dict)) else []
if not names and row.get("planet") in PLANETS:
names = [row["planet"]]
return names
def _conditions(row: dict, yogas_doshas: Any) -> list[dict] | None:
"""The executed cancellation conditions for this row; None when none were returned."""
direct = row.get("cancellation_conditions")
if not isinstance(direct, list):
direct = _record(row.get("formation_evidence")).get("cancellation_reasons")
if isinstance(direct, list):
return [item for item in direct if isinstance(item, dict)]
fallen = _row_planets(row)
for other in _record(_record(yogas_doshas).get("nicha_bhanga_raj")).get("yogas") or []:
if isinstance(other, dict) and other.get("planet") in fallen and isinstance(other.get("cancellation_conditions"), list):
return [item for item in other["cancellation_conditions"] if isinstance(item, dict)]
return None
def neecha_roles(row: Any, yogas_doshas: Any = None) -> dict | None:
"""Fallen planet and witnesses of one Neecha Bhanga row; None for any other row.
``witnesses`` lists each witness planet once. ``independent_witnesses`` are those with at
least one condition that is not a self-reference; ``self_reference_witnesses`` are shown
but are not independent support. ``witnesses_returned`` is False when the detector's
conditions did not reach this row (the witnesses are then unknown, not "none").
"""
row = _record(row)
if not is_neecha_bhanga_row(row):
return None
fallen = _row_planets(row)
conditions = _conditions(row, yogas_doshas)
witnesses: list[str] = []
independent: list[str] = []
for condition in conditions or []:
name = condition.get("planet")
if name not in PLANETS:
continue
if name not in witnesses:
witnesses.append(name)
self_reference = bool(condition.get("self_reference") or condition.get("witness_is_reference")
or condition.get("witness_is_debilitated_planet") or name in fallen)
if not self_reference and name not in independent:
independent.append(name)
return {
"fallen": fallen,
"witnesses": witnesses,
"independent_witnesses": independent,
"self_reference_witnesses": [name for name in witnesses if name not in independent],
"witnesses_returned": conditions is not None,
"conditions": conditions or [],
}
def condition_text(condition: dict, language: str) -> str:
"""One executed condition in reader words (no rule codes)."""
zh = language == "zh"
key = str(condition.get("condition") or "")
name = _planet(condition.get("planet"), language)
house = condition.get("relative_house", condition.get("house"))
for role, (role_zh, role_en) in _ROLE_OF_CONDITION.items():
if key.startswith(role + "_kendra_from_"):
moon = key.endswith("_moon")
if zh:
return f"{role_zh}{name}在{'月亮' if moon else '上升'}起第 {house} 宫(角宫)"
return f"{role_en}, {name}, in house {house} from the {'Moon' if moon else 'Lagna'} (kendra)"
if key == "dispositor_aspect":
return f"落陷星座的主星{name}照到落陷星" if zh else f"lord of the debilitation sign, {name}, aspects the fallen planet"
return f"{name}满足一项化解条件" if zh else f"{name} satisfies one cancellation condition"
def witness_list_text(roles: dict, language: str) -> str:
"""「土星;月亮(自我参照,不作独立印证)」 — each witness once."""
zh = language == "zh"
if not roles.get("witnesses_returned"):
return "本次未返回" if zh else "Not returned this time"
if not roles.get("witnesses"):
return "没有见证星" if zh else "No witness"
parts = []
for name in roles["witnesses"]:
text = _planet(name, language)
if name in roles["self_reference_witnesses"]:
text += "(自我参照,不作独立印证)" if zh else " (self-reference, not independent support)"
parts.append(text)
return (";" if zh else "; ").join(parts)
def overlap_roles(roles: dict, active: Any) -> dict:
"""Which current dasha lords are the fallen planet, and which are witnesses."""
lords = [name for name in (active or []) if name in PLANETS]
return {
"fallen": [name for name in roles.get("fallen") or [] if name in lords],
"witnesses": [name for name in roles.get("witnesses") or [] if name in lords],
}
def witness_overlap_text(roles: dict, active: Any, language: str) -> str | None:
"""Her wording for a current lord that is a witness; None when no witness is a current lord."""
zh = language == "zh"
hit = overlap_roles(roles, active)["witnesses"]
if not hit:
return None
independent = [name for name in hit if name in roles["independent_witnesses"]]
selfref = [name for name in hit if name not in independent]
parts = []
if independent:
names = ("、" if zh else ", ").join(_planet(name, language) for name in independent)
parts.append(f"当前周期关联到该化解条件的见证星:{names}" if zh
else f"The current period is linked to a witness of this cancellation condition: {names}")
if selfref:
names = ("、" if zh else ", ").join(_planet(name, language) for name in selfref)
parts.append(f"当前周期主星{names}在这里只是自我参照的条件,只记原始条件,不作独立印证" if zh
else f"The current period lord {names} is only a self-reference condition here; it is recorded, not counted as independent support")
return (";" if zh else "; ").join(parts)
def participant_cells(item: Any, active: Any, language: str, yogas_doshas: Any = None) -> dict | None:
"""Cells for the yoga participants / current-lord overlap table; None for a row that is not a Neecha Bhanga.
``witness_cell``: the cancellation witnesses, each once. ``witness_overlap_cell``: the
witnesses that are current dasha lords. ``witness_status``: the timing wording for a
witness overlap (None when there is none), to be shown beside the fallen-planet status.
"""
roles = neecha_roles(item, yogas_doshas)
if roles is None:
return None
zh = language == "zh"
hit = overlap_roles(roles, active)["witnesses"]
if not roles["witnesses_returned"]:
overlap_cell = "—"
elif hit:
overlap_cell = ("、" if zh else ", ").join(_planet(name, language) for name in hit)
else:
overlap_cell = "无" if zh else "None"
return {
"roles": roles,
"witness_cell": witness_list_text(roles, language),
"witness_overlap_cell": overlap_cell,
"witness_status": witness_overlap_text(roles, active, language),
}
def attach_neecha_witness_roles(packet: Any) -> int:
"""Write ``cancellation_witnesses`` / ``self_reference_witnesses`` on each detected Neecha Bhanga row.
New keys only; ``planets`` keeps its meaning (the fallen planet). Returns the number of rows annotated.
"""
advanced = _record(_record(_record(packet).get("worksheets")).get("advanced_systems"))
yoga = _record(advanced.get("yoga"))
doshas = advanced.get("yogas_doshas")
count = 0
for group in ("detected_yogas", "yogas"):
for row in yoga.get(group) or []:
roles = neecha_roles(row, doshas)
if roles is None or not roles["witnesses_returned"]:
continue
row["cancellation_witnesses"] = list(roles["witnesses"])
row["self_reference_witnesses"] = list(roles["self_reference_witnesses"])
count += 1
return count
def neecha_participant_row(item: Any, planets_cell: str, status: str, active: Any, language: str,
yogas_doshas: Any = None) -> tuple[str, str]:
"""(participants cell, timing status) for the yoga participants table, with the two roles.
Any other row comes back unchanged. For a Neecha Bhanga row the participants cell names the
fallen planet and, separately, the cancellation witnesses (each once; a self-reference
witness is marked); a witness that is a current dasha lord is added to the status as a link,
never as an activation.
"""
cells = participant_cells(item, active, language, yogas_doshas)
if cells is None:
return planets_cell, status
zh = language == "zh"
planets_cell = (f"{planets_cell}(落陷星);化解条件的见证星:{cells['witness_cell']}" if zh
else f"{planets_cell} (fallen planet); cancellation witnesses: {cells['witness_cell']}")
if cells["witness_status"]:
link = cells["witness_status"] if zh else cells["witness_status"][:1].lower() + cells["witness_status"][1:]
status = f"{status}{';' if zh else '; '}{link}"
return planets_cell, status