Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DbBXp2U3BH1SxwAGyhhbe1
376 lines
20 KiB
Python
376 lines
20 KiB
Python
#!/usr/bin/env python3
|
||
"""One main detector per classical yoga (astrologer rulings 2026-10-03).
|
||
|
||
The same yoga used to be judged by several implementations (local code,
|
||
`references/yoga_rules.json`, upstream ports), merged by name, so whichever
|
||
arrived first won. Each yoga below now has exactly one detector; the data-driven
|
||
rules of the same name are `reference_only` in `yoga_rules.json` and the rule
|
||
engine (`yoga_engine.YogaEngine.detect`) appends the rows built here instead, so
|
||
the reader report, the consultation sieve and `chart.yogas` carry one verdict.
|
||
|
||
Rows are shaped like `yoga_engine` rows (Chinese fields plus `*_en` twins for the
|
||
English reader edition).
|
||
|
||
- Neecha Bhanga (BUG-1205, 乙14): `yogas_doshas.calc_nicha_bhanga_raj_yoga`;
|
||
only the cancellation conditions that hold are listed, never called Raja Yoga.
|
||
- Pancha Mahapurusha (BUG-1207, 甲5): `pancha_mahapurusha.detect_pancha_mahapurusha`;
|
||
kendras from the Lagna only, retrograde does not cancel, combustion / malefic
|
||
conjunction or aspect only mark the yoga `reduced` (部分减弱); D9 debilitation
|
||
only weakens it (round-4 ruling 2026-10-03 Q1, BUG-1213): the yoga stays formed
|
||
with `d9_dignity_modifier: "weakened"` and the reason 「D9 落陷,兑现减弱」.
|
||
- Kemadruma (BUG-1206, 甲7): `yoga_expansion.detect_kemadruma`; the 2nd / 12th
|
||
from the Moon count only Mars, Mercury, Jupiter, Venus, Saturn, and there is no
|
||
kendra cancellation (planets in kendras, including only Rahu / Ketu there, do
|
||
not cancel it).
|
||
|
||
Inputs are D1 rows `{sign, house, lon?, retrograde?, navamsa_sign?}`. A missing
|
||
`navamsa_sign` is derived from the sidereal longitude (Parashari navamsa: each
|
||
3°20' from the movable / fixed / dual starting sign), so every caller that has
|
||
longitudes gets the same verdict.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from typing import Any, Dict, List, Optional
|
||
|
||
try: # scripts/ on sys.path
|
||
from pancha_mahapurusha import _longitude, detect_pancha_mahapurusha
|
||
from yoga_expansion import detect_kemadruma
|
||
from yogas_doshas import calc_nicha_bhanga_raj_yoga
|
||
except ImportError: # package import (scripts.main_yoga_detectors)
|
||
from scripts.pancha_mahapurusha import _longitude, detect_pancha_mahapurusha
|
||
from scripts.yoga_expansion import detect_kemadruma
|
||
from scripts.yogas_doshas import calc_nicha_bhanga_raj_yoga
|
||
|
||
SIGNS = ['Aries', 'Taurus', 'Gemini', 'Cancer', 'Leo', 'Virgo',
|
||
'Libra', 'Scorpio', 'Sagittarius', 'Capricorn', 'Aquarius', 'Pisces']
|
||
SIGN_ZH = {
|
||
'Aries': '白羊座', 'Taurus': '金牛座', 'Gemini': '双子座', 'Cancer': '巨蟹座',
|
||
'Leo': '狮子座', 'Virgo': '处女座', 'Libra': '天秤座', 'Scorpio': '天蝎座',
|
||
'Sagittarius': '射手座', 'Capricorn': '摩羯座', 'Aquarius': '水瓶座', 'Pisces': '双鱼座',
|
||
}
|
||
PLANET_ZH = {
|
||
'Sun': '太阳', 'Moon': '月亮', 'Mars': '火星', 'Mercury': '水星', 'Jupiter': '木星',
|
||
'Venus': '金星', 'Saturn': '土星', 'Rahu': '罗睺', 'Ketu': '计都',
|
||
}
|
||
|
||
NEECHA_BHANGA_NAME = 'Neecha Bhanga'
|
||
NEECHA_BHANGA_NAME_ZH = '落陷取消'
|
||
NEECHA_BHANGA_CATEGORY = 'neecha_bhanga'
|
||
# 原值:'只列成立的取消条件,不单独下结论' / 'Conditions only; no stand-alone conclusion'
|
||
# 新值:她 2026-11-19 第 3 条给的统一说法:条件成立可以明确确认,但不等于入旺、困难不因此全部消失。
|
||
# 原因:BUG-2012。
|
||
# 原值:「按《Light on Life》规则已满足落陷取消条件;…」/ "The cancellation conditions of the Light on Life rule are met; …"
|
||
# 新值:不写书名,其余照旧
|
||
# 原因:BUG-2129 负责人 2026-11-21:报告里不给读者出现书名引文
|
||
NEECHA_BHANGA_NOTE_ZH = '已满足落陷取消条件;这不等于该星入旺,也不代表相关困难全部消失'
|
||
NEECHA_BHANGA_NOTE_EN = ('The cancellation conditions are met; '
|
||
'this is not exaltation, and the related difficulties do not all disappear')
|
||
|
||
|
||
def _lon(row: Any) -> Optional[float]:
|
||
"""Sidereal longitude; same reading as the Pancha Mahapurusha detector
|
||
(`lon` / `degree_raw` / `longitude`, else `degree` as a longitude when
|
||
>= 30 or as a degree in `sign`), so the report rows (degree in sign) and
|
||
the API rows (longitudes) give the same D9 and the same verdict."""
|
||
return _longitude(row) if isinstance(row, dict) else None
|
||
|
||
|
||
def navamsa_sign(lon: float) -> str:
|
||
"""D9 sign of a sidereal longitude (Parashari navamsa)."""
|
||
return SIGNS[int((lon % 360.0) * 9.0 / 30.0) % 12]
|
||
|
||
|
||
def with_navamsa(planets: Dict[str, Any]) -> Dict[str, Dict[str, Any]]:
|
||
"""Copy of `planets` with `navamsa_sign` filled from the longitude when missing."""
|
||
rows: Dict[str, Dict[str, Any]] = {}
|
||
for name, row in (planets or {}).items():
|
||
if not isinstance(row, dict):
|
||
continue
|
||
copy = dict(row)
|
||
lon = _lon(row)
|
||
if not copy.get('navamsa_sign') and lon is not None:
|
||
copy['navamsa_sign'] = navamsa_sign(lon)
|
||
rows[name] = copy
|
||
return rows
|
||
|
||
|
||
def _planet_zh(name: Any) -> str:
|
||
return PLANET_ZH.get(str(name), str(name))
|
||
|
||
|
||
def _sign_zh(name: Any) -> str:
|
||
return SIGN_ZH.get(str(name), str(name))
|
||
|
||
|
||
def _neecha_condition_text(item: Dict[str, Any], debilitated: str) -> tuple[str, str]:
|
||
code = item.get('code')
|
||
planet = item.get('planet')
|
||
house = item.get('house')
|
||
frame_zh = '上升' if item.get('frame') == 'lagna' else '月亮'
|
||
frame_en = 'the Lagna' if item.get('frame') == 'lagna' else 'the Moon'
|
||
if code in ('A', 'B'):
|
||
return (f'落陷星座主星{_planet_zh(planet)}在{frame_zh}起第{house}宫(角宫)',
|
||
f'dispositor {planet} in house {house} from {frame_en} (kendra)')
|
||
if code in ('C', 'D'):
|
||
return (f'该星入旺星座的主星{_planet_zh(planet)}在{frame_zh}起第{house}宫(角宫)',
|
||
f'lord of its exaltation sign, {planet}, in house {house} from {frame_en} (kendra)')
|
||
# BUG-2012:G、H、I 是 Light on Life p.295 的第 4、第 3 类;E、F、J、K 是变体条件(不计入默认规则)。
|
||
if code in ('G', 'H'):
|
||
return (f'会在该星座入旺的{_planet_zh(planet)}在{frame_zh}起第{house}宫(角宫)',
|
||
f'{planet}, the planet exalted in that sign, in house {house} from {frame_en} (kendra)')
|
||
if code == 'I':
|
||
return (f'落陷星座主星{_planet_zh(planet)}照射{_planet_zh(debilitated)}',
|
||
f'dispositor {planet} aspects {debilitated}')
|
||
if code == 'E':
|
||
return (f'{_planet_zh(debilitated)}与落陷星座主星{_planet_zh(planet)}互换星座',
|
||
f'{debilitated} and its dispositor {planet} exchange signs')
|
||
if code == 'F':
|
||
return (f'{_planet_zh(planet)}在 D9 入庙或入旺({_sign_zh(item.get("sign"))})',
|
||
f'{planet} own or exalted in D9 ({item.get("sign")})')
|
||
if code == 'J':
|
||
return (f'落陷星座主星{_planet_zh(planet)}入旺({_sign_zh(item.get("sign"))})',
|
||
f'dispositor {planet} exalted ({item.get("sign")})')
|
||
if code == 'K':
|
||
return (f'会在该星座入旺的{_planet_zh(planet)}与{_planet_zh(debilitated)}同座',
|
||
f'{planet}, the planet exalted in that sign, shares the sign with {debilitated}')
|
||
return (str(item), str(item))
|
||
|
||
|
||
WITNESS_KEYS = ('condition', 'planet', 'reference', 'relative_house', 'self_reference',
|
||
'independent_confirmation_allowed', 'sign', 'aspect_distance')
|
||
|
||
|
||
def _witness_row(cond: Dict[str, Any], *keys: str) -> Dict[str, Any]:
|
||
"""One cancellation witness in her `formation_evidence.cancellation_reasons` shape.
|
||
|
||
BUG-2027: `self_reference` here is the engine's `witness_is_reference` (the witness is the
|
||
reference point itself). `witness_is_debilitated_planet` is written only when true (the
|
||
debilitated planet is its own witness, e.g. Mercury), so existing rows keep their shape.
|
||
"""
|
||
row = {key: cond[key] for key in WITNESS_KEYS + keys if key in cond}
|
||
if cond.get('witness_is_debilitated_planet'):
|
||
row['witness_is_debilitated_planet'] = True
|
||
return row
|
||
|
||
|
||
def neecha_bhanga_rows(planets: Dict[str, Any]) -> List[Dict[str, Any]]:
|
||
"""Formed Neecha Bhanga rows; conditions from `calc_nicha_bhanga_raj_yoga`.
|
||
|
||
BUG-2012: a row exists only when the default named rule `light_on_life_p295` holds. A planet
|
||
for which only a variant condition holds gets no row (see `neecha_bhanga_variant_notes`), so
|
||
nothing states a cancellation the default rule does not give. BUG-2027: neither does a planet
|
||
that hits only the always-true branch (see `neecha_bhanga_literal_only_notes`).
|
||
"""
|
||
result = calc_nicha_bhanga_raj_yoga(with_navamsa(planets), {})
|
||
rows: List[Dict[str, Any]] = []
|
||
for item in result.get('yogas') or []:
|
||
planet = item.get('planet')
|
||
# BUG-2027:行上对读者列出的条件和条数只收实际有效的条件;恒真条件(月亮在月亮起第 1 宫)
|
||
# 不增加支持强度,仍完整留在 formation_evidence.cancellation_reasons 里。
|
||
effective = item.get('effective_conditions')
|
||
if effective is None:
|
||
effective = [cond for cond in item.get('cancellation_conditions') or []
|
||
if not cond.get('witness_is_reference')]
|
||
texts = [_neecha_condition_text(cond, planet) for cond in effective]
|
||
if not texts:
|
||
continue
|
||
zh = [text[0] for text in texts]
|
||
en = [text[1] for text in texts]
|
||
sign = item.get('debilitated_sign')
|
||
rows.append({
|
||
'name': NEECHA_BHANGA_NAME,
|
||
'name_cn': NEECHA_BHANGA_NAME_ZH,
|
||
'category': NEECHA_BHANGA_CATEGORY,
|
||
'planets': [planet],
|
||
'combination': f'{_planet_zh(planet)}落陷于{_sign_zh(sign)};成立条件:' + ';'.join(zh),
|
||
'combination_en': f'{planet} debilitated in {sign}; conditions met: ' + '; '.join(en),
|
||
'conditions': zh,
|
||
'conditions_en': en,
|
||
'effects': [NEECHA_BHANGA_NOTE_ZH],
|
||
'effects_en': [NEECHA_BHANGA_NOTE_EN],
|
||
'strength': f'成立条件 {len(zh)} 条',
|
||
'strength_en': f'{len(zh)} condition(s) met',
|
||
'source': 'Light on Life p.295',
|
||
'rule_id': 'main_detector:neecha_bhanga',
|
||
'detector': 'yogas_doshas.calc_nicha_bhanga_raj_yoga',
|
||
# 占星师 2026-11-08 第六轮 R3:她 62791acb 的结构证据字段。月亮自参照分支按原文成立、照列,
|
||
# 但 independent_confirmation_allowed=false;全部条件都是自参照时 self_reference_only=true,
|
||
# 下游不得多算一票、不得据此提升强度 / 排序 / 置信度。
|
||
'formation_evidence': {
|
||
'planet': planet,
|
||
'cancellation_reasons': [_witness_row(cond) for cond in item.get('cancellation_conditions') or []],
|
||
'self_reference_only': bool(item.get('self_reference_only')),
|
||
'independent_condition_count': item.get('independent_cancellation_count'),
|
||
'profile': 'light_on_life_p295',
|
||
# BUG-2027:产品解释政策版本,和原始规则版本分开记。有行就说明至少一条非恒真条件成立。
|
||
'policy': item.get('policy'),
|
||
'self_witness': bool(item.get('self_witness')),
|
||
'default_rule_met': True,
|
||
# 变体条件(互换、D9、来源待核的两条)只列出,不计入成立条件,也不算独立佐证。
|
||
'variant_reasons': [_witness_row(cond, 'profile') for cond in item.get('variant_conditions') or []],
|
||
'claim_boundary': 'Cancellation is not exaltation; a self-reference branch is not independent support.',
|
||
},
|
||
})
|
||
return rows
|
||
|
||
|
||
def neecha_bhanga_variant_notes(planets: Dict[str, Any]) -> List[Dict[str, Any]]:
|
||
"""Debilitated planets for which the default rule fails and only a variant condition holds.
|
||
|
||
Not yoga rows: 「默认规则未满足;另一具名规则满足某项条件,存在方法差异」(她 2026-11-19 第 1 条).
|
||
"""
|
||
result = calc_nicha_bhanga_raj_yoga(with_navamsa(planets), {})
|
||
notes: List[Dict[str, Any]] = []
|
||
for item in result.get('variant_only') or []:
|
||
planet = item.get('planet')
|
||
texts = [_neecha_condition_text(cond, planet) for cond in item.get('variant_conditions') or []]
|
||
notes.append({
|
||
'planet': planet,
|
||
'debilitated_sign': item.get('debilitated_sign'),
|
||
'default_profile': 'light_on_life_p295',
|
||
'default_rule_met': False,
|
||
'variant_profiles': sorted({str(cond.get('profile')) for cond in item.get('variant_conditions') or []}),
|
||
'variant_conditions': [text[0] for text in texts],
|
||
'variant_conditions_en': [text[1] for text in texts],
|
||
'note': item.get('note'),
|
||
'note_en': item.get('note_en'),
|
||
})
|
||
return notes
|
||
|
||
|
||
def neecha_bhanga_literal_only_notes(planets: Dict[str, Any]) -> List[Dict[str, Any]]:
|
||
"""Debilitated planets that hit only the always-true branch (the Moon in the 1st from the Moon).
|
||
|
||
Backstage evidence only (BUG-2027, 占星师 2026-11-19 第 17 问): not yoga rows, no cancel relation,
|
||
never the basis of a Raja Yoga candidate, and nothing here is shown to the reader. The exclusion
|
||
is the product policy `neecha_bhanga_policy_v1`; the book passage does not state it.
|
||
"""
|
||
result = calc_nicha_bhanga_raj_yoga(with_navamsa(planets), {})
|
||
notes: List[Dict[str, Any]] = []
|
||
for item in result.get('literal_only') or []:
|
||
planet = item.get('planet')
|
||
texts = [_neecha_condition_text(cond, planet) for cond in item.get('literal_conditions') or []]
|
||
notes.append({
|
||
'planet': planet,
|
||
'debilitated_sign': item.get('debilitated_sign'),
|
||
'default_profile': 'light_on_life_p295',
|
||
'policy': item.get('policy'),
|
||
'default_rule_met': False,
|
||
'raw_rule_met': True,
|
||
'tautology_only': True,
|
||
'royal_yoga_candidate_allowed': False,
|
||
'literal_conditions': [_witness_row(cond) for cond in item.get('literal_conditions') or []],
|
||
'literal_conditions_zh': [text[0] for text in texts],
|
||
'literal_conditions_en': [text[1] for text in texts],
|
||
'note': item.get('note'),
|
||
'note_en': item.get('note_en'),
|
||
})
|
||
return notes
|
||
|
||
|
||
# Names as the rule registry and the card closed list spell them.
|
||
MAHAPURUSHA_ROWS = {
|
||
'Mars': ('Ruchaka Yoga', '鲁查卡格局'),
|
||
'Mercury': ('Bhadra Yoga', '巴德拉格局'),
|
||
'Jupiter': ('Hamsa Yoga', '汉萨格局'),
|
||
'Venus': ('Malavya Yoga', '马拉维亚格局'),
|
||
'Saturn': ('Sasa Yoga', '萨萨格局'),
|
||
}
|
||
EXALTATION_SIGN = {'Mars': 'Capricorn', 'Mercury': 'Virgo', 'Jupiter': 'Cancer', 'Venus': 'Pisces', 'Saturn': 'Libra'}
|
||
|
||
|
||
# BUG-2213: per-planet traditional meanings (astrologer upstream b6754475, references/yoga_rules.json
|
||
# mahapurusha_*). A meaning is the tradition's, not a promise about this person's standing.
|
||
MAHAPURUSHA_MEANING_ZH = {
|
||
'Mars': '传统含义:主动进取、领导倾向及在竞争中取得成果',
|
||
'Mercury': '传统含义:学识、条理、独立性与有系统的行事方式',
|
||
'Jupiter': '传统含义:精神力量、受到尊重及善于表达',
|
||
'Venus': '传统含义:舒适享受、健康与艺术才能',
|
||
'Saturn': '传统含义:善于洞察、喜爱游历、勇气与慈善倾向,同时可能有摇摆不定;这些不是对个人性格或未来成就的保证',
|
||
}
|
||
MAHAPURUSHA_MEANING_EN = {
|
||
'Mars': "Traditional indication: initiative, leadership, and success in contests",
|
||
'Mercury': "Traditional indication: learning, order, independence, and systematic conduct",
|
||
'Jupiter': "Traditional indication: spiritual strength, respected standing, and eloquent speech",
|
||
'Venus': "Traditional indication: comfort, health, and ability in the arts",
|
||
'Saturn': "Traditional meaning: insight, enjoyment of travel, courage and charitable tendencies, alongside possible vacillation; not a guarantee of individual character or future achievement",
|
||
}
|
||
MAHAPURUSHA_MEANING_SOURCE = {
|
||
'Mars': 'PVR Integrated Approach, p.129, Ruchaka Yoga',
|
||
'Mercury': 'PVR Integrated Approach, p.129, Bhadra Yoga',
|
||
'Jupiter': 'PVR Integrated Approach, p.130, Hamsa Yoga',
|
||
'Venus': 'PVR Integrated Approach, p.130, Malavya Yoga',
|
||
'Saturn': 'PVR Integrated Approach, pp.129-130, Sasa Yoga',
|
||
}
|
||
|
||
|
||
def pancha_mahapurusha_rows(planets: Dict[str, Any], sun_degree: Optional[float] = None) -> List[Dict[str, Any]]:
|
||
"""Formed Pancha Mahapurusha yogas (full or reduced) from the main detector."""
|
||
rows: List[Dict[str, Any]] = []
|
||
for item in detect_pancha_mahapurusha(planets or {}, sun_degree):
|
||
if not item.get('is_valid'):
|
||
continue
|
||
planet = item['planet']
|
||
name, name_cn = MAHAPURUSHA_ROWS[planet]
|
||
sign = item.get('sign')
|
||
exalted = EXALTATION_SIGN.get(planet) == sign
|
||
reductions = list(item.get('reductions') or [])
|
||
reductions_en = list(item.get('reductions_en') or [])
|
||
combination = f"{_planet_zh(planet)}在第{item.get('house')}宫{_sign_zh(sign)}({'入旺' if exalted else '入庙'})"
|
||
combination_en = f"{planet} in house {item.get('house')}, {sign} ({'exalted' if exalted else 'own sign'})"
|
||
if reductions:
|
||
combination += ';部分减弱:' + ';'.join(reductions)
|
||
combination_en += '; partly weakened: ' + '; '.join(reductions_en)
|
||
rows.append({
|
||
'name': name,
|
||
'name_cn': name_cn,
|
||
'category': 'mahapurusha',
|
||
'planets': [planet],
|
||
'combination': combination,
|
||
'combination_en': combination_en,
|
||
'reductions': reductions,
|
||
'reductions_en': reductions_en,
|
||
'd9_dignity_modifier': item.get('d9_dignity_modifier'),
|
||
# BUG-2213 (占星师 2026-11-22 一楠报告审核第 02 条): 原值五颗星同一句「卓越才能;领域领军;人格魅力」。
|
||
# 新值:每颗星用她上游 b6754475 的传统含义(来源只留在后台字段,不进读者文字)。
|
||
'effects': [MAHAPURUSHA_MEANING_ZH[planet]],
|
||
'effects_en': [MAHAPURUSHA_MEANING_EN[planet]],
|
||
'meaning_source_reference': MAHAPURUSHA_MEANING_SOURCE[planet],
|
||
'strength': '部分减弱' if reductions else '强',
|
||
'strength_en': 'partly weakened' if reductions else 'strong',
|
||
'source': 'BPHS',
|
||
'rule_id': f'main_detector:pancha_mahapurusha:{planet.lower()}',
|
||
'detector': 'pancha_mahapurusha.detect_pancha_mahapurusha',
|
||
})
|
||
return rows
|
||
|
||
|
||
def kemadruma_rows(planets: Dict[str, Any]) -> List[Dict[str, Any]]:
|
||
"""Kemadruma from `yoga_expansion.detect_kemadruma` (no kendra cancellation)."""
|
||
result = detect_kemadruma(planets or {})
|
||
if not result.get('present'):
|
||
return []
|
||
moon_sign = (planets.get('Moon') or {}).get('sign')
|
||
return [{
|
||
'name': 'Kemadruma Yoga',
|
||
'name_cn': '空劫瑜伽',
|
||
'category': 'durbhaga',
|
||
'planets': ['Moon'],
|
||
'combination': f'月亮在{_sign_zh(moon_sign)},第2、12宫无火水木金土(太阳与罗计不计;不启用角宫解除)',
|
||
'combination_en': (f'Moon in {moon_sign}; none of Mars to Saturn in the 2nd or 12th from it '
|
||
'(the Sun and the nodes are not counted; no kendra cancellation)'),
|
||
'effects': ['人生艰辛', '需自力更生', '精神挑战'],
|
||
'effects_en': ['Hard life', 'Must rely on oneself', 'Mental and spiritual challenges'],
|
||
'strength': '弱',
|
||
'strength_en': 'weak',
|
||
'source': 'BPHS',
|
||
'rule_id': 'main_detector:kemadruma',
|
||
'detector': 'yoga_expansion.detect_kemadruma',
|
||
}]
|
||
|
||
|
||
def main_detector_rows(planets: Dict[str, Any], ascendant: Optional[str] = None) -> List[Dict[str, Any]]:
|
||
"""Every main-detector row for one D1 chart, in a fixed order."""
|
||
return pancha_mahapurusha_rows(planets) + kemadruma_rows(planets) + neecha_bhanga_rows(planets)
|