#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Yoga 规则引擎 v1.0 (数据驱动架构) 从 JSON 规则配置中读取 Yoga 定义,通用条件解释器执行检测。 设计原则: - 规则完全数据驱动,加新 Yoga 只需改 JSON - 条件类型可扩展,覆盖 BPHS/PyJHora 主流 Yoga 模式 - 与原 cmd_yoga() API 兼容 """ import ast import functools import inspect import json import math import os import re import textwrap from typing import Dict, List, Any, Optional try: # scripts/ on sys.path from main_yoga_detectors import main_detector_rows except ImportError: # package import (scripts.yoga_engine) from scripts.main_yoga_detectors import main_detector_rows # ============================================================================ # 基础常量(自包含,避免循环导入) # ============================================================================ SIGNS = ['Aries', 'Taurus', 'Gemini', 'Cancer', 'Leo', 'Virgo', 'Libra', 'Scorpio', 'Sagittarius', 'Capricorn', 'Aquarius', 'Pisces'] SIGN_LORDS = { 'Aries': 'Mars', 'Taurus': 'Venus', 'Gemini': 'Mercury', 'Cancer': 'Moon', 'Leo': 'Sun', 'Virgo': 'Mercury', 'Libra': 'Venus', 'Scorpio': 'Mars', 'Sagittarius': 'Jupiter', 'Capricorn': 'Saturn', 'Aquarius': 'Saturn', 'Pisces': 'Jupiter' } EXALTATION = { 'Sun': 'Aries', 'Moon': 'Taurus', 'Mars': 'Capricorn', 'Mercury': 'Virgo', 'Jupiter': 'Cancer', 'Venus': 'Pisces', 'Saturn': 'Libra' } DEBILITATION = { 'Sun': 'Libra', 'Moon': 'Scorpio', 'Mars': 'Cancer', 'Mercury': 'Pisces', 'Jupiter': 'Capricorn', 'Venus': 'Virgo', 'Saturn': 'Aries' } MOOLATRIKONA_SIGN = { 'Sun': 'Leo', 'Moon': 'Taurus', 'Mars': 'Aries', 'Mercury': 'Virgo', 'Jupiter': 'Sagittarius', 'Venus': 'Libra', 'Saturn': 'Aquarius' } # BUG-2222 (upstream b6754475): BPHS 3.51–54 half-open in-sign degree # intervals, the same as native Shadbala and the main engine. MOOLATRIKONA_DEGREES = { 'Sun': (0, 20), 'Moon': (3, 30), 'Mars': (0, 12), 'Mercury': (15, 20), 'Jupiter': (0, 10), 'Venus': (0, 15), 'Saturn': (0, 20), } # PyJHora const.friendly_planets mapped from planet ids to names. FRIENDLY_PLANETS = { 'Sun': ['Moon', 'Mars', 'Jupiter'], 'Moon': ['Sun', 'Mercury'], 'Mars': ['Sun', 'Moon', 'Jupiter'], 'Mercury': ['Sun', 'Venus'], 'Jupiter': ['Sun', 'Moon', 'Mars'], 'Venus': ['Mercury', 'Saturn', 'Rahu'], 'Saturn': ['Mercury', 'Venus', 'Rahu'], 'Rahu': ['Venus', 'Saturn'], 'Ketu': ['Sun', 'Mars'], } # #166 Q5 (BUG-1596): natural (naisargika) enemies, BPHS 3.55; used for the # strict Gajakesari "not in an enemy sign" check (PVR textbook definition). NATURAL_ENEMIES = { 'Sun': ['Venus', 'Saturn'], 'Moon': [], 'Mars': ['Mercury'], 'Mercury': ['Moon'], 'Jupiter': ['Mercury', 'Venus'], 'Venus': ['Sun', 'Moon'], 'Saturn': ['Sun', 'Moon', 'Mars'], } # Combustion orbs (direct motion), same values as jyotish_engine.COMBUSTION_ORBS # direct column; used only when the chart row carries no `combust` flag. COMBUSTION_ORBS_DIRECT = {'Moon': 12.0, 'Mars': 17.0, 'Mercury': 14.0, 'Jupiter': 11.0, 'Venus': 10.0, 'Saturn': 15.0} # Short Chinese planet names for bilingual rule triggers (#166 Q5 / Q6). PLANET_ZH = {'Sun': '太阳', 'Moon': '月亮', 'Mars': '火星', 'Mercury': '水星', 'Jupiter': '木星', 'Venus': '金星', 'Saturn': '土星', 'Rahu': '罗睺', 'Ketu': '计都'} PLANET_CN = { "Ketu": "南交点Ketu", "Venus": "金星Venus", "Sun": "太阳Sun", "Moon": "月亮Moon", "Mars": "火星Mars", "Rahu": "北交点Rahu", "Jupiter": "木星Jupiter", "Saturn": "土星Saturn", "Mercury": "水星Mercury" } BENEFICS = ['Jupiter', 'Venus', 'Mercury', 'Moon'] MALEFICS = ['Mars', 'Saturn', 'Sun', 'Rahu', 'Ketu'] MOVABLE_SIGNS = ['Aries', 'Cancer', 'Libra', 'Capricorn'] FIXED_SIGNS = ['Taurus', 'Leo', 'Scorpio', 'Aquarius'] DUAL_SIGNS = ['Gemini', 'Virgo', 'Sagittarius', 'Pisces'] ALL_PLANETS = ['Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn', 'Rahu', 'Ketu'] # BUG-2298 (upstream 58f37ee5b): Saravali, Santhanam vol1 printed25 (PDF24), # visually checked 2026-11-23. Literal M/B labels, NOT corrected from names or # merged with BPHS editions. An explicit comparison profile, never the default # Raman nature rule. SARAVALI_SHASHTIAMSA_MALEFIC_ORDINALS = frozenset({ 1, 2, 7, 8, 9, 10, 11, 12, 15, 27, 30, 31, 32, 33, 34, 35, 36, 40, 41, 43, 44, 49, 50, 52, 55, 59, }) PLANET_INDEX = {planet: idx for idx, planet in enumerate(ALL_PLANETS)} # Jaimini co-lord comparison only (_stronger_co_lord); not a traditional own sign (BUG-1211). RAHU_KETU_OWNED_SIGN_INDEX = {'Rahu': 10, 'Ketu': 7} # Planets that form the solar / lunar neighbour yogas (BUG-1187, BUG-1206). FIVE_TRUE_PLANETS = ('Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn') # PyJHora const.house_strengths_of_planets, copied to make Yoga rule alignment deterministic. # Strength scale: 5 own/lord, 4 exalted, 3 friend, 2 neutral, 1 enemy, 0 debilitated. def badhaka_house(ascendant_sign: str) -> Optional[int]: """Badhaka 宫的唯一定义:变动 11、固定 9、双体 7;上升未知返回 None。""" if ascendant_sign in MOVABLE_SIGNS: return 11 if ascendant_sign in FIXED_SIGNS: return 9 if ascendant_sign in DUAL_SIGNS: return 7 return None HOUSE_STRENGTHS = { 'Sun': [4, 1, 2, 2, 5, 2, 0, 3, 3, 1, 1, 3], 'Moon': [2, 4, 3, 5, 3, 3, 2, 0, 2, 2, 2, 2], 'Mars': [5, 2, 1, 0, 3, 1, 2, 5, 3, 4, 2, 3], 'Mercury': [2, 3, 5, 1, 3, 5, 3, 2, 2, 2, 2, 0], 'Jupiter': [3, 1, 1, 4, 3, 3, 1, 3, 5, 0, 2, 5], 'Venus': [2, 5, 3, 1, 1, 0, 5, 2, 3, 3, 3, 4], 'Saturn': [0, 3, 3, 1, 1, 3, 4, 1, 2, 5, 5, 2], 'Rahu': [1, 4, 4, 1, 1, 3, 3, 0, 0, 3, 1, 3], 'Ketu': [1, 0, 0, 1, 1, 3, 3, 4, 4, 3, 1, 3], } # ── English twin for combination text (TASK-report-english-edition-20260929) ── # The Chinese combination strings stay exactly as before; each one also carries # an English rendering so the reader's English edition never has to translate # Chinese back. `BiText` compares, hashes and formats as its Chinese text. class BiText(str): """A Chinese string that also carries its English twin in ``.en``.""" en: str def __new__(cls, zh, en=None): obj = super().__new__(cls, zh) obj.en = str(zh) if en is None else str(en) return obj _HAN = re.compile(r'[\u4e00-\u9fff]') def _rule_combination_en(combination, rule: Dict) -> str: """The English twin of a match's combination. BUG-2304 follow-up: her source evaluators return the Chinese definition (`description_zh`) as plain text; its English is her rule-level `combination_en` / the node's `description_en`. Was: the Chinese text itself, which the English edition printed as "[translation missing: combination]". """ if isinstance(combination, BiText): return combination.en text = str(combination) if not _HAN.search(text): return text logic = rule.get('logic') if isinstance(rule.get('logic'), dict) else {} for candidate in (logic.get('description_en'), rule.get('combination_en')): if isinstance(candidate, str) and candidate.strip() and not _HAN.search(candidate): return candidate return text def _en_text(value) -> str: return value.en if isinstance(value, BiText) else str(value) def _planet(p) -> BiText: return BiText(PLANET_CN.get(p, p), p) def _planets(ps) -> BiText: ps = list(ps) return BiText("、".join(PLANET_CN.get(p, p) for p in ps), ", ".join(str(p) for p in ps)) def _bijoin(sep: str, parts) -> BiText: kept = [part for part in parts if part] return BiText(sep.join(str(part) for part in kept), sep.join(_en_text(part) for part in kept)) DEFAULT_COMBO_EN = { "{a}与{b}同在第{h}宫": "{a} and {b} together in house {h}", "{p}在第{h}宫": "{p} in house {h}", "{p}在第{h}宫(从{fp}的{rel})": "{p} in house {h} ({rel} from {fp})", "{p}{dignity}在{sign}": "{p} {dignity} in {sign}", "{count}颗行星满足条件": "{count} planets meet the condition", "行星分布在{count}个宫位": "Planets spread over {count} houses", "第{target}宫被夹击": "House {target} hemmed in", "所有指定行星均落入{houses}": "All listed planets fall in houses {houses}", "所有指定行星均落入候选宫位集合{houses}": "All listed planets fall in the house set {houses}", "指定行星只占据{houses}": "Listed planets occupy only houses {houses}", "指定行星只占据候选宫位集合{houses}": "Listed planets occupy only the house set {houses}", "第{house}宫有{planets}": "House {house} holds {planets}", "{planets}在{fp}的第{rel}宫": "{planets} in house {rel} from {fp}", "{count}个目标宫位有指定行星": "{count} target houses hold listed planets", "{a}与{b}在{sign}内相距{gap:.2f}°": "{a} and {b} within {gap:.2f}° in {sign}", "{la}与{lb}互换星座": "{la} and {lb} exchange signs", "{house}宫主{lord}在第{lh}宫": "Lord of house {house}, {lord}, in house {lh}", "{la}与{lb}同在第{h}宫": "{la} and {lb} together in house {h}", "自定义条件满足": "Custom condition met", } OFFSET_NAME_EN = {0: "same house", 1: "2nd", 2: "3rd", 3: "4th (Kendra)", 4: "5th (Trine)", 5: "6th", 6: "7th (Kendra)", 7: "8th", 8: "9th (Trine)", 9: "10th (Kendra)", 10: "11th", 11: "12th"} STRENGTH_EN = { "强": "Strong", "中": "Moderate", "弱": "Weak", "待评估": "To be assessed", "观察": "Watch", "部分减弱": "partly weakened", # 产品 2026-11-07 同步占星师 Yoga 规则批次:structural_observation 的强度栏(上游 733a931b)。 "observation": "Observation", } # Chinese wording for the English ``note`` of semantic (BVR / PyJHora batch) # conditions. The note stays the English twin. One note maps to one Chinese # sentence, so the dedup key keeps the same equality classes (BUG-1418). _SEMANTIC_NOTES_ZH_PATH = os.path.join( os.path.dirname(os.path.abspath(__file__)), "..", "references", "yoga_semantic_notes_zh.json") # A condition without a note used to print its type key. Keep one fixed # sentence per type so two matches of the same type still dedupe together. _SEMANTIC_TYPE_ZH = { "planet_in_house": "行星落在规则指定的宫位", "planet_in_lagna": "行星落在上升宫", } @functools.lru_cache(maxsize=1) def _semantic_notes_zh() -> Dict[str, str]: try: with open(_SEMANTIC_NOTES_ZH_PATH, "r", encoding="utf-8") as handle: data = json.load(handle) except (OSError, ValueError): return {} return {str(key): str(value) for key, value in data.items()} if isinstance(data, dict) else {} def _semantic_text(cond: Dict, ctype: str): """``cond.get("note", ctype)`` with Chinese text; the old value stays as ``.en``.""" if "note" in cond: note = cond.get("note") zh = _semantic_notes_zh().get(str(note)) if note else None return BiText(zh, note) if zh else note zh = _SEMANTIC_TYPE_ZH.get(str(ctype)) return BiText(zh, ctype) if zh else ctype def _template_text(zh: str, en) -> BiText: """``BiText(zh, en)``; a rule template written only in English gets its Chinese sentence (BUG-1418).""" if not any("\u4e00" <= char <= "\u9fff" for char in zh): chinese = _semantic_notes_zh().get(zh) if chinese: return BiText(chinese, zh if en is None else en) return BiText(zh, en) def _combo(cond: Dict, default_zh: str, **values) -> BiText: """Format the rule's combination template in Chinese (unchanged) and in English.""" zh = cond.get("combo_template", default_zh).format(**values) en_template = cond.get("combo_template_en") if "combo_template" in cond else DEFAULT_COMBO_EN.get(default_zh) en = None if isinstance(en_template, str): try: en = en_template.format(**{key: (value.en if isinstance(value, BiText) else value) for key, value in values.items()}) except (KeyError, IndexError, ValueError): en = None return _template_text(zh, en) def _get_dignity_level(planet: str, sign: str) -> str: """判断行星在某星座的尊严等级""" if EXALTATION.get(planet) == sign: return 'EXALTED' if SIGN_LORDS.get(sign) == planet: return 'OWN_SIGN' if MOOLATRIKONA_SIGN.get(planet) == sign: return 'MOOLATRIKONA' if DEBILITATION.get(planet) == sign: return 'DEBILITATED' return 'NEUTRAL' # ============================================================================ # Yoga formation contracts — the astrologer's scripts/yoga_output_guardrails.py # (upstream 58f37ee5b), copied byte for byte into scripts/report_render/ because # the scripts/ root .py budget is full (tests/test_python_hygiene_budget.py). # BUG-2298: was an inline copy of 1307bf69 without her `self_reference_only` / # `unqualified_formation_label_allowed` fields. # Product difference (announced): this repo's rule logic carries English twin # templates (`combo_template_en`); they are display text, not conditions, so the # definition is compared without them. # ============================================================================ try: # scripts/ on sys.path from report_render.yoga_output_guardrails import ( # noqa: F401 - re-exported 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 as _upstream_yoga_formation_contract, _formation_logic as _upstream_formation_logic, assess_yoga_formation as _upstream_assess_yoga_formation, ) from scripts.report_render.yoga_english_delivery import english_delivery_fields def _formation_logic(value: Any) -> Any: """Her `_formation_logic`, also dropping this repo's `combo_template_en` twin.""" if isinstance(value, dict): return {key: _formation_logic(item) for key, item in value.items() if key not in ('combo_template', 'combo_template_en')} if isinstance(value, list): return [_formation_logic(item) for item in value] 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' # BUG-2392 (占星师 2026-11-25 复核第五项; owner approved this frozen-file change): a kendra–trikona lord # Raja yoga whose structure is satisfied on the chart is formed (「成立」). Was: no reviewed contract, # so every hit stayed `candidate` (`source_definition_not_reviewed`). A lord that also rules the # 6th, 8th or 12th is a modifier written beside it (`formation_modifiers`), not a reason to withhold it. RAJA_STRUCTURAL_RULES = frozenset({ 'raja_yoga', 'raja_yoga_parivartana', 'dharma_karmadhipati', 'dharma_karmadhipati_parivartana', 'raja_yoga_1_4', 'raja_yoga_5_9', 'raja_yoga_4_9', 'raja_yoga_mutual_aspect', 'raja_yoga_1_10', 'raja_yoga_7_9', 'raja_yoga_5_10_lord', }) RAJA_STRUCTURAL_PROFILE = 'kendra_trikona_lord_structure' def _product_formation_contract(rule_id: str) -> Optional[dict[str, Any]]: if rule_id in RAJA_STRUCTURAL_RULES: return { 'profile': RAJA_STRUCTURAL_PROFILE, 'name': None, 'source': {'title': 'BPHS', 'section': 'Raja yoga (kendra and trikona lords)'}, # The rule's own executed definition is the definition (no second detector). 'definition': None, 'required': ['d1_scope', 'consistent_geometry', 'lord_structure'], 'variant_boundary': '角宫主与三方宫主按本条规则结合;兼管第 6、8、12 宫的宫主写在修正里。', } 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'] if contract['definition'] is not None else not evidence.get('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'] or row.get('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) # ============================================================================ # YogaContext: 封装星盘数据,提供查询接口 # ============================================================================ class YogaContext: """Yoga 检测上下文。封装行星数据并提供各类查询方法。""" def __init__(self, planets: Dict[str, Dict], ascendant: str, context: Optional[Dict] = None): self.planets = planets # name -> {sign, house, degree, ...} self.ascendant = ascendant self.asc_idx = SIGNS.index(ascendant) if ascendant in SIGNS else 0 self.context = context or {} # BUG-2298 (upstream 58f37ee5b): her D3 source evaluators read the drekkana chart. self.d3 = self.context.get("d3", {}) if isinstance(self.context, dict) else {} self.d9 = self.context.get("d9", {}) if isinstance(self.context, dict) else {} self.d60 = self.context.get("d60", {}) if isinstance(self.context, dict) else {} self.panchanga = self.context.get("panchanga", {}) if isinstance(self.context, dict) else {} self.upagraha = self.context.get("upagraha", {}) if isinstance(self.context, dict) else {} # 预计算 D1 宫主星。BUG-1211 (ruling 甲12): the main detection path uses the # fixed traditional lords (Scorpio -> Mars, Aquarius -> Saturn), as the lord # chain, functional roles and the frontend do. The v6.0.39 PyJHora "stronger # co-lord" resolver (_stronger_co_lord) is kept for Jaimini variants only and # runs only when a caller asks for dynamic_co_lords=True. self._house_lords: Dict[int, str] = {} for h in range(1, 13): sign = SIGNS[(self.asc_idx + h - 1) % 12] self._house_lords[h] = self._resolve_sign_lord(sign) # 预计算 D9 宫主星(用于依赖 Navamsa 的 B.V. Raman Yoga) d9_asc = self.d9.get("ascendant") d9_asc_idx = SIGNS.index(d9_asc) if d9_asc in SIGNS else None self._d9_house_lords: Dict[int, str] = {} if d9_asc_idx is not None: for h in range(1, 13): sign = SIGNS[(d9_asc_idx + h - 1) % 12] self._d9_house_lords[h] = self._resolve_sign_lord(sign) # 预计算 D60 宫主星(用于依赖 Shashtiamsa 的 B.V. Raman Yoga) d60_asc = self.d60.get("ascendant") d60_asc_idx = SIGNS.index(d60_asc) if d60_asc in SIGNS else None self._d60_house_lords: Dict[int, str] = {} if d60_asc_idx is not None: for h in range(1, 13): sign = SIGNS[(d60_asc_idx + h - 1) % 12] self._d60_house_lords[h] = self._resolve_sign_lord(sign) def _sign_index_of_planet(self, planet: str) -> Optional[int]: sign = self.sign_of(planet) return SIGNS.index(sign) if sign in SIGNS else None def _rasi_drishti_sign_indices_from(self, sign_idx: int) -> List[int]: sign_name = SIGNS[sign_idx] if sign_name in MOVABLE_SIGNS: return [i for i in [1, 4, 7, 10] if i not in ((sign_idx + 1) % 12, (sign_idx - 1) % 12)] if sign_name in FIXED_SIGNS: return [i for i in [0, 3, 6, 9] if i not in ((sign_idx + 1) % 12, (sign_idx - 1) % 12)] return [SIGNS.index(s) for s in DUAL_SIGNS if SIGNS.index(s) != sign_idx] def _stronger_co_lord(self, planet1: str, planet2: str) -> str: """Approximate PyJHora stronger_planet_from_planet_positions() for Sc/Aq co-lords. Jaimini-variant only (BUG-1211): reached only through `_resolve_sign_lord(..., dynamic_co_lords=True)`; no main-path caller. RAHU_KETU_OWNED_SIGN_INDEX is this comparison's internal convention, not a traditional own sign. """ h1 = self._sign_index_of_planet(planet1) h2 = self._sign_index_of_planet(planet2) if h1 is None: return planet2 if h2 is None: return planet1 node_owned_sign = RAHU_KETU_OWNED_SIGN_INDEX.get(planet1) or RAHU_KETU_OWNED_SIGN_INDEX.get(planet2) if node_owned_sign is not None: if h1 == node_owned_sign and h2 != node_owned_sign: return planet2 if h2 == node_owned_sign and h1 != node_owned_sign: return planet1 planet1_co_count = sum(1 for p in self.planets if self._sign_index_of_planet(p) == h1) - 1 planet2_co_count = sum(1 for p in self.planets if self._sign_index_of_planet(p) == h2) - 1 if planet1_co_count > planet2_co_count: return planet1 if planet2_co_count > planet1_co_count: return planet2 dispositor1 = self._resolve_sign_lord(SIGNS[h1], dynamic_co_lords=False) dispositor2 = self._resolve_sign_lord(SIGNS[h2], dynamic_co_lords=False) support1 = sum( self._sign_index_of_planet(p) == h1 for p in ['Mercury', 'Jupiter', dispositor1] if p in self.planets ) support1 += sum( p in self.planets and self._sign_index_of_planet(p) in self._rasi_drishti_sign_indices_from(h1) for p in ['Mercury', 'Jupiter', dispositor1] ) support2 = sum( self._sign_index_of_planet(p) == h2 for p in ['Mercury', 'Jupiter', dispositor2] if p in self.planets ) support2 += sum( p in self.planets and self._sign_index_of_planet(p) in self._rasi_drishti_sign_indices_from(h2) for p in ['Mercury', 'Jupiter', dispositor2] ) if support1 > support2: return planet1 if support2 > support1: return planet2 strength1 = HOUSE_STRENGTHS.get(planet1, [None] * 12)[h1] strength2 = HOUSE_STRENGTHS.get(planet2, [None] * 12)[h2] if strength1 == 4 and strength2 is not None and strength1 > strength2: return planet1 if strength2 == 4 and strength1 is not None and strength2 > strength1: return planet2 def modality_rank(sign_idx: int) -> int: sign_name = SIGNS[sign_idx] if sign_name in DUAL_SIGNS: return 3 if sign_name in FIXED_SIGNS: return 2 return 1 rank1 = modality_rank(h1) rank2 = modality_rank(h2) if rank1 > rank2: return planet1 if rank2 > rank1: return planet2 degree1 = self.degree_of(planet1) degree2 = self.degree_of(planet2) if degree1 is not None and degree2 is not None: return planet1 if degree1 > degree2 else planet2 return planet1 def _resolve_sign_lord(self, sign: str, dynamic_co_lords: Optional[bool] = None) -> Optional[str]: # BUG-2298 (upstream 58f37ee5b): the Jaimini co-lord profile is an explicit # context choice (`lordship_profile: jaimini_dynamic`); the default stays the # fixed traditional lords (BUG-1211). if dynamic_co_lords is None: dynamic_co_lords = isinstance(self.context, dict) and self.context.get('lordship_profile') == 'jaimini_dynamic' if not dynamic_co_lords: return SIGN_LORDS.get(sign) if sign == 'Scorpio': return self._stronger_co_lord('Mars', 'Ketu') if sign == 'Aquarius': return self._stronger_co_lord('Saturn', 'Rahu') return SIGN_LORDS.get(sign) # --- 基础查询 --- def house_of(self, planet: str) -> Optional[int]: return self.planets.get(planet, {}).get("house") def sign_of(self, planet: str) -> Optional[str]: return self.planets.get(planet, {}).get("sign") def degree_of(self, planet: str) -> Optional[float]: data = self.planets.get(planet, {}) return data.get("degree_in_sign", data.get("degree")) def lord_of_house(self, house: int) -> Optional[str]: return self._house_lords.get(house) def planets_in_house(self, house: int) -> List[str]: return [p for p, info in self.planets.items() if info.get("house") == house] # --- D9 / Panchanga / Upagraha 扩展上下文 --- def d9_house_of(self, planet: str) -> Optional[int]: return self.d9.get("planets", {}).get(planet, {}).get("house") def d9_sign_of(self, planet: str) -> Optional[str]: return self.d9.get("planets", {}).get(planet, {}).get("sign") def d9_lord_of_house(self, house: int) -> Optional[str]: return self._d9_house_lords.get(house) def navamsa_dispositor(self, planet: str) -> Optional[str]: sign = self.d9_sign_of(planet) return self._resolve_sign_lord(sign) if sign else None # --- D60 / Shashtiamsa 扩展上下文 --- def d60_house_of(self, planet: str) -> Optional[int]: return self.d60.get("planets", {}).get(planet, {}).get("house") def d60_sign_of(self, planet: str) -> Optional[str]: return self.d60.get("planets", {}).get(planet, {}).get("sign") def d60_lord_of_house(self, house: int) -> Optional[str]: return self._d60_house_lords.get(house) def shashtiamsa_dispositor(self, planet: str) -> Optional[str]: sign = self.d60_sign_of(planet) return self._resolve_sign_lord(sign) if sign else None # --- D9 尊严查询(用于跨分盘 Yoga 判断) --- def is_exalted_in_d9(self, planet: str) -> bool: s = self.d9_sign_of(planet) return s is not None and EXALTATION.get(planet) == s def is_debilitated_in_d9(self, planet: str) -> bool: s = self.d9_sign_of(planet) return s is not None and DEBILITATION.get(planet) == s def is_own_sign_in_d9(self, planet: str) -> bool: s = self.d9_sign_of(planet) return s is not None and self._resolve_sign_lord(s) == planet def is_moolatrikona_in_d9(self, planet: str) -> bool: s = self.d9_sign_of(planet) return s is not None and MOOLATRIKONA_SIGN.get(planet) == s def dignity_in_d9(self, planet: str) -> str: s = self.d9_sign_of(planet) return _get_dignity_level(planet, s) if s else 'NEUTRAL' def is_friendly_navamsa(self, planet: str) -> bool: """Check if planet is in friendly sign in D9 (used by dharidhra method1).""" s = self.d9_sign_of(planet) if not s: return False lord = self._resolve_sign_lord(s) return lord in FRIENDLY_PLANETS.get(planet, []) def is_unfriendly_navamsa(self, planet: str) -> bool: """Check if planet is in unfriendly/enemy sign in D9.""" s = self.d9_sign_of(planet) if not s: return False lord = self._resolve_sign_lord(s) # Enemy if not friendly and not self if lord == planet: return False return lord not in FRIENDLY_PLANETS.get(planet, []) # --- Functional Malefic / Benefic(基于月亮盈亏和宫主关系) --- def functional_malefics(self) -> List[str]: """Ownership roles only; natural nature is a separate rule predicate.""" try: from .functional_benefics import derive_functional_benefic_malefic, moon_paksha_from_planets except ImportError: from functional_benefics import derive_functional_benefic_malefic, moon_paksha_from_planets # 占星师 2026-11-08 第五轮裁定 3:默认 PVR 表 30。 return derive_functional_benefic_malefic( self.ascendant, moon_paksha=moon_paksha_from_planets(self.planets))['functional_malefics'] def functional_benefics(self) -> List[str]: """Use the same named ownership profile as the API and report.""" try: from .functional_benefics import derive_functional_benefic_malefic, moon_paksha_from_planets except ImportError: from functional_benefics import derive_functional_benefic_malefic, moon_paksha_from_planets benefics = derive_functional_benefic_malefic( self.ascendant, moon_paksha=moon_paksha_from_planets(self.planets))['functional_benefics'] return [p for p in benefics if p in self.planets] def source_degree_in_sign(self, planet: str) -> float: """Validate explicit coordinates without guessing relative/absolute units.""" import math data = self.planets.get(planet, {}) # BUG-2298 (product layer, announced): this repo's natal entry (scripts/jyotish_engine.py # cmd_yoga, sealed) sends `degree` = degree within the sign next to `lon` = absolute # longitude; her entry renamed the first to `degree_in_sign`. When an absolute longitude # is present and `degree` equals it modulo 30, `degree` is that relative copy and is read # as `degree_in_sign`. Any other `degree` still goes through her checks unchanged. if isinstance(data, dict) and 'degree_in_sign' not in data and 'degree' in data: absolute = next((data[key] for key in ('longitude', 'lon', 'degree_raw') if isinstance(data.get(key), (int, float)) and not isinstance(data.get(key), bool)), None) relative = data['degree'] if (absolute is not None and isinstance(relative, (int, float)) and not isinstance(relative, bool) and math.isfinite(absolute) and math.isfinite(relative) and abs((float(absolute) % 30) - float(relative)) < 1e-6): data = {**{k: v for k, v in data.items() if k != 'degree'}, 'degree_in_sign': float(relative)} sign = self.sign_of(planet) if sign not in SIGNS: raise MissingYogaInput(planet + '.D1.sign') values = [] for key in ('longitude', 'lon', 'degree_raw', 'degree'): if key not in data: continue value = data[key] if (isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or not 0 <= value < 360 or int(value // 30) != SIGNS.index(sign)): raise MissingYogaInput(planet + '.consistent_absolute_longitude') values.append(float(value) % 30) if 'degree_in_sign' in data: value = data['degree_in_sign'] if (isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or not 0 <= value < 30): raise MissingYogaInput(planet + '.degree_in_sign') values.append(float(value)) if not values or any(abs(v - values[0]) > 1e-9 for v in values): raise MissingYogaInput(planet + '.consistent_source_longitude') return values[0] def raman_shashtiamsa_ordinal(self, planet: str) -> int: """Manual art127: ordinal only, not D60 zodiac or good/evil class.""" segment = int(self.source_degree_in_sign(planet) * 2) + 1 sign = self.sign_of(planet) return segment if SIGNS.index(sign) % 2 == 0 else 61 - segment def saravali_shashtiamsa_comparison(self, planet: str) -> dict: """Named source alternative; no cross-author default or outcome admission.""" ordinal = self.raman_shashtiamsa_ordinal(planet) return {'source_profile': 'saravali_santhanam_vol1_printed25_literal', 'source_id': 'web:saravali_santhanam_shashtiamsa', 'source_locator': 'vol1 printed25-26 / PDF24-25', 'ordinal': ordinal, 'nature': 'malefic' if ordinal in SARAVALI_SHASHTIAMSA_MALEFIC_ORDINALS else 'benefic', 'admission_state': 'reference_only', 'default_raman_rule': False, 'personal_outcome_established': False} # --- Shashtiamsa / Vaiseshikamsa 简化评分 --- def is_shashtiamsa_evil(self, planet: str) -> bool: """D60 sign/house dignity does not establish a named cruel amsa.""" raise MissingYogaInput(f'{planet}.source_admitted_shashtiamsa_nature') def is_shashtiamsa_good(self, planet: str) -> bool: """Keep the named amsa distinction separate from D60 dignity.""" raise MissingYogaInput(f'{planet}.source_admitted_shashtiamsa_nature') def vaiseshikamsa_score(self, planet: str) -> int: """The legacy 0–20 weighted sum is not a Vaiseshikamsa method. Preserve the compatibility entry point, but require a source-defined replacement rather than returning a fabricated score or a false zero. """ raise MissingYogaInput(f'{planet}.source_admitted_vaiseshikamsa_method') def tithi(self) -> Optional[int]: return self.panchanga.get("tithi") def is_waning_moon(self) -> bool: return bool(self.panchanga.get("is_waning_moon")) def upagraha_house(self, name: str) -> Optional[int]: payload = self.upagraha.get(str(name).lower(), {}) return payload.get("house") def upagraha_sign(self, name: str) -> Optional[str]: payload = self.upagraha.get(str(name).lower(), {}) return payload.get("sign") # --- 尊严 --- def is_exalted(self, planet: str) -> bool: s = self.sign_of(planet) return s is not None and EXALTATION.get(planet) == s def is_own_sign(self, planet: str) -> bool: s = self.sign_of(planet) return s is not None and self._resolve_sign_lord(s) == planet def is_moolatrikona(self, planet: str) -> bool: """BUG-2222 (upstream b6754475): sign AND degree interval [start, end). A missing sign or an unusable degree raises `MissingYogaInput`; it is never read as "not in Moolatrikona". """ s = self.sign_of(planet) if s is None: raise MissingYogaInput(f'{planet}.sign') if MOOLATRIKONA_SIGN.get(planet) != s: return False data = self.planets.get(planet, {}) degree = data.get('degree_in_sign', data.get('degree')) if (isinstance(degree, bool) or not isinstance(degree, (int, float)) or not math.isfinite(degree) or degree < 0): raise MissingYogaInput(f'{planet}.degree_in_sign') if 'degree_in_sign' in data: if degree >= 30: raise MissingYogaInput(f'{planet}.degree_in_sign') elif degree >= 30: # Native degree is absolute longitude; historical callers also # provide an in-sign degree. Never wrap a conflicting longitude. if degree >= 360 or int(degree // 30) != SIGNS.index(s): raise MissingYogaInput(f'{planet}.degree_in_sign') degree %= 30 start, end = MOOLATRIKONA_DEGREES[planet] return start <= degree < end def parashari_aspects_house(self, source: str, house: int) -> bool: """BUG-2296: upstream 58f37ee5b (yoga_expression_paths reads it); a planet's graha drishti on a house.""" if source in {'Rahu', 'Ketu'} or source not in self.planets: return False source_house = self.house_of(source) if source_house is None: return False offset = self.house_offset(source_house, house) return offset == 6 or ( source == 'Mars' and offset in (3, 7) ) or ( source == 'Jupiter' and offset in (4, 8) ) or ( source == 'Saturn' and offset in (2, 9) ) def parashari_aspect(self, source: str, target: str) -> bool: """Shared ordinary-reading graha drishti; nodes do not aspect (upstream b6754475).""" if source == target or source in {'Rahu', 'Ketu'}: return False source_house = self.house_of(source) target_house = self.house_of(target) if source_house is None or target_house is None: return False offset = self.house_offset(source_house, target_house) return offset == 6 or ( source == 'Mars' and offset in (3, 7) ) or ( source == 'Jupiter' and offset in (4, 8) ) or ( source == 'Saturn' and offset in (2, 9) ) def is_debilitated(self, planet: str) -> bool: s = self.sign_of(planet) return s is not None and DEBILITATION.get(planet) == s def dignity(self, planet: str) -> str: s = self.sign_of(planet) return _get_dignity_level(planet, s) if s else 'NEUTRAL' # --- 宫位性质 --- def is_kendra(self, house: int) -> bool: return house in [1, 4, 7, 10] def is_trikona(self, house: int) -> bool: return house in [1, 5, 9] def is_dusthana(self, house: int) -> bool: return house in [6, 8, 12] def is_upachaya(self, house: int) -> bool: return house in [3, 6, 10, 11] def is_maraka(self, house: int) -> bool: return house in [2, 7] def is_badhaka(self, house: int) -> bool: """Badhaka 宫:变动上升 11 宫,固定上升 9 宫,双体上升 7 宫。""" return badhaka_house(self.ascendant) == house # --- 相对宫位关系 --- def house_offset(self, from_house: int, to_house: int) -> int: """从 from_house 到 to_house 的宫位偏移 (0=同宫, 1=下一宫, ...)""" return (to_house - from_house) % 12 def is_kendra_from(self, planet: str, from_planet: str) -> bool: h1 = self.house_of(from_planet) h2 = self.house_of(planet) if h1 is None or h2 is None: return False return self.house_offset(h1, h2) in [0, 3, 6, 9] def is_trikona_from(self, planet: str, from_planet: str) -> bool: h1 = self.house_of(from_planet) h2 = self.house_of(planet) if h1 is None or h2 is None: return False return self.house_offset(h1, h2) in [0, 4, 8] def is_2nd_or_12th_from(self, planet: str, from_planet: str) -> bool: h1 = self.house_of(from_planet) h2 = self.house_of(planet) if h1 is None or h2 is None: return False return self.house_offset(h1, h2) in [1, 11] # --- 角色解析 --- def resolve(self, ref: Any) -> List[str]: """ 解析行星引用为具体行星名称列表。 支持: 字符串行星名、角色对象、角色字符串。 """ if isinstance(ref, str): if ref in self.planets: return [ref] if ref == "benefics": return [p for p in BENEFICS if p in self.planets] if ref == "malefics": return [p for p in MALEFICS if p in self.planets] if ref == "all": return list(self.planets.keys()) if ref in ("visible", "sun_to_saturn"): return [p for p in ['Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn'] if p in self.planets] if ref == "kendra_lords": return list(dict.fromkeys([self._house_lords[h] for h in [1, 4, 7, 10]])) if ref == "trikona_lords": return list(dict.fromkeys([self._house_lords[h] for h in [1, 5, 9]])) if ref == "dusthana_lords": return list(dict.fromkeys([self._house_lords[h] for h in [6, 8, 12]])) if ref == "upachaya_lords": return list(dict.fromkeys([self._house_lords[h] for h in [3, 6, 10, 11]])) if ref.startswith("lord:"): house = int(ref.split(":")[1]) lord = self._house_lords.get(house) return [lord] if lord else [] return [] if isinstance(ref, dict): role = ref.get("role") if role == "lord": house = ref.get("house") lord = self._house_lords.get(house) return [lord] if lord else [] if role == "kendra_lords": return list(dict.fromkeys([self._house_lords[h] for h in [1, 4, 7, 10]])) if role == "trikona_lords": return list(dict.fromkeys([self._house_lords[h] for h in [1, 5, 9]])) if role == "dusthana_lords": return list(dict.fromkeys([self._house_lords[h] for h in [6, 8, 12]])) if role == "upachaya_lords": return list(dict.fromkeys([self._house_lords[h] for h in [3, 6, 10, 11]])) if role == "benefics": return [p for p in BENEFICS if p in self.planets] if role == "malefics": return [p for p in MALEFICS if p in self.planets] if role == "all": return list(self.planets.keys()) if role in ("visible", "sun_to_saturn"): return [p for p in ['Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn'] if p in self.planets] if role == "set": return [p for p in ref.get("planets", []) if p in self.planets] return [] def resolve_single(self, ref: Any) -> Optional[str]: """解析为单个行星,返回 None 或行星名""" lst = self.resolve(ref) return lst[0] if lst else None # ============================================================================ # custom 规则表达式的编译缓存(BUG-735) # ============================================================================ # `expr` 只来自仓库内的静态规则表 references/yoga_rules.json,进程生命周期内不变, # 改前却每个请求重新编译一遍(本机实测 386 次/次检测:182 次 eval 字符串编译 + # 204 次 ast.parse/compile)。这里只缓存 code object。 # # 硬约束:求值命名空间 exec_globals 依赖每次不同的盘上下文(ctx),必须每次新建; # 绝不缓存求值结果——缓存结果会让所有人拿到同一张盘的 yoga 判定。 # # maxsize 512:规则表去重后 192 条表达式,留出增长余量,同时给缓存一个硬上界。 _CUSTOM_EXPR_CACHE_MAXSIZE = 512 def _capture_tail_expr(block): """把代码块末尾表达式改写为 __result__ = ;递归处理 if/for/while 分支。""" if not block: return block last = block[-1] if isinstance(last, ast.Expr): block[-1] = ast.Assign(targets=[ast.Name(id="__result__", ctx=ast.Store())], value=last.value) elif isinstance(last, ast.If): last.body = _capture_tail_expr(last.body) last.orelse = _capture_tail_expr(last.orelse) elif isinstance(last, (ast.For, ast.While)): last.body = _capture_tail_expr(last.body) last.orelse = _capture_tail_expr(last.orelse) elif isinstance(last, ast.Try): last.body = _capture_tail_expr(last.body) last.orelse = _capture_tail_expr(last.orelse) last.finalbody = _capture_tail_expr(last.finalbody) for handler in last.handlers: handler.body = _capture_tail_expr(handler.body) return block @functools.lru_cache(maxsize=_CUSTOM_EXPR_CACHE_MAXSIZE) def _compiled_eval_code(expr): """表达式模式的 code object;不是单个 expression 时返回 None(改前由 SyntaxError 表达)。""" try: return compile(expr, "", "eval") except SyntaxError: return None @functools.lru_cache(maxsize=_CUSTOM_EXPR_CACHE_MAXSIZE) def _compiled_exec_code(expr): """多语句模式的 code object:先按 AST 捕获末尾表达式,再编译。 v6.0.32: 支持多行语句(if/else/for 等)+ 末尾表达式求值模式。 不能简单 split 最后一行:多行 if/else 的最后一行经常只是 else 分支内部表达式, 直接 exec 前半段会产生缩进不完整。这里用 AST 捕获“实际执行分支”的末尾表达式。 """ try: tree = ast.parse(expr.strip(), mode="exec") tree.body = _capture_tail_expr(tree.body) ast.fix_missing_locations(tree) return compile(tree, "", "exec") except Exception: # noqa: BLE001 - compile failure; _run_custom_expr raises YogaRuleEvaluationError return None class YogaRuleEvaluationError(Exception): """A rule could not be evaluated (占星师第三轮审查 2026-11-07, item 1). Distinct from "condition false": the caller records the rule as `evaluation_failed` with the error class, never as not formed. """ def __init__(self, error_class: str, message: str = ""): super().__init__(f"{error_class}: {message}" if message else error_class) self.error_class = error_class self.error_message = message class UnsupportedYogaCondition(YogaRuleEvaluationError): """A rule names condition types no evaluator implements (rulings.md A3). Raised by the preflight in `YogaEngine._eval_rule` before any branch is evaluated, so AND short-circuits, a computable OR branch or a NOT inversion cannot turn a missing implementation into "formed" or "not formed". """ def __init__(self, conditions): self.conditions = sorted(set(conditions)) super().__init__("UnsupportedConditionType", ", ".join(self.conditions)) class MissingYogaInput(YogaRuleEvaluationError): """An evaluated predicate lacks a required measurement, not a negative match. BUG-2222 (upstream yinduzhanxing b6754475): a missing sign, degree, house or D9 placement is neither "formed" nor "not formed"; the rule's failure row carries `condition_status = incomplete_conditions` and the missing fields. """ def __init__(self, field): self.fields = [field] super().__init__("MissingYogaInput", field) # BUG-2299 (upstream 58f37ee5b `detect`): the five effect statuses her source evaluators # return; each keeps the structure and source but no traditional verdict as a personal result. EFFECT_QUALIFICATIONS = { 'source_neutralized': ('木星照射的缓解条件已满足;不据月土同宫判定言语性格。', 'The source-neutralizing Jupiter aspect is present; do not infer a speech trait from the conjunction.'), 'incomplete': ('影响表现的条件资料不全;结构记录不等于个人结论。', 'Expression qualifiers have missing inputs; the structural match is not a personal conclusion.'), 'historical_medical_reference': ('仅保留传统结构,不据此判断疾病、伤残或治疗结果。', 'Historical structure only; no diagnosis, disability or treatment outcome is inferred.'), 'historical_injury_reference': ('仅保留传统结构,不据此判断战争、伤害或死亡事件。', 'Historical structure only; no war, injury or death event is established.'), 'historical_conduct_reference': ('仅保留传统结构,不能据此认定本人或伴侣不忠。', 'Historical structure only; no infidelity or personal conduct is established.'), } GATED_EFFECT_STATUSES = frozenset(EFFECT_QUALIFICATIONS) def _withhold_effects(entry: Dict) -> None: """Move the traditional effects (both languages) aside; the row states no verdict.""" entry.setdefault('traditional_effects', entry.get('effects') or []) entry['effects'] = [] # Her rows drop the English twin (`entry.pop('effects_en')`); no empty list is left behind. if entry.get('effects_en'): entry.setdefault('traditional_effects_en', entry['effects_en']) entry.pop('effects_en', None) entry['strength'] = 'conditional' entry['strength_en'] = 'Conditional' def _apply_effect_and_method_gates(entry: Dict, rule: Dict, match: Dict) -> None: """Her `effect_assessment` and `method_review` gates, then her row status fields. BUG-2299 (upstream 58f37ee5b `detect`). Was: neither gate existed here; a matched rule always carried its traditional effects. """ assessment = match.get('effect_assessment') if isinstance(assessment, dict) and assessment: entry['effect_assessment'] = dict(assessment) status = assessment.get('status') if status in EFFECT_QUALIFICATIONS: zh, en = EFFECT_QUALIFICATIONS[status] zh = assessment.get('summary_zh', zh) en = assessment.get('summary_en', en) entry['effect_assessment'].update({'summary_zh': zh, 'summary_en': en}) entry['combination'] = str(entry.get('combination') or '') + ';' + zh if entry.get('combination_en'): entry['combination_en'] = str(entry['combination_en']) + ' ' + en _withhold_effects(entry) if rule.get('method_review'): entry['method_review'] = dict(rule['method_review']) if entry['method_review'].get('status') == 'pending': # Preserve the matched structure and traditional claims without treating # an unresolved method as adjudicated. _withhold_effects(entry) entry.setdefault('condition_status', 'method_requires_review') entry['formation_status'] = entry.get('condition_status', 'conditions_met') entry['evidence_status'] = 'local_rule_match' entry['display_status'] = 'candidate_review' entry['assertion_label'] = 'single_system_inference' entry['claim_boundary'] = ('Named rule conditions only; external validation and real-life ' 'results are not established by detection.') # A local rule match is useful evidence, but it is not an independently verified # traditional yoga. Keep this explicit so downstream cards cannot silently promote it # to a definitive interpretation. (BUG-2301: was set only on restricted rows in # BUG-2299; the chart page reads `card_status` now, see frontend chart-view-insight.ts.) entry['card_eligible'] = False entry['card_status'] = 'reference_only' entry['card_block_reason'] = ( 'Traditional yoga is detected by the local rule library; independent source/case ' 'verification is still required before it can appear as a conclusion card.') def _blocked_rule_row(rule: Dict, exc: BaseException, ctx: "YogaContext") -> Dict: """Her failure row (upstream 58f37ee5b `detect`): neither formed nor ruled out.""" failure_status = ('incomplete_conditions' if isinstance(exc, MissingYogaInput) else 'not_implemented' if isinstance(exc, UnsupportedYogaCondition) else 'evaluation_error') return { 'rule_id': rule.get('id', ''), 'name': rule.get('name', ''), 'name_cn': rule.get('name_cn', ''), 'source': rule.get('source', ''), 'category': rule.get('category') or 'unclassified_rule', 'formation_status': failure_status, 'condition_status': failure_status, 'evidence_status': failure_status, 'unsupported_conditions': getattr(exc, 'conditions', []), 'missing_inputs': getattr(exc, 'fields', []), 'display_status': 'blocked', 'assertion_label': 'blocked', 'card_eligible': False, 'card_status': 'blocked', 'effects': [], 'effects_en': [], 'planets': [], 'strength': 'not_assessed', 'combination': '', 'error_type': type(exc).__name__, 'claim_boundary': 'Rule evaluation failed; no formation or outcome is inferred.', # An unavailable predicate must not erase its reviewed definition/source or turn # a source gap into absence. 'source_reference': rule.get('source_reference', rule.get('source', '')), 'combination_en': rule.get('combination_en', ''), 'english_source_reference': rule.get('english_source_reference', ''), 'traditional_effects': list(rule.get('effects') or []), 'traditional_effects_en': list(rule.get('effects_en') or []), 'source_method_notes': list(rule.get('source_method_notes') or []), 'condition_evidence': { 'rule_id': rule.get('id'), 'definition': rule.get('logic'), 'source_reference': rule.get('source_reference', rule.get('source', '')), 'execution_trace': list(getattr(ctx, 'condition_execution_trace', []) or []), 'trace_scope': 'executed_condition_nodes_before_failure; not a successful evaluation', 'participants': {}, }, } BLOCKED_ROW_STATUSES = frozenset({'incomplete_conditions', 'not_implemented', 'evaluation_error'}) def is_blocked_rule_row(row: Any) -> bool: """True for a `detect` row that records a rule evaluation failure (BUG-2299).""" return (isinstance(row, dict) and row.get('display_status') == 'blocked' and row.get('formation_status') in BLOCKED_ROW_STATUSES) def _upstream_calc_arudha_sign(house_sign_idx: int, lord_sign_idx: int) -> Dict: """Her scripts/jaimini.py `calc_arudha_sign` (upstream 58f37ee5b), copied unchanged (BUG-2301). Shared PVR §9.2 sign-counting rule; lord selection is caller-owned. This repo's jaimini.py is sealed and does not have the function. """ source = house_sign_idx % 12 lord = lord_sign_idx % 12 distance = ((lord - source) % 12) + 1 initial = (lord + distance - 1) % 12 exception = initial in (source, (source + 6) % 12) final = (initial + 9) % 12 if exception else initial return { 'sign': SIGNS[final % 12], 'sign_idx': final, 'distance': distance, 'unadjusted_sign': SIGNS[initial % 12], 'exception_triggered': exception, 'exception_rule': 'pvr_9_2_tenth_from_unadjusted_pada_v1', } _NEECHA_SIGN_ZH = {'Aries': '白羊座', 'Taurus': '金牛座', 'Gemini': '双子座', 'Cancer': '巨蟹座', 'Leo': '狮子座', 'Virgo': '处女座', 'Libra': '天秤座', 'Scorpio': '天蝎座', 'Sagittarius': '射手座', 'Capricorn': '摩羯座', 'Aquarius': '水瓶座', 'Pisces': '双鱼座'} def _neecha_reason_text(reason: Dict, planet: str, ctx: "YogaContext") -> "BiText": """One cancellation witness of her `_eval_neecha_bhanga` in reader words (zh / en).""" code = str(reason.get('condition') or '') other = str(reason.get('planet') or '') oz, pz = PLANET_ZH.get(other, other), PLANET_ZH.get(planet, planet) role_zh, role_en = (('落陷星座主星', 'dispositor') if code.startswith('dispositor') else ('该星入旺星座的主星', 'lord of its exaltation sign') if code.startswith('exaltation_sign_lord') else ('会在该星座入旺的', 'the planet exalted in that sign')) if code.endswith('_kendra_from_lagna'): house = ctx.house_of(other) return BiText(f'{role_zh}{oz}在上升起第{house}宫(角宫)', f'{role_en} {other} in house {house} from the Lagna (kendra)') if code.endswith('_kendra_from_moon'): house = reason.get('relative_house') return BiText(f'{role_zh}{oz}在月亮起第{house}宫(角宫)', f'{role_en} {other} in house {house} from the Moon (kendra)') if code == 'dispositor_aspect': return BiText(f'落陷星座主星{oz}照射{pz}', f'dispositor {other} aspects {planet}') if code == 'dispositor_exchange': return BiText(f'{pz}与落陷星座主星{oz}互换星座', f'{planet} and its dispositor {other} exchange signs') return BiText(code, code) def _neecha_reader_match(match: Dict, ctx: "YogaContext") -> Dict: """BUG-2303 (product layer, announced): her Neecha Bhanga match with a reader combination. Her `_eval_neecha_bhanga` writes condition codes (``dispositor_kendra_from_lagna=Saturn``) into the combination; the reader sees the same witnesses in words, as the retired main detector wrote them. The codes stay in `formation_evidence.cancellation_reasons`. """ evidence = match.get('formation_evidence') or {} planet = evidence.get('planet') reasons = [r for r in evidence.get('cancellation_reasons') or [] if isinstance(r, dict)] if not planet or not reasons: return match sign = ctx.sign_of(planet) # BUG-2027: the Moon measured from itself is recorded but is not listed as a condition for the reader. texts = [_neecha_reason_text(reason, planet, ctx) for reason in reasons if not reason.get('self_reference')] head_zh = f'{PLANET_ZH.get(planet, planet)}落陷于{_NEECHA_SIGN_ZH.get(sign, sign)}' head_en = f'{planet} debilitated in {sign}' if texts: combo = BiText(head_zh + ';成立条件:' + ';'.join(texts), head_en + '; conditions met: ' + '; '.join(t.en for t in texts)) else: combo = BiText(head_zh + ';只有以月亮自身为参照的一条,不算独立的缓解条件', head_en + '; only the branch measured from the Moon itself, which is not an independent mitigation') # Her kendra-from-Lagna witnesses carry no house; the page names it, so a copy of each gets the # witness's house from the Lagna (an added fact, her verdict unchanged). reasons_out = [({**reason, 'house': ctx.house_of(reason.get('planet'))} if str(reason.get('condition') or '').endswith('_kendra_from_lagna') and 'house' not in reason else reason) for reason in evidence.get('cancellation_reasons') or []] return {**match, 'combination': combo, 'combination_en': combo.en, 'formation_evidence': {**evidence, 'cancellation_reasons': reasons_out}} def evaluation_failure_row(rule: Dict, exc: BaseException) -> Dict: """The record of one rule that could not be evaluated on this chart.""" error_class = getattr(exc, "error_class", None) or type(exc).__name__ message = getattr(exc, "error_message", None) if message is None: message = str(exc) if isinstance(exc, MissingYogaInput): # BUG-2222: missing input is an incomplete evaluation, not an error and # not a negative match. return { "rule_id": rule.get("id", ""), "name": rule.get("name", ""), "name_cn": rule.get("name_cn", ""), "category": rule.get("category") or "unclassified_rule", "condition_status": "incomplete_conditions", "evidence_status": "incomplete_conditions", "missing_inputs": list(exc.fields), "error_class": error_class, "error_message": str(message)[:160], "claim_boundary": "Required chart input is missing; the yoga is neither formed nor ruled out.", "claim_boundary_zh": "缺少必要的星盘输入,不能判成立,也不能判不成立。", } return { "rule_id": rule.get("id", ""), "name": rule.get("name", ""), "name_cn": rule.get("name_cn", ""), # 交接 8c775cd0(r40):诊断行保留规则分类 "category": rule.get("category") or "unclassified_rule", "condition_status": "evaluation_failed", "error_class": error_class, "error_message": str(message)[:160], "claim_boundary": "Evaluation failed; this is not evidence that the yoga is absent.", "claim_boundary_zh": "规则求值失败,不能当作该格局不成立。", } @functools.lru_cache(maxsize=1) def _shadbala_mercury_rule(): """shadbala.mercury_malefic_companions, imported on first use. #166 (BUG-1624): the strict Gajakesari supporter check reuses the one implementation of the Mercury-by-association rule (BPHS 3.10-11 as labelled by shadbala.MERCURY_NATURE_CONVENTION) instead of re-deciding it. Imported lazily because shadbala pulls in swisseph; no import cycle (shadbala imports only varga / ayanamsa_utils). """ try: # scripts/ on sys.path from shadbala import mercury_malefic_companions except ImportError: # package import (scripts.yoga_engine) from scripts.shadbala import mercury_malefic_companions return mercury_malefic_companions def _run_custom_expr(expr, exec_globals, branch_run=None): """按改前语义求值 custom 表达式:先表达式模式,SyntaxError 退到多语句 exec 模式。 只有 code object 来自缓存;`exec_globals` 由调用方每次新建。 求值或编译失败抛 YogaRuleEvaluationError(第三轮审查 2026-11-07:改前返回 None, 失败被当成「条件不成立」)。 BUG-2170 (占星师 2026-11-22 裁定 7.2): with a `_BranchRun`, an expression whose top level is `and` / `or` runs as its instrumented code object (`_instrumented_branch_plan`, cached like BUG-735): the same single evaluation, in which each and/or/not operand passes its value through a recorder on the way. Short-circuit order and the returned operand are Python's own; nothing is evaluated a second time. Without `branch_run` (e.g. `participants_expr`) nothing changes. """ result = None code = _compiled_eval_code(expr) if code is not None: recording = False if branch_run is not None: branch_run.mode = "expression" instrumented = _instrumented_branch_plan(expr) if instrumented is not None: code, branch_run.plan, slots = instrumented branch_run.values = [_BRANCH_NOT_REACHED] * slots exec_globals[_BRANCH_RECORDER_NAME] = branch_run.record recording = True try: # 同一命名空间同时作为 globals/locals,保证 list/dict comprehension 能访问 BENEFICS 等名称。 result = eval(code, exec_globals, exec_globals) except SyntaxError: code = None # 运行期 SyntaxError:与改前一样退到多语句分支 except Exception as exc: # noqa: BLE001 - surfaced as evaluation_failed, never as "not formed" if branch_run is not None: branch_run.error = type(exc).__name__ if isinstance(exc, MissingYogaInput): raise # BUG-2222: keep the missing fields; not an expression error raise YogaRuleEvaluationError(type(exc).__name__, str(exc)) from exc finally: if recording: exec_globals.pop(_BRANCH_RECORDER_NAME, None) if code is None: if branch_run is not None: branch_run.mode, branch_run.plan, branch_run.values = "statements", None, None exec_code = _compiled_exec_code(expr) if exec_code is None: if branch_run is not None: branch_run.error = "SyntaxError" raise YogaRuleEvaluationError("SyntaxError", "custom expression does not compile") try: exec(exec_code, exec_globals, exec_globals) result = exec_globals.get("__result__") except Exception as exc: # noqa: BLE001 - surfaced as evaluation_failed, never as "not formed" if branch_run is not None: branch_run.error = type(exc).__name__ if isinstance(exc, MissingYogaInput): raise # BUG-2222: keep the missing fields; not an expression error raise YogaRuleEvaluationError(type(exc).__name__, str(exc)) from exc return result # BUG-2170: the branch record of a custom expression comes from its one original evaluation. _BRANCH_RECORDER_NAME = "__yoga_branch_record__" _BRANCH_NOT_REACHED = object() # a recorder slot that was never written: the operand did not finish _BRANCH_RECORD_IDENTITY = {"record_identity": "branch_record_from_original_evaluation", "record_identity_zh": "原执行分支记录"} class _BranchRun: """The recorder slots of one custom evaluation (BUG-2170); a fresh one per evaluation.""" __slots__ = ("mode", "plan", "values", "error") def __init__(self): self.mode, self.plan, self.values, self.error = None, None, None, None def record(self, slot, value): """Called from the instrumented code with an operand's value; returns it unchanged.""" self.values[slot] = value return value def _branch_splittable(node): """An and/or node, or `not` over one (any depth); everything else is a leaf operand.""" while isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not): node = node.operand return isinstance(node, ast.BoolOp) @functools.lru_cache(maxsize=_CUSTOM_EXPR_CACHE_MAXSIZE) def _instrumented_branch_plan(expr): """(instrumented code, plan, slot count) for an expression whose top level is and/or, else None. The plan is the and/or/not tree read from the rule's own source; each non-root node has a recorder slot, and the copy that is compiled wraps that node as `__yoga_branch_record__(slot, )`. A wrapped operand is still evaluated by its parent and/or in place (an argument of the call, in the same scope), so it runs only when Python reaches it and its value is returned as-is. Leaves are never entered: `any()` / `all()` and comprehensions stay one operand. Plans are read-only tuples / dicts shared through the cache. """ if _compiled_eval_code(expr) is None: return None try: tree = ast.parse(expr, mode="eval") # own copy: the cached _parsed_custom_expr tree stays untouched except SyntaxError: return None if not isinstance(tree.body, ast.BoolOp): return None slots = [0] def wrap(node, slot): call = ast.Call(func=ast.Name(id=_BRANCH_RECORDER_NAME, ctx=ast.Load()), args=[ast.Constant(value=slot), node], keywords=[]) return ast.copy_location(call, node) def plan(node, position): source = ast.get_source_segment(expr, node) or ast.unparse(node) if isinstance(node, ast.BoolOp): children = [] for index, value in enumerate(node.values): child, slot = plan(value, position + (index,)) node.values[index] = wrap(value, slot) children.append(child) item = {"kind": "and" if isinstance(node.op, ast.And) else "or", "source": source, "position": position, "children": tuple(children)} elif isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not) and _branch_splittable(node.operand): child, slot = plan(node.operand, position + (0,)) node.operand = wrap(node.operand, slot) item = {"kind": "not", "source": source, "position": position, "children": (child,)} else: refs = {"planets": sorted({n.value for n in ast.walk(node) if isinstance(n, ast.Constant) and isinstance(n.value, str) and n.value in PLANET_INDEX}), "house_lords": sorted({n.args[0].value for n in ast.walk(node) if isinstance(n, ast.Call) and isinstance(n.func, ast.Name) and n.func.id in ("lords_of", "lord", "lord_of_house") and len(n.args) == 1 and isinstance(n.args[0], ast.Constant) and type(n.args[0].value) is int})} presence = (isinstance(node, ast.Compare) and len(node.ops) == 1 and isinstance(node.ops[0], ast.In) and isinstance(node.comparators[0], ast.Name) and node.comparators[0].id == "planets") item = {"kind": "operand", "source": source, "position": position, "refs": refs, "presence": presence} slot = slots[0] slots[0] += 1 return dict(item, slot=slot), slot try: root, _root_slot = plan(tree.body, ()) # the root's slot is unused: its value is the result code = compile(ast.fix_missing_locations(tree), "", "eval") except Exception: # noqa: BLE001 - an expression that does not instrument stays one whole node return None return code, root, slots[0] def _branch_digest(value): """Short deterministic sha256 of plain data (rules, chart inputs, bindings).""" import hashlib def canon(item): if isinstance(item, dict): return [[str(key), canon(val)] for key, val in sorted(item.items(), key=lambda kv: str(kv[0]))] if isinstance(item, (list, tuple)): return [canon(val) for val in item] if isinstance(item, (set, frozenset)): return sorted((canon(val) for val in item), key=repr) if item is None or isinstance(item, (bool, int, float, str)): return item if callable(item): return f"" if type(item).__str__ is object.__str__ and type(item).__repr__ is object.__repr__: return f"<{type(item).__name__}>" return f"<{type(item).__name__}:{item}>" try: # plain JSON data (rules, charts): the C encoder; anything else goes through canon() text = json.dumps(value, ensure_ascii=False, separators=(",", ":"), sort_keys=True, default=canon) except (TypeError, ValueError): # e.g. dict keys of mixed types text = json.dumps(canon(value), ensure_ascii=False, separators=(",", ":")) return hashlib.sha256(text.encode("utf-8")).hexdigest()[:16] @functools.lru_cache(maxsize=_CUSTOM_EXPR_CACHE_MAXSIZE) def _branch_expression_digest(expr): return _branch_digest(expr) def _branch_record_binding(expr, exec_globals, rule, bindings): """What one record is bound to: rule id + content hash, expression hash, input snapshot hash. The chart part of the snapshot (ascendant, planets, context) and each rule's content are hashed once per YogaContext (one detection); the node's own bindings are added per evaluation. """ ctx = exec_globals.get("ctx") chart = None if ctx is not None: chart = ctx.__dict__.get("_branch_input_digest") if chart is None: chart = _branch_digest({"ascendant": getattr(ctx, "ascendant", None), "planets": getattr(ctx, "planets", None), "context": getattr(ctx, "context", None)}) ctx.__dict__["_branch_input_digest"] = chart rule = rule or {} rule_hash = None if ctx is not None: # one detection = one context: a rule is hashed once per detection cached = ctx.__dict__.setdefault("_branch_rule_digests", {}).get(id(rule)) if cached is not None and cached[0] is rule: rule_hash = cached[1] if rule_hash is None: rule_hash = _branch_digest(rule) if ctx is not None: ctx.__dict__["_branch_rule_digests"][id(rule)] = (rule, rule_hash) return {"rule_id": rule.get("id"), "rule_content_hash": rule_hash, "expression_hash": _branch_expression_digest(expr), "input_snapshot_hash": _branch_digest({"chart": chart, "bindings": bindings or {}}), "hash_method": "sha256_16hex"} def _custom_branch_trace(expr, exec_globals, result, branch_run=None, rule=None, bindings=None): """BUG-2124 → BUG-2170 (占星师 2026-11-22 裁定 7.2): the branch record from the original evaluation. 原执行分支记录 / "branch record from the original evaluation": built from the recorder slots that `_run_custom_expr` filled during the rule's one real evaluation (no second run, no namespace copy). Only an expression whose top level is `and` / `or` is split (nested and/or/not inside it too); each node is 'true' / 'false' by Python truthiness of the value it returned (its `value_type` is kept, so 0, False and [] stay distinguishable); an operand Python skipped by short-circuit is 'not_evaluated' (never 'false'); a `None` value or a failed `'X' in planets` presence check is 'unknown' (missing input); the operand that raised is 'error' with its class (the rule still fails exactly as before; this record rides on the exception). The values recorded on the way must re-derive the result Python returned (and/or return operands); if they do not, a warning is logged and the record is 'unavailable', never silently dropped. Statement-mode expressions and expressions whose top is not and/or (any() / all() included) are one node: 'whole_condition_not_split'. Every record is bound to the rule id, a rule-content hash, the expression hash and an input snapshot hash; each node carries its index path. """ failed = branch_run is not None and branch_run.error is not None held = bool(result) base = dict(_BRANCH_RECORD_IDENTITY) base["binding"] = _branch_record_binding(expr, exec_globals, rule, bindings) plan = branch_run.plan if branch_run is not None else None whole = {"kind": "whole", "result": "error" if failed else ("true" if held else "false"), "label_zh": "整体条件,未拆分", "label_en": "Whole condition, not split"} if failed: whole["error_class"] = branch_run.error if plan is None: mode = (branch_run.mode if branch_run is not None and branch_run.mode else ("expression" if _compiled_eval_code(expr) is not None else "statements")) return {**base, "trace_status": "whole_condition_not_split", "expression_mode": mode, "result": None if failed else held, "tree": whole} values = branch_run.values ctx = exec_globals.get("ctx") mismatch = [] def label_of(value): return "true" if value else "false" def skipped(item): node = {"kind": item["kind"], "source": item["source"], "position": list(item["position"]), "result": "not_evaluated"} if item["kind"] != "operand": node["children"] = [skipped(child) for child in item["children"]] return node def check(item, value, root): """The value re-derived from the children must be what this node really returned.""" actual = result if root else values[item["slot"]] if actual is _BRANCH_NOT_REACHED or not (actual is value or (item["kind"] == "not" and actual == value)): mismatch.append(list(item["position"])) def build(item, root=False): """(value, node, raised) for a node Python reached.""" node = {"kind": item["kind"], "source": item["source"], "position": list(item["position"])} if item["kind"] == "operand": value = values[item["slot"]] if value is _BRANCH_NOT_REACHED: if not failed: mismatch.append(list(item["position"])) node["result"] = "error" node["error_class"] = branch_run.error if failed else None return None, node, True node["value_type"] = type(value).__name__ if value is None: node["result"] = "unknown" elif item["presence"] and not value: node["result"] = "unknown" node["unknown_reason"] = "missing_input" else: node["result"] = label_of(value) facts = {} if ctx is not None: refs = item["refs"] lords = {str(h): ctx.lord_of_house(h) for h in refs["house_lords"]} if lords: facts["house_lords"] = lords named = sorted(set(refs["planets"]) | {p for p in lords.values() if p}) placed = {p: {"house": ctx.house_of(p), "sign": ctx.sign_of(p)} for p in named if p in ctx.planets} if placed: facts["planets"] = placed if facts: node["facts"] = facts return value, node, False if item["kind"] == "not": inner, child, raised = build(item["children"][0]) node["children"] = [child] if raised: node["result"] = "error" return None, node, True value = not inner node["value_type"] = "bool" node["result"] = "unknown" if child["result"] == "unknown" else label_of(value) check(item, value, root) return value, node, False op, nodes, value, last, stopped, raised = item["kind"], [], None, None, False, False for child_item in item["children"]: if stopped: nodes.append(skipped(child_item)) continue value, last, raised = build(child_item) nodes.append(last) stopped = raised or ((not value) if op == "and" else bool(value)) node["children"] = nodes if raised: node["result"] = "error" return None, node, True node["value_type"] = type(value).__name__ # A false and / or that rests on an unknown operand is unknown, not false. node["result"] = "true" if value else ("unknown" if value is None or (last["result"] == "unknown" if op == "and" else any(n["result"] == "unknown" for n in nodes)) else "false") check(item, value, root) return value, node, False try: _value, tree, _raised = build(plan, root=True) except Exception as exc: # noqa: BLE001 - e.g. a value whose truth test raises: no story is made up mismatch.append(f"rebuild_raised:{type(exc).__name__}") tree = whole if mismatch: import logging logging.getLogger(__name__).warning( "BUG-2170 custom branch record unavailable: rule %s, recorded values do not re-derive the " "evaluated result at %s", base["binding"].get("rule_id"), mismatch) return {**base, "trace_status": "unavailable", "unavailable_reason": "recorded_values_differ_from_result", "expression_mode": "expression", "result": None if failed else held, "tree": whole, "mismatch_positions": mismatch} if failed: return {**base, "trace_status": "evaluation_error", "expression_mode": "expression", "result": None, "error_class": branch_run.error, "tree": tree} return {**base, "trace_status": "split", "expression_mode": "expression", "result": held, "tree": tree} def _row_custom_branch_traces(logic, match, execution_trace): """BUG-2124: branch records of the custom nodes that took part in one matched instance. None when the rule has no custom node (the row then has no key). A match that came straight from a custom node (alone, through `or`, `any_planet`/`exists` or a pair loop) still carries its own record. Otherwise (the custom node sat inside `and` / `all_planets` / `count`, which build new match dicts) the records are taken from this rule's execution trace: custom entries that matched, whose input bindings agree with the instance's bindings. In the current rule library every custom node is the rule itself, a direct child of the top-level `and`, or under `all_planets`, where every matched custom entry is part of the instance. """ def has_custom(node): if isinstance(node, dict): return (node.get('type') or node.get('op')) == 'custom' or any(has_custom(v) for v in node.values()) return isinstance(node, list) and any(has_custom(v) for v in node) if not has_custom(logic): return None if isinstance(match.get('custom_branch_trace'), dict): return [match['custom_branch_trace']] bound = {k: v for k, v in (match.get('bindings') or {}).items() if not str(k).startswith('_')} records, seen = [], set() for item in execution_trace or []: record = item.get('custom_branch_trace') if item.get('condition_type') != 'custom' or not item.get('matched') or not isinstance(record, dict): continue given = item.get('input_bindings') or {} if any(key in bound and bound[key] != value for key, value in given.items() if not str(key).startswith('_')): continue if id(record) not in seen: seen.add(id(record)) records.append(record) return records # ============================================================================ # YogaEngine: 规则加载与检测 # ============================================================================ # Lunar / solar duplicates of the BVR precise rules (bvr_002..004, bvr_016..018), # retired so a chart is not judged twice by two definitions (sync4 T5; same # six ids as upstream yinduzhanxing 2dd6062a RETIRED_RULE_IDS). The other four # (Chakra / Vajra Nabhasa, Kalanidhi, Dala) were removed upstream in e628118d / # 8787d9ea: the Nabhasa pair counted occupied kendras / dusthanas instead of the # classical sign pattern, Kalanidhi tested aspects as house differences, and # Dala counted dusthana lords in kendras (product 2026-11-07 engine sync). RETIRED_RULE_IDS = frozenset({ 'voshi_yoga', 'veshi_yoga', 'ubhayachari_yoga', 'anapha_yoga', 'sunapha_yoga', 'durudhura_yoga', 'chakra_nabhasa', 'vajra_nabhasa', 'kalanidhi_yoga', 'dala_yoga', 'asraya_yoga', 'asraya_partial', 'kalatra_dosha_mars_7', 'daridra_11', }) _STRUCTURAL_CONDITION_TYPES = frozenset({"compound", "compound_conditions"}) _NOT_AN_IMPLEMENTATION = frozenset({"placeholder"}) def _rule_condition_types(node) -> set: """Every condition `type` (or legacy `op`) named in a rule's logic tree.""" found = set() if isinstance(node, dict): ctype = node.get("type") or node.get("op") if isinstance(ctype, str) and ctype: found.add(ctype) for value in node.values(): if isinstance(value, (dict, list)): found |= _rule_condition_types(value) elif isinstance(node, list): for value in node: found |= _rule_condition_types(value) return found @functools.lru_cache(maxsize=1) def _supported_condition_types() -> Optional[frozenset]: """Condition types some evaluator handles: `_eval_` methods plus the literal `ctype == "..."` / `ctype in (...)` branches of `_eval_semantic_condition`. Read from the code itself so the list cannot drift; None when the source is unavailable (runtime check still applies). """ handlers = {name[len("_eval_"):] for name in dir(YogaEngine) if name.startswith("_eval_")} try: tree = ast.parse(textwrap.dedent(inspect.getsource(YogaEngine._eval_semantic_condition))) except (OSError, TypeError, SyntaxError): return None semantic = set() for node in ast.walk(tree): if isinstance(node, ast.Compare) and isinstance(node.left, ast.Name) and node.left.id == "ctype": for op, comparator in zip(node.ops, node.comparators): if isinstance(op, ast.Eq) and isinstance(comparator, ast.Constant): semantic.add(comparator.value) elif isinstance(op, ast.In) and isinstance(comparator, (ast.Tuple, ast.List, ast.Set)): semantic |= {e.value for e in comparator.elts if isinstance(e, ast.Constant)} # 原值:`ctype == "placeholder"`(直接 return [])也算已实现 # 新值:placeholder 不算实现,引用它的规则列为 not_implemented # 原因:占星师 2026-11-07 rulings.md A3 / C7(交接 263092b3):71 条含未实现条件, # 占位分支返回空等于把「没写」当成「不成立」(bvr_apakeerthi_yoga) return frozenset((handlers | semantic | _STRUCTURAL_CONDITION_TYPES) - _NOT_AN_IMPLEMENTATION) def _not_implemented_row(rule: Dict, missing) -> Dict: return { "rule_id": rule.get("id", ""), "name": rule.get("name", ""), "name_cn": rule.get("name_cn", ""), # 交接 8c775cd0(r40):诊断行保留规则分类 "category": rule.get("category") or "unclassified_rule", "condition_status": "not_implemented", "formation_status": "not_implemented", "error_class": "UnsupportedConditionType", "missing_condition_types": sorted(set(missing)), "unsupported_conditions": sorted(set(missing)), "effects": [], "card_eligible": False, "card_status": "blocked", "claim_boundary": "No evaluator exists for this rule; it is neither formed nor ruled out.", "claim_boundary_zh": "该规则的条件类型尚无求值实现,既不算成立也不算不成立。", } class YogaEngine: """Yoga 检测引擎。从 JSON 加载规则,对星盘执行条件匹配。""" def __init__(self, rules_path: str): with open(rules_path, 'r', encoding='utf-8') as f: data = json.load(f) # BUG-2298 (upstream 58f37ee5b): an archived or draft rule file never runs. if data.get('runtime_enabled') is False: raise ValueError('Archived Yoga definitions cannot be used as a runtime rule library') self.schema_version = data.get("schema_version", "1.0") self.rules = [r for r in data.get("rules", []) if r.get("enabled", True) and r.get("id") not in RETIRED_RULE_IDS and not r.get("reference_only")] # `reference_only` rules stay in the registry with their source and # logic but are never evaluated: the yoga they name has one main # detector (scripts/main_yoga_detectors.py; astrologer rulings # 2026-10-03), whose rows `detect` appends below. self.reference_only_rule_ids = sorted( r.get("id") for r in data.get("rules", []) if r.get("reference_only")) # Rules the last `detect` call could not evaluate (第三轮审查 2026-11-07). self.last_evaluation_failures: List[Dict] = [] # Rules naming a condition type no evaluator implements. Before # 2026-11-07 they silently returned "not formed" on every chart; they # are now listed as `not_implemented` and never evaluated. self.unimplemented_rules: List[Dict] = [] # BUG-2301: (rule, missing types) of the preflight above, for her blocked rows in `detect`. self._preflight_unimplemented: List[tuple] = [] # Rules found unsupported at evaluation time by the last `detect` call # (e.g. a rule list replaced after loading); same row shape. self.last_unimplemented: List[Dict] = [] if _supported_condition_types() is not None: kept = [] for rule in self.rules: missing = self.unsupported_conditions(rule.get("logic", {})) if missing: self.unimplemented_rules.append(_not_implemented_row(rule, missing)) self._preflight_unimplemented.append((rule, missing)) else: kept.append(rule) self.rules = kept # 原值:reference_only 规则不扫描(69 条) # 新值:也扫描并列出(带 reference_only=true),仍不求值;主检测器结果不替它成立 # 原因:占星师 2026-11-07 rulings.md A3 / C5:bvr_maalavya_yoga 计入 71 条未实现 reference_only = [r for r in data.get("rules", []) if r.get("enabled", True) and r.get("id") not in RETIRED_RULE_IDS and r.get("reference_only")] for rule in reference_only: missing = self.unsupported_conditions(rule.get("logic", {})) if missing: self.unimplemented_rules.append(dict(_not_implemented_row(rule, missing), reference_only=True)) self._loaded_rules = self.rules def unsupported_conditions(self, node) -> List[str]: """Condition types in any branch of `node` that no evaluator implements. Walks the logical children only (`conditions`, `condition`), as the astrologer's `YogaEngine.unsupported_conditions` (263092b3) does, so a binding object such as `{"type": "resolve_single"}` is not a condition. """ supported = _supported_condition_types() if supported is None: return [] if not isinstance(node, dict): return ['invalid_condition_node'] ctype = node.get('type') or node.get('op') missing = [] if ctype not in supported: missing.append(str(ctype or 'missing_condition_type')) for child in node.get('conditions', []) or []: missing.extend(self.unsupported_conditions(child)) if 'condition' in node: missing.extend(self.unsupported_conditions(node['condition'])) return sorted(set(missing)) def _attach_interpretive_evidence(self, entry, ctx): """Expose executed conditions and partial strength facts, not a score. Upstream yinduzhanxing 1307bf69 (产品 2026-11-07 同步占星师 Yoga 规则批次): `formation_checks` are the executed source conditions of a reviewed contract (empty when the rule has none), `formation_assessment` re-evaluates them, and `strength_factors` lists D1/D9 dignity, lordship, combustion and retrograde facts without composing a score. """ planets_bound = entry.get('planets', []) contract = yoga_formation_contract(entry['rule_id']) checks = [] def check(key, passed, witness): checks.append({'id': key, 'passed': passed, 'witness': witness}) if contract: entry['formation_source_profile'] = contract['profile'] chart_type = ctx.context.get('chart_type') check('d1_scope', chart_type == 'D1' if chart_type else None, {'chart_type': chart_type, 'reference': 'Lagna'}) positions = {p: {'sign': ctx.sign_of(p), 'house': ctx.house_of(p)} for p in planets_bound} valid = ctx.ascendant in SIGNS and bool(positions) geometry = None if valid and all(v['sign'] in SIGNS and type(v['house']) is int for v in positions.values()): geometry = all((SIGNS.index(v['sign']) - ctx.asc_idx) % 12 + 1 == v['house'] for v in positions.values()) check('consistent_geometry', geometry, {'ascendant': ctx.ascendant, 'positions': positions}) if contract.get('planet'): planet = contract['planet'] check('kendra', ctx.house_of(planet) in (1, 4, 7, 10), positions.get(planet)) moola = entry['rule_id'].startswith('moolatrikona_') check('dignity', ctx.is_own_sign(planet) if moola or entry['rule_id'].endswith('_own') else ctx.is_exalted(planet), {'planet': planet, 'sign': ctx.sign_of(planet)}) if moola: # BUG-2222 (upstream b6754475): the degree interval is a # required check, not implied by the sign. data = ctx.planets[planet] check('moolatrikona_degree', ctx.is_moolatrikona(planet), { 'planet': planet, 'sign': ctx.sign_of(planet), 'degree_in_sign': data['degree_in_sign'] if 'degree_in_sign' in data else data['degree'] % 30, 'interval': list(MOOLATRIKONA_DEGREES[planet]), 'interval_convention': '[start,end)', 'source': 'PVR Integrated Approach pp.46–47; BPHS 3.51–54', }) elif entry['rule_id'] in {'saraswati_yoga', 'bvr_saraswathi_yoga'}: # BUG-2222 (upstream b6754475): Saraswathi contract checks. houses = {p: ctx.house_of(p) for p in ('Mercury', 'Jupiter', 'Venus')} check('all_three_placements', None if any(h is None for h in houses.values()) else all(h in {1, 2, 4, 5, 7, 9, 10} for h in houses.values()), houses) sign = ctx.sign_of('Jupiter') check('jupiter_dignity', None if not sign else 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') == RAJA_STRUCTURAL_PROFILE: # BUG-2392: the bound lords and the houses each rules; any 6/8/12 lordship is a modifier. lordships = {p: [h for h in range(1, 13) if ctx.lord_of_house(h) == p] for p in planets_bound} royal = {p: [h for h in houses if h in (1, 4, 5, 7, 9, 10)] for p, houses in lordships.items()} check('lord_structure', None if len(planets_bound) < 2 else len(set(planets_bound)) >= 2 and all(royal.values()), {'lordships': lordships} if len(planets_bound) >= 2 else None) modifiers = [{'planet': p, 'houses': [h for h in houses if h in (6, 8, 12)]} for p, houses in lordships.items() if any(h in (6, 8, 12) for h in houses)] if modifiers: entry['formation_modifiers'] = modifiers entry['formation_note_zh'] = '实际作用有利有弊:' + ','.join( f"{PLANET_ZH.get(m['planet'], m['planet'])}同时管第 {'、'.join(map(str, m['houses']))} 宫" for m in modifiers) + '。' entry['formation_note_en'] = 'Mixed in effect: ' + '; '.join( f"{m['planet']} also rules house {', '.join(map(str, m['houses']))}" for m in modifiers) + '.' 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') check('sign_parity', parity in ('odd', 'even'), {'parity': parity, 'ascendant': ctx.ascendant, 'positions': positions}) gender, day = values.get('gender'), values.get('birth_is_daytime') check('gender', None if gender is None else gender == ('male' if parity == 'odd' else 'female'), {'gender': gender}) check('birth_is_daytime', None if type(day) is not bool else day == (parity == 'odd'), {'birth_is_daytime': day}) else: evidence = entry.get('formation_evidence') or {} planet = evidence.get('planet') check('debilitation', bool(planet) and ctx.is_debilitated(planet), {'planet': planet, 'sign': ctx.sign_of(planet)}) check('cancellation', bool(evidence.get('cancellation_reasons')), evidence.get('cancellation_reasons')) if entry['rule_id'] == 'neechabhanga_kendra': check('royal_placement', ctx.house_of(planet) in (1, 4, 5, 7, 9, 10), {'planet': planet, 'house': ctx.house_of(planet)}) entry['formation_checks'] = checks entry['formation_assessment'] = assess_yoga_formation(entry) # BUG-2299 (upstream 58f37ee5b): different lordship roles can refer to one # physical planet. Preserve the literal rule match, but never count roles as # independent witnesses. shared = {p: [h for h in range(1, 13) if ctx.lord_of_house(h) == p] for p in planets_bound} cancellation = entry.get('formation_evidence') or {} entry['evidence_dependencies'] = { 'shared_lordships': {p: houses for p, houses in shared.items() if len(houses) > 1}, 'participant_positions': {p: {'sign': ctx.sign_of(p), 'house': ctx.house_of(p)} for p in planets_bound}, 'self_reference_only': cancellation.get('self_reference_only'), 'independent_confirmation_count': None, 'claim_boundary': 'Shared planets, lordship roles and overlapping yoga names are not independent confirmations. Formation, strength, activation and outcome require separate assessment.', } supporting, limiting, contextual = [], [], [] unassessed = {'functional_benefic_malefic', 'Shadbala', 'Vimsopaka', 'aspect_strength', 'event_timing', 'composite_yoga_strength'} for planet in planets_bound: data = ctx.planets.get(planet) or {} sign = ctx.sign_of(planet) if sign in SIGNS: dignity = _get_dignity_level(planet, sign) target = supporting if dignity in {'OWN_SIGN', 'EXALTED', 'MOOLATRIKONA'} else limiting if dignity == 'DEBILITATED' else contextual target.append({'planet': planet, 'kind': 'd1_dignity', 'value': dignity, 'evidence': {'sign': sign, 'house': ctx.house_of(planet)}, 'text': f'{planet}:D1 {sign},尊贵状态 {dignity}。'}) contextual.append({'planet': planet, 'kind': 'house_lordships', 'value': [h for h in range(1, 13) if ctx.lord_of_house(h) == planet], 'text': f'{planet} 的宫主职责须与自然属性分开判断。'}) if type(data.get('combust')) is bool: (limiting if data['combust'] else contextual).append({ 'planet': planet, 'kind': 'combustion', 'value': data['combust'], 'text': f'{planet}:输入标记为燃烧,效力需复核。' if data['combust'] else f'{planet}:输入标记为未燃烧。'}) else: unassessed.add(f'{planet}.combustion') if type(data.get('retrograde')) is bool: contextual.append({'planet': planet, 'kind': 'retrograde', 'value': data['retrograde'], 'text': f'{planet}:逆行标记 {data["retrograde"]},不自动判作增强或削弱。'}) d9_sign = ctx.d9_sign_of(planet) if d9_sign in SIGNS: dignity = _get_dignity_level(planet, d9_sign) target = supporting if dignity in {'OWN_SIGN', 'EXALTED', 'MOOLATRIKONA'} else limiting if dignity == 'DEBILITATED' else contextual target.append({'planet': planet, 'kind': 'd9_dignity', 'value': dignity, 'text': f'{planet}:D9 {d9_sign},尊贵状态 {dignity}。'}) else: unassessed.add(f'{planet}.D9') entry['strength_factors'] = { 'status': 'partial_factors' if planets_bound else 'not_assessed', 'supporting_factors': supporting, 'limiting_factors': limiting, 'contextual_factors': contextual, 'unassessed_layers': sorted(unassessed), 'composite_strength_assessed': False, } def detect(self, planets: Dict[str, Dict], ascendant: str, context: Optional[Dict] = None) -> List[Dict]: """ 检测 Yoga。 返回: [{name, name_cn, combination, effects, strength, source, bvr_id, category}, ...] """ ctx = YogaContext(planets, ascendant, context=context) results = [] seen_dedup = set() failures: List[Dict] = [] self.last_evaluation_failures = failures unimplemented: List[Dict] = [] self.last_unimplemented = unimplemented # BUG-2301 (upstream 58f37ee5b): her `detect` returns a blocked row for every rule whose # condition type has no evaluator. Here those rules were set aside when the library was # loaded (rulings A3); their blocked rows are returned while the loaded rule list is in use # (a caller that replaced `self.rules` evaluates only its own list, as in her engine). if self.rules is self._loaded_rules: for rule, missing in self._preflight_unimplemented: results.append(_blocked_rule_row(rule, UnsupportedYogaCondition(missing), ctx)) # 规则匹配。一条规则求值失败(异常)记为 evaluation_failed 并带错误类, # 不得静默当成不成立(占星师第三轮审查 2026-11-07)。 for rule in self.rules: # BUG-2299 (upstream 58f37ee5b): her registry English for rules without their own # English fields; the rule's own fields always win. rule = dict(english_delivery_fields(rule), **rule) # BUG-2075 (upstream 19cfd9c0): receipt of the condition nodes this rule actually evaluated. ctx.condition_execution_trace = [] try: matches = self._eval_rule(rule, ctx) except Exception as exc: # noqa: BLE001 - recorded per rule, see evaluation_failure_row if isinstance(exc, UnsupportedYogaCondition): unimplemented.append(_not_implemented_row(rule, exc.conditions)) else: failures.append(evaluation_failure_row(rule, exc)) # BUG-2299 (upstream 58f37ee5b): failure is not evidence of absence or a formed # yoga. Her blocked row stays in `detect`'s list; the product entry points # (`detect_yogas`, `detect_yogas_with_status`) list it apart, as before. results.append(_blocked_rule_row(rule, exc, ctx)) continue for m in matches: # BUG-2303: her Neecha Bhanga rows read in plain words (product layer; codes stay in evidence). if (rule.get('logic') or {}).get('type') == 'neecha_bhanga': m = _neecha_reader_match(m, ctx) combination = m.get("combination", "") strength = m.get("strength", rule.get("strength", "中")) entry = { "name": rule["name"], "name_cn": rule["name_cn"], "combination": str(combination), "effects": rule.get("effects", []), "strength": strength, "source": rule.get("source", ""), "bvr_id": rule.get("bvr_id"), "category": rule.get("category", ""), "rule_id": rule.get("id", ""), # BUG-1657: name the planets the rule actually bound, so reports # can list participants and check current-Dasha overlap. **({"planets": participants} if (participants := _bound_planets(m)) else {}), **({"triggers": m["triggers"]} if m.get("triggers") else {}), **({"triggers_zh": m["triggers_zh"]} if m.get("triggers_zh") else {}), **({"canonical_mapping": rule["canonical_mapping"]} if rule.get("canonical_mapping") else {}), # English twins for the reader's English edition; the Chinese # fields above are unchanged. "combination_en": m.get("combination_en") or _rule_combination_en(combination, rule), "effects_en": list(rule.get("effects_en") or rule.get("effects", [])), "strength_en": rule.get("strength_en") if strength == rule.get("strength") and rule.get("strength_en") else STRENGTH_EN.get(str(strength), str(strength)), } # 产品 2026-11-07 同步占星师 Yoga 规则批次(上游 733a931b): # a structural observation is a recorded lord association, # placement or dignity, not a named Yoga; its former effects # stay under `traditional_effects` and `effects` is the # rule's own boundary sentence. entry['source_reference'] = rule.get('source_reference', rule.get('source', '')) # BUG-2222 (upstream b6754475): where the traditional meaning comes from. if rule.get('meaning_source_reference'): entry['meaning_source_reference'] = rule['meaning_source_reference'] # BUG-2299 (upstream 58f37ee5b): the English source line her renderers read. if rule.get('english_source_reference'): entry['english_source_reference'] = rule['english_source_reference'] entry['claim_kind'] = rule.get('claim_kind', 'named_yoga_candidate') for key in ('legacy_name', 'traditional_effects', 'traditional_effects_en'): if key in rule: entry[key] = rule[key] entry['condition_evidence'] = { 'rule_id': rule.get('id'), 'definition': rule.get('logic'), 'source_reference': entry['source_reference'], 'execution_trace': list(ctx.condition_execution_trace), 'trace_scope': 'executed_condition_nodes; custom_expression_internals_not_traced', 'participants': {p: {'sign': ctx.sign_of(p), 'house': ctx.house_of(p)} for p in entry.get('planets', [])}, } # BUG-2124: the branch records of the custom nodes in this instance, and a scope # line that says how far their insides were traced. branch_records = _row_custom_branch_traces(rule.get('logic'), m, ctx.condition_execution_trace) if branch_records is not None: entry['custom_branch_trace'] = branch_records split = [record.get('trace_status') == 'split' for record in branch_records] if split and all(split): entry['condition_evidence']['trace_scope'] = 'executed_condition_nodes; custom_expression_branches_traced' elif any(split): entry['condition_evidence']['trace_scope'] = 'executed_condition_nodes; custom_expression_partly_traced' if m.get('formation_evidence'): entry['formation_evidence'] = m['formation_evidence'] # BUG-2406: an evaluator's own limiting lines (e.g. Nishkapata's fourth-lord caution). for key in ('reductions', 'reductions_en'): if m.get(key): entry[key] = list(m[key]) if entry['claim_kind'] == 'structural_observation': entry['strength'] = 'observation' entry['strength_en'] = STRENGTH_EN['observation'] # A rule-library grade is not calculated Shadbala or a # probability of the promised outcome. entry['strength_basis'] = 'rule_library_grade_not_chart_strength' # Budha-Aditya is a conjunction witness, but a combust # Mercury must not be presented as an unqualified full yoga # (upstream yinduzhanxing 994638f0; sync5 U7). if rule.get('id') == 'budhaditya_yoga': mercury = ctx.planets.get('Mercury') or {} if mercury.get('combust') is True: entry['condition_status'] = 'combustion_requires_review' entry['traditional_effects'] = entry['effects'] entry['effects'] = [] # BUG-2299 (upstream 58f37ee5b): the English twin moves too. if entry.get('effects_en'): entry['traditional_effects_en'] = entry['effects_en'] # BUG-2301 (upstream 58f37ee5b): the key is dropped, as in her rows. entry.pop('effects_en', None) entry['strength'] = 'conditional' entry['strength_en'] = 'Conditional' entry['combustion_witness'] = { 'planet': 'Mercury', 'combust': True, 'claim_boundary': 'Do not treat Budha-Aditya as an unqualified benefic result while Mercury is combust.' } # Upstream e628118d: an evaluator that cannot check every # condition (Mahabhagya without gender / day-night, Parihasaka # without Vaiseshikamsa) returns a labelled candidate only. if 'condition_status' in m: entry.update({key: m[key] for key in ('condition_status', 'missing_inputs', 'condition_checks')}) if m['condition_status'] == 'incomplete_conditions': entry['traditional_effects'] = entry['effects'] entry['effects'] = [] # BUG-2222 (upstream b6754475): the English twin moves too. if entry.get('effects_en'): entry['traditional_effects_en'] = entry['effects_en'] # BUG-2301 (upstream 58f37ee5b): the key is dropped, as in her rows. entry.pop('effects_en', None) entry['strength'] = 'conditional' entry['strength_en'] = 'Conditional' _apply_effect_and_method_gates(entry, rule, m) self._attach_interpretive_evidence(entry, ctx) # BUG-2299 (upstream 58f37ee5b): rules that name the lordships they rely on share # fact keys, so overlapping rules are listed and never counted as independent votes. roles = rule.get('evidence_lordship_houses', []) if roles: entry['evidence_dependencies']['shared_fact_keys'] = [ f"D1:lord:{house}:{ctx.lord_of_house(house)}:house:{ctx.house_of(ctx.lord_of_house(house))}" for house in roles] # BUG-2075 (upstream 19cfd9c0): names and prose are not identities. # Distinct rules or planetary witnesses may share both; collapse # only identical results, and never count variants as votes. dedup_val = json.dumps(entry, sort_keys=True, ensure_ascii=False, default=str) if dedup_val in seen_dedup: continue seen_dedup.add(dedup_val) results.append(entry) # The algorithmic Veshi/Voshi/Ubhayachari/Sunapha/Anapha/Durudhura block # duplicated bvr_002..004 / bvr_016..018 under other spellings; upstream # e628118d removed it. The precise rules count the same five planets # (BUG-1187 / BUG-1206), so nothing they ruled is lost. # BUG-2299 (upstream 58f37ee5b): rules sharing a lordship fact name each other. for entry in results: dependencies = entry.get('evidence_dependencies', {}) keys = set(dependencies.get('shared_fact_keys', [])) if keys: dependencies['overlapping_rule_ids'] = sorted({ other['rule_id'] for other in results if other is not entry and keys.intersection(other.get('evidence_dependencies', {}).get('shared_fact_keys', []))}) dependencies['independent_confirmation_count'] = None # ── 主检测器(同名 JSON 规则为 reference_only;BUG-1205/1206/1207 产品层) ── # BUG-2301: they stand in for the reference_only rules of the loaded library, so they run # with that library only; a caller that replaced `self.rules` evaluates its own list, as in # her engine. if self.rules is self._loaded_rules: results += main_detector_rows(ctx.planets, ctx.ascendant) return results # ------------------------------------------------------------------------ # 规则级评估 # ------------------------------------------------------------------------ def _eval_rule(self, rule: Dict, ctx: YogaContext) -> List[Dict]: """评估单条规则,返回匹配列表(空表示无匹配)""" # BUG-2406 (上游 322e2f30): a rule admitted only for some charts is not evaluated on another chart. scopes = rule.get('source_chart_scopes') chart_type = ctx.context.get('chart_type', 'D1') if scopes and chart_type not in scopes: raise MissingYogaInput(str(rule.get('id')) + '.source_admitted_' + str(chart_type) + '_scope') logic = rule.get("logic", {}) # 占星师 2026-11-07 rulings.md A3:先查所有分支的实现能力,再求值。 unsupported = self.unsupported_conditions(logic) if unsupported: raise UnsupportedYogaCondition(unsupported) return self._eval_condition(logic, ctx, rule, {}) # ------------------------------------------------------------------------ # BUG-2301: the astrologer's source evaluators (upstream 58f37ee5b), copied unchanged # from `_required_pattern_houses` to `_eval_neecha_bhanga`. The Neecha Bhanga JSON rules # stay reference_only here (main detector, BUG-1205), so `_eval_neecha_bhanga` only # answers the not-implemented scan until the dual-path question is settled. # ------------------------------------------------------------------------ def _required_pattern_houses(self, ctx, planets): houses = {p: ctx.house_of(p) for p in planets} missing = [p + '.house' for p, h in houses.items() if isinstance(h, bool) or not isinstance(h, int) or not 1 <= h <= 12] if missing: raise MissingYogaInput(', '.join(missing)) return houses def _eval_all_planets_in_houses(self, cond, ctx, rule, bindings): """PVR p135 Samudra; exact occupied-house pattern, not a subset.""" planets = cond.get('planets') or ALL_PLANETS[:7] offsets = cond.get('house_offsets') if (not isinstance(offsets, list) or not offsets or any(type(h) is not int or not 0 <= h < 12 for h in offsets)): raise MissingYogaInput('condition.house_offsets_0_based') houses = self._required_pattern_houses(ctx, planets) if set(houses.values()) != {h + 1 for h in offsets}: return [] return [{'combination': '七曜占据全部指定宫位;交点不参与', 'bindings': {'_participants': list(planets)}, 'missing_inputs': [], 'condition_checks': {'planet_houses': houses, 'required_houses': [h+1 for h in offsets]}, 'condition_status': 'conditions_met'}] def _eval_all_7_planets_in_7_consecutive_non_kendra_starting_houses(self, cond, ctx, rule, bindings): """PVR p134 Ardha Chandra; seven occupied signs, non-angular start.""" planets = ALL_PLANETS[:7] houses = self._required_pattern_houses(ctx, planets) occupied = set(houses.values()) starts = [start for start in (2, 3, 5, 6, 8, 9, 11, 12) if occupied == {(start-1+i) % 12+1 for i in range(7)}] if not starts: return [] return [{'combination': '七曜分别占据从非角宫开始的连续七宫;交点不参与', 'bindings': {'_participants': list(planets)}, 'missing_inputs': [], 'condition_checks': {'planet_houses': houses, 'starting_houses': starts}, 'condition_status': 'conditions_met'}] def _eval_planets_in_mutual_trines(self, cond, ctx, rule, bindings): """PVR p142 Trilochana; distinct trines, not conjunction.""" planets = cond.get('planets') or [] if len(planets) != 3 or len(set(planets)) != 3: raise MissingYogaInput('condition.three_distinct_planets') houses = self._required_pattern_houses(ctx, planets) values = list(houses.values()) if not all((a-b) % 12 in (4, 8) for i,a in enumerate(values) for b in values[i+1:]): return [] return [{'combination': '太阳、月亮与火星互为三方宫,非同宫替代', 'bindings': {'_participants': list(planets)}, 'missing_inputs': [], 'condition_checks': {'planet_houses': houses}, 'condition_status': 'conditions_met'}] def _natural_benefics_for_named_pattern(self, ctx): """Explicit waxing-Moon/unafflicted-Mercury convention, not functional roles.""" self._required_pattern_houses(ctx, ALL_PLANETS) benefics = ['Jupiter', 'Venus'] waning = ctx.panchanga.get('is_waning_moon') if not isinstance(waning, bool): raise MissingYogaInput('Moon.phase') if not waning: benefics.append('Moon') malefics = ['Sun', 'Mars', 'Saturn', 'Rahu', 'Ketu'] + (['Moon'] if waning else []) if not any(ctx.house_of(p) == ctx.house_of('Mercury') for p in malefics): benefics.append('Mercury') return benefics def _eval_vasumathi_raman(self, cond, ctx, rule, bindings): """Raman no.9 pp29–31: retain partial occupancy and both references. Benefic count is descriptive, not a calibrated wealth score. Do not require all four houses: the author's example occupies only three. """ benefics = self._natural_benefics_for_named_pattern(ctx) results = [] for reference, origin in [('Lagna', 1), ('Moon', ctx.house_of('Moon'))]: relative = {p: (ctx.house_of(p) - origin) % 12 + 1 for p in ALL_PLANETS} occupied = [p for p in benefics if relative[p] in (3, 6, 10, 11)] if not occupied: continue pressures = [p for p in ALL_PLANETS if p not in benefics and relative[p] in (3, 6, 10, 11)] results.append({ 'combination': reference + ': benefics in upachayas: ' + ', '.join(occupied), 'bindings': {'_participants': occupied}, 'condition_status': 'conditions_met', 'missing_inputs': [], 'condition_checks': {'reference': reference, 'benefics': occupied, 'relative_houses': {p: relative[p] for p in occupied}}, 'formation_evidence': {'reference': reference, 'benefic_count': len(occupied), 'occupied_upachayas': sorted({relative[p] for p in occupied}), 'malefics_in_upachayas': pressures, 'full_results_established': False, 'boundary': 'Partial occupancy retained; strength and competing influences require synthesis. No wealth guarantee or independent vote.'}}) return results def _eval_parvata_pvr(self, cond, ctx, rule, bindings): """PVR indexed p137: occupants, not angular lords or dusthana lords.""" benefics = self._natural_benefics_for_named_pattern(ctx) angular = [p for p in ALL_PLANETS if ctx.house_of(p) in (1, 4, 7, 10)] guarded = [p for p in ALL_PLANETS if ctx.house_of(p) in (7, 8)] if not angular or any(p not in benefics for p in angular + guarded): return [] return [{'combination': '角宫有吉星且无凶星;第7、8宫空置或仅有吉星', 'bindings': {'_participants': list(dict.fromkeys(angular + guarded))}, 'condition_status': 'conditions_met', 'missing_inputs': [], 'condition_checks': {'angular_occupants': angular, 'houses_7_8_occupants': guarded, 'natural_benefics': benefics}}] def _eval_lagna_presence_or_kartari_pvr(self, cond, ctx, rule, bindings): """PVR p136: occupied lagna OR both flanks; no extra aspect veto. Mixed influences may form both geometric patterns. Strength and final interpretation are separate; this does not assert character traits. """ benefics = self._natural_benefics_for_named_pattern(ctx) kind = cond.get('kind') if kind not in ('benefic', 'malefic'): raise UnsupportedYogaCondition(['lagna_presence_or_kartari_pvr.kind']) selected = benefics if kind == 'benefic' else [p for p in ALL_PLANETS if p not in benefics] groups = {h: [p for p in selected if ctx.house_of(p) == h] for h in (1, 2, 12)} if not groups[1] and not (groups[2] and groups[12]): return [] witnesses = groups[1] + (groups[2] + groups[12] if groups[2] and groups[12] else []) return [{'combination': cond['description_zh'], 'bindings': {'_participants': witnesses}, 'condition_status': 'conditions_met', 'missing_inputs': [], 'condition_checks': {'lagna_occupants': groups[1], 'second_occupants': groups[2], 'twelfth_occupants': groups[12], 'scope': 'geometry_only_not_strength_or_outcome'}}] def _eval_chaamara_pvr(self, cond, ctx, rule, bindings): """PVR indexed p137: two alternatives; each pair shares one house.""" lord = ctx.lord_of_house(1) self._required_pattern_houses(ctx, [lord, 'Jupiter']) if not ctx.sign_of(lord): raise MissingYogaInput('ascendant_lord.sign') first = (ctx.is_exalted(lord) and ctx.is_kendra(ctx.house_of(lord)) and ctx.parashari_aspect('Jupiter', lord)) if first: return [{'combination': '上升主入旺且在角宫,受到木星照射', 'bindings': {'_participants': [lord, 'Jupiter']}}] benefics = self._natural_benefics_for_named_pattern(ctx) matches = [] for house in (7, 9, 10): witnesses = [p for p in benefics if ctx.house_of(p) == house] if len(witnesses) >= 2: matches.append({'combination': f'至少两颗自然吉星同在第{house}宫', 'bindings': {'_participants': witnesses}, 'condition_status': 'conditions_met', 'missing_inputs': [], 'condition_checks': {'house': house, 'benefics': witnesses}}) return matches def _eval_kusuma_pvr(self, cond, ctx, rule, bindings): """PVR indexed p139: four conjunctive requirements, not three-of-four. Mercury's benefic role is bounded to the unassociated-with-malefics convention; conjunction with the Moon does not let Moon witness itself. """ required = ('Moon', 'Venus', 'Saturn', 'Jupiter', 'Mercury', 'Sun', 'Mars', 'Rahu', 'Ketu') missing = [p for p in required if not ctx.sign_of(p) or ctx.house_of(p) is None] if missing: return [{'combination': 'Kusuma four-condition check: missing planetary inputs', 'condition_status': 'incomplete_conditions', 'missing_inputs': missing, 'condition_checks': {}, 'bindings': {'_participants': ['Moon', 'Venus', 'Saturn']}}] moon_sign = ctx.sign_of('Moon') witnesses = [p for p in ('Jupiter', 'Venus') if ctx.sign_of(p) == moon_sign] mercury_clean = not any(ctx.sign_of(p) == ctx.sign_of('Mercury') for p in ('Sun', 'Mars', 'Saturn', 'Rahu', 'Ketu')) if ctx.sign_of('Mercury') == moon_sign and mercury_clean: witnesses.append('Mercury') checks = {'fixed_lagna': ctx.ascendant in ('Taurus', 'Leo', 'Scorpio', 'Aquarius'), 'venus_kendra': ctx.house_of('Venus') in (1, 4, 7, 10), 'moon_trine_with_benefic': ctx.house_of('Moon') in (1, 5, 9) and bool(witnesses), 'saturn_tenth': ctx.house_of('Saturn') == 10} if not all(checks.values()): return [] return [{'combination': 'Fixed ascendant; Venus in quadrant; Moon in trine with benefic; Saturn in house 10', 'condition_status': 'conditions_met', 'condition_checks': checks, 'missing_inputs': [], 'bindings': {'_participants': list(dict.fromkeys(['Moon', 'Venus', 'Saturn'] + witnesses))}}] def _eval_nishturabhashi_raman(self, cond, ctx, rule, bindings): """No.296: conjunction is structure; Jupiter/Mars qualify expression.""" houses = self._required_pattern_houses(ctx, ['Moon', 'Saturn']) if houses['Moon'] != houses['Saturn']: return [] missing = [p + '.house' for p in ('Jupiter', 'Mars') if ctx.house_of(p) is None] for p in ('Jupiter', 'Mars'): if ctx.house_of(p) is not None: self._required_pattern_houses(ctx, [p]) jupiter = None if 'Jupiter.house' in missing else ctx.parashari_aspect('Jupiter', 'Moon') mars = None if 'Mars.house' in missing else ctx.parashari_aspect('Mars', 'Moon') status = 'source_neutralized' if jupiter else ('incomplete' if missing else 'traditional_reference_only') return [{'combination': '月亮与土星同宫;木星缓解与火星加重另行核验', 'bindings': {'_participants': ['Moon', 'Saturn']}, 'condition_status': 'conditions_met', 'missing_inputs': [], 'condition_checks': {'moon_saturn_conjunction': True}, 'formation_evidence': {'jupiter_aspect': jupiter, 'mars_aspect': mars}, 'effect_assessment': {'status': status, 'missing_inputs': missing, 'jupiter_neutralizes_source_effect': jupiter, 'mars_intensifies_source_effect': mars, 'personal_character_established': False, 'boundary': 'Conjunction remains visible; source effects are not personality facts. Jupiter neutralization is not overridden by Mars.'}}] def _eval_jada_apakeerti_raman(self, cond, ctx, rule, bindings): """Raman158/244: alternatives and expression qualifiers are separate. Benefic/malefic amsa means its sign lord under the explicit native natural classification, not a friendly/enemy dignity or house proxy. """ profile = cond['profile'] witnesses, branches = {}, {} l2 = ctx.lord_of_house(2) def jada_conjunction(): self._required_pattern_houses(ctx, [l2]) if ctx.house_of(l2) != 10: return False benefics = self._natural_benefics_for_named_pattern(ctx) others = [p for p in ALL_PLANETS if p != l2 and p not in benefics and ctx.house_of(p) == 10] witnesses['lord_with_malefic'] = [l2, *others] return bool(others) def jada_sun_maandi(): self._required_pattern_houses(ctx, ['Sun']) if ctx.house_of('Sun') != 2: return False if ctx.upagraha_house('maandi') is None: raise MissingYogaInput('upagraha.maandi.house') witnesses['sun_maandi'] = ['Sun'] return ctx.upagraha_house('maandi') == 2 def apakeerti_aspect(): benefics = self._natural_benefics_for_named_pattern(ctx) others = [p for p in ALL_PLANETS if p not in ('Sun', 'Saturn') and p not in benefics and ctx.parashari_aspects_house(p, 10)] witnesses['external_malefic_aspect'] = ['Sun', 'Saturn', *others] return bool(others) def apakeerti_navamsa(): signs = [ctx.d9_sign_of(p) for p in ('Sun', 'Saturn')] if any(s not in SIGNS for s in signs): raise MissingYogaInput('Sun_and_Saturn.D9.sign') benefics = self._natural_benefics_for_named_pattern(ctx) witnesses['both_malefic_navamsas'] = ['Sun', 'Saturn'] return all(SIGN_LORDS[s] not in benefics for s in signs) if profile == 'jada_158': evaluators = [('lord_with_malefic', jada_conjunction), ('sun_maandi', jada_sun_maandi)] elif profile == 'apakeerti_244': self._required_pattern_houses(ctx, ['Sun', 'Saturn']) if any(ctx.house_of(p) != 10 for p in ('Sun', 'Saturn')): return [] evaluators = [('external_malefic_aspect', apakeerti_aspect), ('both_malefic_navamsas', apakeerti_navamsa)] else: raise UnsupportedYogaCondition(['jada_apakeerti_raman.' + str(profile)]) for name, evaluate in evaluators: try: branches[name] = {'status': 'met' if evaluate() else 'not_met'} except MissingYogaInput as exc: branches[name] = {'status': 'incomplete', 'missing_input': str(exc)} met = [k for k, v in branches.items() if v['status'] == 'met'] missing = [v['missing_input'] for v in branches.values() if v['status'] == 'incomplete'] if not met and not missing: return [] assessment = {'status': 'historical_conduct_reference', 'personal_outcome_established': False, 'summary_zh': '传统结构不等于实际性格、表达能力或名誉结论。', 'summary_en': 'The traditional structure does not establish character, speaking ability or reputation.'} if met: try: if profile == 'jada_158': sign = ctx.d9_sign_of(l2) if sign not in SIGNS: raise MissingYogaInput('second_lord.D9.sign') relieved = SIGN_LORDS[sign] in self._natural_benefics_for_named_pattern(ctx) assessment['benefic_navamsa_neutralizes'] = relieved if relieved: assessment.update(status='source_neutralized', summary_zh='2宫主位于吉星主宰的D9星座,原书的缓解条件满足;不据此判断公众表达能力。', summary_en='The second lord occupies a benefic-ruled Navamsa: the source mitigation is met; no speaking ability is inferred.') else: self._required_pattern_houses(ctx, ['Jupiter']) assessment['jupiter_mitigation'] = ctx.parashari_aspects_house('Jupiter', 10) # Raman calls this an antidote, not unconditional cancellation. except MissingYogaInput as exc: assessment.update(status='incomplete', missing_inputs=exc.fields, summary_zh='结构条件已满足,但缓解因素资料未齐,不能据此判断实际表现。', summary_en='The structure matches, but mitigation inputs are missing; personal expression is not established.') return [{'combination': cond['description_zh'], 'bindings': {'_participants': list(dict.fromkeys(p for k in met for p in witnesses[k]))}, 'condition_status': 'conditions_met' if met else 'incomplete_conditions', 'missing_inputs': [] if met else missing, 'condition_checks': branches, 'formation_evidence': {'matched_paths': met, 'unresolved_other_paths': missing, 'maandi_house': ctx.upagraha_house('maandi') if profile == 'jada_158' else None, 'amsa_classification': 'D9 sign lord; native waxing-Moon/unafflicted-Mercury convention', 'independent_support_count': 1 if met else 0}, 'effect_assessment': assessment}] def _eval_learning_expression_raman(self, cond, ctx, rule, bindings): """Named Raman definitions and remarks, not psychometric judgments.""" profile = cond['profile'] witnesses, evaluators = {}, [] def asat_definition(): lord = ctx.lord_of_house(2) sign = ctx.sign_of(lord) if sign not in SIGNS: raise MissingYogaInput('second_lord.D1.sign') if SIGN_LORDS[sign] not in ('Mars', 'Saturn'): return False benefics = self._natural_benefics_for_named_pattern(ctx) k = [p for p in ALL_PLANETS if p not in benefics and ctx.house_of(p) in (1, 4, 7, 10)] t = [p for p in ALL_PLANETS if p not in benefics and ctx.house_of(p) in (1, 5, 9)] witnesses['definition'] = [lord, *k, *t] return bool(k and t) def asat_navamsa(): lord = ctx.lord_of_house(2) sign = ctx.d9_sign_of(lord) if sign not in SIGNS: raise MissingYogaInput('second_lord.D9.sign') dispositor = SIGN_LORDS[sign] witnesses['navamsa_dispositor_alternative'] = [lord, dispositor] if dispositor in ('Mars', 'Saturn'): return True sign = ctx.sign_of(dispositor) if sign not in SIGNS: raise MissingYogaInput('second_lord.D9_dispositor.D1.sign') return SIGN_LORDS[sign] in ('Mars', 'Saturn') def buddhi_definition(): lord = ctx.lord_of_house(5) benefics = self._natural_benefics_for_named_pattern(ctx) if lord not in benefics: return False others = [p for p in benefics if p != lord and ctx.parashari_aspect(p, lord)] witnesses['definition'] = [lord, *others] if others: return True sign = ctx.sign_of(lord) if sign not in SIGNS: raise MissingYogaInput('fifth_lord.D1.sign') return SIGN_LORDS[sign] in benefics def buddhi_remarks(): lord = ctx.lord_of_house(5) benefics = self._natural_benefics_for_named_pattern(ctx) occupants = [p for p in benefics if ctx.house_of(p) == 5] others = [p for p in ('Jupiter', 'Mercury', 'Venus') if p != lord and ctx.house_of(p) == ctx.house_of(lord)] witnesses['remarks_distinct_benefic_companion'] = [lord, *occupants, *others] return bool(occupants and others) if profile == 'asatyavadi_157': evaluators = [('definition', asat_definition), ('navamsa_dispositor_alternative', asat_navamsa)] convention = 'At least one natural malefic in kendra and trikona sets; Lagna belongs to both. Separate D9-dispositor alternative.' elif profile == 'buddhimaturya_231': evaluators = [('definition', buddhi_definition), ('remarks_distinct_benefic_companion', buddhi_remarks)] convention = 'Remarks interpreted as at least one distinct Jupiter/Mercury/Venus conjunction, consistent with author example104; no self-conjunction or IQ inference.' elif profile == 'buddhi_jada_233': lord = ctx.lord_of_house(1) self._required_pattern_houses(ctx, [lord, 'Saturn']) if ctx.house_of('Saturn') != 5 or not ctx.parashari_aspect('Saturn', lord): return [] # Saturn's actual aspect also supplies the stated malefic contact. witnesses['definition'] = [lord, 'Saturn'] evaluators = [('definition', lambda: True)] convention = 'Definition only; later example107 is not promoted to a general alternate rule. Saturn cannot aspect itself.' else: raise UnsupportedYogaCondition(['learning_expression_raman.' + str(profile)]) states = {} for name, evaluate in evaluators: try: states[name] = {'status': 'met' if evaluate() else 'not_met'} except MissingYogaInput as exc: states[name] = {'status': 'incomplete', 'missing_input': str(exc)} met = [name for name, state in states.items() if state['status'] == 'met'] missing = [v['missing_input'] for v in states.values() if v['status'] == 'incomplete'] if not met and not missing: return [] return [{'combination': cond['description_zh'], 'bindings': {'_participants': list(dict.fromkeys(p for name in met for p in witnesses[name]))}, 'condition_status': 'conditions_met' if met else 'incomplete_conditions', 'condition_checks': states, 'missing_inputs': [] if met else missing, 'formation_evidence': {'matched_paths': met, 'unresolved_other_paths': missing, 'classification_profile': convention, 'independent_support_count': 1 if met else 0}, 'effect_assessment': {'status': 'historical_conduct_reference', 'personal_outcome_established': False, 'summary_zh': '传统结构仅供综合分析,不据此判定个人智力、诚信、品格或心理疾病。', 'summary_en': 'Traditional structure for synthesis only; it does not establish intelligence, honesty, character or mental illness.'}}] def _eval_wealth_house_observation(self, cond, ctx, rule, bindings): """Legacy placement observations; missing input is not a negative finding.""" lords = list(dict.fromkeys(ctx.lord_of_house(h) for h in cond['lord_houses'])) houses = self._required_pattern_houses(ctx, lords) if not all(h in (6, 8, 12) for h in houses.values()): return [] if cond.get('require_debilitation'): if any(ctx.sign_of(p) not in SIGNS for p in lords): raise MissingYogaInput('wealth_lord.D1.sign') if not all(ctx.is_debilitated(p) for p in lords): return [] return [{'combination': cond['description_zh'], 'bindings': {'_participants': lords}, 'condition_status': 'conditions_met', 'missing_inputs': [], 'condition_checks': {'lord_houses': houses}, 'formation_evidence': {'matched_paths': ['placement_observation'], 'named_yoga_formation': False, 'independent_support_count': None}}] def _eval_vidyut_source_geometry(self, cond, ctx, rule, bindings): """Raman59/PVR: preserve exact peak and broader unresolved reading.""" if ctx.ascendant not in SIGNS: raise MissingYogaInput('ascendant.sign') l1, l11 = ctx.lord_of_house(1), ctx.lord_of_house(11) participants = list(dict.fromkeys([l1, l11, 'Venus'])) signs = {p: ctx.sign_of(p) for p in participants} for p, sign in signs.items(): if sign not in SIGNS: raise MissingYogaInput(p + '.D1.sign') # This is a rasi relation from the ascendant LORD, not from Lagna. conjunction = signs[l11] == signs['Venus'] relative = (SIGNS.index(signs[l11]) - SIGNS.index(signs[l1])) % 12 + 1 if not conjunction or relative not in (1, 4, 7, 10) or signs[l11] != EXALTATION[l11]: return [] try: from .shadbala import EXALTATION_DEG except ImportError: from shadbala import EXALTATION_DEG peak = EXALTATION_DEG[l11] % 30 missing, degree, distance = [], None, None try: degree = ctx.source_degree_in_sign(l11) distance = abs(degree - peak) except MissingYogaInput as exc: missing.extend(exc.fields) exact_peak = distance is not None and distance <= 1e-9 # 1e-9 is coordinate round-off only, not an astrological orb. The # sources give a peak but no finite width; preserve off-peak geometry # without asserting either general formation or categorical absence. if degree is not None and not exact_peak: missing.append('Vidyut.source_admitted_deep_exaltation_extent') if l11 == 'Venus': missing.append('Vidyut.eleventh_lord_Venus_self_association_source_choice') formed = exact_peak and l11 != 'Venus' return [{'combination': cond['description_zh'], 'bindings': {'_participants': participants}, 'condition_status': 'conditions_met' if formed else 'incomplete_conditions', 'missing_inputs': missing, 'condition_checks': {'ascendant_lord': l1, 'eleventh_lord': l11, 'signs': signs, 'same_sign_as_venus': conjunction, 'house_from_ascendant_lord': relative, 'degree_in_sign': degree, 'deep_exaltation_degree': peak, 'distance_from_peak_degrees': distance, 'exact_peak': exact_peak, 'distinct_conjunction_participants': l11 != 'Venus'}, 'formation_evidence': { 'matched_paths': ['raman59_pvr_exact_peak'] if formed else [], 'matched_geometry_paths': ['exaltation_sign_venus_conjunction_kendra_from_l1'], 'unresolved_other_paths': ['finite_deep_exaltation_extent', 'Venus_self_association'], 'implementation_scope': 'exact_peak_sufficient_branch_and_qualified_off_peak_geometry', 'independent_support_count': int(formed), 'numerical_roundoff_degrees': 1e-9, 'astrological_orb_assumed': False}, 'effect_assessment': {'status': 'incomplete', 'personal_outcome_established': False, 'summary_zh': '保留财富管理、享受与慷慨的传统候选含义;实际表现仍需结合两位宫主的强弱与全盘,不能据格局名称推断技术职业、权位或必然财富。', 'summary_en': 'Retain traditional wealth-management, enjoyment and generosity themes conditionally. Expression depends on the lords and whole chart; the name establishes no technology occupation, rank or guaranteed wealth.'}}] def _eval_netranasa_raman_geometry(self, cond, ctx, rule, bindings): """Raman164: literal D1 definition; ambiguous amsa clause stays separate.""" if ctx.ascendant not in SIGNS: raise MissingYogaInput('ascendant.sign') lords = list(dict.fromkeys(ctx.lord_of_house(h) for h in (2, 6, 10))) houses = {p: ctx.house_of(p) for p in lords} # A known contrary placement disproves this conjunction even when a # different planet is missing. Unknowns are not treated as negatives. missing = [p + '.D1.house' for p, h in houses.items() if type(h) is not int or not 1 <= h <= 12] known_false = any(type(h) is int and 1 <= h <= 12 and h != 1 for h in houses.values()) conjunction = False if known_false else (None if missing else True) d9 = {p: ctx.d9_sign_of(p) for p in lords} checks = {p: (None if s not in SIGNS else s == DEBILITATION[p]) for p, s in d9.items()} # The source's "they" and amsa terminology are not silently replaced # by D1 debility or a new all-purpose Navamsa rule. Preserve the actual # D9 observation for review, but do not let it assert formation. unresolved = ['raman164.neechamsa_scope_and_referents_source_choice'] if conjunction is None: unresolved.extend(missing) return [{'combination': cond['description_zh'], 'bindings': {'_participants': lords}, 'condition_status': 'conditions_met' if conjunction is True else 'incomplete_conditions', 'missing_inputs': [] if conjunction is True else unresolved, 'condition_checks': {'d1_lords': houses, 'd1_conjunction': conjunction, 'd9_signs': d9, 'd9_debilitation_observations': checks}, 'formation_evidence': { 'matched_paths': ['raman164_lords_2_6_10_in_lagna'] if conjunction is True else [], 'matched_geometry_paths': ['raman164_lords_2_6_10_in_lagna'] if conjunction is True else [], 'unresolved_other_paths': unresolved, 'implementation_scope': 'literal_d1_branch_amsa_alternative_unresolved', 'independent_support_count': int(conjunction is True)}, 'effect_assessment': {'status': 'historical_medical_reference', 'personal_outcome_established': False, 'summary_zh': '仅核对原书位置结构,不据此判断视力或疾病。作者另强调日月有力且处境有利时不应断失明;该缓解条件未以任意强度阈值代替。', 'summary_en': 'Historical structure only, not a vision or disease conclusion. The author cautions against predicting blindness when both luminaries are strong and favourably placed; no arbitrary strength threshold substitutes for that qualification.'}}] def _eval_raman_strength_qualified_geometry(self, cond, ctx, rule, bindings): """Source-specific positional witnesses are not composite strength tests.""" if ctx.ascendant not in SIGNS: raise MissingYogaInput('ascendant.sign') profile = cond['profile'] paths, participants, checks, missing = [], [], {}, [] if profile == 'suputra_226': if ctx.lord_of_house(5) != 'Jupiter': return [] paths = ['jupiter_fifth_lord'] participants = ['Jupiter', 'Sun'] checks = {'fifth_lord': 'Jupiter', 'ascendant': ctx.ascendant} missing = ['Sun.source_admitted_favourable_position_profile'] elif profile == 'pretasapa_219': participants = ['Sun', 'Saturn', 'Moon', 'Rahu', 'Jupiter'] houses = self._required_pattern_houses(ctx, participants) expected = {'Sun': 5, 'Saturn': 5, 'Moon': 7, 'Rahu': 1, 'Jupiter': 12} if any(houses[p] != target for p, target in expected.items()): return [] paths = ['raman219_five_planet_placements'] checks = {'houses': houses, 'required_houses': expected, 'moon_phase_observation': ctx.panchanga.get('is_waning_moon'), 'moon_weakness_assessed': False} missing = ['Moon.source_admitted_composite_weakness_profile'] elif profile == 'jarajaputra_237': lords = {str(h): ctx.lord_of_house(h) for h in (5, 7, 6)} participants = list(dict.fromkeys(lords.values())) houses = self._required_pattern_houses(ctx, participants) if len(set(houses.values())) != 1: return [] benefics = self._natural_benefics_for_named_pattern(ctx) # Joined lords receive the aspect. A lord's outgoing special # aspect does not turn into an incoming benefic aspect. witnesses = [p for p in benefics if p not in participants and ctx.parashari_aspects_house(p, houses[lords['5']])] if not witnesses: return [] paths = ['raman237_lords_joined_and_receiving_benefic_aspect'] participants.extend(witnesses) checks = {'lords': lords, 'houses': houses, 'benefic_aspect_witnesses': witnesses, 'lord_strength_assessed': False} missing = list(dict.fromkeys(p + '.source_admitted_composite_strength_profile' for p in (lords['5'], lords['7']))) else: benefics = self._natural_benefics_for_named_pattern(ctx) checks['natural_benefics'] = benefics if profile == 'bhagya_241': witnesses = [p for p in benefics if ctx.house_of(p) in (1, 3, 5) and ctx.parashari_aspects_house(p, 9)] checks['ninth_house_aspect_witnesses'] = witnesses for p in witnesses: paths.append('benefic_placement_and_ninth_aspect:' + p) participants.append(p) missing.append(p + '.source_admitted_composite_strength_profile') elif profile == 'bhratruvriddhi_177': l3 = ctx.lord_of_house(3) for label, target in [('third_lord', l3), ('mars', 'Mars'), ('third_house', None)]: # Association is received by the target. Mars' own special # aspect onto a benefic is not a benefic aspect onto Mars. witnesses = [p for p in benefics if p != target and ( (ctx.house_of(p) == 3 or ctx.parashari_aspects_house(p, 3)) if target is None else (ctx.house_of(p) == ctx.house_of(target) or ctx.parashari_aspect(p, target)))] checks[label] = {'target': target or 'house3', 'benefic_witnesses': witnesses} if witnesses: paths.append(label + '_benefic_connection') participants.extend(([target] if target else []) + witnesses) missing.append((target or 'Third_house') + '.source_admitted_composite_strength_profile') else: raise ValueError('Unknown Raman strength-qualified profile: ' + str(profile)) if not paths: return [] return [{'combination': cond['description_zh'], 'bindings': {'_participants': list(dict.fromkeys(participants))}, 'condition_status': 'incomplete_conditions', 'missing_inputs': list(dict.fromkeys(missing)), 'condition_checks': checks, 'formation_evidence': {'matched_paths': [], 'matched_geometry_paths': paths, 'implementation_scope': 'geometry_only_qualification_unresolved', 'independent_support_count': 0, 'benefic_convention': 'waxing Moon and unafflicted Mercury; Jupiter and Venus', 'aspect_convention': 'received Parashari graha aspects; no node aspects'}, 'effect_assessment': {'status': 'incomplete', 'personal_outcome_established': False, 'summary_zh': cond['summary_zh'], 'summary_en': cond['summary_en']}}] def _eval_saarada_pvr_geometry(self, cond, ctx, rule, bindings): """PVR indexed143: all five clauses; no invented composite strength.""" lord = ctx.lord_of_house(10) h = self._required_pattern_houses(ctx, [lord, 'Mercury', 'Jupiter', 'Moon', 'Mars', 'Sun']) sun_sign = ctx.sign_of('Sun') if sun_sign not in SIGNS: raise MissingYogaInput('Sun.D1.sign') trine = [p for p in ('Mercury', 'Jupiter') if (h[p] - h['Moon']) % 12 in (0, 4, 8)] checks = {'tenth_lord_fifth': h[lord] == 5, 'mercury_kendra': h['Mercury'] in (1, 4, 7, 10), 'sun_in_leo': sun_sign == 'Leo', 'mercury_or_jupiter_moon_trine': bool(trine), 'mars_eleventh': h['Mars'] == 11} if not all(checks.values()): return [] # Own-sign placement supports strength, but cannot replace the author's # separate "strong" qualifier with an unreviewed numeric threshold. missing = ['Sun.source_admitted_composite_strength_profile'] return [{'combination': cond['description_zh'], 'bindings': {'_participants': list(dict.fromkeys([lord, 'Mercury', 'Sun', 'Moon', 'Mars', *trine]))}, 'condition_status': 'incomplete_conditions', 'missing_inputs': missing, 'condition_checks': checks, 'formation_evidence': {'matched_paths': [], 'matched_geometry_paths': ['five_clause_geometry'], 'unresolved_other_paths': missing, 'independent_support_count': 0, 'implementation_scope': 'geometry_only_strength_unresolved', 'trine_convention': '1/5/9 from Moon, including conjunction'}, 'effect_assessment': {'status': 'incomplete', 'personal_outcome_established': False, 'summary_zh': '五项位置条件吻合,太阳综合有力的判据尚未核定;保留学习与表达的传统候选含义,不判为完整成立。', 'summary_en': 'Five positional clauses match; the separate solar strength criterion remains unresolved. Retain conditional learning themes, not complete formation.'}}] def _eval_satkathadisravana_raman(self, cond, ctx, rule, bindings): """Raman186: received house/lord aspects, without D1-for-amsa substitution.""" benefics = self._natural_benefics_for_named_pattern(ctx) lord = ctx.lord_of_house(3) house_aspects = [] for p in benefics: offsets = (5, 7, 9) if p == 'Jupiter' else (7,) if (3 - ctx.house_of(p)) % 12 + 1 in offsets: house_aspects.append(p) lord_aspects = [p for p in benefics if p != lord and ctx.parashari_aspect(p, lord)] definition_geometry = lord in benefics and bool(house_aspects) if not definition_geometry and not lord_aspects: return [] return [{'combination': cond['description_zh'], 'bindings': {'_participants': list(dict.fromkeys([lord, *house_aspects, *lord_aspects]))}, 'condition_status': 'incomplete_conditions', 'missing_inputs': ['third_lord.benefic_amsa_source_scope'], 'condition_checks': {'third_house_lord': lord, 'natural_benefic_convention': 'waxing_moon_unafflicted_mercury', 'third_house_benefic_lord': lord in benefics, 'third_house_received_benefic_aspects': house_aspects, 'third_lord_received_benefic_aspects': lord_aspects, 'third_lord_d9_sign_observation': ctx.d9_sign_of(lord)}, 'formation_evidence': {'matched_paths': [], 'matched_geometry_paths': (['definition_geometry'] if definition_geometry else []) + (['remarks_received_aspect'] if lord_aspects else []), 'independent_support_count': 0, 'implementation_scope': 'received_aspect_geometry_amsa_scope_unresolved'}, 'effect_assessment': {'status': 'incomplete', 'personal_outcome_established': False, 'summary_zh': '保留阅读、听讲与经典学习的传统候选含义;分区条件尚未核定,不能据此断定阅读习惯、学识或信仰。', 'summary_en': 'Retain conditional reading and study themes; the amsa qualifier is unresolved, so reading habits, scholarship or beliefs are not established.'}}] def _eval_yuddha_marana_raman(self, cond, ctx, rule, bindings): """Raman275: separate literal, expanded and D3-dispositor alternatives.""" states, witnesses = {}, {} l3 = ctx.lord_of_house(3) def conjunction_path(lord, companions): self._required_pattern_houses(ctx, [lord, l3]) if ctx.house_of(lord) != ctx.house_of(l3): return {'status': 'not_met'} found, unknown = [], [] for p in companions: # One body filling two roles is not an extra companion. if p in (lord, l3): continue house = ctx.upagraha_house('maandi') if p == 'Maandi' else ctx.house_of(p) if house is None: unknown.append(p + '.D1.house') elif house == ctx.house_of(lord): found.append(p) if not found and not unknown: return {'status': 'not_met'} return {'status': 'incomplete', 'lord': lord, 'third_lord': l3, 'companions': found, 'missing_inputs': unknown, 'unresolved_qualifier': 'source_admitted_cruel_amsa_scope_and_nature', 'self_lord_association': lord == l3} for label, lord in [('literal_mars', 'Mars'), ('remarks_sixth', ctx.lord_of_house(6)), ('remarks_eighth', ctx.lord_of_house(8))]: if label == 'literal_mars' and 'Mars' not in (ctx.lord_of_house(6), ctx.lord_of_house(8)): states[label] = {'status': 'not_applicable'} continue try: states[label] = conjunction_path(lord, ('Rahu', 'Maandi', 'Mars') if lord == 'Saturn' else ('Rahu', 'Saturn', 'Maandi')) except MissingYogaInput as exc: states[label] = {'status': 'incomplete', 'missing_input': str(exc)} sign = ctx.d3.get('planets', {}).get('Saturn', {}).get('sign') if sign not in SIGNS: states['saturn_d3_dispositor'] = {'status': 'incomplete', 'missing_input': 'Saturn.D3.sign'} else: lord = SIGN_LORDS[sign] d1, d9 = ctx.sign_of(lord), ctx.d9_sign_of(lord) aspect = None if ctx.house_of('Mars') in range(1, 13) and ctx.house_of(lord) in range(1, 13): aspect = lord != 'Mars' and ctx.parashari_aspect('Mars', lord) checks = {'dispositor_in_mars_d1_sign': d1 in ('Aries', 'Scorpio') if d1 in SIGNS else None, 'dispositor_in_mars_d9_sign': d9 in ('Aries', 'Scorpio') if d9 in SIGNS else None, 'dispositor_receives_mars_d1_aspect': aspect} met = any(v is True for v in checks.values()) states['saturn_d3_dispositor'] = {'status': 'met' if met else ('incomplete' if None in checks.values() else 'not_met'), 'saturn_d3_sign': sign, 'dispositor': lord, 'checks': checks} witnesses['saturn_d3_dispositor'] = list(dict.fromkeys(['Saturn', lord, 'Mars'])) met = [k for k, v in states.items() if v['status'] == 'met'] pending = [k for k, v in states.items() if v['status'] == 'incomplete'] if not met and not pending: return [] return [{'combination': cond['description_zh'], 'bindings': {'_participants': list(dict.fromkeys(p for k in met for p in witnesses.get(k, [])))}, 'condition_status': 'conditions_met' if met else 'incomplete_conditions', 'condition_checks': states, 'missing_inputs': [] if met else pending, 'formation_evidence': {'matched_paths': met, 'unresolved_other_paths': pending, 'independent_support_count': int(bool(met)), 'implementation_scope': 'd3_alternative_wired_conjunction_amsa_partial'}, 'effect_assessment': {'status': 'historical_injury_reference', 'personal_outcome_established': False, 'summary_zh': '保留原书的独立分盘条件与合相条件。此历史条目不能据此判断战争、伤害或死亡事件。', 'summary_en': 'Preserve the separate divisional and conjunction readings. This historical item does not establish war, injury or death.'}}] def _eval_sirachcheda_raman_geometry(self, cond, ctx, rule, bindings): """Raman273: conjunction geometry and two explicitly distinct amsa readings.""" l6 = ctx.lord_of_house(6) self._required_pattern_houses(ctx, [l6, 'Venus', 'Sun', 'Saturn', 'Rahu']) if ctx.house_of(l6) != ctx.house_of('Venus'): return [] joined = [p for p in ('Sun', 'Saturn') if ctx.house_of(p) == ctx.house_of('Rahu')] if not joined: return [] missing = ['source_admitted_shashtiamsa_nature_and_scope_profile'] if l6 == 'Venus': missing.append('Venus_as_sixth_lord.self_association_source_choice') alternatives = {} for planet in joined: ordinals = {} comparison = {} for p in (planet, 'Rahu'): try: ordinals[p] = ctx.raman_shashtiamsa_ordinal(p) comparison[p] = ctx.saravali_shashtiamsa_comparison(p) except MissingYogaInput as exc: missing.append(str(exc)) # Ordinal equality is only the shared-segment clause, not nature. shared = (ordinals[planet] == ordinals['Rahu'] if len(ordinals) == 2 else None) alternatives[planet] = { 'named_amsa_ordinals': ordinals, 'saravali_nature_comparison': comparison, 'shared_amsa_reading': { 'status': 'not_met' if shared is False else 'incomplete', 'same_named_segment': shared}, 'planet_only_amsa_reading': {'status': 'incomplete'}, } return [{'combination': cond['description_zh'], 'bindings': {'_participants': list(dict.fromkeys([l6, 'Venus', 'Rahu', *joined]))}, 'condition_status': 'incomplete_conditions', 'missing_inputs': list(dict.fromkeys(missing)), 'condition_checks': {'sixth_lord_joins_venus': None if l6 == 'Venus' else True, 'sun_or_saturn_joins_rahu': joined, 'source_scope_alternatives': alternatives}, 'formation_evidence': {'matched_paths': [], 'matched_geometry_paths': [] if l6 == 'Venus' else ['raman273_conjunctions'], 'independent_support_count': 0, 'implementation_scope': 'geometry_only_named_amsa_scope_unresolved'}, 'effect_assessment': {'status': 'historical_injury_reference', 'personal_outcome_established': False, 'summary_zh': '部分位置条件吻合;六十分区的性质及两种原文读法仍须分开核定。此传统条目不能用于断言受伤、死亡或具体灾祸。', 'summary_en': 'Some positional clauses match; named-amsa nature and the two source readings remain separate unresolved conditions. This historical item does not establish injury, death or disaster.'}}] def _eval_galakarna_raman(self, cond, ctx, rule, bindings): """264: executable conjunction, separate unresolved named-amsa paths.""" self._required_pattern_houses(ctx, ['Rahu', 'Mars']) states, witnesses = {}, {} if ctx.house_of('Rahu') != 3: states['maandi_rahu'] = {'status': 'not_met'} elif ctx.upagraha_house('maandi') is None: states['maandi_rahu'] = {'status': 'incomplete', 'missing_input': 'maandi.D1.house'} else: states['maandi_rahu'] = {'status': 'met' if ctx.upagraha_house('maandi') == 3 else 'not_met'} witnesses['maandi_rahu'] = ['Maandi', 'Rahu'] # Manual art127 locates Preta Puriha at ordinal12. A D60 sign cannot. if ctx.house_of('Mars') != 3: states['mars_named_amsa_definition'] = {'status': 'not_met'} else: try: ordinal = ctx.raman_shashtiamsa_ordinal('Mars') states['mars_named_amsa_definition'] = { 'status': 'met' if ordinal == 12 else 'not_met', 'named_amsa_ordinal': ordinal, 'source_profile': 'Raman_Manual_art127'} witnesses['mars_named_amsa_definition'] = ['Mars'] except MissingYogaInput as exc: states['mars_named_amsa_definition'] = {'status': 'incomplete', 'missing_input': str(exc)} states['rahu_cruel_amsa_remarks'] = ( {'status': 'incomplete', 'missing_input': 'Rahu.source_admitted_shashtiamsa_nature'} if ctx.house_of('Rahu') == 3 else {'status': 'not_met'}) if ctx.house_of('Rahu') == 3: try: states['rahu_cruel_amsa_remarks']['source_comparison'] = ctx.saravali_shashtiamsa_comparison('Rahu') except MissingYogaInput: pass # Existing unresolved state remains explicit; no false negative. met = [name for name, state in states.items() if state['status'] == 'met'] missing = [state['missing_input'] for state in states.values() if state['status'] == 'incomplete'] if not met and not missing: return [] return [{'combination': cond['description_zh'], 'bindings': {'_participants': list(dict.fromkeys(p for name in met for p in witnesses[name]))}, 'condition_status': 'conditions_met' if met else 'incomplete_conditions', 'condition_checks': states, 'missing_inputs': [] if met else missing, 'formation_evidence': {'matched_paths': met, 'unresolved_other_paths': missing, 'independent_support_count': int(bool(met)), 'implementation_scope': 'partial_named_amsa_unresolved'}, 'effect_assessment': {'status': 'historical_medical_reference', 'personal_outcome_established': False, 'summary_zh': '传统结构参考,不据此判断耳部疾病、听力或其他医学结果。罗睺凶性六十分区的补充口径尚未核定。', 'summary_en': 'Historical structure only, not an ear or hearing diagnosis. The Rahu cruel-shashtiamsa remarks profile remains unresolved.'}}] def _eval_gandharva_pvr_geometry(self, cond, ctx, rule, bindings): """PVR indexed144: retain all positional clauses and unresolved strength.""" l1, l10 = ctx.lord_of_house(1), ctx.lord_of_house(10) self._required_pattern_houses(ctx, [l1, l10, 'Jupiter', 'Moon']) if ctx.sign_of('Sun') not in SIGNS: raise MissingYogaInput('Sun.D1.sign') checks = {'tenth_lord_trine_from_seventh': ctx.house_of(l10) in (7, 11, 3), 'jupiter_contacts_lagna_lord': l1 != 'Jupiter' and ( ctx.house_of(l1) == ctx.house_of('Jupiter') or ctx.parashari_aspect('Jupiter', l1)), 'sun_exalted': ctx.sign_of('Sun') == 'Aries', 'moon_ninth': ctx.house_of('Moon') == 9} # Self-contact cannot silently fulfill an association clause. self_contact = l1 == 'Jupiter' if any(not value for key, value in checks.items() if key != 'jupiter_contacts_lagna_lord' or not self_contact): return [] missing = ['Sun.source_admitted_composite_strength_profile'] if self_contact: missing.append('Jupiter_as_lagna_lord.self_association_source_choice') return [{'combination': cond['description_zh'], 'bindings': {'_participants': list(dict.fromkeys([l1, l10, 'Jupiter', 'Sun', 'Moon']))}, 'condition_status': 'incomplete_conditions', 'missing_inputs': missing, 'condition_checks': checks, 'formation_evidence': {'matched_paths': [], 'matched_geometry_paths': [] if self_contact else ['pvr_four_clause_geometry'], 'unresolved_other_paths': missing, 'independent_support_count': 0, 'implementation_scope': 'geometry_only_strength_unresolved'}, 'effect_assessment': {'status': 'incomplete', 'personal_outcome_established': False, 'summary_zh': '保留艺术与表达主题的传统候选结构;太阳入旺不能单独替代综合有力条件,不能据此确定才艺、名望或实际成就。', 'summary_en': 'Retain the traditional arts/expression candidate structure. Solar exaltation alone does not establish the separate strength condition, talent, fame or achievement.'}}] def _eval_matrudeerghayur_raman_geometry(self, cond, ctx, rule, bindings): """196/197: separate D1 and D9-dispositor paths; neither proves longevity.""" l4 = ctx.lord_of_house(4) states, witnesses = {}, {} def definition196(): if ctx.sign_of(l4) not in SIGNS: raise MissingYogaInput(str(l4) + '.D1.sign') if not ctx.is_exalted(l4): return False benefics = self._natural_benefics_for_named_pattern(ctx) occupants = [p for p in benefics if ctx.house_of(p) == 4] witnesses['raman196_geometry'] = list(dict.fromkeys([l4, 'Moon', *occupants])) return bool(occupants) def definition197(): sign = ctx.d9_sign_of(l4) if sign not in SIGNS: raise MissingYogaInput(str(l4) + '.D9.sign') # Dispositor of the fourth LORD's D9 placement, not D9 fourth lord. dispositor = SIGN_LORDS[sign] self._required_pattern_houses(ctx, [dispositor, 'Moon']) h, moon = ctx.house_of(dispositor), ctx.house_of('Moon') witnesses['raman197_geometry'] = list(dict.fromkeys([l4, dispositor, 'Moon'])) return h in (1, 4, 7, 10) and (h - moon) % 12 + 1 in (1, 4, 7, 10) for name, evaluate in [('raman196_geometry', definition196), ('raman197_geometry', definition197)]: try: geometry = evaluate() states[name] = {'status': 'incomplete' if geometry else 'not_met', 'geometry_met': geometry} if geometry: states[name]['missing_input'] = ('Moon.source_admitted_composite_strength_profile' if name == 'raman196_geometry' else 'Fourth_lord_navamsa_dispositor.source_admitted_composite_strength_profile') except MissingYogaInput as exc: states[name] = {'status': 'incomplete', 'geometry_met': None, 'missing_input': str(exc)} missing = [s['missing_input'] for s in states.values() if s['status'] == 'incomplete'] if not missing: return [] paths = [name for name, state in states.items() if state['geometry_met'] is True] return [{'combination': cond['description_zh'], 'bindings': {'_participants': list(dict.fromkeys(p for name in paths for p in witnesses[name]))}, 'condition_status': 'incomplete_conditions', 'condition_checks': states, 'missing_inputs': missing, 'formation_evidence': {'matched_geometry_paths': paths, 'matched_paths': [], 'independent_support_count': 0, 'unresolved_other_paths': missing, 'implementation_scope': 'geometry_only_strength_unresolved'}, 'effect_assessment': {'status': 'historical_medical_reference', 'personal_outcome_established': False, 'summary_zh': '两项传统位置路径分别保留,相关行星综合有力及整体制约尚未完成判定;不能据此判断母亲寿命或健康。', 'summary_en': 'Retain the two positional paths separately; their strength and whole-chart qualifications remain unresolved. No maternal lifespan or health outcome is established.'}}] def _eval_raja_bhanga_raman(self, cond, ctx, rule, bindings): """298/299 named structural screens, never a blanket Raja cancellation.""" states, witnesses = {}, {} def saturn_base(): if ctx.ascendant != 'Leo': return False if ctx.sign_of('Saturn') not in SIGNS: raise MissingYogaInput('Saturn.D1.sign') return ctx.sign_of('Saturn') == 'Libra' def navamsa(): if not saturn_base(): return False if ctx.d9_sign_of('Saturn') not in SIGNS: raise MissingYogaInput('Saturn.D9.sign') witnesses['raman298_debilitated_navamsa'] = ['Saturn'] return ctx.d9_sign_of('Saturn') == 'Aries' def benefic_aspect(): if not saturn_base(): return False benefics = self._natural_benefics_for_named_pattern(ctx) actual = [p for p in benefics if ctx.parashari_aspect(p, 'Saturn')] witnesses['raman298_definition_benefic_aspect'] = ['Saturn', *actual] return bool(actual) def deep_sun(): if ctx.sign_of('Sun') not in SIGNS: raise MissingYogaInput('Sun.D1.sign') if ctx.sign_of('Sun') != 'Libra': return False # Source299's deep-debilitation point, not an invented degree-wide orb. degree = ctx.source_degree_in_sign('Sun') witnesses['raman299_exact_debilitation'] = ['Sun'] return abs(degree - 10.0) <= 1e-9 for name, evaluate in [('raman298_debilitated_navamsa', navamsa), ('raman298_definition_benefic_aspect', benefic_aspect), ('raman299_exact_debilitation', deep_sun)]: try: states[name] = {'status': 'met' if evaluate() else 'not_met'} except MissingYogaInput as exc: states[name] = {'status': 'incomplete', 'missing_input': str(exc)} met = [name for name, state in states.items() if state['status'] == 'met'] missing = [s['missing_input'] for s in states.values() if s['status'] == 'incomplete'] if not met and not missing: return [] return [{'combination': cond['description_zh'], 'bindings': {'_participants': list(dict.fromkeys(p for name in met for p in witnesses[name]))}, 'condition_status': 'conditions_met' if met else 'incomplete_conditions', 'condition_checks': states, 'missing_inputs': [] if met else missing, 'formation_evidence': {'matched_paths': met, 'unresolved_other_paths': missing, 'independent_support_count': int(bool(met)), 'source_difference': '298 definition includes benefic-aspect alternative; remarks explain the debilitated-Navamsa path only.', 'sun_point_tolerance_degrees': 1e-9, 'raja_yogas_cancelled': False}, 'effect_assessment': {'status': 'incomplete', 'personal_outcome_established': False, 'summary_zh': '保留两条传统位置筛查及各自路径,不自动取消其他吉格;作者明确指出太阳落陷本身不足以否定所有王者格局。实际表现仍需综合支持与制约。', 'summary_en': 'Retain the two source-specific positional screens without cancelling other Yogas. The author explicitly rejects solar debility alone as enough to destroy every Raja Yoga; expression needs the whole support and constraint assessment.'}}] def _eval_aputra_raman(self, cond, ctx, rule, bindings): """224: fifth lord in6/8/12; the author's qualification is essential. The legacy104 identifier is retained for callers, not as a book number. Neither this screen nor the author's example establishes fertility. """ lord = ctx.lord_of_house(5) self._required_pattern_houses(ctx, [lord]) house = ctx.house_of(lord) if house not in (6, 8, 12): return [] return [{'combination': cond['description_zh'], 'bindings': {'_participants': [lord]}, 'condition_status': 'conditions_met', 'missing_inputs': [], 'condition_checks': {'fifth_lord_in_dusthana': { 'status': 'met', 'planet': lord, 'house': house}}, 'formation_evidence': {'matched_paths': ['raman224_definition'], 'independent_support_count': 1, 'source_qualification': 'Examine the entire fifth house and its strength; do not apply this general combination literally.'}, 'effect_assessment': {'status': 'historical_medical_reference', 'personal_outcome_established': False, 'summary_zh': '第五宫主位于第六、八或十二宫,命中传统的一项概括性结构;原作者要求结合第五宫整体强弱,不能单凭它判断是否有子女、生育能力或子女数量。', 'summary_en': 'The fifth lord occupies6/8/12, meeting a general traditional screen. The author requires the whole fifth-house assessment; this alone does not establish parenthood, fertility or number of children.'}}] def _eval_durmarana_geometry_raman(self, cond, ctx, rule, bindings): """Raman274 definition only; geometry is not a mortality prediction.""" lord = ctx.lord_of_house(1) self._required_pattern_houses(ctx, ['Moon', lord]) moon_house = ctx.house_of('Moon') if moon_house not in (6, 8, 12) or not ctx.parashari_aspect(lord, 'Moon'): return [] companions, missing = [], [] for planet in ('Saturn', 'Rahu'): house = ctx.house_of(planet) if house is None: missing.append(planet + '.D1.house') elif house == moon_house: companions.append(planet) mandi = ctx.upagraha_house('maandi') if mandi is None: missing.append('maandi.D1.house') elif mandi == moon_house: companions.append('Maandi') if not companions and not missing: return [] met = bool(companions) return [{'combination': cond['description_zh'], 'bindings': {'_participants': list(dict.fromkeys(['Moon', lord, *companions]))}, 'condition_status': 'conditions_met' if met else 'incomplete_conditions', 'condition_checks': {'companion': {'status': 'met' if met else 'incomplete'}}, 'missing_inputs': [] if met else missing, 'formation_evidence': {'matched_paths': ['definition'] if met else [], 'unresolved_other_paths': missing, 'independent_support_count': int(met)}, 'effect_assessment': {'status': 'historical_medical_reference', 'personal_outcome_established': False, 'summary_zh': '命中传统结构不等于现实危险,不能据此判断死亡方式、寿命或个人健康结果。', 'summary_en': 'This historical configuration does not establish danger, manner of death, lifespan or a personal health outcome.'}}] def _eval_pisacha_raman(self, cond, ctx, rule, bindings): """287: separate definition and author's Saturn-contact remarks.""" self._required_pattern_houses(ctx, ['Moon', 'Rahu']) if ctx.house_of('Moon') != ctx.house_of('Rahu'): return [] witnesses, states = {}, {} def definition(): if ctx.house_of('Moon') != 1: return False benefics = self._natural_benefics_for_named_pattern(ctx) # The conjunction in Lagna must not satisfy its own extra trine test. occupants = {h: [p for p in ALL_PLANETS if p not in benefics and p not in ('Moon', 'Rahu') and ctx.house_of(p) == h] for h in (5, 9)} witnesses['definition_both_non_lagna_trines'] = ['Moon', 'Rahu', *(p for items in occupants.values() for p in items)] return all(occupants.values()) def remarks(): self._required_pattern_houses(ctx, ['Saturn']) witnesses['remarks_saturn_contact'] = ['Moon', 'Rahu', 'Saturn'] return (ctx.house_of('Saturn') == ctx.house_of('Moon') or ctx.parashari_aspect('Saturn', 'Moon')) for name, evaluate in [('definition_both_non_lagna_trines', definition), ('remarks_saturn_contact', remarks)]: try: states[name] = {'status': 'met' if evaluate() else 'not_met'} except MissingYogaInput as exc: states[name] = {'status': 'incomplete', 'missing_input': str(exc)} met = [name for name, state in states.items() if state['status'] == 'met'] missing = [state['missing_input'] for state in states.values() if state['status'] == 'incomplete'] if not met and not missing: return [] return [{'combination': cond['description_zh'], 'bindings': {'_participants': list(dict.fromkeys(p for name in met for p in witnesses[name]))}, 'condition_status': 'conditions_met' if met else 'incomplete_conditions', 'condition_checks': states, 'missing_inputs': [] if met else missing, 'formation_evidence': {'matched_paths': met, 'unresolved_other_paths': missing, 'classification_profile': 'Definition: native natural-malefic classification in both5/9, excluding Moon/Rahu already in Lagna. Remarks: Moon/Rahu with Saturn or receiving Saturn aspect, not restricted to Lagna.', 'independent_support_count': int(bool(met))}, 'effect_assessment': {'status': 'historical_medical_reference', 'personal_outcome_established': False, 'summary_zh': '仅保留具名传统结构,不能据此认定附灵、心理疾病、非理性行为或个人健康结果。', 'summary_en': 'Named historical configuration only; it does not establish spirit possession, mental illness, irrational behavior or a personal health outcome.'}}] # BUG-2406 (负责人 2026-11-26 批准,占星师 322e2f30 ③): Raman 205–206 / 108 / 220–221 as typed # evaluators, copied from upstream; Rogagrastha (Raman 111) is not taken (负责人:先看她的措辞). def _eval_nishkapata_raman(self, cond, ctx, rule, bindings): """Raman205/206 printed194–195: separate alternatives and source warning. Parvata/Uttamamsa are named distinctions, not the retired weighted score >=16. Missing that branch cannot erase an observed alternative. """ chart = ctx.context.get('chart_type', 'D1') if chart != 'D1': raise MissingYogaInput('Nishkapata.source_admitted_' + str(chart) + '_scope') lord = ctx.lord_of_house(1) fourth_lord = ctx.lord_of_house(4) states, witnesses, missing = {}, {}, [] # Known Jupiter/Venus witnesses survive unrelated unknown lunar phase. benefics = {'Jupiter', 'Venus'} try: benefics.update(self._natural_benefics_for_named_pattern(ctx)) except MissingYogaInput as exc: missing.extend(exc.fields) occupants = [p for p in ALL_PLANETS if ctx.house_of(p) == 4] missing.extend(p + '.D1.sign' for p in occupants if ctx.sign_of(p) not in SIGNS) benefic_occupants = [p for p in occupants if p in benefics] dignified = [p for p in occupants if ctx.sign_of(p) in SIGNS and p in HOUSE_STRENGTHS and HOUSE_STRENGTHS[p][SIGNS.index(ctx.sign_of(p))] >= 3] sign_benefic = SIGNS[(ctx.asc_idx + 3) % 12] in { 'Taurus', 'Gemini', 'Cancer', 'Virgo', 'Libra', 'Sagittarius', 'Pisces'} known_occupancy = all(ctx.house_of(p) in range(1, 13) for p in ALL_PLANETS) states['raman205'] = {'status': 'met' if benefic_occupants or dignified or sign_benefic else 'not_met' if known_occupancy and not missing else 'incomplete', 'benefic_occupants': benefic_occupants, 'dignified_occupants': dignified, 'fourth_sign_benefic': sign_benefic} witnesses['raman205'] = list(dict.fromkeys(benefic_occupants + dignified)) contacts = [p for p in ALL_PLANETS if p in benefics and p != lord and ctx.house_of(p) in range(1,13) and (ctx.house_of(p) == 4 or ctx.parashari_aspect(p, lord))] if ctx.house_of(lord) == 4 else [] states['raman206_contact'] = {'status': 'met' if contacts else 'incomplete' if ctx.house_of(lord) not in range(1,13) or (ctx.house_of(lord) == 4 and (missing or not known_occupancy)) else 'not_met', 'contacts': contacts} witnesses['raman206_contact'] = [lord, *contacts] states['raman206_named_amsa'] = {'status': 'incomplete', 'required_names': ['Parvata', 'Uttamamsa']} missing.append(lord + '.source_admitted_Parvata_or_Uttamamsa_method') if not known_occupancy: missing.append('complete_planet_houses') matched = [k for k,v in states.items() if v['status'] == 'met'] # Record the author's caution without turning it into a character test. associations = [p for p in ('Rahu','Saturn') if p != fourth_lord and ctx.house_of(fourth_lord) in range(1,13) and ctx.house_of(p) == ctx.house_of(fourth_lord)] relief = [p for p in ('Jupiter','Venus') if p != fourth_lord and ctx.house_of(p) in range(1,13) and ctx.house_of(fourth_lord) in range(1,13) and ctx.parashari_aspect(p,fourth_lord)] return [{'combination': cond['description_zh'], 'bindings': {'_participants': list(dict.fromkeys(p for k in matched for p in witnesses[k]))}, 'condition_status': 'conditions_met' if matched else 'incomplete_conditions', 'condition_checks': states, 'missing_inputs': [] if matched else list(dict.fromkeys(missing)), 'formation_evidence': {'matched_paths': matched, 'unresolved_other_paths': list(dict.fromkeys(missing)), 'source_locator': 'Raman205–206 printed194–195/PDF204–205', 'implementation_scope': 'partial_named_amsa_unresolved', 'chart_scope': 'D1', 'fourth_lord_malefic_associations': associations, 'fourth_lord_benefic_aspects': relief, 'independent_support_count': int(bool(matched))}, # BUG-2406: upstream marks this row historical_conduct_reference, which in this report withholds # the meaning and prints another rule's infidelity sentence; here the plain meaning stays and the # author's fourth-lord caution is a limiting line when it applies to this chart. **({'reductions': ['第四宫主与' + '、'.join({'Rahu': '罗睺', 'Saturn': '土星'}[p] for p in associations) + '同宫,坦诚的一面不容易显出来'], 'reductions_en': ['The fourth lord shares a house with ' + ' and '.join(associations) + ', so the openness shows less readily']} if associations else {})}] def _eval_sareera_soukhya_raman(self, cond, ctx, rule, bindings): """Raman108 printed130: any of three roles in a D1 quadrant. The author's all-three remark is recorded, not converted to a calculated strength grade or three independent supporting planets. """ roles = {'ascendant_lord': ctx.lord_of_house(1), 'jupiter': 'Jupiter', 'venus': 'Venus'} checks, missing, matched = {}, [], [] for role, planet in roles.items(): try: self._required_pattern_houses(ctx, [planet]) met = ctx.house_of(planet) in (1, 4, 7, 10) checks[role] = {'planet': planet, 'house': ctx.house_of(planet), 'status': 'met' if met else 'not_met'} if met: matched.append(planet) except MissingYogaInput as exc: missing.extend(exc.fields) checks[role] = {'planet': planet, 'status': 'incomplete'} if not matched and not missing: return [] return [{'combination': cond['description_zh'], 'bindings': {'_participants': list(dict.fromkeys(matched))}, 'condition_status': 'conditions_met' if matched else 'incomplete_conditions', 'condition_checks': checks, 'missing_inputs': [] if matched else list(dict.fromkeys(missing)), 'formation_evidence': {'matched_paths': [k for k,v in checks.items() if v['status'] == 'met'], 'unresolved_other_paths': list(dict.fromkeys(missing)), 'all_three_roles_angular': all(v['status'] == 'met' for v in checks.values()), 'distinct_participant_count': len(set(matched)), 'independent_support_count': int(bool(matched)), 'strength_established': False, 'personal_health_or_lifespan_established': False}}] def _eval_bahuputra_raman(self, cond, ctx, rule, bindings): """Raman220/221, printed210–212: independent positional alternatives. Association is evaluated as distinct D1 co-occupancy, not a lord's association with itself. Unknown alternatives cannot erase a match. """ states, witnesses = {}, {} try: self._required_pattern_houses(ctx, ['Rahu']) first = False if ctx.house_of('Rahu') == 5: sign = ctx.d9_sign_of('Rahu') if sign not in SIGNS: raise MissingYogaInput('Rahu.D9.sign') first = sign not in ('Capricorn', 'Aquarius') states['raman220'] = {'status': 'met' if first else 'not_met'} witnesses['raman220'] = ['Rahu'] if first else [] except MissingYogaInput as exc: states['raman220'] = {'status': 'incomplete', 'missing_inputs': exc.fields} lord = ctx.lord_of_house(7) missing, companions, matched = [], [], [] try: self._required_pattern_houses(ctx, [lord]) for planet in ALL_PLANETS: if planet == lord: continue try: self._required_pattern_houses(ctx, [planet]) if ctx.house_of(planet) != ctx.house_of(lord): continue sign = ctx.d9_sign_of(planet) if sign not in SIGNS: raise MissingYogaInput(planet + '.D9.sign') dispositor = SIGN_LORDS[sign] self._required_pattern_houses(ctx, [dispositor]) item = {'planet': planet, 'd9_sign': sign, 'dispositor': dispositor, 'dispositor_d1_house': ctx.house_of(dispositor)} companions.append(item) if ctx.house_of(dispositor) in (1, 2, 5): matched.append(item) except MissingYogaInput as exc: missing.extend(exc.fields) except MissingYogaInput as exc: missing.extend(exc.fields) states['raman221'] = { 'status': 'met' if matched else 'incomplete' if missing else 'not_met', 'seventh_lord': lord, 'companions': companions, 'missing_inputs': list(dict.fromkeys(missing))} witnesses['raman221'] = list(dict.fromkeys( p for item in matched for p in (lord, item['planet'], item['dispositor']))) met = [name for name, state in states.items() if state['status'] == 'met'] unresolved = list(dict.fromkeys( field for state in states.values() for field in state.get('missing_inputs', []))) if not met and not unresolved: return [] return [{'combination': cond['description_zh'], 'bindings': {'_participants': list(dict.fromkeys( p for name in met for p in witnesses[name]))}, 'condition_status': 'conditions_met' if met else 'incomplete_conditions', 'condition_checks': states, 'missing_inputs': [] if met else unresolved, 'formation_evidence': {'matched_paths': met, 'unresolved_other_paths': unresolved, 'association_profile': 'distinct_D1_same_house_companion', 'source_locator': 'Raman220–221 printed210–212/PDF220–222', 'independent_support_count': int(bool(met)), 'personal_child_count_established': False}}] def _eval_family_geometry_raman(self, cond, ctx, rule, bindings): """281/283 geometry only; the author's outcomes are not personal facts.""" profile = cond['profile'] required = ['Moon'] if profile == 'putrakalatraheena_281' else ['Moon', 'Venus'] self._required_pattern_houses(ctx, required) if profile == 'putrakalatraheena_281': if ctx.house_of('Moon') != 5: return [] waning = ctx.panchanga.get('is_waning_moon') if not isinstance(waning, bool): raise MissingYogaInput('Moon.phase') if not waning: return [] # The remarks explicitly illustrate Sun/Mars/Saturn, not node substitutes. self._required_pattern_houses(ctx, ['Sun', 'Mars', 'Saturn']) if {ctx.house_of(p) for p in ('Sun', 'Mars', 'Saturn')} != {1, 7, 12}: return [] path = 'remarks_classical_three_malefics' participants = ['Moon', 'Sun', 'Mars', 'Saturn'] convention = 'Sun/Mars/Saturn occupy distinct houses1/7/12; named remarks profile, not every interpretation of malefics' elif profile == 'vamsacheda_283': if ctx.house_of('Venus') != 7 or ctx.house_of('Moon') not in (7, 10): return [] benefics = self._natural_benefics_for_named_pattern(ctx) houses = [4] if ctx.house_of('Moon') == 10 else [4, 10] occupants = {h: [p for p in ALL_PLANETS if p not in benefics and ctx.house_of(p) == h] for h in houses} if not all(occupants.values()): return [] path = 'definition' if houses == [4] else 'author_alternative' participants = ['Moon', 'Venus', *(p for ps in occupants.values() for p in ps)] convention = 'At least one natural malefic in each required house; native Moon/Mercury classification' else: raise UnsupportedYogaCondition(['family_geometry_raman.' + str(profile)]) return [{'combination': cond['description_zh'], 'bindings': {'_participants': list(dict.fromkeys(participants))}, 'condition_status': 'conditions_met', 'missing_inputs': [], 'condition_checks': {path: {'status': 'met'}}, 'formation_evidence': {'matched_paths': [path], 'classification_profile': convention, 'independent_support_count': 1}, 'effect_assessment': {'status': 'historical_conduct_reference', 'personal_outcome_established': False, 'summary_zh': '仅核实传统位置组合;不能据此断定无婚姻、无子女、后代性别或家系终止。', 'summary_en': 'Only the traditional geometry is established; it does not establish marriage, fertility, descendants or family extinction.'}}] def _eval_dattaputra_raman(self, cond, ctx, rule, bindings): """Raman222/223: preserve alternative identity and missing inputs.""" l1, l5, l7 = [ctx.lord_of_house(h) for h in (1, 5, 7)] witnesses = {} def rule222(): self._required_pattern_houses(ctx, ['Mars', 'Saturn']) if ctx.house_of('Mars') != 5 or ctx.house_of('Saturn') != 5: return False sign = ctx.sign_of(l1) if sign not in SIGNS: raise MissingYogaInput(l1 + '.sign') if sign not in ('Gemini', 'Virgo'): return False if l1 == 'Mercury': raise MissingYogaInput('Raman222_Mercury_self_association_source_choice') self._required_pattern_houses(ctx, [l1, 'Mercury']) witnesses['raman222'] = ['Mars', 'Saturn', l1, 'Mercury'] return (ctx.house_of(l1) == ctx.house_of('Mercury') or ctx.parashari_aspect('Mercury', l1)) def rule223(): self._required_pattern_houses(ctx, [l7, 'Mars', 'Saturn']) occupants = [p for p in ('Mars', 'Saturn') if ctx.house_of(p) == 5] if ctx.house_of(l7) != 11 or not occupants: return False benefics = self._natural_benefics_for_named_pattern(ctx) companions = [p for p in benefics if p != l5 and ctx.house_of(p) == ctx.house_of(l5)] witnesses['raman223'] = [l7, l5, *occupants, *companions] return bool(companions) branches = {} for name, evaluate in [('raman222', rule222), ('raman223', rule223)]: try: branches[name] = {'status': 'met' if evaluate() else 'not_met'} except MissingYogaInput as exc: branches[name] = {'status': 'incomplete', 'missing_input': str(exc)} met = [name for name, value in branches.items() if value['status'] == 'met'] missing = [v['missing_input'] for v in branches.values() if v['status'] == 'incomplete'] if not met and not missing: return [] return [{'combination': 'Dattaputra:分别核对第222、223条;不据格局认定生育或收养事实', 'bindings': {'_participants': list(dict.fromkeys(p for name in met for p in witnesses[name]))}, 'condition_status': 'conditions_met' if met else 'incomplete_conditions', 'missing_inputs': [] if met else missing, 'condition_checks': branches, 'formation_evidence': {'matched_paths': met, 'unresolved_other_paths': missing, 'path_participants': {name: list(dict.fromkeys(witnesses[name])) for name in met}, 'independent_support_count': 1 if met else 0, 'boundary': 'Named traditional alternatives, not fertility, adoption or child-history facts.'}}] def _eval_dhatrutwa_raman(self, cond, ctx, rule, bindings): """No243 definition and two explicitly named alternatives, not votes.""" l1, l9, l10, l12 = [ctx.lord_of_house(h) for h in (1, 9, 10, 12)] witnesses = {} def definition(): if ctx.sign_of(l9) not in SIGNS: raise MissingYogaInput(l9 + '.sign') if not ctx.is_exalted(l9): return False benefics = self._natural_benefics_for_named_pattern(ctx) aspecting = [p for p in benefics if ctx.parashari_aspect(p, l9)] occupying = [p for p in benefics if ctx.house_of(p) == 9] witnesses['definition'] = [l9, *aspecting, *occupying] return bool(aspecting and occupying) def alternative_a(): self._required_pattern_houses(ctx, [l9]) if ctx.house_of(l9) not in (1, 4, 7, 10): return False if ctx.parashari_aspects_house(l9, 1): witnesses['alternative_a'] = [l9] return True self._required_pattern_houses(ctx, [l1]) witnesses['alternative_a'] = [l9, l1] return ctx.parashari_aspect(l9, l1) def alternative_b(): self._required_pattern_houses(ctx, [l9]) if ctx.house_of(l9) != 4: return False self._required_pattern_houses(ctx, [l10]) if ctx.house_of(l10) not in (1, 4, 7, 10): return False self._required_pattern_houses(ctx, [l12, 'Jupiter']) witnesses['alternative_b'] = [l9, l10, l12, 'Jupiter'] return ctx.parashari_aspect('Jupiter', l12) branches = {} for name, evaluate in [('definition', definition), ('alternative_a', alternative_a), ('alternative_b', alternative_b)]: try: branches[name] = {'status': 'met' if evaluate() else 'not_met'} except MissingYogaInput as exc: branches[name] = {'status': 'incomplete', 'missing_input': str(exc)} met = [name for name, value in branches.items() if value['status'] == 'met'] missing = [v['missing_input'] for v in branches.values() if v['status'] == 'incomplete'] if not met and not missing: return [] return [{'combination': 'Dhatrutwa:按定义及两条具名替代路径分别核对', 'bindings': {'_participants': list(dict.fromkeys(p for name in met for p in witnesses[name]))}, 'condition_status': 'conditions_met' if met else 'incomplete_conditions', 'missing_inputs': [] if met else missing, 'condition_checks': branches, 'formation_evidence': {'matched_paths': met, 'unresolved_other_paths': missing, 'path_participants': {name: list(dict.fromkeys(witnesses[name])) for name in met}, 'independent_support_count': 1 if met else 0, 'boundary': 'Alternative source definitions, not independent votes. No observed generosity, wealth or spiritual authority is established.'}}] def _eval_reviewed_raman_geometry(self, cond, ctx, rule, bindings): """Source-located definitions, with explicit one-based relative houses. Detect geometry only. Source outcomes and later qualifications remain traditional references, never observed life facts. """ profile = cond.get('profile') extra = {} if profile == 'vatharoga_290': participants = ['Jupiter', 'Saturn'] houses = self._required_pattern_houses(ctx, participants) checks = {'jupiter_first': houses['Jupiter'] == 1, 'saturn_seventh': houses['Saturn'] == 7} extra['formation_evidence'] = {'source_definition': 'Raman290', 'unlocated_legacy_mars_moon_branch_used': False} extra['effect_assessment'] = {'status': 'historical_medical_reference', 'personal_outcome_established': False, 'boundary': 'Named source geometry only; no disease risk or diagnosis. The author also notes possible Raja Yoga, not a uniformly adverse overall chart.'} elif profile == 'pittharoga_279': self._required_pattern_houses(ctx, ['Sun']) if ctx.house_of('Sun') != 6: return [] benefics = self._natural_benefics_for_named_pattern(ctx) malefics = [p for p in ALL_PLANETS if p not in benefics and p != 'Sun'] conjoined = [p for p in malefics if ctx.house_of(p) == 6] aspecting = [p for p in malefics if ctx.parashari_aspects_house(p, 6)] pairs = [(a, b) for a in conjoined for b in aspecting if a != b] participants = list(dict.fromkeys(['Sun', *[p for pair in pairs for p in pair]])) checks = {'sun_sixth': True, 'distinct_conjunction_and_aspect_witnesses': bool(pairs)} extra['formation_evidence'] = {'witness_pairs': pairs, 'aspect_profile': 'classical_planetary_aspects_no_node_aspects'} extra['effect_assessment'] = {'status': 'historical_medical_reference', 'personal_outcome_established': False, 'boundary': 'Source geometry includes two distinct malefics; no diagnosis or medical risk is inferred.'} elif profile == 'kushtaroga_268_269': groups = {'raman268': list(dict.fromkeys([ctx.lord_of_house(1), 'Mars', 'Mercury'])), 'raman269': ['Jupiter', 'Saturn', 'Moon']} states = {} for name, planets in groups.items(): try: houses = self._required_pattern_houses(ctx, planets) occupied = set(houses.values()) matched = (len(occupied) == 1 and next(iter(occupied)) in (4, 12) if name == 'raman268' else occupied == {6}) states[name] = {'status': 'met' if matched else 'not_met'} except MissingYogaInput as exc: states[name] = {'status': 'incomplete', 'missing_input': str(exc)} met = [name for name, state in states.items() if state['status'] == 'met'] missing = [v['missing_input'] for v in states.values() if v['status'] == 'incomplete'] if not met and not missing: return [] return [{'combination': cond['description_zh'], 'bindings': {'_participants': list(dict.fromkeys(p for n in met for p in groups[n]))}, 'condition_status': 'conditions_met' if met else 'incomplete_conditions', 'missing_inputs': [] if met else missing, 'condition_checks': states, 'formation_evidence': {'matched_paths': met, 'unresolved_other_paths': missing, 'unvalidated_age_19_22_claim_used': False}, 'effect_assessment': {'status': 'historical_medical_reference', 'personal_outcome_established': False, 'boundary': 'Two historical geometries only; no diagnosis, age prediction or disease causation is established.'}}] elif profile == 'vrana_265': lord = ctx.lord_of_house(6) # Author's explicit five-ascendant list uses Sun/Mars/Saturn, # not a blanket classification of every sixth lord as harmful. if lord not in ('Sun', 'Mars', 'Saturn'): return [] self._required_pattern_houses(ctx, [lord]) participants = [lord] checks = {'malefic_sixth_lord_in_1_8_10': ctx.house_of(lord) in (1, 8, 10)} qualifiers_missing = [] try: benefics = self._natural_benefics_for_named_pattern(ctx) relieving = [p for p in benefics if ctx.parashari_aspect(p, lord)] except MissingYogaInput as exc: relieving = None qualifiers_missing = exc.fields extra['formation_evidence'] = {'literal_definition_geometry': True, 'author_suggested_scorpio_exception': ctx.ascendant == 'Scorpio', 'benefic_aspect_witnesses': relieving, 'benefic_classification': 'waxing_moon_unafflicted_mercury'} extra['effect_assessment'] = {'status': 'historical_medical_reference', 'missing_inputs': qualifiers_missing, 'personal_outcome_established': False, 'boundary': 'Source explicitly cautions against literal outcomes and suggests excluding Scorpio; geometry is not cancer, organ disease or medical risk evidence.'} elif profile == 'matru_satrutwa_207': if ctx.lord_of_house(1) != 'Mercury' or ctx.lord_of_house(4) != 'Mercury': return [] benefics = self._natural_benefics_for_named_pattern(ctx) affecting = [p for p in ALL_PLANETS if p != 'Mercury' and p not in benefics and (ctx.house_of(p) == ctx.house_of('Mercury') or ctx.parashari_aspect(p, 'Mercury'))] participants = ['Mercury', *affecting] checks = {'mercury_rules_first_and_fourth': True, 'distinct_malefic_conjoins_or_aspects': bool(affecting)} extra['formation_evidence'] = {'reference': 'D1 Gemini ascendant only', 'benefic_classification': 'waxing_moon_unafflicted_mercury', 'aspect_profile': 'classical_planetary_aspects_no_node_aspects', 'two_person_navamsa_observation_used_as_rule': False, 'boundary': 'Traditional relationship theme only; no hatred or actual family history is established.'} elif profile == 'khalwata_295': if ctx.ascendant not in ('Aries', 'Leo', 'Scorpio', 'Capricorn', 'Aquarius', 'Sagittarius', 'Taurus'): return [] benefics = self._natural_benefics_for_named_pattern(ctx) participants = [p for p in ALL_PLANETS if p not in benefics and ctx.parashari_aspects_house(p, 1)] checks = {'listed_ascendant': True, 'malefic_aspects_ascendant': bool(participants)} extra['formation_evidence'] = {'benefic_classification': 'waxing_moon_unafflicted_mercury', 'aspect_profile': 'classical_planetary_aspects_no_node_aspects', 'leo_included': True} extra['effect_assessment'] = {'status': 'historical_medical_reference', 'personal_outcome_established': False, 'boundary': 'Raman295 explicitly includes Leo and requires aspect in every branch; author does not establish type or timing of baldness.'} elif profile == 'bharyasahavyabhichara_282': participants = ['Venus', 'Saturn', 'Mars', 'Moon'] houses = self._required_pattern_houses(ctx, participants) checks = {p + '_in_seventh': houses[p] == 7 for p in participants} extra['formation_evidence'] = {'source_definition': 'Raman282', 'author_nonmatching_anecdote_used_as_condition': False} extra['effect_assessment'] = {'status': 'historical_conduct_reference', 'personal_outcome_established': False, 'boundary': 'The author explicitly distinguishes the later anecdote from combination282. Neither geometry nor anecdote establishes personal conduct.'} elif profile == 'rajabhrashta_297_unadjusted': # BUG-2301: her scripts/jaimini.py calc_arudha_sign (upstream 58f37ee5b); this repo's # jaimini.py is sealed and has no such function, so her code is copied below. calc_arudha_sign = _upstream_calc_arudha_sign asc = SIGNS.index(ctx.ascendant) pads = {} for house in (1, 12): lord = ctx.lord_of_house(house) sign = ctx.sign_of(lord) if sign not in SIGNS: raise MissingYogaInput(lord + '.D1_sign') pads[house] = calc_arudha_sign((asc + house - 1) % 12, SIGNS.index(sign)) participants = [SIGN_LORDS[pads[h]['unadjusted_sign']] for h in (1, 12)] if participants[0] == participants[1]: raise MissingYogaInput('distinct_arudha_lord_conjunction_source_rule') houses = self._required_pattern_houses(ctx, participants) checks = {'unadjusted_arudha_lords_conjoined': len(set(houses.values())) == 1} extra['formation_evidence'] = {'arudha_profile': 'raman297_literal_unadjusted_count', 'arudha_lagna': pads[1], 'arudha_twelfth': pads[12], 'pvr_exception_changes_coordinates': any(p['exception_triggered'] for p in pads.values()), 'boundary': 'Uses the literal count in Raman297; adjusted PVR coordinates are retained separately, not silently substituted. Same-lord self-conjunction is unresolved.'} elif profile == 'angaheena_285': participants = ['Sun', 'Moon', 'Mars', 'Saturn'] houses = self._required_pattern_houses(ctx, participants) checks = {p + '_from_sun': (houses[p] - houses['Sun']) % 12 + 1 == h for p, h in [('Moon', 10), ('Mars', 7), ('Saturn', 2)]} extra['effect_assessment'] = {'status': 'historical_medical_reference', 'personal_outcome_established': False, 'boundary': 'Historical named geometry only; not a diagnosis, disability forecast or injury timing rule.'} elif profile == 'swetakushta_286': participants = ['Mars', 'Saturn', 'Moon', 'Sun'] houses = self._required_pattern_houses(ctx, participants) checks = {p + '_house': houses[p] == h for p, h in [('Mars', 2), ('Saturn', 12), ('Moon', 1), ('Sun', 7)]} jupiter = ctx.house_of('Jupiter') if jupiter is not None: self._required_pattern_houses(ctx, ['Jupiter']) extra['formation_evidence'] = {'jupiter_aspects_mars_or_saturn': None if jupiter is None else any(ctx.parashari_aspect('Jupiter', p) for p in ('Mars', 'Saturn'))} extra['effect_assessment'] = {'status': 'historical_medical_reference', 'missing_inputs': ['Jupiter.house'] if jupiter is None else [], 'personal_outcome_established': False, 'boundary': 'Author separately qualifies the outcome and mentions Jupiter; not a medical risk estimate or treatment prediction.'} elif profile == 'labha_malika_42': participants = ['Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn'] houses = self._required_pattern_houses(ctx, participants) checks = {'seven_classical_planets_in_seven_consecutive_houses_from_11': set(houses.values()) == {11, 12, 1, 2, 3, 4, 5}} elif profile == 'garuda_66': day = ctx.context.get('birth_is_daytime') waning = ctx.panchanga.get('is_waning_moon') if day is False or waning is True: return [] if type(day) is not bool or type(waning) is not bool: raise MissingYogaInput('birth_is_daytime and Moon.phase') dispositor = ctx.navamsa_dispositor('Moon') if not dispositor: raise MissingYogaInput('Moon.D9_sign') if ctx.sign_of(dispositor) is None: raise MissingYogaInput(dispositor + '.D1_sign') participants = list(dict.fromkeys(['Moon', dispositor])) checks = {'daytime_waxing_moon': True, 'moon_navamsa_dispositor_exalted_in_d1': ctx.is_exalted(dispositor)} elif profile == 'chandika_57': if ctx.ascendant not in ('Taurus', 'Leo', 'Scorpio', 'Aquarius'): return [] sixth, ninth = ctx.lord_of_house(6), ctx.lord_of_house(9) self._required_pattern_houses(ctx, [sixth]) if not ctx.parashari_aspects_house(sixth, 1): return [] dispos = [ctx.navamsa_dispositor(p) for p in (sixth, ninth)] if not all(dispos): raise MissingYogaInput('sixth_and_ninth_lords.D9_sign') participants = list(dict.fromkeys(['Sun', sixth, ninth] + dispos)) houses = self._required_pattern_houses(ctx, ['Sun'] + dispos) checks = {'fixed_lagna_receives_sixth_lord_aspect': True, 'both_d9_dispositors_join_sun_in_d1': all(h == houses['Sun'] for h in houses.values())} elif profile == 'ayatnadhanalabha_143': first, second = ctx.lord_of_house(1), ctx.lord_of_house(2) participants = list(dict.fromkeys([first, second])) houses = self._required_pattern_houses(ctx, participants) checks = {'first_lord_in_second': houses[first] == 2, 'second_lord_in_first': houses[second] == 1, 'distinct_lords': first != second} elif profile == 'jara_236': participants = list(dict.fromkeys(ctx.lord_of_house(h) for h in (10, 2, 7))) houses = self._required_pattern_houses(ctx, participants) checks = {'all_three_lord_roles_in_tenth': all(h == 10 for h in houses.values())} elif profile == 'mooka_163': participants = list(dict.fromkeys([ctx.lord_of_house(2), 'Jupiter'])) houses = self._required_pattern_houses(ctx, participants) if any(h != 8 for h in houses.values()): return [] if ctx.sign_of('Jupiter') is None: raise MissingYogaInput('Jupiter.sign') checks = {'second_lord_and_jupiter_in_eighth': True, 'own_or_exalted_jupiter_exception_absent': not (ctx.is_own_sign('Jupiter') or ctx.is_exalted('Jupiter'))} elif profile == 'duryoga_103': participants = [ctx.lord_of_house(10)] houses = self._required_pattern_houses(ctx, participants) checks = {'tenth_lord_in_6_8_12': houses[participants[0]] in (6, 8, 12)} elif profile == 'sarpaganda_174': participants = ['Rahu'] houses = self._required_pattern_houses(ctx, participants) if houses['Rahu'] != 2: return [] mandi = ctx.upagraha_house('maandi') if type(mandi) is not int or not 1 <= mandi <= 12: raise MissingYogaInput('upagraha.maandi.house') checks = {'rahu_second': True, 'maandi_second': mandi == 2} elif profile == 'ekabhagini_179': lord = ctx.lord_of_house(3) participants = list(dict.fromkeys(['Mercury', lord, 'Moon', 'Mars', 'Saturn'])) houses = self._required_pattern_houses(ctx, participants) checks = {'mercury_third': houses['Mercury'] == 3, 'third_lord_with_moon': houses[lord] == houses['Moon'], 'mars_with_saturn': houses['Mars'] == houses['Saturn']} elif profile == 'vichitra_188': # Raman explicitly allows role overlap (e.g. L4 is Mars/Saturn). participants = list(dict.fromkeys([ctx.lord_of_house(4), ctx.lord_of_house(10), 'Saturn', 'Mars'])) houses = self._required_pattern_houses(ctx, participants) checks = {'all_required_roles_conjoined': len(set(houses.values())) == 1} elif profile == 'marud_160': participants = ['Jupiter', 'Venus', 'Moon', 'Sun'] houses = self._required_pattern_houses(ctx, participants) relative = lambda target, origin: (houses[target] - houses[origin]) % 12 + 1 checks = {'jupiter_5_or_9_from_venus': relative('Jupiter', 'Venus') in (5, 9), 'moon_5_from_jupiter': relative('Moon', 'Jupiter') == 5, 'sun_angular_from_moon': relative('Sun', 'Moon') in (1, 4, 7, 10)} else: raise UnsupportedYogaCondition(['reviewed_raman_geometry.' + str(profile)]) if not all(checks.values()): return [] return [{'combination': cond['description_zh'], 'bindings': {'_participants': participants}, 'condition_status': 'conditions_met', 'missing_inputs': [], 'condition_checks': {'profile': profile, **checks}, **extra}] def _eval_mridanga_navamsa_chain(self, cond, ctx, rule, bindings): """Raman's dispositor chain, without replacing 'powerful' by a house proxy. The existing strength layer does not establish comprehensive Lagna-lord strength. Keep that requirement explicitly open, including when exalted. """ matches = [] lagna_lord = ctx.lord_of_house(1) for planet in EXALTATION: if not ctx.is_exalted(planet): continue missing = ['Lagna_lord_comprehensive_strength'] sign = ctx.d9_sign_of(planet) dispositor = SIGN_LORDS.get(sign) if not dispositor: missing.append(f'{planet}.D9.sign') elif ctx.sign_of(dispositor) not in SIGNS or ctx.house_of(dispositor) is None: missing.append(f'{dispositor}.D1.position') else: dignity_ok = (ctx.is_exalted(dispositor) or ctx.is_own_sign(dispositor) or SIGN_LORDS[ctx.sign_of(dispositor)] in FRIENDLY_PLANETS[dispositor]) if ctx.house_of(dispositor) not in (1, 4, 7, 10) or not dignity_ok: continue participants = [p for p in (planet, dispositor, lagna_lord) if p in ctx.planets] matches.append({ 'combination': f'{planet} exalted; D9 {sign or "unknown"}; dispositor {dispositor or "unknown"}; Lagna lord {lagna_lord}', 'condition_status': 'incomplete_conditions', 'missing_inputs': missing, 'condition_checks': {'exalted_planet': planet, 'navamsa_sign': sign, 'navamsa_dispositor': dispositor, 'lagna_lord_strength': None}, 'formation_evidence': {'exalted_planet': planet, 'navamsa_sign': sign, 'navamsa_dispositor': dispositor, 'dispositor_d1_house': ctx.house_of(dispositor), 'dispositor_d1_sign': ctx.sign_of(dispositor), 'lagna_lord': lagna_lord}, 'bindings': {'planets': participants}, }) return matches @staticmethod def _eval_neecha_bhanga(cond, ctx, rule, bindings): """Light on Life p.295: four cancellation tests, then a separate Raja gate. Exchange is retained as an explicitly separate traditional variant. A missing position never supplies a positive witness. """ results = [] for planet, deb_sign in DEBILITATION.items(): if ctx.sign_of(planet) != deb_sign: continue dispositor = SIGN_LORDS[deb_sign] exaltation_lord = SIGN_LORDS[EXALTATION[planet]] exalted_here = next((p for p, sign in EXALTATION.items() if sign == deb_sign), None) reasons = [] if cond.get('variant') == 'exchange': if dispositor != planet and SIGN_LORDS.get(ctx.sign_of(dispositor)) == planet: reasons.append({'condition': 'dispositor_exchange', 'planet': dispositor}) else: for label, other in (('dispositor', dispositor), ('exaltation_sign_lord', exaltation_lord), ('planet_exalted_in_debility_sign', exalted_here)): if other not in ctx.planets: continue if ctx.house_of(other) in (1, 4, 7, 10): reasons.append({'condition': label + '_kendra_from_lagna', 'planet': other}) moon_sign, other_sign = ctx.sign_of('Moon'), ctx.sign_of(other) if moon_sign in SIGNS and other_sign in SIGNS: relative = (SIGNS.index(other_sign) - SIGNS.index(moon_sign)) % 12 + 1 if relative in (1, 4, 7, 10): witness = {'condition': label + '_kendra_from_moon', 'planet': other, 'reference': 'Moon', 'relative_house': relative, 'self_reference': other == 'Moon'} if other == 'Moon': # Preserve the literal source branch, but it cannot # corroborate itself or add an independent vote. witness['independent_confirmation_allowed'] = False reasons.append(witness) other_sign = ctx.sign_of(dispositor) if other_sign in SIGNS: distance = (SIGNS.index(deb_sign) - SIGNS.index(other_sign)) % 12 + 1 aspects = {'Mars': (4, 7, 8), 'Jupiter': (5, 7, 9), 'Saturn': (3, 7, 10)} if distance in aspects.get(dispositor, (7,)): reasons.append({'condition': 'dispositor_aspect', 'planet': dispositor}) royal = bool(reasons) and ctx.house_of(planet) in (1, 4, 5, 7, 9, 10) if not reasons or (cond.get('require_royal_placement') and not royal): continue participants = list(dict.fromkeys([planet] + [r['planet'] for r in reasons])) detail = '; '.join(f'{p}: {ctx.sign_of(p)}, H{ctx.house_of(p) or "?"}' for p in participants) results.append({ 'combination': f'{planet} debilitated in {deb_sign}; ' + '; '.join(r['condition'] + '=' + r['planet'] for r in reasons) + '; ' + detail, 'strength': 'conditional', 'bindings': {'planets': participants}, 'formation_evidence': { 'planet': planet, 'cancellation_reasons': reasons, 'self_reference_only': all(r.get('self_reference', False) for r in reasons), 'royal_yoga_candidate': royal, 'profile': 'exchange_variant' if cond.get('variant') == 'exchange' else 'light_on_life_p295', 'claim_boundary': 'Cancellation is not exaltation; a Raja candidate is not a guaranteed result.', }, }) return results def _eval_lagna_lord_chain_dispositor_in_kendra_trine_or_exaltation(self, cond, ctx, rule, bindings): """Raman combination47, pp70–71: alternatives, not PVR's all-four test. BUG-2222 (upstream b6754475): Parijatha. The ascendant lord's dispositor has a D1 or D9 dispositor in a kendra, trine, own or exaltation sign; an unassessable branch is never read as failed. """ first = ctx.lord_of_house(1) if not first or not ctx.sign_of(first): raise MissingYogaInput('ascendant_lord.D1_sign') second = SIGN_LORDS.get(ctx.sign_of(first)) candidates = [('rasi', SIGN_LORDS.get(ctx.sign_of(second))), ('navamsa', ctx.navamsa_dispositor(second))] passed, missing = [], [] for branch, planet in candidates: if not planet: missing.append(second + ('.D1_sign' if branch == 'rasi' else '.D9_sign')) continue if ctx.house_of(planet) is None or ctx.sign_of(planet) is None: missing.append(planet + '.D1_position') continue if (ctx.is_kendra(ctx.house_of(planet)) or ctx.is_trikona(ctx.house_of(planet)) or ctx.is_own_sign(planet) or ctx.is_exalted(planet)): passed.append((branch, planet)) if not passed and not missing: return [] # BUG-2222 follow-up: the report's Chinese cell reads `combination`; the English twin rides along. return [{'combination': '上升主星的定位星链末端(本命盘或九分盘)在角宫、三方宫,或入庙、入旺', 'combination_en': 'Raman Parijatha: qualifying final D1 or D9 dispositor branch', 'strength': rule.get('strength', '中'), 'bindings': {'planets': [first, second] + [p for _, p in passed]}, 'condition_status': 'conditions_met' if passed else 'incomplete_conditions', 'missing_inputs': [] if passed else list(dict.fromkeys(missing)), 'condition_checks': {'ascendant_lord': first, 'first_dispositor': second, 'qualifying_branches': passed, 'unassessed_alternatives': missing}}] def _eval_gaja_raman_48(self, cond, ctx, rule, bindings): """Raman pp71–72: ninth FROM eleventh is natal seventh, not ninth. BUG-2222 (upstream b6754475): one definition replaces the two old branches (the second read the ninth from Lagna). """ seventh, eleventh = ctx.lord_of_house(7), ctx.lord_of_house(11) for planet in (seventh, 'Moon'): if planet and ctx.house_of(planet) is not None and ctx.house_of(planet) != 11: return [] for planet in (seventh, eleventh, 'Moon'): if not planet or ctx.house_of(planet) is None: raise MissingYogaInput((planet or 'required_house_lord') + '.house') if not ctx.parashari_aspect(eleventh, seventh): return [] # Source Chart35 explicitly allows Moon to be the seventh lord; # do not manufacture a second physical Moon as a conjunction witness. return [{'combination': '7宫主与月亮在第11宫,受11宫主相照', 'combination_en': 'Seventh lord and Moon in house 11, aspected by the eleventh lord', 'strength': rule.get('strength', '中'), 'bindings': {'planets': list(dict.fromkeys((seventh, 'Moon', eleventh)))}, 'condition_status': 'conditions_met', 'missing_inputs': [], 'condition_checks': {'seventh_lord': seventh, 'eleventh_lord': eleventh, 'moon_is_seventh_lord': seventh == 'Moon', 'aspect_profile': 'parashari_graha_drishthi'}}] def _eval_saraswathi_pvr(self, cond, ctx, rule, bindings): """PVR p143: all three placements, plus Jupiter's sign dignity (BUG-2222, upstream b6754475).""" allowed = {1, 2, 4, 5, 7, 9, 10} bodies = ('Mercury', 'Jupiter', 'Venus') houses = {p: ctx.house_of(p) for p in bodies} if any(h is not None and h not in allowed for h in houses.values()): return [] sign = ctx.sign_of('Jupiter') if sign and not (ctx.is_own_sign('Jupiter') or ctx.is_exalted('Jupiter') or SIGN_LORDS.get(sign) in FRIENDLY_PLANETS['Jupiter']): return [] missing = [p + '.house' for p, h in houses.items() if h is None] if not sign: missing.append('Jupiter.sign') return [{'combination': '水星、木星、金星都在角宫、三方宫或第2宫;木星入庙、入旺或在自然友星的星座', 'combination_en': 'Mercury, Jupiter and Venus each in kendra/trikona/house 2; Jupiter in own, natural-friend or exaltation sign', 'strength': rule.get('strength', '中'), 'bindings': {'_participants': list(bodies)}, 'condition_status': 'incomplete_conditions' if missing else 'conditions_met', 'missing_inputs': missing, 'condition_checks': {**houses, 'Jupiter_sign': sign}}] def _eval_parihasaka(self, cond, ctx, rule, bindings): """Raman no.156; do not substitute the heuristic three-chart score (upstream e628118d).""" sun_d9 = ctx.d9_sign_of('Sun') lord = SIGN_LORDS.get(sun_d9) if lord and ctx.house_of(lord) not in (None, 2): return [] # Explicit executed distinction is required, not an estimated score. distinction = (ctx.context.get('vaiseshikamsa_confirmed') or {}).get(lord) if distinction is False: return [] missing = [] if not lord: missing.append('Sun_D9_sign') elif ctx.house_of(lord) is None: missing.append('Sun_D9_dispositor_D1_house') if type(distinction) is not bool: missing.append('vaiseshikamsa_distinction') return [{'combination': BiText('太阳Navamsa定位星在本命第2宫;需Vaiseshikamsa确认', 'Sun Navamsa dispositor in natal house 2; Vaiseshikamsa required'), 'condition_status': 'incomplete_conditions' if missing else 'conditions_met', 'missing_inputs': missing, 'condition_checks': {'sun_d9_dispositor': lord, 'vaiseshikamsa': distinction}, **({'participants': [lord]} if lord else {})}] def _eval_mahabhagya(self, cond, ctx, rule, bindings): """Raman, Three Hundred Important Combinations, no. 25 (upstream e628118d). Missing inputs preserve a labelled candidate only; a known failed condition cannot be rescued by a different missing condition. """ signs = [ctx.ascendant, ctx.sign_of('Sun'), ctx.sign_of('Moon')] if any(sign not in SIGNS for sign in signs): return [] parities = {SIGNS.index(sign) % 2 for sign in signs} if len(parities) != 1: return [] odd = parities == {0} required_gender, required_day = ('male', True) if odd else ('female', False) raw_gender = str(ctx.context.get('gender') or '').strip().lower() gender = {'m': 'male', 'male': 'male', '男': 'male', 'f': 'female', 'female': 'female', '女': 'female'}.get(raw_gender) day = ctx.context.get('birth_is_daytime') if type(day) is not bool: day = None if gender is not None and gender != required_gender: return [] if day is not None and day != required_day: return [] missing = (['gender'] if gender is None else []) + (['birth_is_daytime'] if day is None else []) combo = (BiText('上升/太阳/月亮均在奇数星座;男性昼生一支', 'Ascendant/Sun/Moon in odd signs; male daytime branch') if odd else BiText('上升/太阳/月亮均在偶数星座;女性夜生一支', 'Ascendant/Sun/Moon in even signs; female nighttime branch')) return [{ 'combination': combo, 'condition_status': 'incomplete_conditions' if missing else 'conditions_met', 'missing_inputs': missing, 'condition_checks': {'sign_parity': 'odd' if odd else 'even', 'gender': gender, 'birth_is_daytime': day}, 'participants': ['Sun', 'Moon'], }] def _eval_condition(self, cond: Dict, ctx: YogaContext, rule: Dict, bindings: Dict) -> List[Dict]: """Record actual node evaluations, including unsuccessful OR branches. BUG-2075 (upstream 19cfd9c0). An execution receipt, not independent source validation: a node that was never reached has no entry. BUG-2124 / BUG-2170: a custom node's own entry carries `custom_branch_trace`, the branch record from the original evaluation (原执行分支记录: which operands of its expression ran and what they returned, see `_custom_branch_trace`); a custom node is a leaf, so the slot set by `_eval_custom` belongs to this very call. """ is_custom = (cond.get('type') or cond.get('op')) == 'custom' if is_custom: ctx.custom_branch_trace_slot = None matches = self._dispatch_condition(cond, ctx, rule, bindings) trace = getattr(ctx, 'condition_execution_trace', None) if trace is not None: entry = {'condition_type': cond.get('type') or cond.get('op'), 'definition': cond, 'input_bindings': dict(bindings), 'matched': bool(matches), 'match_count': len(matches)} if is_custom and getattr(ctx, 'custom_branch_trace_slot', None) is not None: entry['custom_branch_trace'] = ctx.custom_branch_trace_slot trace.append(entry) if is_custom: ctx.custom_branch_trace_slot = None return matches def _dispatch_condition(self, cond: Dict, ctx: YogaContext, rule: Dict, bindings: Dict) -> List[Dict]: """评估条件节点,返回匹配列表""" # v6.0.31: 兼容历史规则中的 "op" 字段。 # 早期批量扩展脚本误用 op 而不是 type;如果只读 type,会导致这些规则静默失效。 ctype = cond.get("type") or cond.get("op") # v6.0.32: 兼容批量生成规则使用的 compound_conditions/compound 结构。 if ctype == "compound_conditions": cond = {**cond, "type": "and"} return self._eval_and(cond, ctx, rule, bindings) if ctype == "compound": operator = str(cond.get("operator", "AND")).lower() cond = {**cond, "type": "or" if operator == "or" else "and"} return self._eval_condition(cond, ctx, rule, bindings) handler = getattr(self, f"_eval_{ctype}", None) if handler: return handler(cond, ctx, rule, bindings) # v6.0.32: 兼容 PyJHora/BVR 批量规则中的语义型 condition type, # 避免未知类型静默导致整条 compound rule 永远失效。 if ctype: return self._eval_semantic_condition(ctype, cond, ctx, rule, bindings) raise YogaRuleEvaluationError("MissingConditionType", "condition node has no type") # ------------------------------------------------------------------------ # 复合条件 # ------------------------------------------------------------------------ def _eval_and(self, cond, ctx, rule, bindings): """AND: 所有子条件必须同时满足""" subs = cond.get("conditions", []) if not subs: return [{"combination": "", "strength": rule.get("strength", "中")}] results = self._eval_condition(subs[0], ctx, rule, bindings) if not results: return [] for sub in subs[1:]: new_results = [] for match in results: b = {**bindings, **match.get("bindings", {})} sub_matches = self._eval_condition(sub, ctx, rule, b) for sm in sub_matches: combo = match.get("combination", "") sm_combo = sm.get("combination", "") merged_combo = _bijoin("; ", [combo, sm_combo]) merged = { "combination": merged_combo, "strength": sm.get("strength", match.get("strength")), # Upstream e628118d: keep both sides' bindings, so a # later condition binding the same key does not drop # the earlier participants. "bindings": {**match.get("bindings", {}), **sm.get("bindings", {}), "_participants": [match.get("bindings", {}), sm.get("bindings", {})]}, **({"participants": list(match.get("participants") or []) + list(sm.get("participants") or [])} if match.get("participants") or sm.get("participants") else {}), **({"triggers": (match.get("triggers") or []) + (sm.get("triggers") or []), "triggers_zh": (match.get("triggers_zh") or []) + (sm.get("triggers_zh") or [])} if match.get("triggers") or sm.get("triggers") else {}), } # BUG-2222 (upstream b6754475): an incomplete side keeps the # AND result incomplete; conflicting checks are not merged. if 'condition_status' in match or 'condition_status' in sm: statuses = {x.get('condition_status', 'conditions_met') for x in (match, sm)} missing = list(dict.fromkeys(match.get('missing_inputs', []) + sm.get('missing_inputs', []))) checks = dict(match.get('condition_checks', {})) for key, value in sm.get('condition_checks', {}).items(): if key in checks and checks[key] != value: missing.append('conflicting_condition_check:' + key) else: checks[key] = value merged.update( condition_status='incomplete_conditions' if missing or statuses != {'conditions_met'} else 'conditions_met', missing_inputs=missing, condition_checks=checks) new_results.append(merged) results = new_results if not results: return [] return results def _eval_or(self, cond, ctx, rule, bindings): """OR: 任一子条件满足即可""" all_results = [] for sub in cond.get("conditions", []): matches = self._eval_condition(sub, ctx, rule, bindings) all_results.extend(matches) return all_results def _eval_not(self, cond, ctx, rule, bindings): """Negate a known result without turning missing evidence into truth. BUG-2222 (upstream b6754475): matches are alternatives, so one fully established match disproves NOT; an incomplete candidate alone establishes neither polarity. """ matches = self._eval_condition(cond.get("condition", {}), ctx, rule, bindings) if not matches: return [{"combination": "", "strength": rule.get("strength", "中")}] if any(m.get('condition_status', 'conditions_met') == 'conditions_met' and not m.get('missing_inputs') for m in matches): return [] return [{**m, 'combination': '', 'condition_status': 'incomplete_conditions'} for m in matches] # ------------------------------------------------------------------------ # 单条件类型 # ------------------------------------------------------------------------ def _eval_same_house(self, cond, ctx, rule, bindings): """两颗行星同宫""" # 支持两种写法: # 1) {"a": ..., "b": ...} # 2) {"planets": ["Sun", "Mercury", ...]}:任意两颗同宫即满足 if "planets" in cond and "a" not in cond and "b" not in cond: planets = cond.get("planets", []) pa = self._resolve_binding({"role": "set", "planets": planets}, ctx, bindings) pb = pa else: pa = self._resolve_binding(cond.get("a"), ctx, bindings) pb = self._resolve_binding(cond.get("b"), ctx, bindings) results = [] for a in pa: for b in pb: if a == b: continue h1 = ctx.house_of(a) h2 = ctx.house_of(b) if h1 is not None and h1 == h2: combo = _combo(cond, "{a}与{b}同在第{h}宫", a=_planet(a), b=_planet(b), h=h1, a_raw=a, b_raw=b) results.append({"combination": combo, "strength": rule.get("strength", "中"), "bindings": {"a": a, "b": b, "house": h1}}) return results def _eval_in_houses(self, cond, ctx, rule, bindings): """行星在指定宫位列表中""" refs = self._resolve_binding(cond.get("planet", "$planet"), ctx, bindings) houses = cond.get("houses", []) exclude = cond.get("exclude", []) results = [] for p in refs: if p in exclude: continue h = ctx.house_of(p) if h is not None and h in houses: combo = _combo(cond, "{p}在第{h}宫", p=_planet(p), h=h, p_raw=p) results.append({"combination": combo, "strength": rule.get("strength", "中"), "bindings": {"planet": p, "house": h}}) return results def _eval_not_in_houses(self, cond, ctx, rule, bindings): """行星不在指定宫位列表中""" refs = self._resolve_binding(cond.get("planet"), ctx, bindings) houses = cond.get("houses", []) results = [] for p in refs: h = ctx.house_of(p) if h is not None and h not in houses: results.append({"combination": "", "strength": rule.get("strength", "中"), "bindings": {"planet": p, "house": h}}) return results def _eval_in_houses_from(self, cond, ctx, rule, bindings): """行星在指定行星/基准的相对宫位关系中""" refs = self._resolve_binding(cond.get("planet"), ctx, bindings) from_ref = cond.get("from") relations = cond.get("relations", []) results = [] # 解析 relations(支持字符串别名和整数偏移) valid_offsets = set() for r in relations: if r == "kendra": valid_offsets.update([0, 3, 6, 9]) elif r == "trikona": valid_offsets.update([0, 4, 8]) elif r == "2nd_12th": valid_offsets.update([1, 11]) elif r == "3rd_11th": valid_offsets.update([2, 10]) elif r == "same": valid_offsets.add(0) elif isinstance(r, int): valid_offsets.add(r) for p in refs: h1 = ctx.house_of(p) if h1 is None: continue # from 可以是行星或固定宫位 if isinstance(from_ref, int): h_base = from_ref else: from_planets = self._resolve_binding(from_ref, ctx, bindings) for fp in from_planets: h_base = ctx.house_of(fp) if h_base is None: continue off = ctx.house_offset(h_base, h1) if off in valid_offsets: rel_name = BiText(self._offset_name(off), OFFSET_NAME_EN.get(off, f"{off + 1}th")) combo = _combo(cond, "{p}在第{h}宫(从{fp}的{rel})", p=_planet(p), h=h1, fp=_planet(fp), rel=rel_name, off=off, p_raw=p, fp_raw=fp) results.append({"combination": combo, "strength": rule.get("strength", "中"), "bindings": {"planet": p, "from": fp, "house": h1}}) return results def _eval_dignity(self, cond, ctx, rule, bindings): """行星尊严检查""" refs = self._resolve_binding(cond.get("planet"), ctx, bindings) dignity_type = cond.get("dignity") # exalted, own, moolatrikona, debilitated results = [] for p in refs: ok = False if dignity_type == "exalted": ok = ctx.is_exalted(p) elif dignity_type == "own": ok = ctx.is_own_sign(p) elif dignity_type == "moolatrikona": ok = ctx.is_moolatrikona(p) elif dignity_type == "debilitated": ok = ctx.is_debilitated(p) elif dignity_type == "strong": ok = ctx.is_exalted(p) or ctx.is_own_sign(p) or ctx.is_moolatrikona(p) elif dignity_type == "not_debilitated": ok = not ctx.is_debilitated(p) elif dignity_type == "not_enemy": ok = True # placeholder, not used in current rules # v6.0.31: 兼容历史规则中的 status 字段。 # 批量规则曾使用 {"op":"dignity", "status":"exalted"},而引擎原本只读取 dignity。 if dignity_type is None: status = cond.get("status") if status == "exalted": ok = ctx.is_exalted(p) dignity_type = status elif status == "own": ok = ctx.is_own_sign(p) dignity_type = status elif status == "moolatrikona": ok = ctx.is_moolatrikona(p) dignity_type = status elif status == "debilitated": ok = ctx.is_debilitated(p) dignity_type = status elif status == "strong": ok = ctx.is_exalted(p) or ctx.is_own_sign(p) or ctx.is_moolatrikona(p) dignity_type = status if ok: sign = ctx.sign_of(p) combo = _combo(cond, "{p}{dignity}在{sign}", p=_planet(p), dignity=dignity_type, sign=sign or "", p_raw=p) results.append({"combination": combo, "strength": rule.get("strength", "中"), "bindings": {"planet": p, "sign": sign}}) return results def _eval_count(self, cond, ctx, rule, bindings): """统计满足条件的行星数量""" refs = self._resolve_binding(cond.get("items", cond.get("planets")), ctx, bindings) sub_cond = cond.get("condition", {}) min_count = cond.get("min", 1) max_count = cond.get("max") matched = [] for p in refs: # 临时把 planet 绑定为 p,评估子条件 sub_bindings = {**bindings, "planet": p} matches = self._eval_condition(sub_cond, ctx, rule, sub_bindings) if matches: matched.append(p) count = len(matched) ok = count >= min_count if max_count is not None: ok = ok and count <= max_count if ok: combo = _combo(cond, "{count}颗行星满足条件", count=count, planets=_planets(matched)) return [{"combination": combo, "strength": rule.get("strength", "中"), "bindings": {"count": count, "matched": matched}}] return [] def _eval_houses_occupied(self, cond, ctx, rule, bindings): """行星占据的宫位数量""" refs = self._resolve_binding(cond.get("planets", "all"), ctx, bindings) occupied = set() for p in refs: h = ctx.house_of(p) if h is not None: occupied.add(h) count = len(occupied) target = cond.get("count") min_count = cond.get("min") max_count = cond.get("max") ok = False if target is not None: ok = count == target else: ok = True if min_count is not None: ok = ok and count >= min_count if max_count is not None: ok = ok and count <= max_count if ok: combo = _combo(cond, "行星分布在{count}个宫位", count=count) return [{"combination": combo, "strength": rule.get("strength", "中"), "participants": list(refs)}] return [] def _eval_adjacent_houses(self, cond, ctx, rule, bindings): """目标宫位的前/后宫位有指定行星""" target = cond.get("house") sides = cond.get("sides", ["prev", "next"]) refs = self._resolve_binding(cond.get("planets"), ctx, bindings) require_both = cond.get("both", False) prev_h = ((target - 2) % 12) + 1 next_h = (target % 12) + 1 prev_ok = any(ctx.house_of(p) == prev_h for p in refs) if "prev" in sides else True next_ok = any(ctx.house_of(p) == next_h for p in refs) if "next" in sides else True if require_both: ok = prev_ok and next_ok else: ok = prev_ok or next_ok if ok: combo = _combo(cond, "第{target}宫被夹击", target=target, prev=prev_h, next=next_h) flanking = [p for p in refs if ctx.house_of(p) in (prev_h, next_h)] return [{"combination": combo, "strength": rule.get("strength", "中"), "participants": flanking}] return [] def _eval_all_in_houses(self, cond, ctx, rule, bindings): """所有指定行星都在给定宫位集合中。""" refs = self._resolve_binding(cond.get("planets", "visible"), ctx, bindings) houses = set(cond.get("houses", [])) if not refs or not houses: return [] occupied = [ctx.house_of(p) for p in refs] ok = all(h is not None and h in houses for h in occupied) # upstream e628118d: an unplaced planet fails if ok: combo = _combo(cond, "所有指定行星均落入{houses}", houses="/".join(str(h) for h in sorted(houses)), planets=_planets(refs)) return [{"combination": combo, "strength": rule.get("strength", "中"), "bindings": {"planets": refs, "houses": sorted(houses)}}] return [] def _eval_all_planets_in_sign_type(self, cond, ctx, rule, bindings): """Explicit complete planet set; absence is not a satisfied universal. BUG-2222 (upstream b6754475): Rajju / Musala / Nala sign modality. """ groups = {'movable': MOVABLE_SIGNS, 'fixed': FIXED_SIGNS, 'dual': DUAL_SIGNS} kind = cond.get('sign_type') refs = cond.get('planets') if kind not in groups or not isinstance(refs, list) or not refs: raise UnsupportedYogaCondition(['all_planets_in_sign_type.invalid_definition']) if len(set(refs)) != len(refs) or any(p not in ALL_PLANETS for p in refs): raise UnsupportedYogaCondition(['all_planets_in_sign_type.invalid_planets']) for planet in refs: if ctx.sign_of(planet) not in SIGNS: raise MissingYogaInput(f'{planet}.sign') if not all(ctx.sign_of(p) in groups[kind] for p in refs): return [] return [{'combination': f'All specified planets occupy {kind} signs', 'strength': rule.get('strength', 'conditional'), 'bindings': {'planets': refs}, 'formation_evidence': {'sign_type': kind, 'positions': {p: ctx.sign_of(p) for p in refs}}}] def _eval_all_in_house_sets(self, cond, ctx, rule, bindings): """所有指定行星都在多个候选宫位集合之一中。""" refs = self._resolve_binding(cond.get("planets", "visible"), ctx, bindings) house_sets = cond.get("house_sets", []) if not refs or not house_sets: return [] for houses in house_sets: houses_set = set(houses) occupied = [ctx.house_of(p) for p in refs] ok = all(h is not None and h in houses_set for h in occupied) # upstream e628118d if ok: combo = _combo(cond, "所有指定行星均落入候选宫位集合{houses}", houses="/".join(str(h) for h in sorted(houses_set)), planets=_planets(refs)) return [{"combination": combo, "strength": rule.get("strength", "中"), "bindings": {"planets": refs, "houses": sorted(houses_set)}}] return [] def _eval_occupied_houses_exact(self, cond, ctx, rule, bindings): """指定行星实际占据的宫位集合与目标集合完全一致。""" refs = self._resolve_binding(cond.get("planets", "visible"), ctx, bindings) houses = set(cond.get("houses", [])) occupied = {ctx.house_of(p) for p in refs if ctx.house_of(p) is not None} if refs and occupied == houses: combo = _combo(cond, "指定行星只占据{houses}", houses="/".join(str(h) for h in sorted(houses)), planets=_planets(refs)) return [{"combination": combo, "strength": rule.get("strength", "中"), "bindings": {"planets": refs, "houses": sorted(houses)}}] return [] def _eval_occupied_houses_exact_sets(self, cond, ctx, rule, bindings): """指定行星实际占据的宫位集合等于候选集合之一。""" refs = self._resolve_binding(cond.get("planets", "visible"), ctx, bindings) house_sets = cond.get("house_sets", []) occupied = {ctx.house_of(p) for p in refs if ctx.house_of(p) is not None} for houses in house_sets: houses_set = set(houses) if refs and occupied == houses_set: combo = _combo(cond, "指定行星只占据候选宫位集合{houses}", houses="/".join(str(h) for h in sorted(houses_set)), planets=_planets(refs)) return [{"combination": combo, "strength": rule.get("strength", "中"), "bindings": {"planets": refs, "houses": sorted(houses_set)}}] return [] def _eval_has_planet_in_house(self, cond, ctx, rule, bindings): """指定行星集合中至少一颗在某宫。""" refs = self._resolve_binding(cond.get("planets", "all"), ctx, bindings) house = cond.get("house") matched = [p for p in refs if ctx.house_of(p) == house] if matched: combo = _combo(cond, "第{house}宫有{planets}", house=house, planets=_planets(matched)) return [{"combination": combo, "strength": rule.get("strength", "中"), "bindings": {"matched": matched, "house": house}}] return [] def _eval_has_planet_in_house_from(self, cond, ctx, rule, bindings): """指定行星集合中至少一颗在某参考行星的相对宫位。houses 使用传统 1-12 口径。""" refs = self._resolve_binding(cond.get("planets", "all"), ctx, bindings) from_planet = cond.get("from") or cond.get("from_planet") from_list = self._resolve_binding(from_planet, ctx, bindings) houses = cond.get("houses", []) exclude = set(cond.get("exclude", [])) results = [] for fp in from_list: base = ctx.house_of(fp) if base is None: continue for rel_house in houses: target = ((base + rel_house - 2) % 12) + 1 matched = [p for p in refs if p not in exclude and p != fp and ctx.house_of(p) == target] if matched: combo = _combo(cond, "{planets}在{fp}的第{rel}宫", planets=_planets(matched), fp=_planet(fp), rel=rel_house, target=target, ) results.append({"combination": combo, "strength": rule.get("strength", "中"), "bindings": {"matched": matched, "from": fp, "rel_house": rel_house, "house": target}}) return results def _eval_houses_with_planets_count(self, cond, ctx, rule, bindings): """在指定宫位集合中,有多少个宫位至少包含一颗指定集合行星。""" refs = self._resolve_binding(cond.get("planets", "all"), ctx, bindings) houses = cond.get("houses", []) min_count = cond.get("min", 1) max_count = cond.get("max") occupied = [] for h in houses: matched = [p for p in refs if ctx.house_of(p) == h] if matched: occupied.append((h, matched)) count = len(occupied) ok = count >= min_count if max_count is not None: ok = ok and count <= max_count if ok: detail = _bijoin("; ", [BiText(f"第{h}宫:" + _planets(ps), f"house {h}: " + _planets(ps).en) for h, ps in occupied]) combo = _combo(cond, "{count}个目标宫位有指定行星", count=count, detail=detail, houses="/".join(str(h) for h, _ in occupied)) return [{"combination": combo, "strength": rule.get("strength", "中"), "bindings": {"occupied": occupied, "count": count}, "participants": list(refs)}] return [] def _eval_degree_gap(self, cond, ctx, rule, bindings): """同星座内两颗行星度数差小于阈值""" pa = self._resolve_binding(cond.get("a"), ctx, bindings) pb = self._resolve_binding(cond.get("b"), ctx, bindings) max_gap = cond.get("max_gap", 1.0) results = [] for a in pa: for b in pb: if a == b: continue s1 = ctx.sign_of(a) s2 = ctx.sign_of(b) if s1 is None or s1 != s2: continue d1 = ctx.degree_of(a) d2 = ctx.degree_of(b) if d1 is None or d2 is None: continue if abs(d1 - d2) < max_gap: combo = _combo(cond, "{a}与{b}在{sign}内相距{gap:.2f}°", a=_planet(a), b=_planet(b), sign=s1, gap=abs(d1 - d2)) results.append({"combination": combo, "strength": rule.get("strength", "中"), "participants": [a, b]}) return results def _eval_parivartana(self, cond, ctx, rule, bindings): """两颗宫主星互换星座(Parivartana/互落)""" # BUG-1572: inside any_pair the lords arrive as "$a" / "$b"; ctx.resolve # knows no bindings, so raja_yoga_parivartana never fired. Only the bare # "$x" form is bound here. def single(ref): if isinstance(ref, str) and ref.startswith("$"): found = self._resolve_binding(ref, ctx, bindings) return found[0] if found else None return ctx.resolve_single(ref) la = single(cond.get("lord_a")) lb = single(cond.get("lord_b")) if la is None or lb is None or la == lb: return [] sa = ctx.sign_of(la) sb = ctx.sign_of(lb) if sa is None or sb is None: return [] lord_of_sa = SIGN_LORDS.get(sa) lord_of_sb = SIGN_LORDS.get(sb) if lord_of_sa == lb and lord_of_sb == la: combo = _combo(cond, "{la}与{lb}互换星座", la=_planet(la), lb=_planet(lb)) 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: set_a = self._resolve_binding({"role": "set", "planets": cond.get("planets", [])}, ctx, bindings) set_b = set_a exclude_self = True else: set_a = self._resolve_binding(cond.get("from"), ctx, bindings) set_b = self._resolve_binding(cond.get("to"), ctx, bindings) exclude_self = cond.get("exclude_self", False) sub_cond = cond.get("condition", {}) results = [] for a in set_a: for b in set_b: if exclude_self and a == b: continue pair_bindings = {**bindings, "a": a, "b": b} matches = self._eval_condition(sub_cond, ctx, rule, pair_bindings) for m in matches: m["bindings"] = {**m.get("bindings", {}), "a": a, "b": b} results.extend(matches) return results def _eval_all_planets(self, cond, ctx, rule, bindings): """所有指定行星都满足某个条件""" refs = self._resolve_binding(cond.get("planets", "all"), ctx, bindings) sub_cond = cond.get("condition", {}) all_match = True matched_combo_parts = [] for p in refs: b = {**bindings, "planet": p} matches = self._eval_condition(sub_cond, ctx, rule, b) if not matches: all_match = False break matched_combo_parts.append(matches[0].get("combination", "")) if all_match and refs: combo = _bijoin("; ", matched_combo_parts) return [{"combination": combo, "strength": rule.get("strength", "中"), "participants": list(refs)}] return [] def _eval_any_planet(self, cond, ctx, rule, bindings): """任一指定行星满足条件""" refs = self._resolve_binding(cond.get("planets"), ctx, bindings) sub_cond = cond.get("condition", {}) for p in refs: b = {**bindings, "planet": p} matches = self._eval_condition(sub_cond, ctx, rule, b) if matches: return matches return [] def _eval_exists(self, cond, ctx, rule, bindings): """存在至少一个行星满足条件""" refs = self._resolve_binding(cond.get("planets"), ctx, bindings) sub_cond = cond.get("condition", {}) for p in refs: b = {**bindings, "planet": p} matches = self._eval_condition(sub_cond, ctx, rule, b) if matches: return matches return [] def _eval_lord_in_house(self, cond, ctx, rule, bindings): """某宫主星在指定宫位""" house = cond.get("house") target_houses = cond.get("target_houses", []) lord = ctx.lord_of_house(house) if lord is None or lord not in ctx.planets: return [] lh = ctx.house_of(lord) if lh is not None and lh in target_houses: combo = _combo(cond, "{house}宫主{lord}在第{lh}宫", house=house, lord=_planet(lord), lh=lh) return [{"combination": combo, "strength": rule.get("strength", "中"), "bindings": {"lord": lord, "house": lh}}] return [] def _eval_lords_relation(self, cond, ctx, rule, bindings): """两个宫主星之间的特定关系(同宫/互落等)""" lord_a = ctx.resolve_single(cond.get("lord_a")) lord_b = ctx.resolve_single(cond.get("lord_b")) # Upstream e628118d: one planet ruling both houses is not a relation # between two lords (Mars alone as 5th + 10th lord for Cancer rising). if lord_a is None or lord_b is None or lord_a == lord_b: return [] relation = cond.get("relation", "same_house") if relation == "same_house": ha = ctx.house_of(lord_a) hb = ctx.house_of(lord_b) if ha is not None and ha == hb: combo = _combo(cond, "{la}与{lb}同在第{h}宫", la=_planet(lord_a), lb=_planet(lord_b), h=ha) return [{"combination": combo, "strength": rule.get("strength", "中"), "participants": [lord_a, lord_b]}] return [] def _eval_custom(self, cond, ctx, rule, bindings): """自定义 Python 表达式(用于复杂规则)""" expr = cond.get("expr", "") if not expr: return [] # BUG-735: exec_globals 每次新建(依赖当前盘 ctx),只有 code object 走进程级缓存。 exec_globals = self._build_custom_exec_globals(ctx, rule, bindings) # BUG-2124 → BUG-2170 (占星师 2026-11-22 裁定 7.2): the branch record comes from this one # evaluation (recorder slots filled on Python's own path); nothing runs a second time. # _eval_condition moves the slot into this node's own execution_trace entry right after this # returns (also when nothing matched); a match also carries it. A failure raises the same # YogaRuleEvaluationError as before, carrying its record as `custom_branch_trace`. branch_run = _BranchRun() try: result = _run_custom_expr(expr, exec_globals, branch_run) except YogaRuleEvaluationError as exc: exc.custom_branch_trace = _custom_branch_trace(expr, exec_globals, None, branch_run, rule, bindings) raise branch_trace = _custom_branch_trace(expr, exec_globals, result, branch_run, rule, bindings) ctx.custom_branch_trace_slot = branch_trace traced = {"custom_branch_trace": branch_trace} if result: combo = cond.get("combo_template", "自定义条件满足") if isinstance(combo, str): # Custom templates were never formatted; keep that, and pair the English text. combo = _template_text(combo, cond.get("combo_template_en") if "combo_template" in cond else DEFAULT_COMBO_EN["自定义条件满足"]) if callable(combo): combo = combo(ctx, bindings) strength = cond.get("strength", rule.get("strength", "中")) if callable(strength): strength = strength(ctx, bindings) # #166 Q6 (BUG-1597): a rule may set `triggers` (list of short strings) # to name what actually fired; they are appended to the combination. # An item is either one string (used in both editions) or a # (Chinese, English) pair, so the Chinese report never carries English glue. # BUG-1657: a custom rule may also set `participants` (planet names). participants = exec_globals.get("participants") # 产品 2026-11-07 同步占星师 Yoga 规则批次(上游 733a931b): a rule # may name its matching witnesses with `participants_expr` # (never every planet the failed branches queried). witnesses = None if not (isinstance(participants, (list, tuple)) and participants) and cond.get("participants_expr"): witnesses = _run_custom_expr(cond["participants_expr"], exec_globals) participants = [p for p in _flatten_planets(witnesses, ctx)] if not (isinstance(participants, (list, tuple)) and participants): participants = _static_custom_participants(expr, ctx) extra = {"participants": list(participants)} if participants else {} # BUG-2301 (upstream 58f37ee5b): her `bindings.planets` is the participants_expr value as returned. if witnesses is not None: extra["bindings"] = {"planets": list(witnesses) if isinstance(witnesses, (list, tuple)) else [witnesses]} triggers = exec_globals.get("triggers") if isinstance(triggers, list) and triggers: pairs = [(item[0], item[1]) if isinstance(item, (list, tuple)) and len(item) == 2 else (item, item) for item in triggers] zh_items = [str(zh) for zh, _ in pairs] en_items = [str(en) for _, en in pairs] combo = BiText(f"{combo}:{';'.join(zh_items)}", f"{_en_text(combo)}: {'; '.join(en_items)}") return [{"combination": combo, "strength": strength, "triggers": en_items, "triggers_zh": zh_items, **extra, **traced}] return [{"combination": combo, "strength": strength, **extra, **traced}] return [] def _build_custom_exec_globals(self, ctx, rule, bindings): """构造 custom 表达式的求值命名空间。每次调用都新建,绑定当前这张盘的 ctx。""" def house_of(p): return ctx.house_of(p) def sign_of(p): return ctx.sign_of(p) def deg_of(p): return ctx.degree_of(p) def lord(h): return ctx.lord_of_house(h) def in_houses(p, hs): h = house_of(p); return h is not None and h in hs def dignity(p): return ctx.dignity(p) def exalted(p): return ctx.is_exalted(p) def own(p): return ctx.is_own_sign(p) def debil(p): return ctx.is_debilitated(p) def moola(p): return ctx.is_moolatrikona(p) def kendra(h): return ctx.is_kendra(h) def trikona(h): return ctx.is_trikona(h) def dusthana(h): return ctx.is_dusthana(h) def upachaya(h): return ctx.is_upachaya(h) def kendra_from(p, fp): return ctx.is_kendra_from(p, fp) def trikona_from(p, fp): return ctx.is_trikona_from(p, fp) def offset(fh, th): return ctx.house_offset(fh, th) def planets_in(h): return ctx.planets_in_house(h) def resolve(ref): return ctx.resolve(ref) # v6.0.32: 修复 custom 规则中常用的缺失辅助函数 def same_house(a, b): """两颗行星是否同宫(允许自比较:同星恒为 True)""" ha = ctx.house_of(a) hb = ctx.house_of(b) return ha is not None and ha == hb def aspect(a, b): """行星a是否aspect行星b(7th aspect + Mars/Jupiter/Saturn的特殊aspect)""" if a == b: return False # Upstream e628118d: in the shared Parashari profile Rahu / Ketu act # by conjunction only (same reading as BUG-1207 / BUG-1625 here). if a in {'Rahu', 'Ketu'}: return False ha = ctx.house_of(a) hb = ctx.house_of(b) if ha is None or hb is None: return False off = ctx.house_offset(ha, hb) # 7th aspect for all planets if off == 6: return True # Mars: 4th, 8th aspects if a == 'Mars' and off in (3, 7): return True # Jupiter: 5th, 9th aspects if a == 'Jupiter' and off in (4, 8): return True # Saturn: 3rd, 10th aspects if a == 'Saturn' and off in (2, 9): return True return False def aspects_house(p, h): if p not in ctx.planets or h is None: return False if p in {'Rahu', 'Ketu'}: # upstream e628118d: nodes do not aspect return False return h == ctx.house_of(p) or offset(ctx.house_of(p), h) in (6, 3 if p == 'Mars' else -1, 7 if p == 'Mars' else -1, 4 if p == 'Jupiter' else -1, 8 if p == 'Jupiter' else -1, 2 if p == 'Saturn' else -1, 9 if p == 'Saturn' else -1) def graha_aspects_house(p, h): if p not in ctx.planets or h is None: return False if p in {'Rahu', 'Ketu'}: # upstream e628118d: nodes do not aspect return False return offset(ctx.house_of(p), h) in (6, 3 if p == 'Mars' else -1, 7 if p == 'Mars' else -1, 4 if p == 'Jupiter' else -1, 8 if p == 'Jupiter' else -1, 2 if p == 'Saturn' else -1, 9 if p == 'Saturn' else -1) def external_benchmark_planets_aspecting_raasi(p, h): """Replicate PyJHora house.planets_aspecting_the_raasi() behavior for source parity.""" if p not in ctx.planets or h is None: return False sign_name = ctx.sign_of(p) if sign_name not in SIGNS: return False target_rasi_idx = (ctx.asc_idx + h - 1) % 12 aspected_signs = rasi_drishti_signs_from(sign_name) planet_ids_in_aspected_signs = [ PLANET_INDEX[q] for q in ctx.planets if q in PLANET_INDEX and ctx.sign_of(q) in aspected_signs ] return target_rasi_idx in planet_ids_in_aspected_signs def external_benchmark_aspected_planets_of_raasi(h): """Replicate PyJHora house.aspected_planets_of_the_raasi(): planets whose rasi drishti hits a target house.""" if h is None: return [] target_sign = house_sign(h) return [ p for p in ctx.planets if p in PLANET_INDEX and target_sign in rasi_drishti_signs_from(ctx.sign_of(p)) ] def rasi_drishti_signs_from(sign_name): if sign_name not in SIGNS: return [] sign_idx = SIGNS.index(sign_name) if sign_name in MOVABLE_SIGNS: return [SIGNS[i] for i in [1, 4, 7, 10] if i not in ((sign_idx + 1) % 12, (sign_idx - 1) % 12)] if sign_name in FIXED_SIGNS: return [SIGNS[i] for i in [0, 3, 6, 9] if i not in ((sign_idx + 1) % 12, (sign_idx - 1) % 12)] return [s for s in DUAL_SIGNS if s != sign_name] def rasi_aspects_house(p, h): if p not in ctx.planets or h is None: return False return house_sign(h) in rasi_drishti_signs_from(ctx.sign_of(p)) def rasi_aspects(a, b): return a in ctx.planets and b in ctx.planets and rasi_aspects_house(a, ctx.house_of(b)) def rasi_aspected_by_planets(h): return [p for p in ctx.planets if rasi_aspects_house(p, h)] def sign_index_of_planet(p): sign_name = ctx.sign_of(p) return SIGNS.index(sign_name) if sign_name in SIGNS else None def house_strength(p): sign_idx = sign_index_of_planet(p) if sign_idx is None or p not in HOUSE_STRENGTHS: return None strength = HOUSE_STRENGTHS[p][sign_idx] sign_name = SIGNS[sign_idx] # v6.0.39: PyJHora dynamic co-lord owner strength for Scorpio/Aquarius. # Without this, Ketu/Rahu can become house lords but still look non-owner in strength checks. if sign_name in ('Scorpio', 'Aquarius') and ctx._resolve_sign_lord(sign_name) == p: return max(strength, 5) return strength def strong(p, include_neutral=False): strength = house_strength(p) if strength is None: return False return strength >= (2 if include_neutral else 3) def weak(p): strength = house_strength(p) return strength is not None and strength <= 2 def combust(p): """#166 Q5: the chart's `combust` flag, else the direct-motion orb from the Sun.""" info = ctx.planets.get(p) or {} if isinstance(info.get('combust'), bool): return info['combust'] if p not in COMBUSTION_ORBS_DIRECT or 'Sun' not in ctx.planets: return False def lon(q): sign, deg = ctx.sign_of(q), ctx.degree_of(q) if sign not in SIGNS or deg is None: return None return SIGNS.index(sign) * 30.0 + float(deg) % 30.0 a, b = lon(p), lon('Sun') if a is None or b is None: return False return abs(((a - b + 180.0) % 360.0) - 180.0) <= COMBUSTION_ORBS_DIRECT[p] def in_natural_enemy_sign(p): """#166 Q5: the sign lord is a natural enemy of p (BPHS 3.55). Natural (not five-fold) enmity is a named choice, 待核 (#166 astrologer 2026-11-05: the PVR strict definition does not say which). """ sign = ctx.sign_of(p) return sign in SIGN_LORDS and SIGN_LORDS[sign] in NATURAL_ENEMIES.get(p, []) def mercury_malefic_companions(): """BUG-1624: natural malefics sharing Mercury's sign; non-empty = Mercury is a natural malefic. Same rule and label as Drik Bala (shadbala.MERCURY_NATURE_CONVENTION): Sun, Mars, Saturn and the waning Moon count, Rahu / Ketu do not. """ return list(_shadbala_mercury_rule()(ctx.planets)) def associated(a, b): return a in ctx.planets and b in ctx.planets and (same_house(a, b) or aspect(a, b) or aspect(b, a)) def temporal_friend(a, b): if a not in ctx.planets or b not in ctx.planets or a == b: return False # PyJHora temporary friends: 2/3/4/10/11/12 from a planet. return offset(ctx.house_of(a), ctx.house_of(b)) in [1, 2, 3, 9, 10, 11] def natural_friend(a, b): return a in FRIENDLY_PLANETS.get(b, []) and b in FRIENDLY_PLANETS.get(a, []) def occupants(h): return ctx.planets_in_house(h) if h is not None else [] def only_benefics_in_house(h): ps = occupants(h) return bool(ps) and all(p in BENEFICS for p in ps) def only_malefics_in_house(h): ps = occupants(h) return bool(ps) and all(p in MALEFICS for p in ps) def house_has_benefic(h): return any(p in BENEFICS for p in occupants(h)) def house_has_malefic(h): return any(p in MALEFICS for p in occupants(h)) def house_sign(h): if h is None: return None return SIGNS[(ctx.asc_idx + h - 1) % 12] def movable_house(h): return house_sign(h) in MOVABLE_SIGNS def d9_house_of(p): return ctx.d9_house_of(p) def d9_sign_of(p): return ctx.d9_sign_of(p) def d9_lord_of_house(h): return ctx.d9_lord_of_house(h) def navamsa_dispositor(p): return ctx.navamsa_dispositor(p) def tithi(): return ctx.tithi() def is_waning_moon(): return ctx.is_waning_moon() def upagraha_house(name): return ctx.upagraha_house(name) def upagraha_sign(name): return ctx.upagraha_sign(name) def gulika_house(): return ctx.upagraha_house("gulika") def maandi_house(): return ctx.upagraha_house("maandi") def gulika_sign(): return ctx.upagraha_sign("gulika") def maandi_sign(): return ctx.upagraha_sign("maandi") def exal(p): return ctx.is_exalted(p) def lord_of_house(h): return ctx.lord_of_house(h) def sign(p): return ctx.sign_of(p) def check_amala_from(base_house): """Amala: 第10宫仅有吉星,支持从Lagna/Moon等基准宫位计算。""" target = ((base_house - 1 + 9) % 12) + 1 occupants = ctx.planets_in_house(target) return bool(occupants) and all(p in BENEFICS for p in occupants) def external_benchmark_natural_benefics(): """Replicate PyJHora yoga._get_natural_benefics(): Jupiter, Venus, plus benefic Mercury.""" benefics = [p for p in ["Jupiter", "Venus"] if p in ctx.planets] mercury_house = ctx.house_of("Mercury") if mercury_house is not None: mercury_alone = len(ctx.planets_in_house(mercury_house)) == 1 mercury_with_jupiter_or_venus = any(ctx.house_of(p) == mercury_house for p in ["Jupiter", "Venus"] if p in ctx.planets) if mercury_alone or mercury_with_jupiter_or_venus: benefics.append("Mercury") return benefics # 辅助:获取星盘所有行星名列表 def _planets_list(): return list(ctx.planets.keys()) # 辅助:获取所有宫主星(1-12宫) def _all_lords(): return [ctx.lord_of_house(h) for h in range(1, 13)] # 辅助:获取角宫主星列表 def _kendra_lords_list(): ai = SIGNS.index(ctx.ascendant) if ctx.ascendant in SIGNS else 0 # set 顺序随进程哈希变化;排序后同一张盘的角宫主参与者顺序才稳定。 return sorted(set([SIGN_LORDS[SIGNS[(ai + h - 1) % 12]] for h in [1, 4, 7, 10]])) # 辅助:获取三方宫主星列表 def _trikona_lords_list(): ai = SIGNS.index(ctx.ascendant) if ctx.ascendant in SIGNS else 0 # set 顺序随进程哈希变化;排序后同一张盘的三方主参与者顺序才稳定。 return sorted(set([SIGN_LORDS[SIGNS[(ai + h - 1) % 12]] for h in [1, 5, 9]])) safe_globals = { # 安全内置函数:只开放规则表达式需要的纯函数,避免 custom 规则因 all/any/len/set 缺失而静默失效。 "all": all, "any": any, "len": len, "set": set, "tuple": tuple, "sorted": sorted, "abs": abs, "min": min, "max": max, "sum": sum, "range": range, "list": list, "bool": bool, "ctx": ctx, "bindings": bindings, "rule": rule, "SIGNS": SIGNS, "SIGN_LORDS": SIGN_LORDS, "FRIENDLY_PLANETS": FRIENDLY_PLANETS, "RAHU_KETU_OWNED_SIGN_INDEX": RAHU_KETU_OWNED_SIGN_INDEX, "EXALTATION": EXALTATION, "DEBILITATION": DEBILITATION, "PLANET_CN": PLANET_CN, "BENEFICS": BENEFICS, "MALEFICS": MALEFICS, "MOVABLE_SIGNS": MOVABLE_SIGNS, "FIXED_SIGNS": FIXED_SIGNS, "DUAL_SIGNS": DUAL_SIGNS, "PLANET_INDEX": PLANET_INDEX, "HOUSE_STRENGTHS": HOUSE_STRENGTHS, "ALL_PLANETS": ALL_PLANETS, "MOOLATRIKONA_SIGN": MOOLATRIKONA_SIGN, # 基础查询 "house_of": house_of, "sign_of": sign_of, "deg_of": deg_of, "get_sign_of": sign_of, # 别名 "lord": lord, "lords_of": lord, # 别名(接受宫位数) # 尊严检查 "dignity": dignity, "exalted": exalted, "is_exalted": exalted, "own": own, "is_own_sign": own, "debil": debil, "is_debilitated": debil, "moola": moola, "is_moolatrikona": moola, # 宫位类型 "in_houses": in_houses, "planets_in": planets_in, "kendra": kendra, "is_kendra": kendra, "trikona": trikona, "is_trikona": trikona, "dusthana": dusthana, "is_dusthana": dusthana, "upachaya": upachaya, "is_upachaya": upachaya, "kendra_from": kendra_from, "trikona_from": trikona_from, "offset": offset, # v6.0.32: 同宫与相位检查(custom规则常用) "same_house": same_house, "aspect": aspect, "aspects_house": aspects_house, "graha_aspects_house": graha_aspects_house, "external_benchmark_planets_aspecting_raasi": external_benchmark_planets_aspecting_raasi, "external_benchmark_aspected_planets_of_raasi": external_benchmark_aspected_planets_of_raasi, "rasi_drishti_signs_from": rasi_drishti_signs_from, "rasi_aspects_house": rasi_aspects_house, "rasi_aspects": rasi_aspects, "rasi_aspected_by_planets": rasi_aspected_by_planets, "house_strength": house_strength, "strong": strong, "weak": weak, "associated": associated, "temporal_friend": temporal_friend, "natural_friend": natural_friend, "combust": combust, "in_natural_enemy_sign": in_natural_enemy_sign, "mercury_malefic_companions": mercury_malefic_companions, "PLANET_ZH": PLANET_ZH, "occupants": occupants, "only_benefics_in_house": only_benefics_in_house, "only_malefics_in_house": only_malefics_in_house, "house_has_benefic": house_has_benefic, "house_has_malefic": house_has_malefic, "house_sign": house_sign, "movable_house": movable_house, "external_benchmark_natural_benefics": external_benchmark_natural_benefics, "d9_house_of": d9_house_of, "d9_sign_of": d9_sign_of, "d9_lord_of_house": d9_lord_of_house, "navamsa_dispositor": navamsa_dispositor, "tithi": tithi, "is_waning_moon": is_waning_moon, "upagraha_house": upagraha_house, "upagraha_sign": upagraha_sign, "gulika_house": gulika_house, "maandi_house": maandi_house, "gulika_sign": gulika_sign, "maandi_sign": maandi_sign, # v6.1.3: D60 / Shashtiamsa 扩展 "d60_house_of": lambda p: ctx.d60_house_of(p), "d60_sign_of": lambda p: ctx.d60_sign_of(p), "d60_lord_of_house": lambda h: ctx.d60_lord_of_house(h), "shashtiamsa_dispositor": lambda p: ctx.shashtiamsa_dispositor(p), "is_shashtiamsa_evil": lambda p: ctx.is_shashtiamsa_evil(p), "is_shashtiamsa_good": lambda p: ctx.is_shashtiamsa_good(p), # v6.1.3: D9 尊严扩展 "is_exalted_in_d9": lambda p: ctx.is_exalted_in_d9(p), "is_debilitated_in_d9": lambda p: ctx.is_debilitated_in_d9(p), "is_own_sign_in_d9": lambda p: ctx.is_own_sign_in_d9(p), "is_moolatrikona_in_d9": lambda p: ctx.is_moolatrikona_in_d9(p), "dignity_in_d9": lambda p: ctx.dignity_in_d9(p), "is_friendly_navamsa": lambda p: ctx.is_friendly_navamsa(p), "is_unfriendly_navamsa": lambda p: ctx.is_unfriendly_navamsa(p), # v6.1.3: Functional malefic / benefic "functional_malefics": lambda: ctx.functional_malefics(), "functional_benefics": lambda: ctx.functional_benefics(), # v6.1.3: Vaiseshikamsa scoring "vaiseshikamsa_score": lambda p: ctx.vaiseshikamsa_score(p), "exal": exal, "lord_of_house": lord_of_house, "sign": sign, "check_amala_from": check_amala_from, "Benefics": BENEFICS, "Malefics": MALEFICS, "planets": ctx.planets, # 解析 "resolve": resolve, # 列表辅助 "planets_list": _planets_list, "all_lords": _all_lords, "kendra_lords_list": _kendra_lords_list, "trikona_lords_list": _trikona_lords_list, } return {"__builtins__": {}, **safe_globals} def _eval_semantic_condition(self, ctype, cond, ctx, rule, bindings): """兼容批量抽取规则中的语义型条件。返回保守布尔匹配。""" def success(combo=None, planets=()): # BUG-2301 (upstream 58f37ee5b): the bound planets are recorded; the Chinese text stays ours. text = combo or _semantic_text(cond, ctype) return [{"combination": text, "strength": rule.get("strength", "中"), "bindings": {"planets": list(planets)}}] def house(ref): if isinstance(ref, int): return ref if isinstance(ref, str): if ref in ctx.planets: return ctx.house_of(ref) low = ref.lower() if low in ("lagna", "asc", "ascendant"): return 1 if low == "moon": return ctx.house_of("Moon") return None def planet_list(default=None): ps = cond.get("planets", default or []) if ps == "all": return [p for p in ALL_PLANETS if p in ctx.planets] if isinstance(ps, str): return [ps] if ps in ctx.planets else [] return [p for p in ps if p in ctx.planets] def aspects(a, b): # b 可为行星名或宫位整数;支持检查行星对宫位/行星的传统相位。 ha = ctx.house_of(a) hb = ctx.house_of(b) if isinstance(b, str) else b if ha is None or hb is None or a == b: return False off = ctx.house_offset(ha, hb) return off == 6 or (a == "Mars" and off in (3, 7)) or (a == "Jupiter" and off in (4, 8)) or (a == "Saturn" and off in (2, 9)) def related(a, b): return a in ctx.planets and b in ctx.planets and (ctx.house_of(a) == ctx.house_of(b) or aspects(a, b) or aspects(b, a)) def house_lord(h): return ctx.lord_of_house(h) if isinstance(h, int) else None def is_benefic(p): return p in BENEFICS def is_malefic(p): return p in MALEFICS def is_strong(p): return p in ctx.planets and (ctx.is_exalted(p) or ctx.is_own_sign(p) or ctx.is_moolatrikona(p) or ctx.is_kendra(ctx.house_of(p)) or ctx.is_trikona(ctx.house_of(p))) def rel_house(base, offset0): return ((base - 1 + offset0) % 12) + 1 if base else None if ctype == "placeholder": return [] if ctype == "planet_in_lagna": p = cond.get("planet") return success() if p in ctx.planets and ctx.house_of(p) == 1 else [] if ctype == "planet_in_house": p = cond.get("planet") h = cond.get("house") return success() if p in ctx.planets and ctx.house_of(p) == h else [] if ctype == "venus_in_house": h = cond.get("house") return success() if "Venus" in ctx.planets and ctx.house_of("Venus") == h else [] if ctype == "benefic_in_house": h = cond.get("house") return success() if any(ctx.house_of(p) == h for p in BENEFICS if p in ctx.planets) else [] if ctype == "planets_in_house": h = cond.get("house") ps = planet_list() return success() if h and ps and all(ctx.house_of(p) == h for p in ps) else [] if ctype == "planets_conjunct_in_same_house": ps = planet_list() return success() if len(ps) >= 2 and len({ctx.house_of(p) for p in ps}) == 1 else [] if ctype == "planets_in_exactly_n_signs": ps = planet_list(['Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn']) n = cond.get("n") # Upstream e628118d: every listed planet must be placed. return success(planets=ps) if n and ps and all(p in ctx.planets and ctx.sign_of(p) for p in ps) and len({ctx.sign_of(p) for p in ps}) == n else [] if ctype == "planets_in_kendras": ps = planet_list() return success() if ps and all(ctx.is_kendra(ctx.house_of(p)) for p in ps) else [] if ctype == "planets_in_trines": ps = planet_list() return success() if ps and all(ctx.is_trikona(ctx.house_of(p)) for p in ps) else [] if ctype == "malefics_in_kendras_and_trines": ps = [p for p in MALEFICS if p in ctx.planets] return success() if any(ctx.is_kendra(ctx.house_of(p)) for p in ps) and any(ctx.is_trikona(ctx.house_of(p)) for p in ps) else [] if ctype == "malefics_in_lagna": ps = [p for p in MALEFICS if p in ctx.planets and ctx.house_of(p) == 1] return success(planets=ps) if ps else [] if ctype == "malefics_in_trines": return success() if any(ctx.is_trikona(ctx.house_of(p)) for p in MALEFICS if p in ctx.planets) else [] if ctype == "planet_exalted_in_kendra": p = cond.get("planet") return success() if p in ctx.planets and ctx.is_exalted(p) and ctx.is_kendra(ctx.house_of(p)) else [] if ctype == "lord_exalted": p = house_lord(cond.get("lord_of") or cond.get("house")) return success() if p and ctx.is_exalted(p) else [] if ctype == "lord_in_kendra": p = house_lord(cond.get("lord_of") or cond.get("house")) return success() if p and ctx.is_kendra(ctx.house_of(p)) else [] if ctype == "lord_in_exaltation_own_or_mool_trikona": p = house_lord(cond.get("lord_of") or cond.get("house")) return success() if p and (ctx.is_exalted(p) or ctx.is_own_sign(p) or ctx.is_moolatrikona(p)) else [] if ctype == "mercury_strong_in_kendra_or_trikona": return success() if "Mercury" in ctx.planets and is_strong("Mercury") and (ctx.is_kendra(ctx.house_of("Mercury")) or ctx.is_trikona(ctx.house_of("Mercury"))) else [] if ctype == "moon_strong": return success() if "Moon" in ctx.planets and is_strong("Moon") else [] if ctype == "planet_in_own_or_exalted_sign": p = cond.get("planet") return success() if p in ctx.planets and (ctx.is_own_sign(p) or ctx.is_exalted(p)) else [] if ctype == "planet_aspected_by_planet": p = cond.get("planet") or cond.get("to") by = cond.get("by") or cond.get("from") return success() if p in ctx.planets and by in ctx.planets and aspects(by, p) else [] if ctype == "navamsa_lord_of_2_5_11_exalted_joins_9th_lord": l9 = house_lord(9) for h in (2, 5, 11): lord_h = house_lord(h) disp = ctx.navamsa_dispositor(lord_h) if lord_h else None if disp and l9 and disp in ctx.planets and ctx.is_exalted(disp) and related(disp, l9): return success() return [] if ctype == "navamsa_lord_of_moon_exalted_in_rasi": disp = ctx.navamsa_dispositor("Moon") return success() if disp and disp in ctx.planets and ctx.is_exalted(disp) else [] if ctype == "navamsa_dispositor_exalted_in_10th_with_lagna_lord": ref = cond.get("reference_planet") if ref == "10th_lord": ref_planet = house_lord(10) else: ref_planet = ref if ref in ctx.planets else None disp = ctx.navamsa_dispositor(ref_planet) if ref_planet else None l1 = house_lord(1) return success() if disp and l1 and disp in ctx.planets and ctx.is_exalted(disp) and ctx.house_of(disp) == 10 and related(disp, l1) else [] if ctype == "navamsa_lord_of_4th_lord_in_12th": l4 = house_lord(4) disp = ctx.navamsa_dispositor(l4) if l4 else None return success() if disp and disp in ctx.planets and ctx.house_of(disp) == 12 else [] if ctype == "moon_with_malefics_in_navamsa_cancer_scorpio": moon_sign = ctx.d9_sign_of("Moon") moon_house = ctx.d9_house_of("Moon") return success() if moon_sign in {"Cancer", "Scorpio"} and moon_house and any(ctx.d9_house_of(p) == moon_house for p in MALEFICS if p in ctx.planets and p != "Moon") else [] if ctype == "sun_and_mandi_in_house": target = cond.get("house") or cond.get("in_house") if target is None and cond.get("house_offset") is not None: target = int(cond.get("house_offset")) + 1 return success() if target and ctx.house_of("Sun") == target and ctx.upagraha_house("maandi") == target else [] if ctype == "planet_conjunct_planet": a = cond.get("planet") or cond.get("a") b = cond.get("with") or cond.get("b") return success() if a in ctx.planets and b in ctx.planets and ctx.house_of(a) == ctx.house_of(b) else [] if ctype == "lord_in_house": lord = ctx.lord_of_house(cond.get("lord_of") or cond.get("house") or cond.get("lord_house")) target = cond.get("in_house") or cond.get("target_house") return success() if lord and ctx.house_of(lord) == target else [] if ctype == "house_lord_in_kendra": lord = ctx.lord_of_house(cond.get("house")) return success() if lord and ctx.is_kendra(ctx.house_of(lord)) else [] if ctype == "house_lord_in_trine": lord = ctx.lord_of_house(cond.get("house")) return success() if lord and ctx.is_trikona(ctx.house_of(lord)) else [] if ctype in ("lagna_hemmed_by_malefics_not_aspected_by_benefics", "lagna_hemmed_by_benefics_not_aspected_by_malefics"): group = MALEFICS if "malefics" in ctype else BENEFICS blockers = BENEFICS if "malefics" in ctype else MALEFICS has_2 = any(ctx.house_of(p) == 2 for p in group if p in ctx.planets) has_12 = any(ctx.house_of(p) == 12 for p in group if p in ctx.planets) aspected = any(aspects(p, 1) for p in blockers if p in ctx.planets) return success() if has_2 and has_12 and not aspected else [] if ctype == "planets_in_mutual_kendras_or_conjunction": ps = planet_list() if len(ps) >= 2: a, b = ps[0], ps[1] ha, hb = ctx.house_of(a), ctx.house_of(b) return success() if ha and hb and (ha == hb or ctx.house_offset(ha, hb) in (0, 3, 6, 9)) else [] if ctype == "lords_in_mutual_conjunction_or_aspect": houses = cond.get("lords") or [] ps = [house_lord(h) for h in houses] return success() if len(ps) >= 2 and related(ps[0], ps[1]) else [] if ctype == "aspected_by_benefics": p = cond.get("planet") if isinstance(p, str) and p.endswith("_lord"): p = house_lord(int(p.split("_")[0])) if p.split("_")[0].isdigit() else None return success() if p and any(aspects(b, p) for b in BENEFICS if b in ctx.planets) else [] if ctype == "aspected_by_malefic": p = cond.get("planet") if p == "4th_lord": p = house_lord(4) return success() if p and any(aspects(m, p) for m in MALEFICS if m in ctx.planets) else [] if ctype == "5th_lord_afflicted_by_saturn_or_rahu": p = house_lord(5) return success() if p and (related(p, "Saturn") or related(p, "Rahu")) else [] if ctype == "malefic_in_lagna_or_gulika_in_trine_OR_gulika_with_kendra_trine_lord_OR_l1_with_rahu_sat_ket": l1 = house_lord(1) gh = ctx.upagraha_house("gulika") # PyJHora: condition 3 stands alone; condition 1 requires BOTH malefic in Lagna AND Gulika in trine. l1_with_rahu_sat_ket = l1 and any(ctx.house_of(l1) == ctx.house_of(p) for p in ["Rahu", "Saturn", "Ketu"] if p in ctx.planets and p != l1) if l1_with_rahu_sat_ket: return success() if gh is None: return [] malefic_in_lagna = any(ctx.house_of(p) == 1 for p in MALEFICS if p in ctx.planets) gulika_in_trine = gh in (1, 5, 9) if malefic_in_lagna and gulika_in_trine: return success() kendra_trine_lords = {house_lord(h) for h in (1, 4, 5, 7, 9, 10)} gulika_with_kendra_trine_lord = any( lord and lord in ctx.planets and ctx.house_of(lord) == gh for lord in kendra_trine_lords ) return success() if gulika_with_kendra_trine_lord else [] if ctype == "same_lord_for_1st_and_4th": return success() if house_lord(1) == house_lord(4) else [] if ctype == "1st_and_4th_lords_are_natural_or_temporal_friends": # 保守近似:同宫/互相位视作 temporal association。 l1, l4 = house_lord(1), house_lord(4) return success() if l1 and l4 and related(l1, l4) else [] if ctype == "1st_and_4th_lords_aspected_by_benefics": l1, l4 = house_lord(1), house_lord(4) ok1 = l1 and any(aspects(b, l1) for b in BENEFICS if b in ctx.planets) ok4 = l4 and any(aspects(b, l4) for b in BENEFICS if b in ctx.planets) return success() if ok1 and ok4 else [] if ctype == "4th_lord_is_benefic_aspected_by_benefic": l4 = house_lord(4) return success() if l4 and is_benefic(l4) and any(aspects(b, l4) for b in BENEFICS if b in ctx.planets and b != l4) else [] if ctype == "4th_house_or_lord_with_aspect_of_jupiter": l4 = house_lord(4) return success() if "Jupiter" in ctx.planets and (aspects("Jupiter", 4) or (l4 and related("Jupiter", l4))) else [] if ctype == "4th_lord_with_benefics": l4 = house_lord(4) return success() if l4 and any(ctx.house_of(l4) == ctx.house_of(b) for b in BENEFICS if b in ctx.planets and b != l4) else [] if ctype == "4th_lord_aspected_by_benefics": l4 = house_lord(4) return success() if l4 and any(aspects(b, l4) for b in BENEFICS if b in ctx.planets and b != l4) else [] if ctype == "4th_lord_in_kendra_or_trikona": l4 = house_lord(4) return success() if l4 and (ctx.is_kendra(ctx.house_of(l4)) or ctx.is_trikona(ctx.house_of(l4))) else [] if ctype == "lagna_lord_in_dry_sign": l1 = house_lord(1) # PyJHora const.dry_signs = [0,1,2,4,5,8] = Aries,Taurus,Gemini,Leo,Virgo,Sagittarius dry_signs = {"Aries", "Taurus", "Gemini", "Leo", "Virgo", "Sagittarius"} # PyJHora const.dry_planets = [0,2,6] = Sun,Mars,Saturn dry_lords = {"Sun", "Mars", "Saturn"} # PyJHora Y112: (ll_house in dry_signs) OR (ll_house_owner in dry_planets) # ll_house = sign of lagna lord; ll_house_owner = dynamic lord of that sign ll_in_dry = l1 and ctx.sign_of(l1) in dry_signs l1_house = ctx.house_of(l1) if l1 else None ll_owner_dry = l1_house and ctx.lord_of_house(l1_house) in dry_lords ps = [l1] + ([ctx.lord_of_house(l1_house)] if ll_owner_dry else []) return success(planets=ps) if l1 and (ll_in_dry or ll_owner_dry) else [] if ctype == "navamsa_lagna_in_dry_planet_sign": d9_asc = ctx.d9.get("ascendant") dry_lords = {"Sun", "Mars", "Saturn"} return success(planets=[SIGN_LORDS.get(d9_asc)]) if d9_asc and SIGN_LORDS.get(d9_asc) in dry_lords else [] if ctype == "lagna_lord_and_navamsa_lord_both_in_watery_signs": l1 = house_lord(1) navamsa_lord = ctx.navamsa_dispositor(l1) if l1 else None watery = {"Cancer", "Scorpio", "Pisces"} return success() if l1 and navamsa_lord and ctx.sign_of(l1) in watery and ctx.sign_of(navamsa_lord) in watery else [] if ctype == "jupiter_in_lagna_or_aspects_lagna_from_watery": return success() if "Jupiter" in ctx.planets and (ctx.house_of("Jupiter") == 1 or (ctx.sign_of("Jupiter") in {"Cancer", "Scorpio", "Pisces"} and aspects("Jupiter", 1))) else [] if ctype == "lagna_watery_with_benefics_or_lagna_lord_watery": l1 = house_lord(1) asc_watery = ctx.ascendant in {"Cancer", "Scorpio", "Pisces"} watery_planets = {"Moon", "Venus"} return success() if (asc_watery and any(ctx.house_of(b) == 1 for b in BENEFICS if b in ctx.planets)) or (l1 in watery_planets) else [] if ctype == "jupiter_in_lagna_mars_in_7th": return success() if ctx.house_of("Jupiter") == 1 and ctx.house_of("Mars") == 7 else [] if ctype == "saturn_in_lagna_mars_in_5_7_9": return success() if ctx.house_of("Saturn") == 1 and ctx.house_of("Mars") in (5, 7, 9) else [] if ctype == "saturn_in_12th_with_waning_moon": return success() if ctx.house_of("Saturn") == 12 and ctx.is_waning_moon() else [] if ctype == "moon_mercury_in_kendra_with_planet": return success() if ctx.house_of("Moon") == ctx.house_of("Mercury") and ctx.is_kendra(ctx.house_of("Moon")) and len(ctx.planets_in_house(ctx.house_of("Moon"))) >= 3 else [] if ctype == "four_planet_chain_all_in_kendra_trine_or_exaltation": # BUG-2301 (upstream 58f37ee5b): PVR pp139–140 chain; a missing input is not "not formed". l1 = house_lord(1) if not l1: raise MissingYogaInput('ascendant_lord') chain = [l1] current = l1 for _ in range(2): sign_current = ctx.sign_of(current) current = SIGN_LORDS.get(sign_current) if sign_current else None if not current: raise MissingYogaInput(chain[-1] + '.sign') chain.append(current) # PVR pp139–140: both final dispositors belong to the SECOND # member. Shivaji example: Sun -> Saturn -> Venus / Saturn. d9_disp = ctx.navamsa_dispositor(chain[1]) if not d9_disp: raise MissingYogaInput(chain[1] + '.D9_sign') chain.append(d9_disp) for p in chain: if ctx.sign_of(p) is None or ctx.house_of(p) is None: raise MissingYogaInput(p + '.D1_position') ok = all( p in ctx.planets and (ctx.is_kendra(ctx.house_of(p)) or ctx.is_trikona(ctx.house_of(p)) or ctx.is_exalted(p)) for p in chain ) return success(planets=chain) if ok else [] if ctype == "planets_in_relative_houses": base = house(cond.get("from", "lagna")) or 1 offsets = cond.get("houses") or cond.get("offsets") or [] ps = planet_list(ALL_PLANETS) targets = {rel_house(base, int(o) % 12) for o in offsets} return success() if any(ctx.house_of(p) in targets for p in ps) else [] if ctype == "house_empty": h = cond.get("house") return success() if h and not ctx.planets_in_house(h) else [] if ctype == "planet_in_house_with_aspect_or_conjunction": """Jupiter in 2nd/5th, conjoined or aspected by Mercury AND Venus (kalaanidhi yoga)""" planet = cond.get("planet", "") house_offsets = cond.get("house_offsets", []) aspecting_or_conjoining = cond.get("aspecting_or_conjoining", []) if not planet or planet not in ctx.planets: return [] ph = ctx.house_of(planet) if ph is None: return [] # Check planet is in one of the target houses (from lagna) target_houses = set() for off in house_offsets: h = (1 + off) % 12 if h == 0: h = 12 target_houses.add(h) if ph not in target_houses: return [] # Check ALL specified planets must conjoin or aspect for other in aspecting_or_conjoining: if other not in ctx.planets: return [] # Check conjunction (same house) if ctx.house_of(other) == ph: continue # Check aspect (graha drishti) if aspects(other, planet): continue # Neither conjoined nor aspecting → fail return [] return success() # No branch knows this condition type: the rule cannot be evaluated, # which is not the same as "condition false" (第三轮审查 2026-11-07). raise YogaRuleEvaluationError("UnsupportedConditionType", str(ctype)) # ------------------------------------------------------------------------ # 辅助方法 # ------------------------------------------------------------------------ def _resolve_binding(self, ref, ctx, bindings): """解析引用,支持变量绑定替换""" if ref is None: return [] if isinstance(ref, str) and ref.startswith("$"): # 绑定变量引用,如 "$a" val = bindings.get(ref[1:]) if val is None: return [] return [val] if isinstance(val, str) else (val if isinstance(val, list) else [val]) return ctx.resolve(ref) @staticmethod def _offset_name(off: int) -> str: names = {0: "同宫", 1: "2宫", 2: "3宫", 3: "4宫(Kendra)", 4: "5宫(Trine)", 5: "6宫", 6: "7宫(Kendra)", 7: "8宫", 8: "9宫(Trine)", 9: "10宫(Kendra)", 10: "11宫", 11: "12宫"} return names.get(off, f"{off+1}宫") # ============================================================================ # 便捷入口 # ============================================================================ _PARTICIPANT_ORDER = ("Sun", "Moon", "Mars", "Mercury", "Jupiter", "Venus", "Saturn", "Rahu", "Ketu") _LOOP_NODES = (ast.comprehension, ast.Lambda, ast.For, ast.While) _LORD_CALLS = {"lord", "lords_of"} def _expr_planet_refs(node, ctx) -> Optional[set]: """Planets one expression node refers to; None when it cannot be decided.""" refs = set() for sub in ast.walk(node): if isinstance(sub, _LOOP_NODES): return None if isinstance(sub, ast.Constant) and isinstance(sub.value, str) and sub.value in _PARTICIPANT_ORDER: refs.add(sub.value) if isinstance(sub, ast.Call) and isinstance(sub.func, ast.Name) and sub.func.id in _LORD_CALLS: arg = sub.args[0] if sub.args else None if not (isinstance(arg, ast.Constant) and isinstance(arg.value, int)): return None lord = ctx.lord_of_house(arg.value) if lord not in _PARTICIPANT_ORDER: return None refs.add(lord) return refs @functools.lru_cache(maxsize=1024) def _parsed_custom_expr(expr: str): try: return ast.parse(expr, mode="eval") except SyntaxError: return None def _flatten_planets(values, ctx) -> List[str]: """Planet names in a `participants_expr` result, in order, once each (upstream 733a931b).""" out: List[str] = [] def walk(value) -> None: if isinstance(value, (list, tuple)): for item in value: walk(item) elif isinstance(value, str) and value in ctx.planets and value not in out: out.append(value) walk(values) return out def _static_custom_participants(expr: str, ctx) -> List[str]: """BUG-1657: participants of a loop-free custom rule. The planets an expression checks are its literal planet names plus the lords of literal house numbers. An `or` whose branches check different planets is ambiguous (only one branch may have held), so nothing is returned for it. """ tree = _parsed_custom_expr(expr or "") if tree is None: return [] for node in ast.walk(tree): if isinstance(node, ast.BoolOp) and isinstance(node.op, ast.Or): branch_refs = [_expr_planet_refs(value, ctx) for value in node.values] if any(refs is None for refs in branch_refs): return [] non_empty = [refs for refs in branch_refs if refs] if any(refs != non_empty[0] for refs in non_empty[1:]): return [] refs = _expr_planet_refs(tree, ctx) return _ordered(refs) if refs else [] def _ordered(names) -> List[str]: return [name for name in _PARTICIPANT_ORDER if name in set(names)] def _bound_planets(match: Dict) -> List[str]: """Planets named in a match's bindings or set by a custom rule. Only values the evaluators bound are used; combination text is never parsed. """ found = set() def take(value) -> None: if isinstance(value, str) and value in _PARTICIPANT_ORDER: found.add(value) elif isinstance(value, (list, tuple, set)): for item in value: take(item) elif isinstance(value, dict): for item in value.values(): take(item) for value in (match.get("bindings") or {}).values(): take(value) take(match.get("participants")) return [name for name in _PARTICIPANT_ORDER if name in found] def detect_yogas(planets: Dict[str, Dict], ascendant: str, rules_path: Optional[str] = None, context: Optional[Dict] = None) -> List[Dict]: """便捷函数:检测 Yoga""" if rules_path is None: # 自动查找规则文件 script_dir = os.path.dirname(os.path.abspath(__file__)) skill_dir = os.path.dirname(script_dir) rules_path = os.path.join(skill_dir, "references", "yoga_rules.json") engine = YogaEngine(rules_path) # BUG-2299: her blocked rows are listed apart (`detect_yogas_with_status`), not as yogas. return [row for row in engine.detect(planets, ascendant, context=context) if not is_blocked_rule_row(row)] def detect_yogas_with_status(planets: Dict[str, Dict], ascendant: str, rules_path: Optional[str] = None, context: Optional[Dict] = None) -> Dict: """Formed yogas plus the rules that could not be evaluated. `evaluation_failures` rows carry `condition_status: evaluation_failed` and the error class; a rule listed there was neither formed nor ruled out. """ if rules_path is None: script_dir = os.path.dirname(os.path.abspath(__file__)) rules_path = os.path.join(os.path.dirname(script_dir), "references", "yoga_rules.json") engine = YogaEngine(rules_path) # BUG-2299: her blocked rows (upstream 58f37ee5b) stay out of `yogas`; the same rules are in # `evaluation_failures` / `unimplemented_rules`, so the /api/yogas shape is unchanged. yogas = [row for row in engine.detect(planets, ascendant, context=context) if not is_blocked_rule_row(row)] failures = list(engine.last_evaluation_failures) unimplemented = list(engine.unimplemented_rules) + list(engine.last_unimplemented) return { "yogas": yogas, "rules_evaluated": len(engine.rules), "evaluation_failures": failures, "unimplemented_rules": unimplemented, "evaluation_status": ("evaluation_failed_present" if failures else "unimplemented_rules_present" if unimplemented else "complete"), } def detect_yogas_from_json(chart_json: Dict, rules_path: Optional[str] = None) -> List[Dict]: """从 chart JSON 结构中提取 planets + ascendant 并检测""" planets = chart_json.get("planets", {}) asc = chart_json.get("ascendant", chart_json.get("ascendant_sign", "Aries")) return detect_yogas(planets, asc, rules_path, context=chart_json.get("context")) if __name__ == "__main__": # 简单自测 test_planets = { "Sun": {"sign": "Aries", "house": 1, "degree": 10.5}, "Moon": {"sign": "Cancer", "house": 4, "degree": 15.0}, "Jupiter": {"sign": "Libra", "house": 7, "degree": 20.0}, } print("YogaEngine loaded. Run with a rules file to test.")