From e54db1a7561ee66d962e9709594bb49478bd130f Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 18:02:48 +0800 Subject: [PATCH] feat(yoga): Maha, Khala and Dainya parivartana as formed named yogas (BUG-2388) Owner 2026-11-25 option A. Kind by the two exchanged houses (Phaladeepika ch.6: 28 Maha / 8 Khala / 30 Dainya). yoga_engine.py (frozen) edit approved by the owner for exactly these three rules: parivartana_class condition, product formation contracts looked up before hers, sign_exchange/house_class checks. Chart page drops the plain exchange support card when a named one is formed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8 --- docs/BUG_HISTORY.md | 17 +++ frontend/src/lib/chart-yoga-groups.ts | 4 + .../tests/chart-yoga-parivartana-2388.test.ts | 51 ++++++++ references/yoga_rule_topics.v1.json | 29 ++++- references/yoga_rules.json | 76 ++++++++++- scripts/yoga_engine.py | 119 +++++++++++++++++- tests/test_parivartana_classes_2388.py | 82 ++++++++++++ 7 files changed, 373 insertions(+), 5 deletions(-) create mode 100644 frontend/tests/chart-yoga-parivartana-2388.test.ts create mode 100644 tests/test_parivartana_classes_2388.py diff --git a/docs/BUG_HISTORY.md b/docs/BUG_HISTORY.md index fe64f241d..6d9932a4b 100644 --- a/docs/BUG_HISTORY.md +++ b/docs/BUG_HISTORY.md @@ -32422,3 +32422,20 @@ - **修复**:改为只写「{行星}落陷。」/ "{planet} is debilitated."。 - **验证**:`tests/test_report_neecha_short_cell_2155.py` 三处按原值/新值/原因更新。 - **修复版本**:分支 `claude/report-audit-1125`。 + +## BUG-2388 | 规则库没有大互换、三宫互换(Khala)、凶互换(Dainya)三种互换格局;巨蟹上升盘木星与土星互换只显示为「支持组合」 + +- **状态**:resolved(staging 待负责人验收) +- **现象**:负责人 2026-11-25 看星盘页「全局 Yoga」:一张巨蟹上升盘(木星在摩羯第 7 宫、土星在双鱼第 9 宫)显示「本命盘没有满足条件的命名格局」,木星与土星互换只出现在「支持组合」。负责人选 A:补上三种互换,作为成立的格局显示。 +- **触发条件**:任何两颗主星互换星座的盘。 +- **根因**:规则库只有「王者互换格局」(角宫主与三方宫主互换,引擎判为候选),没有按互换所在两宫分类的大互换 / Khala / Dainya 三条;占星师的上游 app 有大互换(只列了 17 对宫)和凶互换,没有 Khala。 +- **修复**: + - `references/yoga_rules.json` 新增 `maha_parivartana_yoga`(大互换格局,auspicious)、`khala_parivartana_yoga`(三宫互换格局,special)、`dainya_parivartana_yoga`(凶互换格局,durbhaga),来源 Phaladeepika 第 6 章。 + - 分类按被互换的两个宫:含第 6、8、12 宫为凶互换;否则含第 3 宫为三宫互换;其余(两宫都在 1、2、4、5、7、9、10、11)为大互换。66 对宫分成 28 / 8 / 30,与经典一致。一颗星兼管别的宫(如巨蟹上升木星管 6、9)不改变分类。 + - `scripts/yoga_engine.py`(冻结文件,负责人「补上三种互换」即为本次改动的批准,只加这三条所需):新条件类型 `parivartana_class`;产品自己的成立合同(先查产品合同,再查占星师的;她的合同表原样不动);成立检查 `sign_exchange`、`house_class`。 + - `references/yoga_rule_topics.v1.json` 由构建脚本重写:三条新规则为 `unmapped`(冻结主题快照未改,待占星师给主题)。 + - 星盘页:具名互换成立时,不再重复出「X与Y互换」支持卡;凶互换进「留意」,图都是互换图。 +- **验证**:巨蟹例在完整引擎上只出 `maha_parivartana_yoga`,`formed_under_source`,两宫 [7, 9];三种各一张合成盘的正例、无互换反例、缺 D1 范围时为候选;66 对宫 28/8/30。yoga 相关 Python 测试、2324 英文泄漏测试、星盘与格局前端测试通过;tsc 无错,改动文件 ESLint 0 错。 +- **防复发**:`tests/test_parivartana_classes_2388.py`、`frontend/tests/chart-yoga-parivartana-2388.test.ts`。 +- **关联记录**:BUG-2387(同一张盘的落陷卡)、BUG-1572(王者互换此前从未触发)、BUG-1975 / BUG-2218(规则级主题映射冻结)。 +- **修复版本**:1.4(staging)。 diff --git a/frontend/src/lib/chart-yoga-groups.ts b/frontend/src/lib/chart-yoga-groups.ts index 95958fe0f..08961d9da 100644 --- a/frontend/src/lib/chart-yoga-groups.ts +++ b/frontend/src/lib/chart-yoga-groups.ts @@ -380,6 +380,7 @@ export function buildYogaGroups(input: Readonly<{ const seen = new Set(); const neechaIndex = new Map(); const neechaLines = new Map(); + const namedExchanges = new Set(); const rows = input.rows.map(record).filter((row): row is Row => row !== null) .sort((left, right) => orderOf(left) - orderOf(right)); @@ -411,6 +412,8 @@ export function buildYogaGroups(input: Readonly<{ } if (unjudged(row)) continue; seen.add(id); + // BUG-2388: a named exchange (大互换 / 三宫互换 / 凶互换) replaces the plain 「X与Y互换」 support card. + if (/_parivartana_yoga$/u.test(id) && planets.length === 2) namedExchanges.add([...planets].sort().join(":")); if (isAdverse(row)) { const key = planets[0] ?? id; adverseRows.set(key, [...(adverseRows.get(key) ?? []), row]); @@ -450,6 +453,7 @@ export function buildYogaGroups(input: Readonly<{ if (!bodyA || !bodyB || SIGN_LORD[bodyA.sign] !== b || SIGN_LORD[bodyB.sign] !== a) continue; exchanged.add(a); exchanged.add(b); + if (namedExchanges.has([a, b].sort().join(":"))) continue; support.push({ id: `exchange:${a}:${b}`, group: "support", name: `${zh(a)}与${zh(b)}互换`, alias: null, text: `${lordWords(a, rules)}在${zh(b)}的${signZh(bodyA.sign)},${lordWords(b, rules)}在${zh(a)}的${signZh(bodyB.sign)}。`, diff --git a/frontend/tests/chart-yoga-parivartana-2388.test.ts b/frontend/tests/chart-yoga-parivartana-2388.test.ts new file mode 100644 index 000000000..6fe838b47 --- /dev/null +++ b/frontend/tests/chart-yoga-parivartana-2388.test.ts @@ -0,0 +1,51 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { buildYogaGroups } from "../src/lib/chart-yoga-groups.ts"; + +/** + * BUG-2388 (owner 2026-11-25, option A 「补上三种互换」): the Jupiter–Saturn exchange of a Cancer-rising chart + * (houses 7 and 9) is the named 大互换格局, shown under 成立 with the exchange diagram, and the plain + * 「木星与土星互换」 support card is not repeated. Synthetic chart, no birth data. + */ +const planets = [ + { name: "Sun", sign: "Cancer", house: 1 }, + { name: "Moon", sign: "Virgo", house: 3 }, + { name: "Mars", sign: "Libra", house: 4 }, + { name: "Mercury", sign: "Leo", house: 2 }, + { name: "Jupiter", sign: "Capricorn", house: 7 }, + { name: "Venus", sign: "Gemini", house: 12 }, + { name: "Saturn", sign: "Pisces", house: 9 }, +]; + +// The row scripts/yoga_engine.py writes for the rule (reader sentence added by the API). +const row = (kind: string, nameCn: string, category: string) => ({ + rule_id: `${kind}_parivartana_yoga`, name: `${kind[0]!.toUpperCase()}${kind.slice(1)} Parivartana Yoga`, name_cn: nameCn, + category, planets: ["Jupiter", "Saturn"], combination: "木星在第7宫、土星在第9宫互换星座", + reader_condition_zh: "木星在第7宫、土星在第9宫互换星座", + formation_status: "conditions_met", condition_status: "conditions_met", + formation_assessment: { status: "formed_under_source" }, +}); + +test("大互换 is a formed card with the exchange diagram and replaces the plain exchange card", () => { + const groups = buildYogaGroups({ rows: [row("maha", "大互换格局", "auspicious")], planets, ascendant: "Cancer" })!; + const card = groups.formed.find((item) => item.id === "maha_parivartana_yoga"); + assert.ok(card, "the named exchange is under 成立"); + assert.equal(card.name, "大互换格局"); + assert.equal(card.text, "木星在第7宫、土星在第9宫互换星座"); + assert.deepEqual(card.diagram, { kind: "swap", a: "Jupiter", b: "Saturn", label: "互换" }); + assert.equal(groups.support.filter((item) => item.id.startsWith("exchange:")).length, 0); +}); + +test("without the named row the plain exchange support card is still there", () => { + const groups = buildYogaGroups({ rows: [], planets, ascendant: "Cancer" })!; + assert.deepEqual(groups.support.filter((item) => item.id.startsWith("exchange:")).map((item) => item.id), ["exchange:Jupiter:Saturn"]); +}); + +test("凶互换 goes to 留意 with the exchange diagram", () => { + const groups = buildYogaGroups({ rows: [row("dainya", "凶互换格局", "durbhaga")], planets, ascendant: "Cancer" })!; + const card = groups.adverse.find((item) => item.name === "凶互换格局"); + assert.ok(card); + assert.equal(card.diagram.kind, "swap"); + assert.equal(groups.support.filter((item) => item.id.startsWith("exchange:")).length, 0); +}); diff --git a/references/yoga_rule_topics.v1.json b/references/yoga_rule_topics.v1.json index 887f2b7e9..0f3da3798 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": "932f9515becb", + "built_from_sha256": "8719c8e69d6e", "builder": "scripts/research/build_yoga_rule_topics.py", "rule": "Topics come from references/yoga_rule_topics.frozen.json (BUG-2218); a keyword match on the rule's own effect text is only a keyword_proposal. unmapped = no snapshot topic (待映射, never dropped). longevity, fame_authority and spirituality are recorded for review; no chat domain selects by them.", "rules": { @@ -3459,6 +3459,14 @@ "basis_text": "Fulfilled life | Balanced development in all areas | Favoured by fortune | 生活圆满 | 各方面均衡发展 | 命运眷顾", "mapping": "unmapped" }, + "dainya_parivartana_yoga": { + "name": "Dainya Parivartana Yoga", + "category": "durbhaga", + "topics": [], + "matched_words": {}, + "basis_text": "The two houses' affairs are drawn into trouble; setbacks and losses come more easily | 两宫的事被难处牵连,容易有意外和消耗", + "mapping": "unmapped" + }, "dala_yoga": { "name": "Dala Yoga", "category": "nabhasa", @@ -4506,6 +4514,17 @@ "basis_text": "Abundant wealth | Outstanding eloquence | Steadfast character | 财富充裕 | 口才出众 | 品格坚定", "mapping": "frozen" }, + "khala_parivartana_yoga": { + "name": "Khala Parivartana Yoga", + "category": "special", + "topics": [], + "matched_words": {}, + "basis_text": "Circumstances swing between good and bad; gains come by one's own effort | 处境时好时坏,起伏较大,多靠自己争取", + "mapping": "unmapped", + "keyword_proposal": [ + "wealth" + ] + }, "kita_nabhasa": { "name": "Kita Nabhasa Yoga", "category": "nabhasa", @@ -4560,6 +4579,14 @@ "basis_text": "Continuous good fortune | Unbroken blessings | 幸运连绵 | 福气不断", "mapping": "unmapped" }, + "maha_parivartana_yoga": { + "name": "Maha Parivartana Yoga", + "category": "auspicious", + "topics": [], + "matched_words": {}, + "basis_text": "The two houses' affairs lift each other | 两宫的事互相带动、彼此助力", + "mapping": "unmapped" + }, "mahabhagya_yoga": { "name": "Mahabhagya Yoga", "category": "special", diff --git a/references/yoga_rules.json b/references/yoga_rules.json index 1858c90c4..ea00894c2 100644 --- a/references/yoga_rules.json +++ b/references/yoga_rules.json @@ -1,7 +1,7 @@ { "schema_version": "1.0", "description": "Yoga 规则库 - 数据驱动架构 v1.0", - "total_rules": 481, + "total_rules": 484, "rules": [ { "id": "raja_yoga", @@ -17532,7 +17532,79 @@ "effects_en": [ "Traditional theme: personal influence and charisma; the ascendant lord's strength and the timing must be assessed separately." ] + }, + { + "id": "maha_parivartana_yoga", + "name": "Maha Parivartana Yoga", + "name_cn": "大互换格局", + "source": "Phaladeepika", + "bvr_id": null, + "category": "auspicious", + "logic": { + "type": "parivartana_class", + "class": "maha", + "combo_template": "{la}在第{ha}宫、{lb}在第{hb}宫互换星座", + "combo_template_en": "{la} in house {ha} and {lb} in house {hb} exchange signs" + }, + "effects": [ + "两宫的事互相带动、彼此助力" + ], + "effects_en": [ + "The two houses' affairs lift each other" + ], + "strength": "强", + "strength_en": "strong", + "enabled": true, + "source_reference": "Phaladeepika 6" + }, + { + "id": "khala_parivartana_yoga", + "name": "Khala Parivartana Yoga", + "name_cn": "三宫互换格局", + "source": "Phaladeepika", + "bvr_id": null, + "category": "special", + "logic": { + "type": "parivartana_class", + "class": "khala", + "combo_template": "{la}在第{ha}宫、{lb}在第{hb}宫互换星座", + "combo_template_en": "{la} in house {ha} and {lb} in house {hb} exchange signs" + }, + "effects": [ + "处境时好时坏,起伏较大,多靠自己争取" + ], + "effects_en": [ + "Circumstances swing between good and bad; gains come by one's own effort" + ], + "strength": "中", + "strength_en": "moderate", + "enabled": true, + "source_reference": "Phaladeepika 6" + }, + { + "id": "dainya_parivartana_yoga", + "name": "Dainya Parivartana Yoga", + "name_cn": "凶互换格局", + "source": "Phaladeepika", + "bvr_id": null, + "category": "durbhaga", + "logic": { + "type": "parivartana_class", + "class": "dainya", + "combo_template": "{la}在第{ha}宫、{lb}在第{hb}宫互换星座", + "combo_template_en": "{la} in house {ha} and {lb} in house {hb} exchange signs" + }, + "effects": [ + "两宫的事被难处牵连,容易有意外和消耗" + ], + "effects_en": [ + "The two houses' affairs are drawn into trouble; setbacks and losses come more easily" + ], + "strength": "弱", + "strength_en": "weak", + "enabled": true, + "source_reference": "Phaladeepika 6" } ], - "total_enabled_rules": 404 + "total_enabled_rules": 407 } diff --git a/scripts/yoga_engine.py b/scripts/yoga_engine.py index 42bd172fc..ce52da9c2 100644 --- a/scripts/yoga_engine.py +++ b/scripts/yoga_engine.py @@ -298,14 +298,14 @@ def _get_dignity_level(planet: str, sign: str) -> str: # ============================================================================ try: # scripts/ on sys.path from report_render.yoga_output_guardrails import ( # noqa: F401 - re-exported - yoga_formation_contract, + yoga_formation_contract as _upstream_yoga_formation_contract, _formation_logic as _upstream_formation_logic, assess_yoga_formation as _upstream_assess_yoga_formation, ) from report_render.yoga_english_delivery import english_delivery_fields except ImportError: # package import (scripts.yoga_engine) from scripts.report_render.yoga_output_guardrails import ( # noqa: F401 - re-exported - yoga_formation_contract, + yoga_formation_contract as _upstream_yoga_formation_contract, _formation_logic as _upstream_formation_logic, assess_yoga_formation as _upstream_assess_yoga_formation, ) @@ -322,11 +322,94 @@ def _formation_logic(value: Any) -> Any: return value +# BUG-2388 (owner 2026-11-25 「补上三种互换」, product difference, announced): the three classical +# sign-exchange yogas. Which kind is decided by the two houses whose signs are exchanged +# (Phaladeepika ch.6: 28 Maha among houses 1,2,4,5,7,9,10,11; 8 Khala with the 3rd; 30 Dainya with +# the 6th, 8th or 12th), not by every house a lord also rules. Her contract table has none of the +# three, so the product's own contracts are looked up first; hers are unchanged. +PARIVARTANA_CLASSES = ('maha', 'khala', 'dainya') +_PARIVARTANA_NAMES = {'maha': 'Maha Parivartana Yoga', 'khala': 'Khala Parivartana Yoga', + 'dainya': 'Dainya Parivartana Yoga'} +_PARIVARTANA_BOUNDARY = { + 'maha': '按互换所在的两个宫判断:两宫都在第 1、2、4、5、7、9、10、11 宫之中。', + 'khala': '按互换所在的两个宫判断:其中一宫是第 3 宫,另一宫不是第 6、8、12 宫。', + 'dainya': '按互换所在的两个宫判断:其中一宫是第 6、8 或 12 宫。', +} + + +def parivartana_class(house_a: int, house_b: int) -> Optional[str]: + """The kind of exchange between two houses (BUG-2388): dusthana first, then the 3rd, else Maha.""" + pair = {house_a, house_b} + if len(pair) != 2 or not pair <= set(range(1, 13)): + return None + if pair & {6, 8, 12}: + return 'dainya' + if 3 in pair: + return 'khala' + return 'maha' + + +def _product_formation_contract(rule_id: str) -> Optional[dict[str, Any]]: + for kind in PARIVARTANA_CLASSES: + if rule_id == f'{kind}_parivartana_yoga': + return { + 'profile': 'phaladeepika_6_parivartana_houses', 'name': _PARIVARTANA_NAMES[kind], + 'source': {'title': 'Phaladeepika', 'section': '6'}, + 'definition': {'type': 'parivartana_class', 'class': kind}, + 'required': ['d1_scope', 'consistent_geometry', 'sign_exchange', 'house_class'], + 'variant_boundary': _PARIVARTANA_BOUNDARY[kind], + } + return None + + +def yoga_formation_contract(rule_id: str) -> Optional[dict[str, Any]]: + """The product's contracts (BUG-2388), then hers.""" + return _product_formation_contract(rule_id) or _upstream_yoga_formation_contract(rule_id) + + +def _assess_product_contract(row: dict[str, Any], contract: dict[str, Any]) -> dict[str, Any]: + """Her assessment rules applied to a product contract (same fields, same status words).""" + evidence = row.get('condition_evidence') or {} + checks = [check for check in (row.get('formation_checks') or []) if isinstance(check, dict)] + by_id = {check.get('id'): check for check in checks} + required = contract['required'] + satisfied = [key for key in required if by_id.get(key, {}).get('passed') is True + and by_id[key].get('witness') not in (None, '', [], {})] + failed = [key for key in required if by_id.get(key, {}).get('passed') is False] + missing = [key for key in required if key not in satisfied and key not in failed] + issues = [] + if (row.get('formation_source_profile') != contract['profile'] or + evidence.get('definition') != contract['definition']): + issues.append('source_definition_mismatch') + if len(by_id) != len(checks): + issues.append('duplicate_condition_evidence') + statuses = {str(row.get(key) or '') for key in + ('condition_status', 'formation_status', 'evidence_status', 'claim_status')} + restricted = statuses & {'blocked', 'evaluation_error', 'not_implemented', 'incomplete_conditions', + 'combustion_requires_review', 'method_requires_review'} + if restricted or row.get('missing_inputs'): + issues.extend(sorted(restricted)) + issues.extend(row.get('missing_inputs') or []) + formed = not issues and not missing and not failed + return { + 'status': 'formed_under_source' if formed else 'conditions_not_met' if failed else 'candidate', + 'name': contract['name'], 'source_profile': contract['profile'], 'source': dict(contract['source']), + 'required_conditions': list(required), 'satisfied_conditions': satisfied, + 'missing_conditions': missing, 'failed_conditions': failed, + 'review_issues': issues, 'checks': checks, 'variant_boundary': contract['variant_boundary'], + 'outcome_admitted': False, 'self_reference_only': False, + 'unqualified_formation_label_allowed': formed, + } + + def assess_yoga_formation(row: dict[str, Any]) -> dict[str, Any]: """Her `assess_yoga_formation` on a row whose definition has no English twin templates.""" evidence = row.get('condition_evidence') if isinstance(evidence, dict) and 'definition' in evidence: row = {**row, 'condition_evidence': {**evidence, 'definition': _formation_logic(evidence['definition'])}} + product = _product_formation_contract(str(row.get('rule_id', ''))) + if product: + return _assess_product_contract(row, product) return _upstream_assess_yoga_formation(row) @@ -1809,6 +1892,19 @@ class YogaEngine: ctx.is_own_sign('Jupiter') or ctx.is_exalted('Jupiter') or SIGN_LORDS.get(sign) in FRIENDLY_PLANETS['Jupiter'], {'planet': 'Jupiter', 'sign': sign, 'friendship': 'natural'}) + elif contract.get('profile') == 'phaladeepika_6_parivartana_houses': + # BUG-2388: the two lords sit in each other's signs, and the two houses decide the kind. + pair = [p for p in planets_bound if p in SIGN_LORDS.values()][:2] + a, b = (pair + [None, None])[:2] + sa, sb = ctx.sign_of(a) if a else None, ctx.sign_of(b) if b else None + exchanged = bool(a and b and a != b and sa and sb + and SIGN_LORDS.get(sa) == b and SIGN_LORDS.get(sb) == a) + check('sign_exchange', exchanged if a and b else None, + {'planets': [a, b], 'signs': [sa, sb]} if a and b else None) + ha, hb = (ctx.house_of(a) if a else None), (ctx.house_of(b) if b else None) + kind = parivartana_class(ha, hb) if ha and hb else None + check('house_class', None if kind is None else kind == contract['definition']['class'], + {'houses': sorted([ha, hb]), 'class': kind} if kind else None) elif entry['rule_id'] == 'mahabhagya_yoga': values = entry.get('condition_checks') or {} parity = values.get('sign_parity') @@ -4360,6 +4456,25 @@ class YogaEngine: return [{"combination": combo, "strength": rule.get("strength", "强"), "participants": [la, lb]}] return [] + def _eval_parivartana_class(self, cond, ctx, rule, bindings): + """BUG-2388: one sign exchange of the seven planets whose two houses fall in the asked kind.""" + wanted = cond.get('class') + planets = ['Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn'] + results = [] + for index, a in enumerate(planets): + for b in planets[index + 1:]: + sa, sb = ctx.sign_of(a), ctx.sign_of(b) + if not sa or not sb or SIGN_LORDS.get(sa) != b or SIGN_LORDS.get(sb) != a: + continue + ha, hb = ctx.house_of(a), ctx.house_of(b) + if not ha or not hb or parivartana_class(ha, hb) != wanted: + continue + combo = _combo(cond, "{la}在第{ha}宫、{lb}在第{hb}宫互换星座", + la=_planet(a), lb=_planet(b), ha=ha, hb=hb) + results.append({"combination": combo, "strength": rule.get("strength", "中"), + "participants": [a, b]}) + return results + def _eval_any_pair(self, cond, ctx, rule, bindings): """从集合 A 和集合 B 中各取一个元素,配对满足条件""" if "planets" in cond and "from" not in cond and "to" not in cond: diff --git a/tests/test_parivartana_classes_2388.py b/tests/test_parivartana_classes_2388.py new file mode 100644 index 000000000..11783bacf --- /dev/null +++ b/tests/test_parivartana_classes_2388.py @@ -0,0 +1,82 @@ +"""BUG-2388: the three classical sign-exchange yogas (Maha, Khala, Dainya) as formed named yogas. + +Synthetic charts only. The kind is decided by the two houses whose signs are exchanged +(Phaladeepika ch.6: 28 Maha, 8 Khala, 30 Dainya out of the 66 house pairs). +""" +from itertools import combinations +from pathlib import Path + +import pytest + +from scripts.yoga_engine import SIGNS, YogaEngine, parivartana_class + +RULES = Path(__file__).resolve().parents[1] / "references" / "yoga_rules.json" +IDS = {"maha_parivartana_yoga", "khala_parivartana_yoga", "dainya_parivartana_yoga"} + + +@pytest.fixture(scope="module") +def engine(): + e = YogaEngine(str(RULES)) + e.rules = [r for r in e.rules if r["id"] in IDS] + assert len(e.rules) == 3 + return e + + +def chart(ascendant, signs): + asc = SIGNS.index(ascendant) + return {p: {"sign": s, "house": (SIGNS.index(s) - asc) % 12 + 1} for p, s in signs.items()} + + +def run(engine, ascendant, signs): + return engine.detect(chart(ascendant, signs), ascendant, context={"chart_type": "D1"}) + + +def test_the_66_house_pairs_split_28_8_30(): + kinds = [parivartana_class(a, b) for a, b in combinations(range(1, 13), 2)] + assert (kinds.count("maha"), kinds.count("khala"), kinds.count("dainya")) == (28, 8, 30) + assert parivartana_class(3, 6) == "dainya" # a dusthana outranks the 3rd + assert parivartana_class(4, 4) is None + + +def test_cancer_jupiter_capricorn_saturn_pisces_is_maha(engine): + # Jupiter (lord of 6 and 9) in Capricorn = 7th, Saturn (lord of 7 and 8) in Pisces = 9th: + # the exchanged houses are 7 and 9, so it is Maha, not Dainya, although each lord also rules a dusthana. + rows = run(engine, "Cancer", {"Jupiter": "Capricorn", "Saturn": "Pisces", "Sun": "Cancer", + "Moon": "Virgo", "Mars": "Libra", "Mercury": "Leo", "Venus": "Gemini"}) + assert [r["rule_id"] for r in rows] == ["maha_parivartana_yoga"] + row = rows[0] + assert set(row["planets"]) == {"Jupiter", "Saturn"} + assert row["formation_assessment"]["status"] == "formed_under_source" + assert row["formation_assessment"]["unqualified_formation_label_allowed"] is True + checks = {c["id"]: c for c in row["formation_checks"]} + assert checks["house_class"]["witness"] == {"houses": [7, 9], "class": "maha"} + assert row["name_cn"] == "大互换格局" + + +def test_khala_exchange_with_the_third(engine): + # Aries asc: Mercury (lord of 3) in Aquarius = 11th, Saturn (lord of 11) in Gemini = 3rd. + rows = run(engine, "Aries", {"Mercury": "Aquarius", "Saturn": "Gemini", "Sun": "Aries", + "Moon": "Taurus", "Mars": "Scorpio", "Jupiter": "Sagittarius", "Venus": "Libra"}) + assert [r["rule_id"] for r in rows] == ["khala_parivartana_yoga"] + assert rows[0]["formation_assessment"]["status"] == "formed_under_source" + + +def test_dainya_exchange_with_a_dusthana(engine): + # Aries asc: Mercury (lord of 6) in Capricorn = 10th, Saturn (lord of 10) in Virgo = 6th. + rows = run(engine, "Aries", {"Mercury": "Capricorn", "Saturn": "Virgo", "Sun": "Aries", + "Moon": "Taurus", "Mars": "Scorpio", "Jupiter": "Sagittarius", "Venus": "Libra"}) + assert [r["rule_id"] for r in rows] == ["dainya_parivartana_yoga"] + assert rows[0]["formation_assessment"]["status"] == "formed_under_source" + assert rows[0]["category"] == "durbhaga" + + +def test_no_exchange_no_row(engine): + assert run(engine, "Aries", {"Sun": "Aries", "Moon": "Taurus", "Mars": "Scorpio", "Mercury": "Gemini", + "Jupiter": "Sagittarius", "Venus": "Libra", "Saturn": "Capricorn"}) == [] + + +def test_without_d1_scope_it_stays_a_candidate(engine): + signs = {"Jupiter": "Capricorn", "Saturn": "Pisces", "Sun": "Cancer", "Moon": "Virgo", + "Mars": "Libra", "Mercury": "Leo", "Venus": "Gemini"} + rows = engine.detect(chart("Cancer", signs), "Cancer", context={}) + assert rows and rows[0]["formation_assessment"]["status"] == "candidate"