From c1957e31645da43df71e362c1358ea87ae08acbc Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 12:03:34 +0800 Subject: [PATCH] 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 Claude-Session: https://claude.ai/code/session_01DbBXp2Vp62Ur3C7yRWQdSq --- docs/BUG_HISTORY.md | 45 +++ references/topic_varga_routes.json | 92 ++++++ references/yoga_rule_topics.v1.json | 10 +- references/yoga_rules.json | 34 ++- scripts/annual_native/saham_traces.py | 4 +- scripts/pl9_full_data_export.py | 27 +- scripts/pl9_interpretation_packs.py | 80 ++++- scripts/pl9_reader_export.py | 30 +- scripts/report_render/indirect_activation.py | 277 +++++++++++++----- scripts/report_render/neecha_witness.py | 131 ++++++++- scripts/report_render/parity_chapters.py | 152 +++++++++- scripts/report_render/pd_range_stability.py | 242 +++++++++++++++ .../report_render/upstream_sync_chapters.py | 14 +- scripts/report_render/yoga_rule_aliases.py | 124 ++++++++ scripts/report_render/yoga_status_words.py | 47 ++- scripts/tajika.py | 32 +- scripts/yogas_doshas.py | 7 +- tests/test_natal_vivaha_saham_2156.py | 89 ++++++ tests/test_reading_facts_2106.py | 4 +- tests/test_report_english_edition.py | 4 +- tests/test_report_fixes_2105.py | 30 +- tests/test_report_indirect_activation_2121.py | 114 +++++-- tests/test_report_indirect_activation_2157.py | 164 +++++++++++ tests/test_report_mars_rule_2154.py | 120 ++++++++ tests/test_report_neecha_short_cell_2155.py | 120 ++++++++ tests/test_report_reader_main.py | 5 +- 26 files changed, 1807 insertions(+), 191 deletions(-) create mode 100644 references/topic_varga_routes.json create mode 100644 scripts/report_render/pd_range_stability.py create mode 100644 scripts/report_render/yoga_rule_aliases.py create mode 100644 tests/test_natal_vivaha_saham_2156.py create mode 100644 tests/test_report_indirect_activation_2157.py create mode 100644 tests/test_report_mars_rule_2154.py create mode 100644 tests/test_report_neecha_short_cell_2155.py diff --git a/docs/BUG_HISTORY.md b/docs/BUG_HISTORY.md index 0cbd193df..b12ba8b7d 100644 --- a/docs/BUG_HISTORY.md +++ b/docs/BUG_HISTORY.md @@ -29166,3 +29166,48 @@ - 尚未处理:模型路径下的追问照常扣点(照常取数是因为回答必须先调用排盘工具,不调用会被判为回答未完成);只有首页按钮的原样文字走免费追问。 - 关联记录:BUG-2160(首页文案)、BUG-2158(分支写法)、BUG-1980(免费回复路径)。 - 修复版本:`claude/plan-clarify-2161`。 + +## BUG-2154 | 两条条件相同的火星规则重复计数,并给出「婚姻延迟」等定论 + +- 状态:fixed-pending-verify。 +- 首次发现 / 最近更新:2026-11-21 / 2026-11-22。 +- 触发与现象:`kalatra_dosha_mars_7` 与 `kalatra_dosha_mars_1_4_7_8_12` 条件相同、都启用,乔布斯盘火星在第 8 宫时两条各成一页,再加 Dosha 表一行,同一事实三处;文案写「婚姻延迟;需要匹配化解」「配偶关系紧张」。占星师 2026-11-22 第 3 节裁定选 2。 +- 修复:`references/yoga_rules.json` 中短编号规则 `enabled:false` 并记 `duplicate_of`、`archived_reason`;长编号为规范入口,中文名「火星婚姻相关配置(1/4/7/8/12宫筛查)」,解释改为裁定原句,去掉定论和「需要匹配化解」,来源记为「当前采用的五宫筛查口径;具体原典定位待核」(`source_verified:false`,旧来源仅存档、不向读者显示)。新 `scripts/report_render/yoga_rule_aliases.py` 把旧编号解析到规范入口;报告去重键含参考点、盘种和来源口径;格局页与 Dosha 表共用证据身份 `ev:mars_marriage_screen@D1:lagna`,两处各写一句「同一项火星位置事实,只算一项」。`yoga_rule_topics.v1.json` 重建。 +- 验证与防复发:`tests/test_report_mars_rule_2154.py`(5 条);乔布斯格局页 54 → 53,两种语言不再出现「火星障碍」。 +- 尚未处理:Dosha 表的火星检查算 1/2/4/7/8/12 宫,规范规则算 1/4/7/8/12 宫,火星在第 2 宫时两者不一致,需占星师裁定;缺火星位置时冻结引擎记为不成立。 +- 关联记录:BUG-2089、BUG-2110,占星师 2026-11-22 第 3 节。 +- 修复版本:`claude/astro-defg-2154`。 + +## BUG-2155 | 尊贵栏遇到落陷取消用长句,且已核、候选、未计算混在一起 + +- 状态:fixed-pending-verify。 +- 首次发现 / 最近更新:2026-11-21 / 2026-11-22。 +- 触发与现象:表格格子里印 BUG-2030 的长句;条件候选和没有计算时也可能被写成有缓解;宫主说明写「尊贵为落陷取消」,丢了原始落陷。占星师 2026-11-22 第 4 节裁定选 2。 +- 修复:按状态写短句——已核实「落陷;另有缓解条件¹」(表下脚注指向该星的落陷取消页,并说明缓解不是新的尊贵等级);候选「落陷;缓解条件待核」;未计算只写「落陷」并另注「这次没有计算,这不表示没有缓解条件」;仅自我参照保留原口径。没有脚注的句子写「落陷;另有缓解条件(见格局说明)」。完整解释只在落陷取消页写一次;只改按行星判断过的格子,不做全局替换。状态来自 `neecha_witness.neecha_state`。 +- 验证与防复发:`tests/test_report_neecha_short_cell_2155.py`(7 条,两张公开盘中英文 + 候选、未计算合成例);奥巴马盘 7 个格子中英文都改为短句,长句不再出现在任何表格。 +- 尚未处理:`reading_facts.py` 和前端卡片仍用长句(证据包窗口跟进)。 +- 关联记录:BUG-2030、BUG-2105,占星师 2026-11-22 第 4 节。 +- 修复版本:`claude/astro-defg-2154`。 + +## BUG-2156 | 本命 Vivaha Saham 的 30° 修正说不清条件,本命与年运值混在一起 + +- 状态:fixed-pending-verify。 +- 首次发现 / 最近更新:2026-11-21 / 2026-11-22。 +- 触发与现象:报告让人以为「夜间出生」就加 30°,本命值和 2026 年运值放在一起比较。占星师 2026-11-22 第 5 节:保留 PVR 条件修正,夜间只决定是否交换 A、B,是否加 30° 看 B 顺行到 A 是否经过 C。 +- 根因:计算本身是对的,只是没有逐步记录和显示;无公式元数据时的兜底说明写错成「Asc + Venus - Mars」。 +- 修复:`scripts/tajika.py` 为每个 Saham 记下是否昼夜交换、A/B/C 黄经、B→A 弧长、C 的位置、是否经过 C;Saham 集合记盘种(本命 / 年运)和时刻;端点和 A=B 的处理写明是本方实现选择。资料章节「本命 Vivah Saham」加说明「本命婚姻Saham,采用PVR Saham计算口径;本命书例数值对照待完成。」和逐步表,只读本命集合。修正兜底说明。数值不变:乔布斯 90.4927°(不加),奥巴马 139.7212° + 30° = 169.7212°。 +- 验证与防复发:`tests/test_natal_vivaha_saham_2156.py`(9 条:昼夜 × 是否触发、跨 0°、A=B、C 在端点、本命 / 年运不混)。 +- 尚未处理:书中 Example 104 数值复算。 +- 关联记录:BUG-1547、BUG-2065,占星师 2026-11-22 第 5 节。 +- 修复版本:`claude/astro-defg-2154`。 + +## BUG-2157 | 五种关联:细运凭「确认到分钟」开关,定位链截断写成没对上,主题分盘按宫硬配 + +- 状态:fixed-pending-verify。 +- 首次发现 / 最近更新:2026-11-21 / 2026-11-22。 +- 触发与现象:占星师 2026-11-22 第 6 节:细运不能凭分钟标签认证;定位链只追三步会把没追完写成没关联;不要给十二宫各配一张分盘,D9 不是无条件的第二事业盘。 +- 修复:新 `scripts/report_render/pd_range_stability.py`:用 `report_birth_window` 的声明范围(同 BUG-2123 扫描的取盘与界线函数),范围两端细运相同且范围内没有细运界线才用细运;不同就并列分支、不选边;没有范围、只是 ±30 分钟试算或复算与引擎不一致时写「细运稳定性未评估」,不用细运,大运小运照常。定位链追到自座、循环(列出成员)、缺失或安全上限 12(标「截断」),显示前三步,截断且没对上写「未判定」而不是「未对上」;交点不作定位星(`NODE_DISPOSITOR_CONVENTION`)。新 `references/topic_varga_routes.json` 按裁定 6.4 定主题 → 分盘(事业 D10、财富 D2/D11/D1、婚恋 D9、手足 D3、居所 D4、子女 D7、父母 D12、学业 D24;1/6/8/9/12 宫整体不配;D9 不作无条件第二事业盘),问答侧也读这份;无路由时写「这项主题的分盘关联尚未评估」,并注明分盘内的互换和定位链未计算。 +- 验证与防复发:`tests/test_report_indirect_activation_2157.py`(12 条:一步自座、四步以上、互换、多星循环、缺节点、交点、上限;细运稳定 / 分裂 / 无范围);`tests/test_report_indirect_activation_2121.py` 等按原值、新值、原因更新。乔布斯 ±2 分钟细运稳定;±10 分钟分成水星、计都两支并列。 +- 尚未处理:多数用户没有声明范围,这张表里细运会不再使用;父母(D12 配第 4、9 宫)、学业(D24 配第 4、5 宫)的宫位映射和 D11 算法身份待占星师确认;UL/A7/A10 尚未加入路径计算;开篇指引和宫主页的「当前主星」直接检查仍含细运;细运相同而主题分盘上升在范围内换座时尚未标出。 +- 关联记录:BUG-2121、BUG-2123,占星师 2026-11-22 第 6 节。 +- 修复版本:`claude/astro-defg-2154`。 diff --git a/references/topic_varga_routes.json b/references/topic_varga_routes.json new file mode 100644 index 000000000..880392be4 --- /dev/null +++ b/references/topic_varga_routes.json @@ -0,0 +1,92 @@ +{ + "_comment": "BUG-2157 (G3): topic -> divisional charts, from the astrologer's ruling 2026-11-22 §6.4. A route proposal per topic, not a full traditional rule table per house. Shape: topics[] = {topic, label_zh, label_en, houses (natal houses whose topic this is), charts (preferred vargas in order; varga_full key prefixes such as D10), supporting_points (already-computed points read with the topic, e.g. A10 / UL / A7; not charts), limits_zh / limits_en (usage limits, plain text)}. houses_without_whole_house_chart lists houses that hold several topics and get no chart as a whole: the per-house report table never assigns them a chart, a topic route (e.g. parents) may still be used when the question names that topic. not_unconditional records charts that must not be used as an automatic second chart for a topic (D9 for career). D1 in a route means the natal chart itself (its paths are already the report's D1 paths). Readers: scripts/report_render/indirect_activation.py (report) and frontend chat-basis-completeness.ts (chat). Status pending_astrologer_review: the routes are hers; which named algorithm each varga uses (e.g. D11) is still to be confirmed.", + "schema": "jyotish.topic_varga_routes.v1", + "status": "pending_astrologer_review", + "source": "astrologer ruling 2026-11-22 §6.4 (topic routes)", + "topics": [ + { + "topic": "career", + "label_zh": "事业", + "label_en": "Career", + "houses": [10], + "charts": ["D10"], + "supporting_points": ["A10"], + "limits_zh": "D9 不是无条件的第二事业盘,用到时要说明具体辅助命题。", + "limits_en": "D9 is not an automatic second career chart; when it is used, the specific supporting question must be stated." + }, + { + "topic": "wealth", + "label_zh": "财富", + "label_en": "Wealth", + "houses": [2, 11], + "charts": ["D2", "D11", "D1"], + "supporting_points": [], + "limits_zh": "收入、利润、资源控制和留存分开看;D11 先确认所用算法的身份。", + "limits_en": "Income, profit, control of resources and retention are read separately; the algorithm used for D11 is to be confirmed first." + }, + { + "topic": "marriage", + "label_zh": "婚恋", + "label_en": "Relationships and marriage", + "houses": [7], + "charts": ["D9"], + "supporting_points": ["UL", "A7"], + "limits_zh": "恋爱、建立关系、法律婚姻不混用。", + "limits_en": "Romance, forming a relationship and legal marriage are not mixed." + }, + { + "topic": "siblings", + "label_zh": "手足", + "label_en": "Siblings", + "houses": [3], + "charts": ["D3"], + "supporting_points": [], + "limits_zh": "不直接替代第三宫的所有主题。", + "limits_en": "Does not stand in for every 3rd-house topic." + }, + { + "topic": "home", + "label_zh": "居所、住宅与长期迁移", + "label_en": "Home, residence and long-term relocation", + "houses": [4], + "charts": ["D4"], + "supporting_points": [], + "limits_zh": "具体的迁移事项另查相关本命和应期结构。", + "limits_en": "A specific move is checked separately in the related natal and timing structures." + }, + { + "topic": "children", + "label_zh": "子女", + "label_en": "Children", + "houses": [5], + "charts": ["D7"], + "supporting_points": [], + "limits_zh": "不把第五宫的所有问题都当作子女问题。", + "limits_en": "Not every 5th-house question is about children." + }, + { + "topic": "parents", + "label_zh": "父母", + "label_en": "Parents", + "houses": [4, 9], + "charts": ["D12"], + "supporting_points": [], + "limits_zh": "父母关系、资源、事件分别判断。", + "limits_en": "Relations with parents, their resources and events are judged separately." + }, + { + "topic": "education", + "label_zh": "学业", + "label_en": "Education", + "houses": [4, 5], + "charts": ["D24"], + "supporting_points": [], + "limits_zh": "与职业培训或工作成就按问题区分。", + "limits_en": "Kept apart from vocational training or work achievement, according to the question." + } + ], + "houses_without_whole_house_chart": [1, 6, 8, 9, 12], + "not_unconditional": [ + {"chart": "D9", "topic": "career", "note_zh": "D9 不是无条件的第二事业盘", "note_en": "D9 is not an automatic second career chart"} + ] +} diff --git a/references/yoga_rule_topics.v1.json b/references/yoga_rule_topics.v1.json index fd141126b..18496ac12 100644 --- a/references/yoga_rule_topics.v1.json +++ b/references/yoga_rule_topics.v1.json @@ -2,7 +2,7 @@ "schema": "yoga-rule-topics-v1", "status": "pending_astrologer_review", "built_from": "references/yoga_rules.json", - "built_from_sha256": "f5dc213593f3", + "built_from_sha256": "c0e7ef2a5195", "builder": "scripts/research/build_yoga_rule_topics.py", "rule": "A topic is assigned only when the rule's own effect text names the domain with a listed keyword; condition text is not read. unmapped = the text names no domain (待映射, never dropped). longevity, fame_authority and spirituality are recorded for review; no chat domain selects by them.", "rules": { @@ -4030,7 +4030,7 @@ "mapping": "keyword_proposal" }, "kalatra_dosha_mars_1_4_7_8_12": { - "name": "Mangal Dosha (Mars in 1/4/7/8/12)", + "name": "Mars Marriage-Related Placement (1/4/7/8/12 House Screen)", "category": "kalatra", "topics": [ "marriage" @@ -4038,12 +4038,10 @@ "matched_words": { "marriage": [ "marriage", - "spouse", - "婚", - "配偶" + "婚" ] }, - "basis_text": "Delayed marriage | Strained relationship with spouse | 婚姻延迟 | 配偶关系紧张", + "basis_text": "The Mars placement screen is met; the traditional relationship reading still depends on the reference point, restraining and mitigating conditions, and the chart as a whole | It does not establish delayed marriage or relationship strain | 命中这一火星位置筛查条件;关系层面的传统解释仍需结合参考点、制约与缓解条件及整体结构 | 不能据此确定婚姻延迟或关系紧张", "mapping": "keyword_proposal" }, "kalatra_dosha_mars_7": { diff --git a/references/yoga_rules.json b/references/yoga_rules.json index 5c7aa70f3..8b606a07d 100644 --- a/references/yoga_rules.json +++ b/references/yoga_rules.json @@ -4550,7 +4550,9 @@ ], "strength": "弱", "strength_en": "weak", - "enabled": true + "enabled": false, + "duplicate_of": "kalatra_dosha_mars_1_4_7_8_12", + "archived_reason": "BUG-2154 (astrologer ruling 2026-11-22 §3): same 1/4/7/8/12 condition as kalatra_dosha_mars_1_4_7_8_12; kept as an archived alias for old report ids, never executed or counted on its own." }, { "id": "ayur_yoga_strong", @@ -5968,9 +5970,9 @@ }, { "id": "kalatra_dosha_mars_1_4_7_8_12", - "name": "Mangal Dosha (Mars in 1/4/7/8/12)", - "name_cn": "火星婚姻煞(火星入1/4/7/8/12宫)", - "source": "BPHS", + "name": "Mars Marriage-Related Placement (1/4/7/8/12 House Screen)", + "name_cn": "火星婚姻相关配置(1/4/7/8/12宫筛查)", + "source": "当前采用的五宫筛查口径;具体原典定位待核", "bvr_id": "KT-D1", "category": "kalatra", "enabled": true, @@ -5978,12 +5980,12 @@ "strength": "弱", "strength_en": "weak", "effects": [ - "婚姻延迟", - "配偶关系紧张" + "命中这一火星位置筛查条件;关系层面的传统解释仍需结合参考点、制约与缓解条件及整体结构", + "不能据此确定婚姻延迟或关系紧张" ], "effects_en": [ - "Delayed marriage", - "Strained relationship with spouse" + "The Mars placement screen is met; the traditional relationship reading still depends on the reference point, restraining and mitigating conditions, and the chart as a whole", + "It does not establish delayed marriage or relationship strain" ], "logic": { "type": "in_houses", @@ -5995,7 +5997,19 @@ 8, 12 ] - } + }, + "legacy_name": "Mangal Dosha (Mars in 1/4/7/8/12)", + "legacy_source": "BPHS", + "source_en": "Current five-house screening profile; exact classical citation pending", + "source_verified": false, + "reference_point": "lagna", + "source_profile": "mars_marriage_five_house_screen_v1", + "aliases": [ + "kalatra_dosha_mars_7" + ], + "sync_note": "BUG-2154 (astrologer ruling 2026-11-22 §3): canonical entry for the Mars 1/4/7/8/12 screen; kalatra_dosha_mars_7 is an archived alias that resolves here. Report dedup key = dedup_key + reference_point + chart + source_profile.", + "reader_explanation": "命中这一火星位置筛查条件。关系层面的传统解释仍需结合参考点、制约与缓解条件及整体结构,不能据此确定婚姻延迟或关系紧张。", + "reader_explanation_en": "This Mars placement screen is met. The traditional relationship reading still depends on the reference point, restraining and mitigating conditions, and the chart as a whole; it does not establish delayed marriage or relationship strain." }, { "id": "ayur_yoga_saturn_strong", @@ -16764,5 +16778,5 @@ "bvr_chapter": "" } ], - "total_enabled_rules": 406 + "total_enabled_rules": 405 } diff --git a/scripts/annual_native/saham_traces.py b/scripts/annual_native/saham_traces.py index cdb7c9f30..1bb6551e1 100644 --- a/scripts/annual_native/saham_traces.py +++ b/scripts/annual_native/saham_traces.py @@ -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), diff --git a/scripts/pl9_full_data_export.py b/scripts/pl9_full_data_export.py index 0459dbca4..67cff5820 100644 --- a/scripts/pl9_full_data_export.py +++ b/scripts/pl9_full_data_export.py @@ -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"), {}) diff --git a/scripts/pl9_interpretation_packs.py b/scripts/pl9_interpretation_packs.py index 82c4796b5..3db946e34 100644 --- a/scripts/pl9_interpretation_packs.py +++ b/scripts/pl9_interpretation_packs.py @@ -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. diff --git a/scripts/pl9_reader_export.py b/scripts/pl9_reader_export.py index f48ffe3ae..bf88bed0c 100644 --- a/scripts/pl9_reader_export.py +++ b/scripts/pl9_reader_export.py @@ -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), '']) diff --git a/scripts/report_render/indirect_activation.py b/scripts/report_render/indirect_activation.py index a244ba3f3..854c7669c 100644 --- a/scripts/report_render/indirect_activation.py +++ b/scripts/report_render/indirect_activation.py @@ -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.", "", diff --git a/scripts/report_render/neecha_witness.py b/scripts/report_render/neecha_witness.py index ca9388d26..3417e8f5f 100644 --- a/scripts/report_render/neecha_witness.py +++ b/scripts/report_render/neecha_witness.py @@ -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: diff --git a/scripts/report_render/parity_chapters.py b/scripts/report_render/parity_chapters.py index c3b49f014..24c775b76 100644 --- a/scripts/report_render/parity_chapters.py +++ b/scripts/report_render/parity_chapters.py @@ -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: diff --git a/scripts/report_render/pd_range_stability.py b/scripts/report_render/pd_range_stability.py new file mode 100644 index 000000000..97acc7b97 --- /dev/null +++ b/scripts/report_render/pd_range_stability.py @@ -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) diff --git a/scripts/report_render/upstream_sync_chapters.py b/scripts/report_render/upstream_sync_chapters.py index 44ae76f18..09fd3d7cf 100644 --- a/scripts/report_render/upstream_sync_chapters.py +++ b/scripts/report_render/upstream_sync_chapters.py @@ -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, "")], ] diff --git a/scripts/report_render/yoga_rule_aliases.py b/scripts/report_render/yoga_rule_aliases.py new file mode 100644 index 000000000..83475f280 --- /dev/null +++ b/scripts/report_render/yoga_rule_aliases.py @@ -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@: 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() diff --git a/scripts/report_render/yoga_status_words.py b/scripts/report_render/yoga_status_words.py index 4e1acf710..bd6a64dac 100644 --- a/scripts/report_render/yoga_status_words.py +++ b/scripts/report_render/yoga_status_words.py @@ -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 diff --git a/scripts/tajika.py b/scripts/tajika.py index 873a27f40..6fc5395a7 100644 --- a/scripts/tajika.py +++ b/scripts/tajika.py @@ -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: diff --git a/scripts/yogas_doshas.py b/scripts/yogas_doshas.py index 166413abb..b3a41ff4d 100644 --- a/scripts/yogas_doshas.py +++ b/scripts/yogas_doshas.py @@ -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: diff --git a/tests/test_natal_vivaha_saham_2156.py b/tests/test_natal_vivaha_saham_2156.py new file mode 100644 index 000000000..209df6bc0 --- /dev/null +++ b/tests/test_natal_vivaha_saham_2156.py @@ -0,0 +1,89 @@ +"""BUG-2156 (占星师 2026-11-22 §5, F): natal Vivaha Saham — day/night swap and the +30° arc rule are separate steps. + +Formula A − B + C (PVR named profile, references/saham_rules.json): day/night only picks A and B; the +30° +is added when the zodiacal arc from B forward to A does not pass C. Edge cases the source does not spell out +(inclusive ends, A == B) are our documented choice in scripts/tajika.py, not a ruling. +Synthetic longitudes for the arithmetic; public fixtures (Jobs, Obama) for the rendered chapter. +""" + +from __future__ import annotations + +import pytest + +from scripts.annual_native.saham_traces import attach_formula_traces +from scripts.report_render.parity_chapters import VIVAH_CAPTION, vivah_saham_steps +from scripts.tajika import _formula_saham_trace +from tests.public_chart_reports import public_chart_reports + + +def _vivaha(venus: float, saturn: float, asc: float, *, day: bool) -> dict: + return _formula_saham_trace("Vivaha_Saham", {"Venus": venus, "Saturn": saturn}, asc, day, {}) + + +@pytest.mark.parametrize( + "day, venus, saturn, asc, passes, final", + [ + # Day: A = Venus, B = Saturn. Arc Saturn 50 → Venus 100. + (True, 100.0, 50.0, 70.0, True, 120.0), # C inside: no +30 + (True, 100.0, 50.0, 200.0, False, 280.0), # C outside: 250 + 30 + # Night: A = Saturn, B = Venus. Arc Venus 100 → Saturn 50 runs 310° forward. + (False, 100.0, 50.0, 200.0, True, 150.0), # night birth, C inside: no +30 (night is not the trigger) + (False, 100.0, 50.0, 70.0, False, 50.0), # C outside: 20 + 30 + ], +) +def test_day_night_times_trigger(day, venus, saturn, asc, passes, final) -> None: + trace = _vivaha(venus, saturn, asc, day=day) + assert trace["swaps_by_day_night"] is True + assert trace["formula_operands"] == (["Venus", "Saturn", "Ascendant"] if day else ["Saturn", "Venus", "Ascendant"]) + assert trace["arc_passes_c"] is passes and trace["zodiacal_order_exception_applied"] is (not passes) + assert trace["longitude"] == pytest.approx(final) + assert 0 <= trace["longitude"] < 360 + + +def test_arc_crossing_zero_aries() -> None: + inside = _vivaha(10.0, 350.0, 5.0, day=True) # arc 350 → 10 wraps through 0 + assert inside["arc_b_to_a"] == pytest.approx(20.0) and inside["arc_passes_c"] is True + assert inside["longitude"] == pytest.approx(25.0) + outside = _vivaha(10.0, 350.0, 180.0, day=True) + assert outside["arc_passes_c"] is False and outside["longitude"] == pytest.approx(230.0) + wrap = _vivaha(10.0, 350.0, 345.0, day=True) # 345 + 20 = 365 → 5, then outside: +30 → 35 + assert wrap["longitude"] == pytest.approx(35.0) + + +def test_a_equals_b_and_c_at_an_end_point() -> None: + # A == B: zero-length arc; it passes C only when C sits on that same point (our choice). + assert _vivaha(40.0, 40.0, 40.0, day=True)["arc_passes_c"] is True + same = _vivaha(40.0, 40.0, 41.0, day=True) + assert same["arc_passes_c"] is False and same["longitude"] == pytest.approx(71.0) + # C exactly at B or at A counts as on the arc: no +30 (inclusive ends, our choice). + assert _vivaha(100.0, 50.0, 50.0, day=True)["zodiacal_order_exception_applied"] is False + assert _vivaha(100.0, 50.0, 100.0, day=True)["zodiacal_order_exception_applied"] is False + + +def test_fallback_trace_text_is_the_vivaha_formula() -> None: + results = {"vivah_saham": {"name": "Vivaha Saham", "longitude": 12.0}} + # 原值:缺公式元数据时写「Asc + Venus - Mars」;新值:白天 Venus − Saturn、夜间 Saturn − Venus;原因:BUG-2156 + assert attach_formula_traces(results, is_day=True)[0]["rule"] == "Asc + Venus - Saturn" + assert attach_formula_traces(results, is_day=False)[0]["rule"] == "Asc + Saturn - Venus" + + +@pytest.mark.parametrize("case, final, plus_thirty", [("steve_jobs_1955_aa", 90.4927, False), ("barack_obama_1961_aa", 169.7212, True)]) +def test_natal_chapter_lists_every_step_and_never_the_annual_value(case, final, plus_thirty) -> None: + packet, chinese, english = public_chart_reports(case) + sahams = packet["advanced_systems"]["sahams"] + assert sahams["chart_kind"] == "natal" and sahams["vivah_saham"]["longitude"] == pytest.approx(final) + annual = packet["worksheets"]["timing_and_predictive_systems"]["annual_tajika_pack"]["sahams"]["data"] + assert annual.get("chart_kind") in (None, "varsha") + steps = dict(vivah_saham_steps(packet, "zh")) + assert steps["盘种"] == "本命盘" and steps["昼夜依据"].startswith("夜间出生") + assert steps["公式(A − B + C)"] == "土星 − 金星 + 上升" + assert steps["是否加 30°"].startswith("是" if plus_thirty else "否") + assert steps["最终值(归一到 0–360°)"].startswith(f"{final:.4f}°") + for text, caption in ((chinese, VIVAH_CAPTION["zh"]), (english, VIVAH_CAPTION["en"])): + start = text.index("### 本命 Vivah Saham" if text is chinese else "### Natal Vivah Saham") + chapter = text[start:text.index("\n### ", start + 5)] + assert caption in chapter and f"{final:.4f}°" in chapter + annual_value = annual["vivah_saham"]["longitude"] + assert f"{annual_value:.4f}" not in chapter + assert "《" not in chapter and "Integrated Approach" not in chapter + assert "本命婚姻Saham,采用PVR Saham计算口径;本命书例数值对照待完成。" == VIVAH_CAPTION["zh"] diff --git a/tests/test_reading_facts_2106.py b/tests/test_reading_facts_2106.py index a03bb1f82..311d029c5 100644 --- a/tests/test_reading_facts_2106.py +++ b/tests/test_reading_facts_2106.py @@ -33,7 +33,9 @@ def test_rules_sharing_an_english_name_keep_their_own_chinese_name() -> None: # 「火星婚姻煞(火星入1/4/7/8/12宫)」;新值:各按 rule_id 取引擎行自己的 name_cn;原因:BUG-2106。 facts = _facts("steve_jobs_1955_aa") assert _yoga(facts, "ev:yoga:amala_yoga@D1")["name_cn"] == "无瑕格局" - assert _yoga(facts, "ev:yoga:kalatra_dosha_mars_7@D1")["name_cn"] == "火星障碍(火星在关键宫)" + # 原值:kalatra_dosha_mars_7 印「火星障碍(火星在关键宫)」;新值:别名不再执行,规范规则印规范中文名 + # 原因:BUG-2154(占星师 2026-11-22 §3) + assert _yoga(facts, "ev:yoga:kalatra_dosha_mars_1_4_7_8_12@D1")["name_cn"] == "火星婚姻相关配置(1/4/7/8/12宫筛查)" def test_neecha_bhanga_row_names_the_fallen_planet_and_the_witnesses_as_two_roles() -> None: diff --git a/tests/test_report_english_edition.py b/tests/test_report_english_edition.py index 63f06d5ab..a35015a8c 100644 --- a/tests/test_report_english_edition.py +++ b/tests/test_report_english_edition.py @@ -130,7 +130,9 @@ def test_english_dignity_takes_the_english_half() -> None: # 原值: _dignity_label("落陷取消(Neecha Bhanga)", "en") == "Neecha Bhanga" # 新值: "Debilitated; the adverse effect of this placement has mitigating factors, but this does not mean the difficulties are gone" # 原因: BUG-2105 the engine status overwrote the debilitation in every dignity cell - assert _dignity_label("落陷取消(Neecha Bhanga)", "en") == "Debilitated; the adverse effect of this placement has mitigating factors, but this does not mean the difficulties are gone" + # 原值: "Debilitated; the adverse effect of this placement has mitigating factors, but this does not mean the difficulties are gone" + # 新值: "Debilitated; mitigating conditions present¹";原因: BUG-2155(占星师 2026-11-22 §4) + assert _dignity_label("落陷取消(Neecha Bhanga)", "en") == "Debilitated; mitigating conditions present¹" assert _dignity_label("入旺(Exalted)") == "入旺" diff --git a/tests/test_report_fixes_2105.py b/tests/test_report_fixes_2105.py index b7df8927f..937789583 100644 --- a/tests/test_report_fixes_2105.py +++ b/tests/test_report_fixes_2105.py @@ -94,12 +94,14 @@ def test_neecha_bhanga_dignity_cells_keep_the_debilitation(): zh, en = _dignity_cells(chinese, _DIGNITY_HEADERS_ZH), _dignity_cells(english, _DIGNITY_HEADERS_EN) assert "落陷取消" not in zh and "Neecha Bhanga" not in en # Planet table, both house-lord tables (2 rows each), raw positions, Shodashvarga matrix. - assert zh.count("落陷;这一配置的不利影响有缓解因素,但不能据此认为困难全部消失") == 7 - assert en.count("Debilitated; the adverse effect of this placement has mitigating factors, but this does not mean the difficulties are gone") == 7 - assert "| 木星 | 土星 | 太阳 | 金星 | 木星 | 落陷;这一配置的不利影响有缓解因素,但不能据此认为困难全部消失 | 0.96 |" in chinese - assert "| Jupiter | Saturn | Sun | Venus | Jupiter | Debilitated; the adverse effect of this placement has mitigating factors, but this does not mean the difficulties are gone | 0.96 |" in english + # 原值:七格都印 BUG-2030 长句;新值:短句「落陷;另有缓解条件¹」,长句只在格局页写一次 + # 原因:BUG-2155(占星师 2026-11-22 §4) + assert zh.count("落陷;另有缓解条件¹") == 7 + assert en.count("Debilitated; mitigating conditions present¹") == 7 + assert "| 木星 | 土星 | 太阳 | 金星 | 木星 | 落陷;另有缓解条件¹ | 0.96 |" in chinese + assert "| Jupiter | Saturn | Sun | Venus | Jupiter | Debilitated; mitigating conditions present¹ | 0.96 |" in english _packet, jobs_zh, _jobs_en = public_chart_reports(JOBS) - assert "这一配置的不利影响有缓解因素" not in jobs_zh # no cancellation on this chart + assert "另有缓解条件" not in jobs_zh # no cancellation on this chart # 3. Yoga pages keyed by rule ---------------------------------------------------------------------- @@ -107,15 +109,15 @@ def test_neecha_bhanga_dignity_cells_keep_the_debilitation(): def test_yoga_pages_are_keyed_by_rule_in_both_editions(): _packet, chinese, english = public_chart_reports(JOBS) zh, en = _section_pages(chinese, "### 瑜伽解释"), _section_pages(english, "### Yoga interpretation") - assert len(zh) == len(en) == 54 + # 原值:54 页;新值:53 页;原因:BUG-2154,kalatra_dosha_mars_7 归档为别名,不再单独一页 + assert len(zh) == len(en) == 53 assert len(set(en)) == len(en) and len(set(zh)) == len(zh) for title in ("Amala Yoga (Benefics in the 10th/11th houses)", "Amala Yoga (Only benefics in the 10th house)", "Durmukha Yoga (Malefic in the 2nd house)", - "Mangal Dosha (Mars in 1/4/7/8/12) (Mars in house 8)", - # 原值: "Mangal Dosha (Mars in 1/4/7/8/12) (rule from classical texts)" - # 新值: 不写出处,另一条已有条件说明,所以这条不加括号 - # 原因: BUG-2129 负责人 2026-11-21:报告不写书名出处 - "Mangal Dosha (Mars in 1/4/7/8/12)"): + # 原值: "Mangal Dosha (Mars in 1/4/7/8/12) (Mars in house 8)" 与 "Mangal Dosha (Mars in 1/4/7/8/12)" 两页 + # 新值: 规范规则一页,英文名改为规范名 + # 原因: BUG-2154(占星师 2026-11-22 §3):同一条件的两条规则只留规范入口 + "Mars Marriage-Related Placement (1/4/7/8/12 House Screen)"): assert title in en assert not any("rule from" in title for title in en) assert "Combination: ." not in english and "Combination: ;" not in english @@ -137,13 +139,15 @@ def test_yoga_pages_are_keyed_by_rule_in_both_editions(): def test_candidate_table_rows_keep_their_own_rule_names(): packet, chinese, english = public_chart_reports(JOBS) layer_ids = [row.get("rule_id") for row in packet["report_yoga_conditions"]["rows"]] - assert "amala_yoga" in layer_ids and "kalatra_dosha_mars_7" in layer_ids + # 原值:kalatra_dosha_mars_7 在层里;新值:规范规则在、别名不在;原因:BUG-2154 + assert "amala_yoga" in layer_ids and "kalatra_dosha_mars_1_4_7_8_12" in layer_ids and "kalatra_dosha_mars_7" not in layer_ids zh_rows = [row for header, body in _tables(chinese) if header[:2] == ["瑜伽", "状态"] for row in body] en_rows = [row for header, body in _tables(english) if header[:2] == ["Yoga candidate", "Status"] for row in body] zh_names = {row[0]: row for row in zh_rows} assert "无瑕格局" in zh_names and "纯净瑜伽" not in zh_names assert zh_names["无瑕格局"][4] == "吉星在10/11宫" - assert "火星障碍(火星在关键宫)" in zh_names and "火星婚姻煞(火星入1/4/7/8/12宫)" not in zh_names + # 原值:「火星障碍(火星在关键宫)」在表里;新值:规范中文名一行;原因:BUG-2154 + assert "火星婚姻相关配置(1/4/7/8/12宫筛查)" in zh_names and "火星障碍(火星在关键宫)" not in zh_names amala_en = [row for row in en_rows if row[0] == "Amala Yoga"] assert amala_en and all(row[4] == "Benefics in the 10th/11th houses" for row in amala_en) # BUG-2089 same-fact merge still joins the two names. diff --git a/tests/test_report_indirect_activation_2121.py b/tests/test_report_indirect_activation_2121.py index a7811941d..3910d29a3 100644 --- a/tests/test_report_indirect_activation_2121.py +++ b/tests/test_report_indirect_activation_2121.py @@ -61,21 +61,30 @@ def _section(markdown: str, title: str) -> str: def test_five_paths_are_kept_apart_and_the_table_is_in_both_editions(case_id: str) -> None: packet, chinese, english = public_chart_reports(case_id) structure = build_indirect_activation(packet) - assert structure["status"] == "computed" and structure["levels_used"] == ["md", "ad", "pd"] + # 原值:levels_used == ["md", "ad", "pd"](夹具没有出生时间范围,按「确认到分钟」用细运) + # 新值:["md", "ad"];没有可定义的出生时间范围时细运稳定性未评估,细运不用 + # 原因:BUG-2157 G1(占星师 2026-11-22 §6.2):不用「确认到分钟」作开关,不假定前后 1 分钟 + assert structure["status"] == "computed" and structure["levels_used"] == ["md", "ad"] for number in range(1, 13): paths = structure["houses"][str(number)]["paths"] assert tuple(paths) == PATHS - assert all(path["status"] in {"matched", "not_matched", "not_determined"} for path in paths.values()) + # BUG-2157 G3: a house the topic routes give no chart is not_assessed (not "未判定", not "no"). + assert all(path["status"] in {"matched", "not_matched", "not_determined", "not_assessed"} for path in paths.values()) zh = _section(chinese, "### 当前周期主星与各宫的关联路径") en = _section(english, "### How the current period lords connect to each house") assert "| 宫位 | 宫主 | 直接(宫主或落宫) | 同宫或相位 | 互换星座 | 定位链 | 主题分盘 |" in zh - assert "所用周期层级:Vimshottari 大运、小运、细运。" in zh and "不是激活判定,也不打分" in zh + assert "所用周期层级:Vimshottari 大运、小运。" in zh and "不是激活判定,也不打分" in zh + assert "- 细运稳定性未评估:没有出生时间的误差范围。细运不参加下列关联;大运和小运照常使用。" in zh assert "| House | Lord | Direct (lord or occupant) | Same sign or aspect | Sign exchange | Dispositor chain | Topic varga |" in en - assert "Period levels used: Vimshottari MD, AD, PD." in en and "It is not an activation verdict" in en + assert "Period levels used: Vimshottari MD, AD." in en and "It is not an activation verdict" in en + assert "- PD stability not assessed: no birth-time margin is available." in en assert zh.count("\n| ") == 14 and en.count("\n| ") == 14 # header, rule, houses 1–12 # Not computable is 未判定, never 否; no internal keys in the Chinese edition. - assert "| 否 |" not in zh and "未判定(本报告没有给这一宫指定主题分盘)" in zh - for key in ("matched", "not_determined", "same_sign", "topic_varga", "dispositor_chain", "md", "pd"): + # 原值:「未判定(本报告没有给这一宫指定主题分盘)」;新值:「这项主题的分盘关联尚未评估」;原因:BUG-2157 G3 + assert "| 否 |" not in zh and "这项主题的分盘关联尚未评估" in zh and "本报告没有给这一宫指定主题分盘" not in zh + assert "The divisional link for this topic has not been assessed" in en + for key in ("matched", "not_determined", "not_assessed", "same_sign", "topic_varga", "dispositor_chain", "md", "pd", + "own_sign", "loop", "truncated"): assert key not in zh.replace("Vimshottari", ""), key # The table sits right after the house-lord table. assert chinese.index("### 当前周期主星与各宫的关联路径") > chinese.index("| 宫位 | 星座 | 宫主 | 宫主落位 | 宫主尊贵 |") @@ -96,19 +105,25 @@ def test_named_paths_on_the_public_charts() -> None: # The chain is stated hop by hop and stops when it comes back to a planet already in it. chain = jobs["2"]["paths"]["dispositor_chain"] assert [step["planet"] for step in chain["chain"]] == ["Venus", "Jupiter", "Mercury", "Saturn"] - assert chain["chain_end"] == "loop" and [hit["hop"] for hit in chain["hits"]] == [1, 2] - # Synthetic: a five-planet chain (Sun → Venus → Mercury → Moon → Jupiter) is cut at three steps. + # 原值:hops [1, 2](第 2 步到细运主星水星);新值:[1];原因:BUG-2157 G1,夹具没有出生时间范围,细运不用 + assert chain["chain_end"] == "loop" and [hit["hop"] for hit in chain["hits"]] == [1] + assert chain["loop_members"] == ["Venus", "Jupiter", "Mercury", "Saturn"] + # Synthetic: a five-planet chain (Sun → Venus → Mercury → Moon → Jupiter). + # 原值:在第 3 步截断(depth_cap),链只有 4 项;新值:追到终点,木星在射手座自座;显示仍最多 3 步 + # 原因:BUG-2157 G2(占星师 2026-11-22 §6.3):三步是显示长度,计算追到终点 capped = build_indirect_activation(_synthetic({**_CHART, "Sun": "Taurus", "Venus": "Gemini", "Mercury": "Cancer", "Moon": "Sagittarius"}))["houses"]["5"]["paths"]["dispositor_chain"] - assert [step["planet"] for step in capped["chain"]] == ["Sun", "Venus", "Mercury", "Moon"] - assert capped["chain_end"] == "depth_cap" and capped["max_hops"] == 3 + assert [step["planet"] for step in capped["chain"]] == ["Sun", "Venus", "Mercury", "Moon", "Jupiter"] + assert capped["chain_end"] == "own_sign" and capped["display_steps"] == 3 + assert path_cell(capped, "zh").startswith("太阳在金牛座→金星在双子座→水星在巨蟹座→月亮在射手座→…(共 4 步,止于自座)") # Mars rules houses 3 and 8 and no path reaches them: computed as no match, not unknown. assert all(jobs["3"]["paths"][name]["status"] == "not_matched" for name in PATHS[:4]) obama = build_indirect_activation(public_chart_reports("barack_obama_1961_aa")[0])["houses"] chain = obama["3"]["paths"]["dispositor_chain"] assert chain["chain_end"] == "own_sign" and chain["hits"][0]["lord"] == "Saturn" and chain["hits"][0]["hop"] == 1 varga = obama["10"]["paths"]["topic_varga"] - assert varga["charts"] == ["D10_Dasamsa", "D9_Navamsa"] + # 原值:["D10_Dasamsa", "D9_Navamsa"];新值:只有 D10;原因:BUG-2157 G3,D9 不是无条件的第二事业盘 + assert varga["charts"] == ["D10_Dasamsa"] and varga["not_computed_in_vargas"] == ["sign_exchange", "dispositor_chain"] assert path_cell(varga, "zh").startswith("D10 中土星(大运主星)是第 10 宫宫主") @@ -120,17 +135,24 @@ def test_house_lord_pages_and_domain_summary_name_another_path(case_id: str) -> "不过,罗睺(大运主星)与第 2 宫宫主金星同在射手座(同一星座,不是精确合相)。") in chinese assert ("this direct-lord check alone does not establish whether the house is activated indirectly. " "However, Rahu (MD lord) shares Sagittarius with the lord of house 2, Venus (same sign, not an exact conjunction).") in english + # 原值:「不过,水星(细运主星)落在第 5 宫。」;新值:小运主星木星的相位;原因:BUG-2157 G1,夹具不用细运 assert ("土星不在当前三级大运里;这只说明这条直接路径没有对上,第5宫是否通过其他路径被带动,单凭这一项看不出来。" - "不过,水星(细运主星)落在第 5 宫。") in chinese - assert "whether house 5 is activated indirectly. However, Mercury (PD lord) occupies house 5." in english - # Mars (houses 3 and 8): no path connects, the sentence stays as it was. - assert "第3宫是否通过其他路径被带动,单凭这一项看不出来。\n" in chinese - assert "whether house 3 is activated indirectly.\n" in english + "不过,木星(小运主星)从第 10 宫相位第 5 宫宫主土星所在的第 2 宫(第 5 宫特殊相位)。") in chinese + assert "whether house 5 is activated indirectly. However, Jupiter (AD lord) aspects the lord of house 5" in english + # 原值:火星(第 3、8 宫)没有路径,句子不变;新值:第 3 宫经 D3(手足)路由连到大运主星罗睺;第 8 宫仍不变 + # 原因:BUG-2157 G3 按主题给第 3 宫 D3;第 8 宫不整体指定分盘 + assert "第3宫是否通过其他路径被带动,单凭这一项看不出来。不过,D3 中罗睺(大运主星)与第 3 宫宫主火星同在白羊座" in chinese + assert "第8宫是否通过其他路径被带动,单凭这一项看不出来。\n" in chinese + assert "whether house 8 is activated indirectly.\n" in english else: assert ("第7宫是否通过其他路径被带动,单凭这一项看不出来。不过,土星(大运主星)从第 1 宫相位第 7 宫(第 7 宫相位)。") in chinese assert "whether house 7 is activated indirectly. However, Saturn (MD lord) aspects house 7 from house 1 (7th-house aspect)." in english - assert "第4宫是否通过其他路径被带动,单凭这一项看不出来。\n" in chinese - assert "whether house 4 is activated indirectly.\n" in english + # 原值:第 4 宫没有其他路径;新值:D4(居所)里大运主星土星是第 4 宫宫主;第 5 宫没有路径,句子不变 + # 原因:BUG-2157 G3 按主题给第 4 宫 D4 + assert "第4宫是否通过其他路径被带动,单凭这一项看不出来。不过,D4(居所、住宅与长期迁移)中土星(大运主星)是第 4 宫宫主。" in chinese + assert "However, in D4 (Home, residence and long-term relocation), Saturn (MD lord) is the lord of house 4." in english + assert "第5宫是否通过其他路径被带动,单凭这一项看不出来。\n" in chinese + assert "whether house 5 is activated indirectly.\n" in english def test_sign_exchange_with_a_period_lord_is_its_own_path() -> None: @@ -155,19 +177,45 @@ def test_two_planets_merely_in_d9_are_not_a_divisional_link() -> None: assert path_cell(path, "zh") == "未对上" and path_cell(path, "en") == "No match" -def test_pd_is_left_out_when_the_birth_minute_is_not_confirmed() -> None: - packet = copy.deepcopy(public_chart_reports("steve_jobs_1955_aa")[0]) - packet["worksheets"]["advanced_systems"].pop("indirect_activation", None) - packet["report_birth_window"] = {"source": "user_stated", "before_minutes": 10, "after_minutes": 10} - structure = build_indirect_activation(packet) - assert structure["levels_used"] == ["md", "ad"] - assert structure["pd"] == {"used": False, "reason": "birth_time_not_minute_confirmed"} - assert "- 细运没有使用:出生时间没有确认到分钟。" in table_lines(structure, "zh") - assert "- PD not used: the birth time is not confirmed to the minute." in table_lines(structure, "en") - # Mercury was only the PD lord: without PD, house 5 is no longer reached through Mercury. - assert all(hit["lord"] != "Mercury" for name in PATHS for hit in structure["houses"]["5"]["paths"][name]["hits"]) - packet["report_birth_window"] = {"source": "confirmed_minute", "before_minutes": 1, "after_minutes": 1} - assert build_indirect_activation(packet)["levels_used"] == ["md", "ad", "pd"] +def test_pd_follows_the_declared_range_not_a_minute_label() -> None: + """BUG-2157 G1 (占星师 2026-11-22 §6.2): stable / split / no range. + + 原值(test_pd_is_left_out_when_the_birth_minute_is_not_confirmed):user_stated ±10 分钟 → 细运不用, + reason birth_time_not_minute_confirmed;confirmed_minute → 用细运。新值:看范围两端的细运; + confirmed_minute 没有范围 → 细运稳定性未评估。原因:「确认到分钟」不能为细运担保。 + Jobs: reported 19:15, current PD Mercury, the PD boundary sits at 19:17:50 (computed). + """ + base = copy.deepcopy(public_chart_reports("steve_jobs_1955_aa")[0]) + base["worksheets"]["advanced_systems"].pop("indirect_activation", None) + + def run(window): + packet = copy.deepcopy(base) + packet.pop("pd_range_stability", None) + if window is not None: + packet["report_birth_window"] = window + return build_indirect_activation(packet) + + stable = run({"source": "user_stated", "before_minutes": 2, "after_minutes": 2}) + assert stable["levels_used"] == ["md", "ad", "pd"] and stable["pd"]["used"] is True + assert stable["pd"]["stability"]["checked_ranges"] == [{"from": "1955-02-24T19:13:00", "to": "1955-02-24T19:17:00"}] + assert "- 细运:在出生时间范围 19:13:00–19:17:00 的两端当前细运都是水星细运,范围内没有细运交界,本表使用细运。" in table_lines(stable, "zh") + split = run({"source": "user_stated", "before_minutes": 10, "after_minutes": 10}) + assert split["levels_used"] == ["md", "ad"] and split["pd"] == {**split["pd"], "used": False, "reason": "pd_range_split"} + branches = [(b["from"][11:], b["to"][11:], b["pd"]) for b in split["pd"]["stability"]["branches"]] + assert branches == [("19:05:00", "19:17:50", "Mercury"), ("19:17:50", "19:25:00", "Ketu")] + zh = table_lines(split, "zh") + assert "- 细运按出生时间分支:19:05:00–19:17:50 为水星细运;19:17:50–19:25:00 为计都细运。本表不在其中选一个,细运不参加下列关联;大运和小运照常使用。" in zh + assert any(line.startswith("- The PD branches with the birth time: 19:05:00–19:17:50: Mercury PD; 19:17:50–19:25:00: Ketu PD.") for line in table_lines(split, "en")) + # Mercury was only the PD lord: without PD, house 5 is not reached through Mercury. + assert all(hit["lord"] != "Mercury" for name in PATHS for hit in split["houses"]["5"]["paths"][name]["hits"]) + for window, reason in (({"source": "confirmed_minute", "before_minutes": 1, "after_minutes": 1}, "minute_without_range"), + ({"source": "default_unknown_30", "before_minutes": 30, "after_minutes": 30}, "trial_range_only"), + (None, "no_birth_window")): + structure = run(window) + assert structure["levels_used"] == ["md", "ad"], window + assert structure["pd"]["reason"] == "pd_stability_not_assessed" and structure["pd"]["stability"]["reason"] == reason + assert "- 细运稳定性未评估:出生时间只填写到分钟,没有误差范围,不按前后 1 分钟假定。细运不参加下列关联;大运和小运照常使用。" in \ + table_lines(run({"source": "confirmed_minute", "before_minutes": 1, "after_minutes": 1}), "zh") def test_missing_input_is_not_determined_never_no() -> None: @@ -179,7 +227,9 @@ def test_missing_input_is_not_determined_never_no() -> None: assert connection_sentence(structure, 1, "zh") == "" and connection_sentence(structure, 1, "en") == "" # A house without a topic varga, and a topic varga that did not come back: both unknown, not "no". houses = build_indirect_activation(_synthetic(_CHART))["houses"] - assert path_cell(houses["3"]["paths"]["topic_varga"], "zh") == "未判定(本报告没有给这一宫指定主题分盘)" + # 原值:第 3 宫「未判定(本报告没有给这一宫指定主题分盘)」;新值:第 3 宫有 D3 路由,第 1 宫写「这项主题的分盘关联尚未评估」 + # 原因:BUG-2157 G3 + assert path_cell(houses["1"]["paths"]["topic_varga"], "zh") == "这项主题的分盘关联尚未评估" assert path_cell(houses["7"]["paths"]["topic_varga"], "zh") == "未判定(主题分盘没有随报告返回)" diff --git a/tests/test_report_indirect_activation_2157.py b/tests/test_report_indirect_activation_2157.py new file mode 100644 index 000000000..b65b9f23a --- /dev/null +++ b/tests/test_report_indirect_activation_2157.py @@ -0,0 +1,164 @@ +"""BUG-2157 (占星师 2026-11-22 §6): dispositor chain to its end, topic varga routes, no double counting. + +G1 (PD by the declared range) is tested in tests/test_report_indirect_activation_2121.py on the Jobs fixture. +Public fixtures where they have the case; synthetic charts (house lords and signs only) for the rest. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from scripts.report_render import indirect_activation as ia +from scripts.report_render.indirect_activation import _chain, build_indirect_activation, house_routes, path_cell +from scripts.report_render.pd_range_stability import cycle_position, periods_at +from tests.public_chart_reports import public_chart_reports +from tests.test_report_indirect_activation_2121 import _CHART, _synthetic + +ROUTES = Path(__file__).resolve().parents[1] / "references" / "topic_varga_routes.json" + + +def _planets(signs: dict[str, str]) -> dict[str, dict]: + return {name: {"sign": sign} for name, sign in signs.items()} + + +# G2 — the chain ------------------------------------------------------------------------------------- + +def test_one_step_own_sign_on_a_public_chart() -> None: + obama = build_indirect_activation(public_chart_reports("barack_obama_1961_aa")[0])["houses"] + chain = obama["3"]["paths"]["dispositor_chain"] + assert [step["planet"] for step in chain["chain"]] == ["Jupiter", "Saturn"] + assert chain["chain_end"] == "own_sign" and chain["start"] == "Jupiter" and chain["reference_chart"] == "D1" + assert path_cell(chain, "zh").startswith("木星在摩羯座→土星在摩羯座(止于自座):第 1 步到土星") + + +def test_four_step_path_is_computed_past_the_display_length() -> None: + # Jobs house 11: Moon → Jupiter → Mercury → Saturn → (Venus) → loop; four hops, three shown. + jobs = build_indirect_activation(public_chart_reports("steve_jobs_1955_aa")[0])["houses"] + chain = jobs["11"]["paths"]["dispositor_chain"] + assert [step["planet"] for step in chain["chain"]] == ["Moon", "Jupiter", "Mercury", "Saturn", "Venus"] + assert chain["chain_end"] == "loop" and chain["loop_members"] == ["Jupiter", "Mercury", "Saturn", "Venus"] + assert path_cell(chain, "zh").startswith( + "月亮在双鱼座→木星在双子座→水星在摩羯座→土星在天秤座→…(共 4 步,止于循环:木星、水星、土星、金星)") + assert "→ … (4 steps, ends: loop: Jupiter, Mercury, Saturn, Venus)" in path_cell(chain, "en") + # Synthetic: a hit beyond the display length still counts (MD lord Mars at hop 4). + signs = {**_CHART, "Sun": "Taurus", "Venus": "Gemini", "Mercury": "Cancer", "Moon": "Aries", "Mars": "Aries"} + deep = build_indirect_activation(_synthetic(signs))["houses"]["5"]["paths"]["dispositor_chain"] + assert [step["planet"] for step in deep["chain"]] == ["Sun", "Venus", "Mercury", "Moon", "Mars"] + assert deep["status"] == "matched" and [(hit["lord"], hit["hop"]) for hit in deep["hits"]] == [("Mercury", 2), ("Mars", 4)] + + +def test_mutual_exchange_is_a_two_planet_loop() -> None: + # Synthetic: Mars in Cancer, Moon in Aries — the 4th lord's chain is Moon → Mars → Moon. + chain, end, members = _chain("Moon", _planets(_CHART)) + assert [step["planet"] for step in chain] == ["Moon", "Mars"] and end == "loop" and members == ["Moon", "Mars"] + + +def test_multi_planet_loop_counts_each_planet_once() -> None: + jobs = build_indirect_activation(public_chart_reports("steve_jobs_1955_aa")[0])["houses"] + chain = jobs["2"]["paths"]["dispositor_chain"] + assert chain["loop_members"] == ["Venus", "Jupiter", "Mercury", "Saturn"] + assert len({hit["lord"] for hit in chain["hits"]}) == len(chain["hits"]) + + +def test_missing_position_ends_the_chain_as_missing_not_as_no() -> None: + signs = {key: value for key, value in _CHART.items() if key != "Saturn"} + signs["Mercury"] = "Capricorn" # Mercury's dispositor Saturn has no position + chain, end, _members = _chain("Mercury", _planets(signs)) + assert [step["planet"] for step in chain] == ["Mercury"] and end == "sign_missing" + path = build_indirect_activation(_synthetic({**signs, "Sun": "Gemini"}))["houses"]["5"]["paths"]["dispositor_chain"] + assert path["chain_end"] == "sign_missing" and "止于缺失" in path_cell(path, "zh") + + +def test_node_convention_is_fixed_sign_lord_only() -> None: + # Rahu as a period lord is never reached by dispositorship: no sign has Rahu as its lord here. + assert ia.NODE_DISPOSITOR_CONVENTION == "sign_lord_only_no_node_co_lordship" + chain, end, _ = _chain("Rahu", _planets({**_CHART, "Rahu": "Aquarius", "Saturn": "Capricorn"})) + assert [step["planet"] for step in chain] == ["Rahu", "Saturn"] and end == "own_sign" + structure = build_indirect_activation(public_chart_reports("steve_jobs_1955_aa")[0]) + assert structure["method"]["node_dispositor"] == "sign_lord_only_no_node_co_lordship" + assert all(hit["lord"] != "Rahu" for row in structure["houses"].values() + for hit in row["paths"]["dispositor_chain"].get("hits", [])) + + +def test_hard_cap_is_truncated_never_not_connected(monkeypatch: pytest.MonkeyPatch) -> None: + chain, end, _ = _chain("Sun", _planets({**_CHART, "Sun": "Taurus", "Venus": "Gemini", "Mercury": "Cancer", + "Moon": "Sagittarius"}), cap=1) + assert end == "truncated" and len(chain) == 2 + monkeypatch.setattr(ia, "DISPOSITOR_SAFETY_CAP", 0) + # House 1 (Mars in Cancer → Moon in Aries → loop) without a hit: the cap makes it not determined. + signs = {**_CHART, "Mars": "Cancer", "Moon": "Aries"} + path = build_indirect_activation(_synthetic(signs, dasha=True))["houses"]["1"]["paths"]["dispositor_chain"] + assert path["chain_end"] == "truncated" + if not path["hits"]: + assert path["status"] == "not_determined" and path["reason"] == "chain_truncated" + assert path_cell(path, "zh").startswith("未判定(定位链超过计算上限被截断,没有算完") + assert "未对上" not in path_cell(path, "zh") + + +# G3 — topic routes --------------------------------------------------------------------------------- + +def test_topic_routes_file_shape() -> None: + data = json.loads(ROUTES.read_text(encoding="utf-8")) + assert data["_comment"] and data["schema"] == "jyotish.topic_varga_routes.v1" + by_topic = {item["topic"]: item for item in data["topics"]} + assert by_topic["career"]["charts"] == ["D10"] and "A10" in by_topic["career"]["supporting_points"] + assert by_topic["wealth"]["charts"] == ["D2", "D11", "D1"] + assert by_topic["marriage"]["charts"] == ["D9"] and set(by_topic["marriage"]["supporting_points"]) == {"UL", "A7"} + assert [by_topic[key]["charts"] for key in ("siblings", "home", "children", "parents", "education")] == \ + [["D3"], ["D4"], ["D7"], ["D12"], ["D24"]] + assert data["houses_without_whole_house_chart"] == [1, 6, 8, 9, 12] + assert {"chart": "D9", "topic": "career"}.items() <= data["not_unconditional"][0].items() + for item in data["topics"]: + assert set(item) == {"topic", "label_zh", "label_en", "houses", "charts", "supporting_points", "limits_zh", "limits_en"} + + +def test_report_reads_the_routes_file() -> None: + assert [route["topic"] for route in house_routes(10)] == ["career"] + assert all("D9" not in route["charts"] for route in house_routes(10)) + assert [house_routes(n) for n in (1, 6, 8, 9, 12)] == [[], [], [], [], []] + assert [route["charts"] for route in house_routes(2)] == [["D2", "D11"]] # D1 is the natal paths already + structure = build_indirect_activation(public_chart_reports("steve_jobs_1955_aa")[0]) + assert structure["method"]["topic_routes"] == "references/topic_varga_routes.json" + assert structure["method"]["topic_vargas"]["4"] == ["D4", "D12", "D24"] + house4 = structure["houses"]["4"]["paths"]["topic_varga"] + assert house4["topics"] == ["home", "parents", "education"] + assert path_cell(house4, "zh").startswith("D4(居所、住宅与长期迁移)中") + for number in ("1", "6", "8", "9", "12"): + path = structure["houses"][number]["paths"]["topic_varga"] + assert path["status"] == "not_assessed" and path_cell(path, "zh") == "这项主题的分盘关联尚未评估" + + +def test_one_relation_is_not_counted_twice() -> None: + structure = build_indirect_activation(public_chart_reports("steve_jobs_1955_aa")[0]) + for row in structure["houses"].values(): + hits = row["paths"]["topic_varga"].get("hits", []) + keys = [(hit["chart"], hit["kind"], hit["lord"]) for hit in hits] + assert len(keys) == len(set(keys)) + chain_hits = [hit["lord"] for hit in row["paths"]["dispositor_chain"].get("hits", [])] + assert len(chain_hits) == len(set(chain_hits)) + + +# G1 arithmetic --------------------------------------------------------------------------------------- + +def test_vimshottari_position_is_continuous_across_a_nakshatra_line() -> None: + span = 360 / 27 + # End of Ashwini (Ketu, 7 years) meets the start of Bharani (Venus). + assert cycle_position(span - 1e-9) == pytest.approx(7.0, abs=1e-6) + assert cycle_position(span) == pytest.approx(7.0) + assert cycle_position(9 * span) == pytest.approx(120.0) + + +def test_recomputed_periods_match_the_engine_on_both_fixtures() -> None: + from datetime import datetime + + for case, expected in (("steve_jobs_1955_aa", ("Rahu", "Jupiter", "Mercury")), + ("barack_obama_1961_aa", ("Saturn", "Rahu", "Ketu"))): + packet = public_chart_reports(case)[0] + dasha = packet["worksheets"]["timing_and_predictive_systems"]["dasha"] + moon = packet["worksheets"]["d1_rasi_bhava"]["planets"]["Moon"]["degree_raw"] + birth = datetime.fromisoformat(dasha["birth_datetime"].replace(" ", "T")) + got = periods_at(moon, birth, datetime.fromisoformat(dasha["reference_date"]), dasha["year_days"]) + assert (got["md"], got["ad"], got["pd"]) == expected diff --git a/tests/test_report_mars_rule_2154.py b/tests/test_report_mars_rule_2154.py new file mode 100644 index 000000000..85d7fd507 --- /dev/null +++ b/tests/test_report_mars_rule_2154.py @@ -0,0 +1,120 @@ +"""BUG-2154 (占星师 2026-11-22 §3, D): one Mars 1/4/7/8/12 rule, one evidence identity. + +kalatra_dosha_mars_1_4_7_8_12 is the canonical entry; kalatra_dosha_mars_7 is an archived alias that +never executes or counts on its own. Public fixtures (Jobs: Mars in house 8) plus synthetic charts. +""" + +from __future__ import annotations + +import json +import re +from pathlib import Path + +from scripts.pl9_interpretation_packs import build_dosha_remedy_pack, build_yoga_interpretation_pack +from scripts.report_render.yoga_rule_aliases import ( + canonical_rule_id, + dosha_evidence_identity, + evidence_identity, + report_dedup_key, + resolve_row, +) +from scripts.report_render.yoga_status_words import _report_yoga_rows +from scripts.yoga_engine import YogaEngine +from tests.public_chart_reports import public_chart_reports + +RULES = Path(__file__).resolve().parents[1] / "references" / "yoga_rules.json" +CANON, ALIAS = "kalatra_dosha_mars_1_4_7_8_12", "kalatra_dosha_mars_7" +NAME_ZH = "火星婚姻相关配置(1/4/7/8/12宫筛查)" +NAME_EN = "Mars Marriage-Related Placement (1/4/7/8/12 House Screen)" +SIGNS = ("Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo", "Libra", "Scorpio", "Sagittarius", "Capricorn", + "Aquarius", "Pisces") + + +def _rules() -> dict[str, dict]: + return {rule["id"]: rule for rule in json.loads(RULES.read_text(encoding="utf-8"))["rules"]} + + +def _chart(mars_house: int | None) -> dict: + planets = {name: {"sign": "Libra", "house": 7, "degree": 190.0} for name in ("Sun", "Moon", "Mercury", "Jupiter", "Venus", "Saturn")} + if mars_house is not None: + planets["Mars"] = {"sign": SIGNS[mars_house - 1], "house": mars_house, "degree": (mars_house - 1) * 30 + 5.0} + return planets + + +def _mars_rows(rows: list[dict]) -> list[dict]: + return [row for row in rows if str(row.get("rule_id") or row.get("id") or "").startswith("kalatra_dosha_mars")] + + +def test_rule_table_keeps_one_canonical_entry_and_an_archived_alias() -> None: + rules = _rules() + canon, alias = rules[CANON], rules[ALIAS] + assert canon["enabled"] is True and canon["name_cn"] == NAME_ZH and canon["name"] == NAME_EN + assert alias["enabled"] is False and alias["duplicate_of"] == CANON and "BUG-2154" in alias["archived_reason"] + assert canon["source_verified"] is False and canon["legacy_source"] == "BPHS" + assert canon["reference_point"] == "lagna" and canon["source_profile"] and canon["dedup_key"] == "mangal_dosha" + effects = canon["effects"] + canon["effects_en"] + assert not any(re.fullmatch(r"婚姻延迟|配偶关系紧张|需要匹配化解|Delayed marriage|Strained relationship with spouse", text) for text in effects) + assert any("不能据此确定婚姻延迟或关系紧张" in text for text in canon["effects"]) + + +def test_engine_runs_the_canonical_rule_once_and_never_the_alias() -> None: + engine = YogaEngine(str(RULES)) + assert ALIAS not in {rule["id"] for rule in engine.rules} and CANON in {rule["id"] for rule in engine.rules} + for house in (1, 4, 7, 8, 12): + hits = _mars_rows(engine.detect(_chart(house), "Aries")) + assert [row.get("rule_id") for row in hits] == [CANON], house + assert _mars_rows(engine.detect(_chart(2), "Aries")) == [] + # Mars missing: the rule does not fire. The dosha table (below) calls it not assessed, never "no". + assert _mars_rows(engine.detect(_chart(None), "Aries")) == [] + pack = build_dosha_remedy_pack({"mangal_dosha": {"has_dosha": False, "severity": "none"}}, {}, language="zh") + assert pack["dosha_rows"][0]["state"] == "not_assessed" and pack["dosha_rows"][0]["present"] is None + + +def test_old_ids_resolve_to_one_identity_and_one_page() -> None: + assert canonical_rule_id(ALIAS) == CANON == canonical_rule_id(CANON) + old = {"rule_id": ALIAS, "name": "Mangal Dosha (Mars in 1/4/7/8/12)", "name_cn": "火星障碍(火星在关键宫)", + "planets": ["Mars"], "combination": "火星在第8宫", "effects": ["婚姻延迟", "需要匹配化解"]} + new = {"rule_id": CANON, "name": "Mangal Dosha (Mars in 1/4/7/8/12)", "name_cn": "火星婚姻煞(火星入1/4/7/8/12宫)", + "planets": ["Mars"], "combination": "火星在第8宫"} + resolved = resolve_row(old) + assert resolved["rule_id"] == CANON and resolved["legacy_rule_id"] == ALIAS and resolved["name_cn"] == NAME_ZH + assert resolved["evidence_identity"] == resolve_row(new)["evidence_identity"] == "ev:mars_marriage_screen@D1:lagna" + assert "需要匹配化解" not in resolved["effects"] + # An old packet with both ids: one page, one candidate row. + pages = build_yoga_interpretation_pack({"detected_yogas": [old, new]}, {}, language="zh")["pages"] + assert [page["name"] for page in pages] == [NAME_ZH] + assert len(_report_yoga_rows([old, new])) == 1 + + +def test_dedup_key_keeps_reference_point_chart_and_profile_apart() -> None: + key = report_dedup_key(CANON) + assert key == ("mangal_dosha", "lagna", "D1", "mars_marriage_five_house_screen_v1") == report_dedup_key(ALIAS) + assert report_dedup_key(CANON, "D9") != key + assert evidence_identity(CANON, "D9") != evidence_identity(CANON) + assert dosha_evidence_identity("mangal_dosha") == evidence_identity(CANON) + assert dosha_evidence_identity("kaal_sarp_dosha") is None and evidence_identity("amala_yoga") is None + + +def test_dosha_table_and_yoga_page_share_one_identity_on_a_public_chart() -> None: + packet, chinese, english = public_chart_reports("steve_jobs_1955_aa") + advanced = packet["worksheets"]["advanced_systems"] + assert advanced["yogas_doshas"]["mangal_dosha"]["evidence_identity"] == "ev:mars_marriage_screen@D1:lagna" + dosha_row = next(row for row in advanced["dosha_remedy_pack"]["dosha_rows"] if row["id"] == "mangal_dosha") + assert dosha_row["evidence_identity"] == "ev:mars_marriage_screen@D1:lagna" + layer = [row for row in packet["report_yoga_conditions"]["rows"] if row.get("rule_id") == CANON] + assert len(layer) == 1 + assert packet["report_yoga_conditions"]["evidence_identities"][CANON] == dosha_row["evidence_identity"] + assert not [row for row in packet["report_yoga_conditions"]["rows"] if row.get("rule_id") == ALIAS] + for text, name, banned in ((chinese, NAME_ZH, ("火星障碍", "需要匹配化解", "火星婚姻煞(火星入")), + (english, NAME_EN, ("Needs careful matching", "Mangal Dosha (Mars in 1/4/7/8/12)"))): + assert text.count(f"#### {name}\n") == 1 + for word in banned: + assert word not in text, word + assert "这与 Dosha 表里的「火星婚姻煞」是同一项火星位置事实,只算一项,不是另一个不利因素。" in chinese + assert "这与格局表里的「火星婚姻相关配置(1/4/7/8/12宫筛查)」是同一项火星位置事实,只算一项,不是另一个不利因素。" in chinese + assert "it counts once, not as a further adverse factor." in english + assert "命中这一火星位置筛查条件。关系层面的传统解释仍需结合参考点、制约与缓解条件及整体结构,不能据此确定婚姻延迟或关系紧张。" in chinese + # Fixed verdicts only appear negated. + assert re.findall(r".{0,6}婚姻延迟", chinese) and all("不能据此确定" in hit for hit in re.findall(r".{0,6}婚姻延迟", chinese)) + # No source line for the rule (no 「BPHS」 next to its name). + assert not re.search(r"火星婚姻相关配置[^\n]*BPHS", chinese) diff --git a/tests/test_report_neecha_short_cell_2155.py b/tests/test_report_neecha_short_cell_2155.py new file mode 100644 index 000000000..13c599dcc --- /dev/null +++ b/tests/test_report_neecha_short_cell_2155.py @@ -0,0 +1,120 @@ +"""BUG-2155 (占星师 2026-11-22 §4, E): short debilitation cells that name the real state. + +Obama (public fixture): Jupiter debilitated, the default named rule met (verified). Jobs: no debilitated +planet. Candidate, self-reference-only and not-computed states are synthetic (neither fixture has them). +""" + +from __future__ import annotations + +import pytest + +from scripts.pl9_reader_export import _dignity_label +from scripts.report_render.neecha_witness import ( + NEECHA_BHANGA_DIGNITY_CELL, + neecha_bhanga_dignity_cell, + neecha_state, + neecha_states, + neecha_table_notes, +) +from scripts.report_render.upstream_sync_chapters import _dignity_section +from tests.public_chart_reports import public_chart_reports + +LONG_ZH = NEECHA_BHANGA_DIGNITY_CELL["zh"] +LONG_EN = NEECHA_BHANGA_DIGNITY_CELL["en"] + + +def _snapshot(**lists) -> dict: + return {"nicha_bhanga_raj": {"yogas": [], "variant_only": [], "literal_only": [], **lists}} + + +def test_states_come_from_the_detector_lists() -> None: + snap = _snapshot(yogas=[{"planet": "Jupiter"}], variant_only=[{"planet": "Mars"}], literal_only=[{"planet": "Venus"}]) + assert neecha_state("Jupiter", snap) == "verified" + assert neecha_state("Mars", snap) == "candidate" + assert neecha_state("Venus", snap) == "self_reference_only" + assert neecha_state("Saturn", snap) == "not_met" + assert neecha_state("Jupiter", {}) == "not_computed" + + +def test_cells_for_each_state_in_both_editions() -> None: + states = neecha_states(_snapshot(yogas=[{"planet": "Jupiter"}], variant_only=[{"planet": "Mars"}], + literal_only=[{"planet": "Venus"}])) + assert neecha_bhanga_dignity_cell("落陷取消(Neecha Bhanga)", "zh", "Jupiter", states) == "落陷;另有缓解条件¹" + assert neecha_bhanga_dignity_cell("落陷取消(Neecha Bhanga)", "en", "Jupiter", states) == "Debilitated; mitigating conditions present¹" + assert neecha_bhanga_dignity_cell("落陷取消(Neecha Bhanga)", "zh", "Jupiter", states, footnote=False) == "落陷;另有缓解条件(见格局说明)" + assert neecha_bhanga_dignity_cell("落陷(Debilitated)", "zh", "Mars", states) == "落陷;缓解条件待核" + assert neecha_bhanga_dignity_cell("落陷(Debilitated)", "en", "Mars", states) == "Debilitated; mitigating conditions to be checked" + # Self-reference only: product policy neecha_bhanga_policy_v1 keeps 落陷 (the special note lives with the detector). + assert neecha_bhanga_dignity_cell("落陷(Debilitated)", "zh", "Venus", states) == "落陷" + not_computed = neecha_states({}) + assert neecha_bhanga_dignity_cell("落陷(Debilitated)", "zh", "Saturn", not_computed) == "落陷" + # Never a global replacement: other dignities, and 落陷 without a planet, are left alone. + assert neecha_bhanga_dignity_cell("入旺(Exalted)", "zh", "Saturn", states) is None + assert neecha_bhanga_dignity_cell("落陷(Debilitated)", "zh") is None + assert _dignity_label("落陷(Debilitated)", "zh") == "落陷" + assert _dignity_label("落陷(Debilitated)", "zh", "Mars", states) == "落陷;缓解条件待核" + + +def test_notes_under_a_table() -> None: + states = {"Jupiter": "verified", "Mars": "candidate", "Saturn": "not_computed", "Venus": "self_reference_only"} + statuses = {"Jupiter": "落陷取消(Neecha Bhanga)", "Mars": "落陷(Debilitated)", "Saturn": "落陷(Debilitated)", + "Venus": "落陷(Debilitated)", "Sun": "入旺(Exalted)"} + zh = neecha_table_notes(list(statuses), statuses, states, "zh") + assert zh == [ + "¹ 缓解条件和见证星见「瑜伽解释」里的「落陷取消(木星)」;缓解不是新的尊贵等级,原始的落陷不变。", + "火星「缓解条件待核」:只有另一种读法下的化解条件成立,默认规则没有成立,这里不按已缓解处理。", + "土星的落陷取消条件这次没有计算,这不表示没有缓解条件。", + ] + en = neecha_table_notes(list(statuses), statuses, states, "en") + assert en[0].startswith("¹ The mitigating conditions and their witnesses are on the \"Neecha Bhanga (Jupiter)\" page") + assert en[2] == "The cancellation conditions for Saturn's debilitation were not computed this time; this does not mean there are none." + assert neecha_table_notes(["Sun"], {"Sun": "入旺(Exalted)"}, states, "zh") == [] + + +def test_candidate_state_in_a_rendered_table() -> None: + packet = { + "worksheets": {"d1_rasi_bhava": {"planets": {"Mars": {"status": "落陷(Debilitated)"}, "Sun": {"status": "入旺(Exalted)"}}}, + "advanced_systems": {"yogas_doshas": _snapshot(variant_only=[{"planet": "Mars"}])}}, + } + lines = _dignity_section(packet, "zh") + assert any("落陷;缓解条件待核" in line for line in lines) + assert "火星「缓解条件待核」:只有另一种读法下的化解条件成立,默认规则没有成立,这里不按已缓解处理。" in lines + uncomputed = {"worksheets": {"d1_rasi_bhava": {"planets": {"Mars": {"status": "落陷(Debilitated)"}}}}} + lines = _dignity_section(uncomputed, "en") + assert any("| Debilitated |" in line for line in lines) + assert "The cancellation conditions for Mars's debilitation were not computed this time; this does not mean there are none." in lines + + +@pytest.mark.parametrize("language", ["zh", "en"]) +def test_public_chart_tables_use_the_short_cell_and_one_explanation(language: str) -> None: + _packet, chinese, english = public_chart_reports("barack_obama_1961_aa") + text = chinese if language == "zh" else english + short = "落陷;另有缓解条件¹" if language == "zh" else "Debilitated; mitigating conditions present¹" + long_cell = LONG_ZH if language == "zh" else LONG_EN + # 原值:五张表和两句宫主说明各印一次 BUG-2030 的长句(共 10 处);新值:表格短句加脚注,长句只留在格局页 + # 原因:BUG-2155(占星师 2026-11-22 §4) + assert text.count(short) >= 6 + assert long_cell not in text + footnote = ("¹ 缓解条件和见证星见「瑜伽解释」里的「落陷取消(木星)」;缓解不是新的尊贵等级,原始的落陷不变。" if language == "zh" + else "¹ The mitigating conditions and their witnesses are on the \"Neecha Bhanga (Jupiter)\" page under Yoga interpretation; " + "mitigation is not a new dignity and the original debilitation stands.") + assert text.count(footnote) >= 4 + heading = "#### 落陷取消(木星)" if language == "zh" else "#### Neecha Bhanga (Jupiter)" + assert heading in text + sentence = "尊贵状态为落陷;另有缓解条件(见格局说明)。" if language == "zh" else \ + "with dignity/status Debilitated; mitigating conditions present (see the yoga notes)." + assert sentence in text + # Body pages (planet and house-lord pages) keep the original 落陷 and point to the notes. + # 原值:「尊贵为落陷取消」;新值:「尊贵为落陷;另有缓解条件(见格局说明)」;原因:BUG-2155 + body = "木星落在摩羯座第1宫,尊贵为落陷;另有缓解条件(见格局说明)。" if language == "zh" else \ + "dignity Debilitated; mitigating conditions present (see the yoga notes)" + assert body in text and "尊贵为落陷取消" not in text + # The original 落陷 always stays next to the clause. + assert "落陷取消(Neecha Bhanga)" not in text + dignity_tables = [line for line in text.splitlines() if line.startswith("| 木星 |") or line.startswith("| Jupiter |")] + assert dignity_tables and not any("| 落陷取消 |" in line or "| Neecha Bhanga |" in line for line in dignity_tables) + + +def test_a_chart_without_debilitation_gets_no_footnote() -> None: + _packet, chinese, english = public_chart_reports("steve_jobs_1955_aa") + assert "¹" not in chinese and "¹" not in english diff --git a/tests/test_report_reader_main.py b/tests/test_report_reader_main.py index 1c950880e..cf14d7cb6 100644 --- a/tests/test_report_reader_main.py +++ b/tests/test_report_reader_main.py @@ -430,7 +430,10 @@ def test_reader_headings_drop_field_jargon_and_dignity_is_one_name(reader_packet # 原值: _dignity_label("落陷取消(Neecha Bhanga)") == "落陷取消" # 新值: "落陷;这一配置的不利影响有缓解因素,但不能据此认为困难全部消失" (the original dignity stays, the cancellation is a separate clause) # 原因: BUG-2105 the engine status 「落陷取消」 overwrote the debilitation in every dignity cell - assert _dignity_label("落陷取消(Neecha Bhanga)") == "落陷;这一配置的不利影响有缓解因素,但不能据此认为困难全部消失" + # 原值: "落陷;这一配置的不利影响有缓解因素,但不能据此认为困难全部消失" + # 新值: "落陷;另有缓解条件¹"(表下脚注指向该星的落陷取消页) + # 原因: BUG-2155(占星师 2026-11-22 §4):表格写短句,完整解释只在详情页写一次 + assert _dignity_label("落陷取消(Neecha Bhanga)") == "落陷;另有缓解条件¹" assert _dignity_label("极敌(Great Enemy)") == "极敌" assert _dignity_label("中性") == "中性" assert _dignity_label(None) == ""