Files
Jyotisha/scripts/narayana_rath.py
T
ClaudeandClaude Opus 5.5 8a958b5a65
Independent Staging Quality Gate / validate-frontend (push) Successful in 5m19s
Independent Staging Quality Gate / validate-python (push) Successful in 6m49s
Independent Staging Quality Gate / publish (push) Successful in 3m22s
fix(narayana): separate AD start step from AD direction in method_status
ad_start (小运起点) is its own step: an unresolved MD-vs-7th comparison or its
lord blocks ad_start (ad_direction not_reached); Saturn + Ketu in the MD sign
blocks ad_direction. Card step names, narayanaStepsToName, timing whitelist,
contract wording, golden (TTL=0) and fixtures updated.

占星师 2026-11-09 第七轮回复 R2 选 D;产品负责人同意 (BUG-1830)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
2026-11-09 16:21:06 +08:00

1880 lines
112 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Narayana Dasha, Sanjay Rath profile (`sanjay_rath`) — research only (BUG-1215 / BUG-1218).
Astrologer round-4 ruling (Q4): the second time axis should be Sanjay Rath's
Narayana Dasha. Round-5 ruling 2026-10-03 fixed the open points (book pages
in brackets; Sanjay Rath, *Narayana Dasa*):
Start sign = the stronger of Lagna and 7th [p.48]. General rule, seven levels,
stop at the first level that separates the two signs, no weighting [p.35-36,
p.63]:
1. more occupants (actual bodies, Rahu/Ketu included);
2. more support from three roles — Jupiter, Mercury and the sign lord — each
role counted once when the planet is in the sign or casts Rasi Drishti on
it [p.48; no graha drishti]; roles are not de-duplicated by planet
(Jupiter as Jupiter and as lord counts twice) [p.36];
3. occupant dignity: exalted > moolatrikona > own sign (whole sign) > none >
debilitated — best rank, then the number of dignified occupants; Rahu /
Ketu by Rath Table 9 (p.41-42, Phalita set; round-6 ruling Q2,
BUG-1224), debilitation below none per p.67;
4. dual > fixed > movable;
5. the lord's degree inside its sign (higher is stronger; only Ketu is
30 - degree, and Ketu at 0° compares as 30; Rahu and the seven grahas
use the raw degree, retrograde included — round-7 ruling Q3, p.71
footnote 42, BUG-1228);
6. the lord placed in a sign of the opposite parity to the sign it rules;
7. the sign giving the longer dasha.
"Contains the AK" / "lord is the AK" are not general rules [p.35]. The
Indira example (p.65-66) decides Cancer by the AK; it is kept as a flagged
book example (`book_example_exception: rath_p66_indira_ak`), used only when
all seven levels tie.
MD order: Table 10 by the start sign [p.51]; Saturn in the start sign -> zodiacal,
sign by sign (Table 11) [p.51-53]; Ketu in the start sign -> Table 10 direction
reversed, keeping the fixed / dual stepping (not the whole table read
backwards) [p.51, p.53 Table 12; p.54 Table 14 is the AD table]. Saturn and
Ketu both in the start sign: Ketu first (PyJHora's practice, product owner
ruling 2026-10-03, `method_note`).
Years: `jaimini_odd_footed_dignity_v2` count, then exalted +1 / debilitated
-1. The seven grahas use the frozen dignity table. Rahu / Ketu use the
Phalita pair (Rahu exalted Gemini / debilitated Sagittarius, Ketu the
reverse) and are clamped to 0–12 (p.40 (a), round-7, BUG-1229). Scorpio /
Aquarius lords follow book p.43 (a)–(e) with the round-7 ruling (option A):
(d) compares the signs the two lords occupy with this module's seven
levels; (c) counts only Scorpio / Aquarius themselves, not Mars in Aries or
Saturn in Capricorn; same-sign identity uses the level-5 degree rule and
returns undecided on an exact tie (BUG-1227). Cycle 2 = 12 minus cycle 1.
AD [p.48 Arambha Rasi, p.50 note 2]: compare the MD sign and its 7th with the
same seven levels, take the stronger, start from the sign holding that sign's
lord (dual lords by the same rule), twelve equal parts. Order: Table 13 from
the start sign (direction by the start sign's odd/even, as in Table 25;
round-6 ruling Q7); Saturn in the MD sign -> Table 11 (zodiacal); Ketu in the
MD sign -> Table 14 (Ketu first when both) [p.51]. The book's other two
statements (p.47 J.S. 1.1.34: by the MD sign; J.S. 2.4.31-32: by the MD sign
or its lord's sign) disagree with Table 25; each AD rule carries them as
`direction.book_divergence` (BUG-1225), not applied.
Ported verbatim from upstream yinduzhanxing c7117f92 `scripts/narayana_dasha.py`:
`_rath_ketu_table12_sequence` (the `rath_ketu_table12_v1` branch of
`build_narayana_sign_sequence`), `_RATH_CLASSICAL_MOOLATRIKONA_SIGNS`, and the
level 1-2 counting of `select_narayana_seed_sign(strength_profile=
"rath_p36_role_conjunction_v1")` (`_role_candidate`; tests compare it with the
upstream function). Tables 10 / 11 / 13 / 14, `_rasi_aspects`, the year and
dual-lord functions are the same in both repositories and are reused from the
frozen local `narayana_dasha.py`, which this module does not modify.
Table 18 (Indira) is a book-internal contradiction (BOOK_EXAMPLES): the
general rule's Capricorn is output as is; the book's Cancer only with the
start sign given explicitly and flagged (product owner, 2026-10-03 evening).
Not wired into scoring.
"""
from __future__ import annotations
from typing import Any, Dict, List, Optional, Tuple
try: # scripts/ on sys.path
import narayana_dasha as nd
from jaimini import calc_chara_karaka_8
except ImportError: # pragma: no cover - package import
from scripts import narayana_dasha as nd
from scripts.jaimini import calc_chara_karaka_8
PROFILE = "sanjay_rath"
DURATION_PROFILE = "jaimini_odd_footed_dignity_v2"
DUAL_LORD_PROFILE = "rath_p43_text_first_round7_v1"
P43_SOURCE = "p.43; p.116; p.71 fn 42; Jaimini course p.276"
P43_VERSION_ZH = "按原书 p.43 正文(第七轮裁定)"
P43_VERSION_EN = "Book p.43 text (round-7 ruling)"
_DUAL_PAIRS = {7: ("Mars", "Ketu"), 10: ("Saturn", "Rahu")}
ROLE_PROFILE = "rath_p36_role_conjunction_v1"
INDIRA_EXCEPTION = "rath_p66_indira_ak"
# Book examples whose printed start sign the general rule does not give.
# Product owner ruling 2026-10-03 (evening, red line 3 revised): reproduce
# them only with the start sign given explicitly, flagged; never by code that
# bends the general rule.
BOOK_EXAMPLES = {
INDIRA_EXCEPTION: {
"book_table": "Table 18",
"book_start_sign": "Cancer",
"book_internal_contradiction": True,
"evidence": ("Hand example (PDF Page 62; astrologer cites p.65-66) concludes Cancer because "
"'Saturn is the Atmakaraka and has gained the highest longitude', but Saturn sits in "
"Cancer and rules Capricorn, so rules 5 and 6 read literally point to Capricorn; the "
"book's own software verdict for the same native (Table 27) also has Capricorn "
"stronger than Cancer. Audit docs/research/shared_engine_reuse_audit_2026_10_03.md N1."),
},
}
# Book software verdicts the general rule does not follow (round-6 ruling
# Q6b, BUG-1226): Table 25 (Krishnaraja Wadiyar IV) takes Gemini over
# Sagittarius and Virgo over Pisces; the seven general levels decide
# Sagittarius / Pisces at level 5 (Mercury 1.3 deg vs Jupiter 10.0 deg). Only
# the book software's Rule 8 at the seventh level separates them that way — a
# software special case. The general result is kept and every output carries
# this note.
BOOK_SOFTWARE_RULE8 = "book_software_rule8_exception"
BOOK_SOFTWARE_DIFFERENCES = {
BOOK_SOFTWARE_RULE8: {
"book_table": "Table 25",
"pairs": [{"book": "Gemini", "general_rule": "Sagittarius", "general_level": 5},
{"book": "Virgo", "general_rule": "Pisces", "general_level": 5}],
"kept": "general_rule",
"note": "原书软件判定差异:原书软件用第 7 级 Rule 8 取双子、处女;通则第 5 级取射手、双鱼,保持通则",
"note_en": ("Book software verdict differs: the book's software used Rule 8 at the seventh level to take "
"Gemini and Virgo; the general rule takes Sagittarius and Pisces at level 5 and is kept"),
"ruling": "astrologer round 6, 2026-10-04, Q6b (p.36, p.95)",
},
}
# 原值:「PyJHora 兼容:计都优先」,土星与计都同宫时默认计都优先(产品负责人 2026-10-03)。
# 新值:默认 blocked(saturn_ketu_priority_unresolved);计都优先只在明确选中
# `pyjhora_ketu_priority_compat_v1` 时用,并标「非原典优先级证据」。
# 原因:占星师 2026-11-08 第五轮逐项答复 N4:原书没有规定计都或土星优先。
KETU_FIRST_NOTE = "PyJHora 兼容:计都优先(非原典优先级证据)"
KETU_FIRST_NOTE_EN = "PyJHora-compatible: Ketu takes precedence (not canonical priority evidence)"
SATURN_KETU_BLOCKED = "saturn_ketu_priority_unresolved"
SATURN_KETU_DEFAULT = "rath_saturn_ketu_unresolved_v1"
KETU_PRIORITY_PROFILE = "pyjhora_ketu_priority_compat_v1"
SATURN_KETU_PROFILES = (SATURN_KETU_DEFAULT, KETU_PRIORITY_PROFILE)
SOURCE = {
"book": "Sanjay Rath, Narayana Dasa",
"start_sign": "p.48 (stronger of Lagna / 7th); levels p.35-36, p.63; Rasi Drishti p.48",
"md_order": "p.51 Table 10; Saturn p.51-53 Table 11; Ketu p.51, p.53 Table 12",
"ad": "p.48 Arambha Rasi, p.50 note 2; Tables 13 / 11 / 14 (p.54)",
"indira_example": "p.65-66 (AK), Table 18 p.67",
"ruling": "astrologer round 5, 2026-10-03, Q1-Q4; round 6, 2026-10-04, Q2 (node dignity); round 7, 2026-10-04, Q1 option A (p.43), Q3 (only Ketu reversed); 2026-11-08 round-5 item reply N1-N5 (highest occupant tier, AD direction profiles, 0-year rows, Saturn + Ketu blocked, Table 8 years)",
"dual_lord": P43_SOURCE,
"dual_lord_version": P43_VERSION_ZH,
"dual_lord_version_en": P43_VERSION_EN,
"node_dignity": "Table 9 p.41-42 (Phalita exaltation Rahu Gemini / Ketu Sagittarius); debilitated weaker p.67",
"port": "upstream yinduzhanxing c7117f92 scripts/narayana_dasha.py",
}
SIGNS = nd.SIGNS
SIGN_LORDS = nd.SIGN_LORDS
GRAHAS = ("Sun", "Moon", "Mars", "Mercury", "Jupiter", "Venus", "Saturn", "Rahu", "Ketu")
LEVELS = (
"occupant_count",
"role_conjunction_or_rasi_aspect",
"occupant_dignity",
"modality",
"lord_degree_in_sign",
"lord_opposite_parity",
"longer_dasha",
)
# Ported from upstream c7117f92 (Rath p80, whole-sign scope).
_RATH_CLASSICAL_MOOLATRIKONA_SIGNS = dict(Sun=4, Moon=1, Mars=0,
Mercury=5, Jupiter=8, Venus=6, Saturn=10) # Rath p80, whole-sign scope.
def _rath_ketu_table12_sequence(seed_sign_idx: int) -> List[int]:
# Ported from upstream c7117f92 build_narayana_sign_sequence,
# profile "rath_ketu_table12_v1".
# Rath pp.53-54 Table12 note: reverse Table10 direction, retain motion.
return [(2 * seed_sign_idx - sign) % 12
for sign in nd._NARAYANA_RATH_GENERAL_SEQUENCE[seed_sign_idx]]
def _grahas(planet_lons: Dict[str, float]) -> Dict[str, float]:
return {planet: float(planet_lons[planet]) for planet in GRAHAS if planet_lons.get(planet) is not None}
def _strength_degree(planet: str, lon: float) -> float:
"""Degree used when a higher value is stronger (BUG-1228, round-7 Q3).
Grahas and Rahu keep the raw degree inside the sign. Only Ketu is
reversed (p.71 footnote 42). Ketu at 0° compares as 30, not 0.
"""
degree = float(lon) % 30.0
if planet == "Ketu":
return 30.0 - degree
return degree
def _ck_degree(planet: str, lon: float) -> float:
return _strength_degree(planet, lon)
def rath_period_years(sign_idx: int, lord: str, lord_sign_idx: int) -> Dict[str, Any]:
"""Base years, dignity adjustment and final years (BUG-1229).
The count is the frozen odd/even-footed duration. Graha exaltation /
debilitation stays in `calculate_narayana_period_years`. Rahu / Ketu add
or subtract one year on the Phalita exaltation pair only, then clamp to
0–12 (p.40 (a)).
"""
base = nd.calculate_narayana_duration(sign_idx, lord_sign_idx, profile=DURATION_PROFILE)
if lord in RATH_NODE_DIGNITY:
table = RATH_NODE_DIGNITY[lord]
if lord_sign_idx in table["exalted"]:
adjustment = 1
elif lord_sign_idx in table["debilitated"]:
adjustment = -1
else:
adjustment = 0
source = "p40a_phalita_nodes"
years = max(0, min(12, base + adjustment))
else:
years, adjustment = nd.calculate_narayana_period_years(
sign_idx, lord, lord_sign_idx, profile=DURATION_PROFILE)
source = "p40a_grahas"
return {
"lord": lord,
"base_years": base,
"dignity_adjustment": adjustment,
"years": years,
"adjustment_source": source,
}
_BASIS = {
"a": (
"两主都在本宫,年数 12;身份按同宫经度,只倒算计都",
"Both lords are in the sign, so the period is 12 years; identity is by same-sign degree, and only Ketu is reversed",
),
"b": (
"两主同在另一宫,年数数到该宫;身份按同宫经度,只倒算计都",
"Both lords share another sign, so the years are counted to it; identity is by same-sign degree, and only Ketu is reversed",
),
"c": (
"一主在天蝎或水瓶本宫,取在外面的那颗;火星在白羊、土星在摩羯不算本宫",
"One lord is in Scorpio or Aquarius itself, so the lord outside it is taken; Mars in Aries and Saturn in Capricorn do not count as that own sign",
),
"d": (
"两主分落别的星座,按七级比较所落星座",
"The two lords occupy different signs, compared on the seven strength levels",
),
"e": (
"两主所落星座七级全平,取年数较多的一颗",
"The occupied signs tie on all seven levels, so the lord giving more years is taken",
),
}
def _dual_decision(*, status: str, rule: Optional[str], lord: Optional[str], compared: List[Dict[str, Any]],
strength_level_decided: Optional[int] = None, reason: Optional[str] = None,
period: Optional[Dict[str, Any]] = None, identity_rule: Optional[str] = None,
length_branches: Optional[List[Dict[str, Any]]] = None) -> Dict[str, Any]:
if reason == "resolution_cycle":
zh, en = ("双主星判定遇到循环,返回未决", "Dual-lord resolution hit a cycle and stays undecided")
elif rule is None:
zh, en = ("", "")
else:
zh, en = _BASIS.get(rule, ("双主星未决", "Dual lord undecided"))
if rule == "d" and strength_level_decided and lord:
zh = f"{zh},第 {strength_level_decided} 级取 {lord}"
en = f"{en}; level {strength_level_decided} takes {lord}"
elif lord and rule in {"a", "b", "c", "e"}:
zh = f"{zh},取 {lord}"
en = f"{en}; takes {lord}"
return {
"status": status,
"rule": rule,
"identity_rule": identity_rule,
"lord": lord,
"compared": compared,
"strength_level_decided": strength_level_decided,
"basis_text": zh,
"basis_text_en": en,
"source": P43_SOURCE,
"reason": reason,
"period": period,
# R2 (占星师 2026-11-08 第六轮): an undecided lord keeps each candidate's length.
"length_branches": length_branches,
}
def _same_sign_identity(first: str, second: str, planet_lons: Dict[str, float]) -> Dict[str, Any]:
"""p.116 plus p.71 footnote 42. Exact equality stays undecided."""
first_degree = _strength_degree(first, planet_lons[first])
second_degree = _strength_degree(second, planet_lons[second])
if first_degree == second_degree:
return {"status": "undecided", "lord": None, "reason": "equal_degree",
"degrees": {first: first_degree, second: second_degree}}
winner = first if first_degree > second_degree else second
return {"status": "selected", "lord": winner, "reason": None,
"degrees": {first: first_degree, second: second_degree}}
def resolve_dual_lord(sign_idx: int, planet_lons: Dict[str, float], *,
strength_scope: Optional[str] = None,
_resolution_path: Tuple[int, ...] = ()) -> Dict[str, Any]:
"""p.43 (a)–(e) for Scorpio / Aquarius. Other signs return their one lord.
Comparing the signs the two lords occupy can ask for another dual lord.
A sign already on `_resolution_path` stays undecided instead of looping.
"""
lons = _grahas(planet_lons)
pair = _DUAL_PAIRS.get(sign_idx)
if pair is None:
lord = SIGN_LORDS[SIGNS[sign_idx]]
return _dual_decision(status="selected", rule=None, lord=lord, compared=[], period=None)
if sign_idx in _resolution_path:
return _dual_decision(status="undecided", rule=None, lord=None, compared=[], reason="resolution_cycle")
path = _resolution_path + (sign_idx,)
first, second = pair
first_sign = nd._get_planet_sign(first, lons)
second_sign = nd._get_planet_sign(second, lons)
if first_sign is None or second_sign is None:
return _dual_decision(status="selected", rule=None, lord=SIGN_LORDS[SIGNS[sign_idx]], compared=[],
reason="longitude_missing")
compared = [
{"lord": first, "sign": SIGNS[first_sign], "sign_idx": first_sign},
{"lord": second, "sign": SIGNS[second_sign], "sign_idx": second_sign},
]
home_first = first_sign == sign_idx
home_second = second_sign == sign_idx
if home_first and home_second:
identity = _same_sign_identity(first, second, lons)
period = {"lord": identity["lord"], "base_years": 12, "dignity_adjustment": 0, "years": 12,
"adjustment_source": "p43a_both_in_sign"}
return _dual_decision(status=identity["status"], rule="a", lord=identity["lord"], compared=compared,
reason=identity["reason"], period=period, identity_rule="p116_longitude")
if first_sign == second_sign:
identity = _same_sign_identity(first, second, lons)
if identity["status"] != "selected":
left = rath_period_years(sign_idx, first, first_sign)
right = rath_period_years(sign_idx, second, second_sign)
period = left if left["years"] == right["years"] else None
if period is not None:
period = {**period, "lord": None}
return _dual_decision(status="undecided", rule="b", lord=None, compared=compared,
reason="equal_degree", period=period, identity_rule="p116_longitude",
length_branches=[left, right])
period = rath_period_years(sign_idx, identity["lord"], first_sign)
return _dual_decision(status="selected", rule="b", lord=identity["lord"], compared=compared,
period=period, identity_rule="p116_longitude")
if home_first != home_second:
lord = second if home_first else first
lord_sign = second_sign if home_first else first_sign
return _dual_decision(status="selected", rule="c", lord=lord, compared=compared,
period=rath_period_years(sign_idx, lord, lord_sign))
comparison = compare_signs(first_sign, second_sign, lons, strength_scope=strength_scope,
_resolution_path=path)
if comparison["status"] == "selected":
winner = comparison["selected_sign_idx"]
lord = first if first_sign == winner else second
return _dual_decision(status="selected", rule="d", lord=lord, compared=compared,
strength_level_decided=comparison["strength_level_decided"],
period=rath_period_years(sign_idx, lord, winner))
if comparison["status"] == "undecided":
# 原值:(d) 的比较 unresolved 时 period 为空,该宫年数整段未决。
# 新值:unresolved(规则 / 输入不足)不进 (e);但两个候选主星给出的年数相同时保留该年数(主星身份仍未决)。
# 原因:占星师 2026-11-08 第六轮 R2:主星身份未决但候选年长相同 → 保留年长,阻塞依赖身份的小运 / 解释。
left = rath_period_years(sign_idx, first, first_sign)
right = rath_period_years(sign_idx, second, second_sign)
period = {**left, "lord": None} if left["years"] == right["years"] else None
return _dual_decision(status="undecided", rule="d", lord=None, compared=compared,
reason=comparison.get("reason") or "dual_lord_unresolved", period=period,
length_branches=[left, right])
left = rath_period_years(sign_idx, first, first_sign)
right = rath_period_years(sign_idx, second, second_sign)
if left["years"] == right["years"]:
return _dual_decision(status="undecided", rule="e", lord=None, compared=compared, reason="equal_years",
period={**left, "lord": None})
period = left if left["years"] > right["years"] else right
return _dual_decision(status="selected", rule="e", lord=period["lord"], compared=compared, period=period)
def _lord(sign_idx: int, planet_lons: Dict[str, float], *, strength_scope: Optional[str] = None,
_resolution_path: Tuple[int, ...] = ()) -> Optional[str]:
return resolve_dual_lord(sign_idx, planet_lons, strength_scope=strength_scope,
_resolution_path=_resolution_path).get("lord")
def _role_candidate(sign_idx: int, planet_lons: Dict[str, float], lord: str) -> Dict[str, Any]:
"""Levels 1-2 for one sign: upstream `select_narayana_seed_sign` with
strength_profile="rath_p36_role_conjunction_v1" (c7117f92), per sign."""
occupants = sorted(
planet
for planet in planet_lons
if nd._get_planet_sign(planet, planet_lons) == sign_idx
)
aspect_factors = []
role_factors = []
roles = (("jupiter", "Jupiter"), ("mercury", "Mercury"), ("sign_lord", lord))
for role, planet in roles:
planet_sign_idx = nd._get_planet_sign(planet, planet_lons)
conjunction = planet_sign_idx == sign_idx
if planet_sign_idx is not None and (conjunction or nd._rasi_aspects(planet_sign_idx, sign_idx)):
aspect_factors.append(planet)
role_factors.append(dict(role=role, planet=planet, contact="conjunction" if conjunction else "rasi_aspect"))
return {
"sign": SIGNS[sign_idx],
"lord": lord,
"occupants": occupants,
"occupant_count": len(occupants),
"aspect_factors": aspect_factors,
"aspect_factor_count": len(aspect_factors),
"role_factors": role_factors,
}
# Rahu / Ketu dignity inside Rath Narayana only (round-6 ruling Q2, Rath
# Table 9 p.41-42): own sign Rahu Aquarius / Ketu Scorpio; moolatrikona Rahu
# Virgo / Ketu Pisces; exaltation for Phalita dasas such as Narayana Rahu
# Gemini / Ketu Sagittarius (the Taurus / Scorpio pair is for Ayur dasas
# only), debilitation in the opposite signs. Not the natal dignity table
# (BUG-1211 "nodes have no own sign" still holds on the D1 main path).
RATH_NODE_DIGNITY = {
"Rahu": {"exalted": {2}, "moolatrikona": 5, "own": {10}, "debilitated": {8}},
"Ketu": {"exalted": {8}, "moolatrikona": 11, "own": {7}, "debilitated": {2}},
}
DEBILITATED_RANK = -1
OWN_RANK = 1
# Rule 3 (occupant dignity) as a named, conditional engineering convention
# (占星师 2026-11-08 第五轮逐项答复 N1). p.34 Rule 3 lists exaltation /
# Moolatrikona / own sign but gives no formula for several occupants; "highest
# tier first" is an implementation convention, not a literal canonical
# algorithm. Tiers: the seven grahas plus the book's Rahu / Ketu exaltation /
# Moolatrikona / own signs (RATH_NODE_DIGNITY). When both signs' highest tier
# is below own sign and equal, the friend / enemy tiers that could separate them
# are not implemented: the comparison is blocked, never passed on to Rule 4.
RULE3_PROFILE = "rath_highest_occupant_dignity_v1"
RULE3_BLOCKED = "rule3_highest_tier_below_own_sign_tied"
RULE3_CONVENTION = {
"profile": RULE3_PROFILE,
"kind": "named_conditional_engineering_convention",
"source": "Rath p.34 Rule 3 (exaltation, Moolatrikona, own sign); no multi-planet aggregation formula in the book",
"rule": ("compare the highest occupant tier (exalted 3 > moolatrikona 2 > own 1 > other 0 > debilitated -1); "
"equal highest tier at own sign or above: the number of dignified occupants (convention, not closed), "
"then the next level; equal highest tier below own sign: blocked"),
"not_implemented": ["friend / neutral / enemy tiers", "full seven-tier aggregation"],
"ruling": "astrologer 2026-11-08 round-5 item reply N1",
}
# R2 (占星师 2026-11-08 第六轮): one strength profile wherever the source compares two signs.
# 原值:Rule 3 「最高档低于本宫且相同」只在起运比较 blocked;小运起点(大运宫对第 7 宫)与 p.43 (d)
# 双主星所落星座照旧进入第 4 级(rule3_tie_below_own_passed_through)。
# 新值:默认 `seed_ad_start_p43d_v1`:三处同一 profile,该情形都是 unresolved(不当作相等);
# 旧范围 `seed_only_v0` 保留为具名 profile,只供重放旧结果与对照。
# 原因:占星师 2026-11-08 第六轮 R2:不能在起运承认低档未实现,换到 AD 或双主星年数就把未知当相等。
STRENGTH_PROFILE = RULE3_PROFILE
STRENGTH_SCOPE_ALL = "seed_ad_start_p43d_v1"
STRENGTH_SCOPE_SEED_ONLY = "seed_only_v0"
STRENGTH_SCOPES = (STRENGTH_SCOPE_ALL, STRENGTH_SCOPE_SEED_ONLY)
# 原值(2):STRENGTH_SCOPE_DEFAULT = STRENGTH_SCOPE_ALL(`seed_ad_start_p43d_v1`)
# 新值(2):STRENGTH_SCOPE_DEFAULT = STRENGTH_SCOPE_SEED_ONLY(`seed_only_v0`);R2 代码(局部传播、
# selected / equal / unresolved 状态)全部保留,`seed_ad_start_p43d_v1` 作为具名非默认 profile;
# profile_config / 缓存键随 DEFAULT_STEP_PROFILES 记 strength_scope = seed_only_v0。R1(p.50 小运方向)、R3 不变。
# 原因(2):产品负责人 2026-11-09:R2 范围扩大待占星师裁定,暂按 seed_only_v0(BUG-1784)。
# 原值(3):STRENGTH_SCOPE_DEFAULT = STRENGTH_SCOPE_SEED_ONLY(`seed_only_v0`)
# 新值(3):STRENGTH_SCOPE_DEFAULT = STRENGTH_SCOPE_ALL(`seed_ad_start_p43d_v1`):起运、AD 起点、p43(d) 用同一强弱规则;
# 未决不当相等,具名候选另列在 `narayana_branches`(R2 选 D);`seed_only_v0` 只作「条件性旧版分支」
# (假设跳过 Rule 3 时的结果),不覆盖主状态、不独立加票。
# 原因(3):占星师 2026-11-09 第七轮回复 R2 选 D;产品负责人同意(BUG-1829)。
STRENGTH_SCOPE_DEFAULT = STRENGTH_SCOPE_ALL
def _occupant_dignity(planet: str, sign_idx: int) -> int:
"""Level 3 rank: exalted 3 > moolatrikona 2 > own 1 > none 0 > debilitated -1.
Debilitated below none: p.67 (Indira, Table 18) "Ketu is debilitated and
as per Rule (3) of first source of strength is weaker than Mars" (Mars in
Leo, no dignity). Applied to all nine bodies (Rule 3 is general).
"""
node = RATH_NODE_DIGNITY.get(planet)
if node is not None:
exalted, moolatrikona, own, debilitated = node["exalted"], node["moolatrikona"], node["own"], node["debilitated"]
else:
table = nd._NARAYANA_DIGNITY.get(planet)
if table is None:
return 0
exalted, debilitated = table["exalted"], table["debilitated"]
moolatrikona = _RATH_CLASSICAL_MOOLATRIKONA_SIGNS[planet]
own = {idx for idx, sign in enumerate(SIGNS) if SIGN_LORDS[sign] == planet}
if sign_idx in exalted:
return 3
if sign_idx == moolatrikona:
return 2
if sign_idx in own:
return 1
if sign_idx in debilitated:
return DEBILITATED_RANK
return 0
def sign_strength(sign_idx: int, planet_lons: Dict[str, float], *, strength_scope: Optional[str] = None,
_resolution_path: Tuple[int, ...] = (),
_forced_lords: Optional[Dict[int, str]] = None) -> Dict[str, Any]:
"""All seven level values for one sign (see module docstring)."""
lons = _grahas(planet_lons)
if _forced_lords and sign_idx in _forced_lords:
# Common-field test only (seed_comparison): this sign's lord is assumed, never decided here.
decision = {"status": "assumed", "lord": _forced_lords[sign_idx], "rule": "forced_candidate", "compared": [],
"period": None}
else:
decision = resolve_dual_lord(sign_idx, lons, strength_scope=strength_scope, _resolution_path=_resolution_path)
lord = decision.get("lord")
row = _role_candidate(sign_idx, lons, lord or SIGN_LORDS[SIGNS[sign_idx]])
row["dual_lord_decision"] = decision
row["lord_undecided"] = not lord
if not lord:
row["lord"] = None
row["role_factors"] = []
row["aspect_factors"] = []
row["aspect_factor_count"] = None
ranks = {planet: _occupant_dignity(planet, sign_idx) for planet in row["occupants"]}
best = max(ranks.values(), default=0)
dignified = sum(1 for value in ranks.values() if value > 0)
debilitated = sum(1 for value in ranks.values() if value == DEBILITATED_RANK)
lord_sign_idx = nd._get_planet_sign(lord, lons) if lord else None
if lord_sign_idx is None:
lord_sign_idx = sign_idx
period = rath_period_years(sign_idx, lord, lord_sign_idx) if lord else None
years = period["years"] if period else None
degree = _strength_degree(lord, lons[lord]) if lord and lord in lons else None
row.update({
"occupant_dignity": {"ranks": ranks, "best_rank": best, "dignified_count": dignified,
"debilitated_count": debilitated},
"modality": "dual" if sign_idx in (2, 5, 8, 11) else "fixed" if sign_idx in nd._FIXED_SIGNS else "movable",
"lord_sign": SIGNS[lord_sign_idx] if lord else None,
"lord_degree_in_sign": degree,
"lord_opposite_parity": (lord_sign_idx % 2 != sign_idx % 2) if lord else None,
"dasha_years": years,
"period": period,
})
row["level_values"] = [
row["occupant_count"],
row["aspect_factor_count"],
(best, dignified),
{"movable": 0, "fixed": 1, "dual": 2}[row["modality"]],
degree if degree is not None else -1.0,
int(row["lord_opposite_parity"] or False),
years if years is not None else -1,
]
return row
def _rule3(first: Dict[str, Any], second: Dict[str, Any]) -> Optional[Any]:
"""`rath_highest_occupant_dignity_v1`: 0 / 1 = winner position, None = no separation, "blocked"."""
if not first["occupant_count"] and not second["occupant_count"]:
return None # Rule 3 is about occupants; two empty signs go on to the next level
a, b = first["occupant_dignity"], second["occupant_dignity"]
if a["best_rank"] != b["best_rank"]:
return 0 if a["best_rank"] > b["best_rank"] else 1
if a["best_rank"] < OWN_RANK:
return "blocked"
if a["dignified_count"] != b["dignified_count"]:
return 0 if a["dignified_count"] > b["dignified_count"] else 1
return None
def _atmakaraka(planet_lons: Dict[str, float]) -> Optional[str]:
lons = {planet: lon for planet, lon in _grahas(planet_lons).items() if planet != "Ketu"}
table = calc_chara_karaka_8(lons).get("karaka_table_8") or {}
for row in table.values():
if row.get("rank") == 1:
return row.get("planet")
return None
def compare_signs(first_idx: int, second_idx: int, planet_lons: Dict[str, float],
*, allow_book_example: bool = False, rule3_block: bool = False,
strength_scope: Optional[str] = None,
_resolution_path: Tuple[int, ...] = (),
_forced_lords: Optional[Dict[int, str]] = None) -> Dict[str, Any]:
"""Stronger of two signs by the seven general levels.
`allow_book_example`: only when all seven tie, the Indira example's AK
tie-break may decide; the result then carries `book_example_exception`.
`rule3_block` (the seed comparison, N1): equal highest occupant tier below
own sign -> undecided.
`strength_scope` (R2, 占星师 2026-11-08 第六轮): under the named non-default
`STRENGTH_SCOPE_ALL` the same strength profile, Rule 3 block included, runs in
every comparison (seed, AD start = MD sign vs 7th, p.43 (d) dual-lord signs).
`STRENGTH_SCOPE_SEED_ONLY` (the default again since 2026-11-09, pending the
astrologer's ruling on R2; also the pre-R2 default) blocks only
where `rule3_block` is passed (the seed); elsewhere the tie passes on to Rule 4
and says so in `rule3_tie_below_own_passed_through` (BUG-1768).
Result status: `selected` (a level separated them; lower levels never run and
never block), `tie` (all seven levels fully computed and equal = `equal`),
`undecided` (a rule or input is missing = `unresolved`, never treated as equal).
Two empty signs skip Rule 3 (it compares occupants) and go on to Rule 4 — the
source's empty-sign path, not "both dignities 0".
"""
scope = strength_scope or STRENGTH_SCOPE_DEFAULT
if scope not in STRENGTH_SCOPES:
raise ValueError(f"unknown strength scope: {scope}")
rule3_block = rule3_block or scope == STRENGTH_SCOPE_ALL
candidates = {
first_idx: sign_strength(first_idx, planet_lons, strength_scope=scope, _resolution_path=_resolution_path,
_forced_lords=_forced_lords),
second_idx: sign_strength(second_idx, planet_lons, strength_scope=scope, _resolution_path=_resolution_path,
_forced_lords=_forced_lords),
}
base = {"candidates": {SIGNS[idx]: row for idx, row in candidates.items()},
"book_example_exception": None, "rule3_tie_below_own_passed_through": False,
"strength_profile": STRENGTH_PROFILE, "strength_scope": scope}
for level, name in enumerate(LEVELS):
if level >= 1 and (candidates[first_idx].get("lord_undecided") or candidates[second_idx].get("lord_undecided")):
return {**base, "status": "undecided", "reason": "dual_lord_unresolved",
"strength_level_decided": None, "strength_level_name": None, "blocked_level": level + 1,
"comparison_status": "unresolved"}
if level == 2:
outcome = _rule3(candidates[first_idx], candidates[second_idx])
if outcome == "blocked" and not rule3_block:
base["rule3_tie_below_own_passed_through"] = True
continue
if outcome == "blocked":
# 原值:两边最高档同为「无尊贵」或同为落陷时打平,进入第 4 级(星座性质)。
# 新值:blocked(rule3_highest_tier_below_own_sign_tied),不进入后面各级。
# 原因:占星师 2026-11-08 第五轮逐项答复 N1:较低的友敌档未实现,不能假装已比较。
return {**base, "status": "undecided", "reason": RULE3_BLOCKED, "rule3_profile": RULE3_PROFILE,
"strength_level_decided": None, "strength_level_name": None, "blocked_level": 3,
"comparison_status": "unresolved"}
if outcome is None:
continue
winner = first_idx if outcome == 0 else second_idx
return {**base, "status": "selected", "selected_sign_idx": winner, "selected_sign": SIGNS[winner],
"strength_level_decided": level + 1, "strength_level_name": name, "rule3_profile": RULE3_PROFILE,
"comparison_status": "selected"}
a = candidates[first_idx]["level_values"][level]
b = candidates[second_idx]["level_values"][level]
if a != b:
winner = first_idx if a > b else second_idx
return {**base, "status": "selected", "selected_sign_idx": winner, "selected_sign": SIGNS[winner],
"strength_level_decided": level + 1, "strength_level_name": name, "comparison_status": "selected"}
if allow_book_example:
ak = _atmakaraka(planet_lons)
holders = [idx for idx in (first_idx, second_idx) if ak and nd._get_planet_sign(ak, planet_lons) == idx]
if len(holders) == 1:
winner = holders[0]
return {**base, "status": "selected", "selected_sign_idx": winner, "selected_sign": SIGNS[winner],
"strength_level_decided": None, "strength_level_name": "book_example_atmakaraka",
"book_example_exception": INDIRA_EXCEPTION, "atmakaraka": ak}
return {**base, "status": "tie", "reason": "all_seven_general_levels_tie",
"strength_level_decided": None, "strength_level_name": None, "comparison_status": "equal"}
SEED_COMMON_FIELD = "common_across_dual_lord_candidates"
def seed_comparison(lagna_sign_idx: int, planet_lons: Dict[str, float], *, strength_scope: Optional[str] = None,
allow_book_example: bool = False) -> Dict[str, Any]:
"""The seed comparison (Lagna vs 7th, Rule 3 block on), with her common-field rule.
占星师 2026-11-09 第七轮回复 §1:「若所有合法分支在某一字段上相同,可以保留这个公共字段,但不能顺带确定
主星身份、完整时间轴或其他分支。」When the comparison is unresolved only because a dual sign's lord
(Scorpio / Aquarius, p.43) is undecided, it is re-run with each candidate lord assumed. If every
candidate gives the same seed sign, that sign is kept (`seed_common_field`); the lord identity stays
unresolved (`lord_identity_unresolved`), and what depends on it (that sign's MD length, ADs from it)
is still decided -- or branched -- by its own step. Otherwise the comparison stays unresolved.
"""
seventh = (lagna_sign_idx + 6) % 12
selection = compare_signs(lagna_sign_idx, seventh, planet_lons, allow_book_example=allow_book_example,
rule3_block=True, strength_scope=strength_scope)
if selection.get("status") != "undecided" or selection.get("reason") != "dual_lord_unresolved":
return selection
undecided = [SIGNS.index(sign) for sign, row in selection["candidates"].items() if row.get("lord_undecided")]
choices: List[Dict[int, str]] = [{}]
for sign_idx in undecided:
pair = _DUAL_PAIRS.get(sign_idx)
if not pair:
return selection
choices = [{**choice, sign_idx: lord} for choice in choices for lord in pair]
outcomes = {}
for choice in choices:
forced = compare_signs(lagna_sign_idx, seventh, planet_lons, allow_book_example=allow_book_example,
rule3_block=True, strength_scope=strength_scope, _forced_lords=choice)
label = ",".join(f"{SIGNS[idx]}={lord}" for idx, lord in sorted(choice.items()))
outcomes[label] = {"status": forced["status"], "selected_sign": forced.get("selected_sign"),
"strength_level_decided": forced.get("strength_level_decided"),
"reason": forced.get("reason")}
signs = {row["selected_sign"] for row in outcomes.values() if row["status"] == "selected"}
if len(signs) != 1 or any(row["status"] != "selected" for row in outcomes.values()):
return {**selection, "dual_lord_candidate_outcomes": outcomes}
sign = signs.pop()
levels = {row["strength_level_decided"] for row in outcomes.values()}
return {**selection, "status": "selected", "comparison_status": "selected",
"selected_sign_idx": SIGNS.index(sign), "selected_sign": sign,
"strength_level_decided": levels.pop() if len(levels) == 1 else None,
"strength_level_name": SEED_COMMON_FIELD, "reason": None,
"seed_common_field": {"seed_sign": sign, "rule": SEED_COMMON_FIELD,
"lord_identity_unresolved": [SIGNS[idx] for idx in undecided],
"candidate_outcomes": outcomes,
"source": "占星师 2026-11-09 第七轮回复 §1(公共字段)"}}
def md_order(seed_sign_idx: int, planet_lons: Dict[str, float], *,
saturn_ketu: str = SATURN_KETU_DEFAULT) -> Dict[str, Any]:
"""MD sign order for one start sign, with the exception that decided it.
Saturn and Ketu both in the start sign: `status: blocked`
(`saturn_ketu_priority_unresolved`) unless `saturn_ketu` names the
PyJHora-compatible Ketu-priority profile (not canonical priority evidence).
"""
saturn = nd._get_planet_sign("Saturn", planet_lons) == seed_sign_idx
ketu = nd._get_planet_sign("Ketu", planet_lons) == seed_sign_idx
method_note = None
if saturn and ketu and saturn_ketu != KETU_PRIORITY_PROFILE:
# 原值:计都优先(PyJHora 兼容,产品负责人 2026-10-03)。
# 新值:blocked,saturn_ketu_priority_unresolved。
# 原因:占星师 2026-11-08 第五轮逐项答复 N4。
return {"status": "blocked", "reason": SATURN_KETU_BLOCKED, "order": None, "direction": None,
"exception_applied": None, "method_note": None, "method_note_en": None,
"saturn_in_seed": saturn, "ketu_in_seed": ketu, "saturn_ketu_profile": saturn_ketu}
if ketu:
order = _rath_ketu_table12_sequence(seed_sign_idx)
direction = "table12_ketu_reversed"
exception = "ketu_in_start_sign"
if saturn:
method_note = KETU_FIRST_NOTE
elif saturn:
order = nd.build_narayana_sign_sequence(seed_sign_idx, profile="rath_saturn_table11_v1")
direction = "table11_saturn_zodiacal"
exception = "saturn_in_start_sign"
else:
order = nd.build_narayana_sign_sequence(seed_sign_idx, profile="rath_general_table10_v1")
direction = "table10_general"
exception = None
return {"status": "selected", "order": order, "direction": direction, "exception_applied": exception,
"method_note": method_note, "method_note_en": KETU_FIRST_NOTE_EN if method_note else None,
"saturn_in_seed": saturn, "ketu_in_seed": ketu}
# AD direction (占星师 2026-11-08 第五轮逐项答复 N2): two named executable profiles.
# Both start from the sign holding the lord of the stronger of the MD sign / 7th
# (p.48, p.50 note 2), twelve equal parts. The usual direction is set by the odd /
# even of
# rath_p50_md_parity_v1 - the MD sign (p.50 rule (12) and note 2: the text rule);
# rath_stronger_lord_start_parity_v1 - the actual AD start sign (Table 13 / Table 25
# practice, round-6 ruling Q7; the product default).
# Exceptions in both (p.51): Saturn in the MD sign -> zodiacal; Ketu in the MD sign ->
# the usual direction reversed; both -> blocked `saturn_ketu_priority_unresolved`
# (Ketu priority only under `pyjhora_ketu_priority_compat_v1`). She declined to say which
# predicts better: the default stays the start-sign parity, and the step is
# `disputed_pending_choice` with the other profile shown.
AD_PROFILE_START_PARITY = "rath_stronger_lord_start_parity_v1"
AD_PROFILE_MD_PARITY = "rath_p50_md_parity_v1"
AD_PROFILES = (AD_PROFILE_START_PARITY, AD_PROFILE_MD_PARITY)
AD_PROFILE_TEXT = {
AD_PROFILE_START_PARITY: ("按小运起点星座奇偶(Table 13 / Table 25;第六轮 Q7)",
"by the odd/even of the AD start sign (Table 13 / Table 25; round-6 Q7)"),
AD_PROFILE_MD_PARITY: ("按大运星座奇偶(p.50 规则 (12) 与注 2)",
"by the odd/even of the MD sign (p.50 rule (12) and note 2)"),
}
# Order tables of the default profile (start-sign parity): identical to the generic rule.
AD_DIRECTION_RULE = {
"rath_table13_v1": ("按小运起点星座奇偶(Table 13)", "by the odd/even of the AD start sign (Table 13)"),
"rath_saturn_table11_v1": ("大运星座有土星:一律顺行(Table 11)", "Saturn in the MD sign: always zodiacal (Table 11)"),
"rath_ketu_table14_v1": ("大运星座有计都:反向(Table 14)", "Ketu in the MD sign: reversed (Table 14)"),
}
# The other named statements, reported beside the applied profile and never applied.
AD_BOOK_DIVERGENCE = (
(AD_PROFILE_MD_PARITY, "Rath p.50 rule (12), note 2 (J.S. 1.1.34, p.47)",
"p.50 规则 (12) 与注 2 看大运星座奇偶(含土星 / 计都例外)",
"p.50 rule (12) and note 2 by the odd/even of the MD sign (Saturn / Ketu exceptions included)"),
("js_2_4_31_32", "J.S. 2.4.31-32 (Rath p.47-48)",
"J.S. 2.4.31–32 看大运星座或其宫主所落星座", "J.S. 2.4.31-32 by the MD sign or the sign its lord occupies"),
)
def _is_odd_sign(sign_idx: int) -> bool:
return sign_idx % 2 == 0 # Aries (index 0) is the first, odd sign
def _flip(direction: str) -> str:
return "reverse" if direction == "zodiacal" else "zodiacal"
def ad_profile_direction(profile: str, md_sign_idx: int, start_sign_idx: int, planet_lons: Dict[str, float], *,
saturn_ketu: str = SATURN_KETU_DEFAULT) -> Dict[str, Any]:
"""Direction of the twelve ADs under one named profile, or blocked."""
lord_sign = None
if profile == "js_2_4_31_32":
lord_sign = nd._get_planet_sign(_lord(md_sign_idx, planet_lons) or "", planet_lons)
if profile in ("parashara_equal_v1", "js_2_4_31_32"):
# Book statements / legacy implementation without the p.51 exceptions.
odd = _is_odd_sign(md_sign_idx) or (profile == "js_2_4_31_32" and lord_sign is not None and _is_odd_sign(lord_sign))
return {"status": "selected", "direction": "zodiacal" if odd else "reverse", "exception_applied": None}
if profile not in AD_PROFILES:
raise ValueError(f"unknown AD direction profile: {profile}")
parity_sign = start_sign_idx if profile == AD_PROFILE_START_PARITY else md_sign_idx
usual = "zodiacal" if _is_odd_sign(parity_sign) else "reverse"
saturn = nd._get_planet_sign("Saturn", planet_lons) == md_sign_idx
ketu = nd._get_planet_sign("Ketu", planet_lons) == md_sign_idx
if saturn and ketu and saturn_ketu != KETU_PRIORITY_PROFILE:
return {"status": "blocked", "reason": SATURN_KETU_BLOCKED, "direction": None, "usual_direction": usual,
"exception_applied": None}
if ketu:
return {"status": "selected", "direction": _flip(usual), "usual_direction": usual,
"exception_applied": "ketu_in_md_sign", "method_note": KETU_FIRST_NOTE if saturn else None}
if saturn:
return {"status": "selected", "direction": "zodiacal", "usual_direction": usual,
"exception_applied": "saturn_in_md_sign"}
return {"status": "selected", "direction": usual, "usual_direction": usual, "exception_applied": None}
def _ad_order_profile(md_sign_idx: int, planet_lons: Dict[str, float]) -> Tuple[str, Optional[str]]:
ketu = nd._get_planet_sign("Ketu", planet_lons) == md_sign_idx
saturn = nd._get_planet_sign("Saturn", planet_lons) == md_sign_idx
if ketu:
return "rath_ketu_table14_v1", (KETU_FIRST_NOTE if saturn else None)
if saturn:
return "rath_saturn_table11_v1", None
return "rath_table13_v1", None
def ad_direction(md_sign_idx: int, start_sign_idx: int, profile: str, planet_lons: Dict[str, float], *,
ad_profile: str = AD_PROFILE_START_PARITY,
saturn_ketu: str = SATURN_KETU_DEFAULT) -> Dict[str, Any]:
"""Applied AD direction plus the other named statements it does not follow."""
picked = ad_profile_direction(ad_profile, md_sign_idx, start_sign_idx, planet_lons, saturn_ketu=saturn_ketu)
applied = picked["direction"]
if ad_profile == AD_PROFILE_START_PARITY:
zh, en = AD_DIRECTION_RULE[profile]
others = AD_BOOK_DIVERGENCE
else:
zh, en = AD_PROFILE_TEXT[ad_profile]
# R1: under the p.50 default the Saturn / Ketu exception is named in the rule text too.
table = {"saturn_in_md_sign": "rath_saturn_table11_v1", "ketu_in_md_sign": "rath_ketu_table14_v1"}.get(
picked.get("exception_applied") or "")
if table:
zh, en = f"{zh};{AD_DIRECTION_RULE[table][0]}", f"{en}; {AD_DIRECTION_RULE[table][1]}"
others = ((AD_PROFILE_START_PARITY, "Rath Table 13 / Table 25 (round-6 Q7)", *AD_PROFILE_TEXT[AD_PROFILE_START_PARITY]),
AD_BOOK_DIVERGENCE[1])
rows = []
for key, source, rule_zh, rule_en in others:
other = ad_profile_direction(key, md_sign_idx, start_sign_idx, planet_lons, saturn_ketu=saturn_ketu)
rows.append({"id": key, "source": source, "rule_text": rule_zh, "rule_text_en": rule_en,
"direction": other.get("direction") or "blocked", "differs": other.get("direction") != applied,
"applied": False})
return {
"direction": applied,
"rule": profile,
"profile": ad_profile,
"exception_applied": picked.get("exception_applied"),
"rule_text": zh,
"rule_text_en": en,
"book_divergence": rows,
}
def rath_sign_period(sign_idx: int, planet_lons: Dict[str, float], *,
strength_scope: Optional[str] = None) -> Dict[str, Any]:
"""Years of one sign under the production Narayana profile.
Dual-lord choice (p.43), dignity adjustment and node rules included.
Shared by Narayana and Drig (BUG-1678: astrologer ruling 2026-11-07,
PVR Integrated Approach 21.2(5): Drig years are found as in Narayana).
"""
decision = resolve_dual_lord(sign_idx, planet_lons, strength_scope=strength_scope)
period = decision.get("period")
lord = decision.get("lord")
if period is None and lord:
lord_sign_idx = nd._get_planet_sign(lord, planet_lons)
if lord_sign_idx is None:
lord_sign_idx = sign_idx
period = rath_period_years(sign_idx, lord, lord_sign_idx)
elif period is None:
lord_sign_idx = sign_idx
else:
lord_sign_idx = nd._get_planet_sign(lord, planet_lons) if lord else None
if lord_sign_idx is None:
lord_sign_idx = sign_idx
return {"decision": decision, "period": period, "lord": lord, "lord_sign_idx": lord_sign_idx,
"years": None if period is None else period["years"]}
def mahadasha_sequence(seed_sign_idx: int, planet_lons: Dict[str, float],
*, start_age: float = 0.0, cycle_count: int = 2,
saturn_ketu: str = SATURN_KETU_DEFAULT,
strength_scope: Optional[str] = None) -> Dict[str, Any]:
"""Rath MD rows from one start sign (cycle 2 = twelve minus cycle 1).
A 0-year row (占星师 2026-11-08 第五轮逐项答复 N3: the formula value is kept,
e.g. Sagittarius with Jupiter in Capricorn 1 - 1 = 0; cycle 2 = 12 - 0 = 12)
stays in the raw structure with `zero_duration: True`. On the half-open
interval [start, end) it occupies no time and is never the running MD.
R2 (占星师 2026-11-08 第六轮) local propagation: when one sign's length is
unresolved (dual lords, lengths differ), the rows before it keep their dates;
that row and every later row keep sign order, lord and (where known) length,
but no absolute ages (`undated: True`); the unresolved row carries its
`length_branches`. Cycle 2 is undated from its first row on.
"""
order = md_order(seed_sign_idx, planet_lons, saturn_ketu=saturn_ketu)
if order["status"] == "blocked":
return {**order, "seed_sign": SIGNS[seed_sign_idx], "seed_sign_idx": seed_sign_idx, "mahadasha": None}
rows: List[Dict[str, Any]] = []
cursor: Optional[float] = float(start_age)
unresolved: Optional[Dict[str, Any]] = None
for position, sign_idx in enumerate(order["order"], start=1):
sign_period = rath_sign_period(sign_idx, planet_lons, strength_scope=strength_scope)
decision, period, lord = sign_period["decision"], sign_period["period"], sign_period["lord"]
lord_sign_idx = sign_period["lord_sign_idx"]
years = None if period is None else period["years"]
row = {
"sign": SIGNS[sign_idx], "sign_idx": sign_idx, "lord": lord,
"lord_in_sign": SIGNS[lord_sign_idx] if lord_sign_idx is not None else None,
"lord_sign_idx": lord_sign_idx,
"years": years,
"base_years": None if period is None else period["base_years"],
"dignity_adjustment": None if period is None else period["dignity_adjustment"],
"adjustment_source": None if period is None else period["adjustment_source"],
"cycle_index": 1,
"period_key": f"narayana_rath:1:{position:02d}:{SIGNS[sign_idx]}",
"start_age": None if cursor is None else round(cursor, 4),
"end_age": None if cursor is None or years is None else round(cursor + years, 4),
"zero_duration": years == 0,
}
if sign_idx in _DUAL_PAIRS:
row["dual_lord_decision"] = decision
if cursor is None:
row["undated"] = True
if years is None:
row["undated"] = True
row["length_branches"] = [
{key: branch.get(key) for key in ("lord", "years", "base_years", "dignity_adjustment")}
for branch in decision.get("length_branches") or []
]
if unresolved is None:
unresolved = {"sign": row["sign"], "sign_idx": sign_idx, "position": position, "cycle_index": 1,
"start_age": None if cursor is None else round(cursor, 4),
"start_age_exact": cursor,
"reason": decision.get("reason") or "dual_lord_unresolved",
"length_branches": row["length_branches"]}
cursor = None
elif cursor is not None:
cursor += years
rows.append(row)
if cycle_count == 2:
for position, first in enumerate(list(rows), start=1):
years = None if first["years"] is None else 12 - first["years"]
second = {**first, "years": years, "base_years": None, "dignity_adjustment": None,
"adjustment_source": None, "cycle_index": 2, "zero_duration": years == 0,
"period_key": f"narayana_rath:2:{position:02d}:{first['sign']}",
"start_age": None if cursor is None else round(cursor, 4),
"end_age": None if cursor is None or years is None else round(cursor + years, 4)}
if first.get("length_branches"):
second["length_branches"] = [{**branch, "years": None if branch.get("years") is None
else 12 - branch["years"]} for branch in first["length_branches"]]
if cursor is None:
second["undated"] = True
else:
cursor += years
rows.append(second)
out = {**order, "seed_sign": SIGNS[seed_sign_idx], "seed_sign_idx": seed_sign_idx, "mahadasha": rows}
if unresolved is not None:
out["status"] = "undecided"
out["years_unresolved"] = unresolved
return out
def _equal_rows(md_row: Dict[str, Any], sequence: List[int], order_profile: str) -> List[Dict[str, Any]]:
"""Twelve equal rows in an explicit order (same fields as nd.subdivide_narayana_equal_order)."""
total = float(md_row.get("years", 0))
start = float(md_row.get("start_age", 0))
end = float(md_row.get("end_age", start + total))
rows = []
for index, sign_idx in enumerate(sequence):
lo = start + total * index / 12
hi = end if index == 11 else start + total * (index + 1) / 12
rows.append({"level": "AD", "sign": SIGNS[sign_idx], "sign_idx": sign_idx, "lord": SIGN_LORDS[SIGNS[sign_idx]],
"years": round(max(0.0, hi - lo), 6), "start_age": round(lo, 6), "end_age": round(hi, 6),
"sequence_index": index, "order_profile": order_profile,
"start_sign_source": "explicit_source_profile_start_sign", "parent_md": md_row["sign"]})
return rows
def antardasha(md_row: Dict[str, Any], planet_lons: Dict[str, float], *,
ad_profile: str = AD_PROFILE_MD_PARITY,
saturn_ketu: str = SATURN_KETU_DEFAULT,
strength_scope: Optional[str] = None) -> Dict[str, Any]:
"""Twelve equal ADs: start from the sign of the lord of the stronger of
the MD sign and its 7th (round-5 Q4); direction by `ad_profile` (N2).
原值:默认 `rath_stronger_lord_start_parity_v1`(按小运起点星座奇偶,Tables 13 / 11 / 14)。
新值:默认 `rath_p50_md_parity_v1`(按大运星座奇偶,含土星 / 计都例外);起点奇偶保留为可选研究 profile。
原因:占星师 2026-11-08 第六轮 R1(依据 Rath p.50 注 2 的文字,不是三盘投票)。
Saturn and Ketu both in the MD sign: blocked `saturn_ketu_priority_unresolved`.
R2: a blocked AD start (MD sign vs 7th unresolved, or its lord unresolved) blocks
only this MD's ADs (and their PDs); the MD row and other MDs are untouched.
"""
ad_profile = AD_PROFILE_ALIASES.get(ad_profile, ad_profile)
md_sign_idx = md_row["sign_idx"]
seventh = (md_sign_idx + 6) % 12
if md_row.get("start_age") is None or md_row.get("years") is None:
return {"status": "blocked", "reason": "md_dates_unresolved", "rows": [], "ad_profile": ad_profile,
"antardasha_start_rule": {"rule": "stronger_of_md_sign_and_seventh_then_its_lord_sign",
"compared": [SIGNS[md_sign_idx], SIGNS[seventh]],
"strength_level_decided": None}}
comparison = compare_signs(md_sign_idx, seventh, planet_lons, strength_scope=strength_scope)
profile, note = _ad_order_profile(md_sign_idx, planet_lons)
if comparison["status"] != "selected":
return {"status": "blocked", "reason": comparison.get("reason"), "rows": [], "ad_profile": ad_profile,
"comparison_status": comparison.get("comparison_status"),
"antardasha_start_rule": {"rule": "stronger_of_md_sign_and_seventh_then_its_lord_sign",
"compared": [SIGNS[md_sign_idx], SIGNS[seventh]],
"strength_level_decided": None,
"blocked_level": comparison.get("blocked_level"),
"strength_scope": comparison.get("strength_scope")}}
stronger = comparison["selected_sign_idx"]
decision = resolve_dual_lord(stronger, planet_lons, strength_scope=strength_scope)
lord = decision.get("lord")
if not lord:
return {"status": "blocked", "reason": decision.get("reason") or "dual_lord_undecided", "rows": [],
"antardasha_start_rule": {"rule": "stronger_of_md_sign_and_seventh_then_its_lord_sign",
"compared": [SIGNS[md_sign_idx], SIGNS[seventh]],
"stronger_sign": SIGNS[stronger],
"dual_lord_decision": decision}}
start = nd._get_planet_sign(lord, planet_lons)
if start is None:
return {"status": "blocked", "reason": "stronger_sign_lord_longitude_missing", "rows": []}
rule = {
"rule": "stronger_of_md_sign_and_seventh_then_its_lord_sign",
"compared": [SIGNS[md_sign_idx], SIGNS[seventh]],
"stronger_sign": SIGNS[stronger],
"strength_level_decided": comparison["strength_level_decided"],
"lord": lord,
"dual_lord_rule": decision.get("rule") if stronger in _DUAL_PAIRS else None,
"dual_lord_decision": decision if stronger in _DUAL_PAIRS else None,
"start_sign": SIGNS[start],
"ad_profile": ad_profile,
"strength_scope": comparison.get("strength_scope"),
}
picked = ad_profile_direction(ad_profile, md_sign_idx, start, planet_lons, saturn_ketu=saturn_ketu)
if picked["status"] != "selected":
# 原值:土星与计都同在大运星座时按计都优先(Table 14)。
# 新值:blocked saturn_ketu_priority_unresolved。原因:占星师 2026-11-08 第五轮逐项答复 N4。
return {"status": "blocked", "reason": picked["reason"], "rows": [],
"antardasha_start_rule": {**rule, "order_profile": None, "method_note": None}}
if ad_profile == AD_PROFILE_START_PARITY:
rows = nd.subdivide_narayana_equal_order(
md_row, start_sign_idx=start, order_profile=profile, level="AD",
parent_key="parent_md", parent_name=md_row["sign"],
)
else:
step = 1 if picked["direction"] == "zodiacal" else -1
profile = f"{ad_profile}:{picked['direction']}"
note = picked.get("method_note")
rows = _equal_rows(md_row, [(start + step * index) % 12 for index in range(12)], profile)
for row in rows:
row["start_sign_source"] = "lord_of_stronger_md_or_seventh_sign"
direction = ad_direction(md_sign_idx, start, profile, planet_lons, ad_profile=ad_profile, saturn_ketu=saturn_ketu)
return {"status": "selected", "rows": rows,
"antardasha_start_rule": {**rule, "order_profile": profile, "method_note": note, "direction": direction}}
def calc_narayana_rath(lagna_sign_idx: int, planet_lons: Dict[str, float],
*, seed_sign_idx: Optional[int] = None, cycle_count: int = 2,
allow_book_example: bool = False,
book_example: Optional[str] = None,
saturn_ketu: str = SATURN_KETU_DEFAULT,
strength_scope: Optional[str] = None,
ad_profile: Optional[str] = None) -> Dict[str, Any]:
"""Rath Narayana Dasha for one chart.
`seed_sign_idx` overrides the start sign (book-table replay only); with
`book_example` (a key of BOOK_EXAMPLES) the output is flagged
`book_example_exception` and still carries the general rule's own
verdict, unchanged, in `general_rule_selection`.
`allow_book_example` lets the Indira AK example decide a full seven-level
tie (flagged in the output).
`saturn_ketu`: default blocks Saturn + Ketu in the seed sign; only
`pyjhora_ketu_priority_compat_v1` (research, not canonical) gives Ketu priority.
`strength_scope` / `ad_profile`: recorded in `profile_config` (the AD profile is
applied by `antardasha`; it is recorded here so every output names the full config).
R2 local propagation (占星师 2026-11-08 第六轮):
- seed unresolved -> no unique sequence (`mahadasha` None, `status: blocked`), but
the named candidate sequences stay in `seed_candidates` (conditional);
- one MD length unresolved -> `status: partial_blocked`; `mahadasha` keeps the
dated rows before it, `undated_mahadasha` keeps that row (with its
`length_branches`) and every later row without absolute ages.
"""
if book_example is not None and (seed_sign_idx is None or book_example not in BOOK_EXAMPLES):
raise ValueError("book_example needs an explicit seed_sign_idx and a known BOOK_EXAMPLES key")
scope = strength_scope or STRENGTH_SCOPE_DEFAULT
config = profile_config(ad_profile=ad_profile, saturn_ketu=saturn_ketu, strength_scope=scope)
base = {
"profile": PROFILE,
"step_profiles": dict(config),
"profile_config": dict(config),
# 原值 "jaimini_odd_footed_dignity_v2"(只是计数口径名);新值 Table 8 年数 profile 名,计数口径另列。
# 原因:占星师 2026-11-08 第五轮逐项答复 N5:旧名只是历史七曜口径,不能再称完整 Table 8。
"duration_profile": YEARS_PROFILE,
"duration_count_profile": DURATION_PROFILE,
"dual_lord_rule": DUAL_LORD_PROFILE,
"source": SOURCE,
"lagna_sign": SIGNS[lagna_sign_idx],
"antardasha_start_rule": "stronger_of_md_sign_and_seventh_then_its_lord_sign (p.48, p.50 note 2)",
"known_book_differences": BOOK_SOFTWARE_DIFFERENCES,
}
if seed_sign_idx is not None:
selection = {"status": "explicit", "selected_sign_idx": seed_sign_idx,
"strength_level_decided": None, "book_example_exception": book_example}
if book_example is not None:
general = compare_signs(lagna_sign_idx, (lagna_sign_idx + 6) % 12, planet_lons, rule3_block=True,
strength_scope=scope)
base["general_rule_selection"] = {
key: general.get(key) for key in
("status", "selected_sign", "strength_level_decided", "strength_level_name", "reason")
}
base["book_example"] = BOOK_EXAMPLES[book_example]
else:
# 原值:compare_signs(上升, 第 7 宫, rule3_block=True);双主未决即起运 undecided。
# 新值:seed_comparison:只因双主主星未定而未决、且各候选主星给出同一起运宫时,保留起运宫为公共字段,
# 主星身份仍未定。原因:占星师 2026-11-09 第七轮回复 §1 公共字段规则(R2 选 D;产品负责人同意)。
selection = seed_comparison(lagna_sign_idx, planet_lons, allow_book_example=allow_book_example,
strength_scope=scope)
base["seed_selection"] = selection
if selection.get("seed_common_field"):
base["seed_common_field"] = selection["seed_common_field"]
base["strength_level_decided"] = selection.get("strength_level_decided")
base["book_example_exception"] = selection.get("book_example_exception")
def candidates() -> Dict[str, Any]:
out = {}
for idx in (lagna_sign_idx, (lagna_sign_idx + 6) % 12):
seq = mahadasha_sequence(idx, planet_lons, cycle_count=cycle_count, saturn_ketu=saturn_ketu,
strength_scope=scope)
out[SIGNS[idx]] = {"seed_sign": seq["seed_sign"], "status": seq.get("status", "selected"),
"reason": seq.get("reason"), "direction": seq.get("direction"),
"exception_applied": seq.get("exception_applied"),
"years_unresolved": seq.get("years_unresolved"),
"mahadasha": seq.get("mahadasha"), "conditional": True}
return out
if selection["status"] == "undecided":
# 原值:起运比较定不出(双主未决 / Rule 3 低档打平)时 blocked,不给候选表(第五轮 N1 / N5)。
# 新值:仍 blocked(没有唯一主序列 / 唯一当前运),但两个具名候选(上升 / 第 7 宫起)的序列保留在
# seed_candidates,标 conditional,不进主结论、不计分。
# 原因:占星师 2026-11-08 第六轮 R2 传播表:起运宫未决 → 保留各具名候选。
return {**base, "status": "blocked", "reason": selection.get("reason") or "seed_undecided",
"blocked_step": "seed", "seed_sign": None, "direction": None, "exception_applied": None,
"method_note": None, "method_note_en": None, "mahadasha": None,
"unique_sequence": False, "seed_candidates": candidates()}
if selection["status"] in ("selected", "explicit"):
seq = mahadasha_sequence(selection["selected_sign_idx"], planet_lons, cycle_count=cycle_count,
saturn_ketu=saturn_ketu, strength_scope=scope)
if seq.get("status") == "blocked":
# 占星师 2026-11-08 第五轮逐项答复 N4:土星与计都同在起运宫,不选优先级。
return {**base, "status": "blocked", "reason": seq["reason"], "blocked_step": "seed",
"seed_sign": seq["seed_sign"], "direction": None, "exception_applied": None,
"method_note": None, "method_note_en": None, "mahadasha": None}
if selection["status"] == "explicit" and book_example is not None:
status, basis = "book_example_exception", f"explicit_seed:book_example:{book_example}"
elif selection["status"] == "explicit":
status, basis = "explicit_seed", "explicit_seed"
elif selection.get("book_example_exception"):
status, basis = "book_example_exception", f"book_example:{selection['book_example_exception']}"
else:
status = "partial_verified"
basis = f"stronger_of_lagna_seventh:level_{selection['strength_level_decided']}_{selection['strength_level_name']}"
body = {"seed_sign": seq["seed_sign"], "seed_basis": basis,
"direction": seq["direction"], "exception_applied": seq["exception_applied"],
"method_note": seq["method_note"], "method_note_en": seq["method_note_en"]}
if seq.get("status") == "undecided":
# 原值:双主星未决、某宫年数定不出时整层 blocked(mahadasha 为空,截断表只在 partial_mahadasha)。
# 新值:partial_blocked:该段之前的大运及日期照常;该段终点与之后所有绝对日期 blocked;
# 该段的各年长分支保留(undated_mahadasha / years_unresolved.length_branches)。
# 原因:占星师 2026-11-08 第六轮 R2 传播表:双主星造成 MD 年长未决 → 只停该段终点与后续日期。
unresolved = seq["years_unresolved"]
rows = seq["mahadasha"]
dated = [row for row in rows if not row.get("undated")]
return {**base, **body, "status": "partial_blocked", "dated_status": status,
"reason": "dual_lord_undecided_for_sign_years", "blocked_step": "years",
"blocked_sign": unresolved["sign"], "years_unresolved": unresolved,
"mahadasha": dated or None,
"undated_mahadasha": [row for row in rows if row.get("undated")],
"partial_mahadasha": rows}
return {**base, **body, "status": status, "mahadasha": seq["mahadasha"]}
alternatives = candidates()
return {**base, "status": "parameter_sensitive", "reason": selection.get("reason"),
"seed_sign": None, "seed_basis": "tie_lagna_seventh_both_listed",
"direction": None, "exception_applied": None, "method_note": None, "method_note_en": None,
"mahadasha": None, "unique_sequence": False, "seed_candidates": alternatives,
"alternatives": {sign: {"seed_sign": seq["seed_sign"], "direction": seq["direction"],
"exception_applied": seq["exception_applied"],
"mahadasha": seq["mahadasha"]} for sign, seq in alternatives.items()}}
# ── Per-step profiles (astrologer round-5 ruling 1, 2026-11-08, B3/B4) ──────
#
# Narayana is split into five explicitly named steps. Each step has one
# source-version profile (Sanjay Rath, *Narayana Dasa*), which is what the
# product computes, plus named comparison profiles. A comparison profile never
# replaces the source profile; it is recomputed with only that one step
# swapped, and the step is `disputed` on a chart when the swap changes the
# running MD or AD sign there. `reference` profiles (the old fixed-lord and
# forward-count algorithm) are listed but never make a step disputed: the
# ruling keeps a fixed lord only as an independent comparison and forbids a
# majority vote. A step the source profile cannot decide is `blocked`.
#
# 原值:Narayana 只有一套 Rath 输出,B3/B4(上游实现与本产品的当前大运 / 小运不同)运行时
# 点不出是哪一步(BUG-1732 记为 unknown)。
# 新值:起运、年数、双宫主、小运方向、出生起点五步各有来源版 profile 与具名对照 profile,
# 逐步替换重算,点名哪一步改变了当前分支。
# 原因:占星师 2026-11-08 第五轮裁定 1(B3/B4)。
# 原值:起运 profile 名 rath_seven_level_lagna_seventh_v1;年数 rath_p40_footed_count_phalita_dignity_v1;
# 小运方向 rath_table13_start_sign_parity_v1;起运对照 upstream_rath_empty_sign_lord_strength_v1;
# 年数对照 upstream_grahas_only_dignity_v2(comparison);小运对照 rath_p47_js_1_1_34(不含例外)。
# 新值:与占星师本地新增 profile 同名:rath_highest_occupant_dignity_v1、rath_table8_phalita_dignity_v1、
# rath_stronger_lord_start_parity_v1;起运对照 rath_empty_sign_lord_strength_v1(她的默认);
# 年数旧口径 jaimini_odd_footed_dignity_v2 降为 reference(不能再称完整 Table 8);小运对照
# rath_p50_md_parity_v1(含土星 / 计都例外);旧名作别名保留。
# 原因:占星师 2026-11-08 第五轮逐项答复 N1、N2、N5。
SEED_PROFILE = RULE3_PROFILE
EMPTY_SIGN_SEED_PROFILE = "rath_empty_sign_lord_strength_v1"
YEARS_PROFILE = "rath_table8_phalita_dignity_v1"
LEGACY_GRAHA_YEARS_PROFILE = "jaimini_odd_footed_dignity_v2"
# 原值:AD_DIRECTION_PROFILE = rath_stronger_lord_start_parity_v1(起点奇偶,第六轮 Q7),状态 disputed_pending_choice。
# 新值:rath_p50_md_parity_v1(大运星座奇偶,p.50 注 2);起点奇偶保留为可选研究 profile(comparison)。
# 原因:占星师 2026-11-08 第六轮 R1:推荐新版本默认 p.50 MD 奇偶;显式配置、版本化迁移,旧报告不覆盖。
AD_DIRECTION_PROFILE = AD_PROFILE_MD_PARITY
START_PROFILE = "birth_moment_v1"
# Clock: ages and dates on a 365.25-day year from the birth instant (narayana_legacy_label.narayana_age).
CLOCK_PROFILE = "birth_moment_julian_year_365_25_v1"
# Algorithm version: bump whenever any default step profile or a propagation rule changes.
# 原值:无(只有各步 profile 名)。新值:rath-2026-11-08-r7(R1 默认小运方向、R2 强弱 profile 一致与局部传播)。
# 原因:占星师 2026-11-08 第六轮 R1:缓存键与校时运行标签须含全部参数与算法版本。
# 原值(2):narayana_rath:2026-11-08:r7。新值(2):narayana_rath:2026-11-09:r8d(默认强弱范围改为 seed_ad_start_p43d_v1,
# 未决处保留具名候选分支 narayana_branches、条件性旧版分支)。原因(2):占星师 2026-11-09 第七轮回复 R2 选 D;产品负责人同意。
ALGORITHM_VERSION = "narayana_rath:2026-11-09:r8d"
# The config before R1 / R2 (round-6 engine, BUG-1768 / BUG-1769): replay only.
PRE_R7_ALGORITHM_VERSION = "narayana_rath:2026-11-08:r6"
SEED_PROFILE_ALIASES = {"rath_seven_level_lagna_seventh_v1": SEED_PROFILE,
"upstream_rath_empty_sign_lord_strength_v1": EMPTY_SIGN_SEED_PROFILE}
YEARS_PROFILE_ALIASES = {"rath_p40_footed_count_phalita_dignity_v1": YEARS_PROFILE,
"upstream_grahas_only_dignity_v2": LEGACY_GRAHA_YEARS_PROFILE}
AD_PROFILE_ALIASES = {"rath_table13_start_sign_parity_v1": AD_PROFILE_START_PARITY,
"rath_p47_js_1_1_34": "parashara_equal_v1"}
# 原值:PROFILE_STEPS = ("seed", "years", "dual_lord", "ad_direction", "start");小运起点未决记在 ad_direction。
# 新值:加 ad_start(小运起点:大运宫对第 7 宫取强、其宫主所在星座);ad_direction 只管方向(含土星 / 计都例外)。
# 原因:占星师 2026-11-09 第七轮回复 R2 选 D;产品负责人同意:小运起点(大运宫对第 7 宫取强)与小运方向是两步,回答要点名对的那一步。
PROFILE_STEPS = ("seed", "years", "dual_lord", "ad_start", "ad_direction", "start")
AD_START_PROFILE = "rath_p48_p50_stronger_of_md_seventh_lord_sign_v1"
# One fingerprint of every step profile the product uses: cache keys, audit rows and
# test seal tags carry it, so a profile change invalidates old results (K3).
# 原值:seed / years / dual_lord / ad_direction / saturn_ketu / start 六项。
# 新值:再加 strength(强弱 profile)、strength_scope(用在哪些比较)、clock(年长与起点)、
# algorithm_version;years 即 duration profile。
# 原因:占星师 2026-11-08 第六轮 R1 接入要求 1:记录 seed、strength、duration、dual-lord、AD-direction、
# Saturn/Ketu、clock 全套 profile,不得只记录一个总名称。
DEFAULT_STEP_PROFILES = {
"seed": SEED_PROFILE, "strength": STRENGTH_PROFILE, "strength_scope": STRENGTH_SCOPE_DEFAULT,
"years": YEARS_PROFILE, "dual_lord": DUAL_LORD_PROFILE,
"ad_direction": AD_DIRECTION_PROFILE, "saturn_ketu": SATURN_KETU_DEFAULT, "start": START_PROFILE,
"clock": CLOCK_PROFILE, "algorithm_version": ALGORITHM_VERSION,
}
# The full config the product used before R1 / R2, for replay and change lists only.
PRE_R7_STEP_PROFILES = {
**DEFAULT_STEP_PROFILES, "strength_scope": STRENGTH_SCOPE_SEED_ONLY,
"ad_direction": AD_PROFILE_START_PARITY, "algorithm_version": PRE_R7_ALGORITHM_VERSION,
}
def profile_config(*, ad_profile: Optional[str] = None, saturn_ketu: Optional[str] = None,
strength_scope: Optional[str] = None) -> Dict[str, str]:
"""The full Narayana profile config of one computation (flat strings: cache keys, run labels).
A non-default AD direction or strength scope is a different config; when it
matches the pre-R7 pair the pre-R7 algorithm version is named.
"""
config = dict(DEFAULT_STEP_PROFILES)
if ad_profile:
config["ad_direction"] = AD_PROFILE_ALIASES.get(ad_profile, ad_profile)
if saturn_ketu:
config["saturn_ketu"] = saturn_ketu
if strength_scope:
config["strength_scope"] = strength_scope
if (config["ad_direction"], config["strength_scope"]) == (AD_PROFILE_START_PARITY, STRENGTH_SCOPE_SEED_ONLY):
config["algorithm_version"] = PRE_R7_ALGORITHM_VERSION
return config
def profile_config_label(config: Optional[Dict[str, str]] = None) -> str:
"""One stable label for a config (rectification run labels, receipts)."""
config = config or DEFAULT_STEP_PROFILES
return "|".join(f"{key}={config[key]}" for key in sorted(config))
STEP_PROFILES = {
"seed": {
"profile": SEED_PROFILE,
"source": "Rath p.34-36 (First Source Rules 2, 3, 4, 6, 7, 8 and Second Source Rule 1), p.48",
"rule": ("stronger of Lagna / 7th by the seven levels; first level that separates decides; Rule 3 by the "
"highest occupant tier (named conditional convention); Saturn + Ketu in the seed sign blocked"),
"convention": RULE3_CONVENTION,
"comparisons": (
(EMPTY_SIGN_SEED_PROFILE, "comparison",
"her default select_narayana_seed_sign: occupants, three roles, then modality / lord degree / parity for empty signs only; occupied ties blocked", "seed"),
(KETU_PRIORITY_PROFILE, "reference",
"PyJHora-compatible Ketu priority when Saturn and Ketu share the seed sign; not canonical priority evidence", "saturn_ketu"),
# R2: the other strength scope stays listed, never makes a step disputed.
# 原值:列的是 STRENGTH_SCOPE_SEED_ONLY(当时它是非默认的旧范围)
# 新值:列 STRENGTH_SCOPE_ALL(R2 扩大范围,现在是具名非默认 profile)
# 原因:产品负责人 2026-11-09:R2 范围扩大待占星师裁定,暂按 seed_only_v0。
# 原值(2):列 STRENGTH_SCOPE_ALL(非默认)。新值(2):列 STRENGTH_SCOPE_SEED_ONLY,作「条件性旧版分支」
# (reference:不改变步骤状态、不投票)。原因(2):占星师 2026-11-09 第七轮回复 R2 选 D;产品负责人同意。
(STRENGTH_SCOPE_SEED_ONLY, "reference",
"conditional legacy branch (assumes Rule 3 is skipped below own sign): shown for comparison only; never overrides the main status, never an independent vote",
"strength_scope"),
),
},
"years": {
"profile": YEARS_PROFILE,
"source": "Rath p.39-42: Table 7 odd/even-footed count reduced by one; (3)(a) exalted +1 / debilitated -1 with Table 8 (Phalita, Rahu Gemini / Ketu Sagittarius); (3)(b) maximum 12, 0 allowed",
"rule": "Vimsapada signs count zodiacally, Samapada signs in reverse, to the lord's sign; lord in the sign = 12; +1 / -1 by Table 8 including the nodes; clamp 0-12",
"comparisons": (
(LEGACY_GRAHA_YEARS_PROFILE, "reference",
"historical seven-graha profile: same count, exaltation / debilitation for the seven grahas only, nodes unadjusted; not the complete Table 8", "years"),
("legacy_forward_v0", "reference",
"old algorithm: always counts forward, no dignity", "years"),
),
},
"dual_lord": {
"profile": DUAL_LORD_PROFILE,
"source": P43_SOURCE,
"rule": "Scorpio / Aquarius by p.43 (a)-(e); (d) compares the signs the two lords occupy on the seven levels",
"comparisons": (
("upstream_jaimini_dual_lord_source_v1", "comparison",
"her upstream _resolve_narayana_lord: other lord when one is home, else occupants / Rasi aspects / node own-moolatrikona, then longer years", "dual"),
("fixed_primary_lord_v0", "reference", "fixed lord: Mars for Scorpio, Saturn for Aquarius", "dual"),
),
},
"ad_start": {
"profile": AD_START_PROFILE,
"source": "Rath p.48 (Arambha Rasi) and p.50 note 2: the AD starts from the sign holding the lord of the stronger of the MD sign and its 7th",
"rule": "stronger of MD sign / 7th by the seven levels (same strength scope as the seed); its lord (p.43 for Scorpio / Aquarius); that lord's sign",
"comparisons": (),
},
"ad_direction": {
"profile": AD_DIRECTION_PROFILE,
"source": "Rath p.50 rule (12) and note 2 (Phalita Dasa: by the MD sign's odd / even); Saturn / Ketu exceptions p.51",
"rule": ("twelve equal ADs from the sign holding the lord of the stronger of MD sign / 7th; direction by the "
"MD sign's odd / even; Saturn in the MD sign zodiacal, Ketu reverses; both blocked"),
# 原值:profile_status disputed_pending_choice,默认起点奇偶、待产品选定。
# 新值:selected_default(R1);起点奇偶是可选研究 profile,仍逐盘对照。
# 原因:占星师 2026-11-08 第六轮 R1。
"profile_status": "selected_default",
"default_choice": {
"default": AD_DIRECTION_PROFILE,
"research_option": AD_PROFILE_START_PARITY,
"note": ("Rath p.50 note 2 states the MD-sign parity for Phalita Dasa; the start-sign parity "
"(Table 13 / Table 25 practice) stays an optional research profile; a reproducible product "
"default, not a final ruling for every school"),
"ruling": "astrologer 2026-11-08 round-6 R1",
},
"comparisons": (
(AD_PROFILE_START_PARITY, "comparison",
"research option: by the odd/even of the AD start sign (Table 13 / Table 25 practice, round-6 Q7)", "ad"),
("js_2_4_31_32", "comparison", AD_BOOK_DIVERGENCE[1][3], "ad"),
("parashara_equal_v1", "reference",
"legacy implementation: MD-sign odd / even without the Saturn / Ketu exceptions", "ad"),
(KETU_PRIORITY_PROFILE, "reference",
"PyJHora-compatible Ketu priority when Saturn and Ketu share the MD sign; not canonical priority evidence", "saturn_ketu"),
),
},
"start": {
"profile": START_PROFILE,
"source": "astrologer round-5 ruling 1 (2026-11-08): the actual birth moment, not the birth date",
"rule": "age = (reference instant - birth instant) / 365.25 days; dates = birth instant + age x 365.25 days",
"comparisons": (),
},
}
STEP_LABEL_ZH = {"seed": "起运比较", "years": "年数 profile", "dual_lord": "双主比较",
"ad_start": "小运起点", "ad_direction": "小运方向", "start": "出生起点"}
def _seed_under(profile: str, lagna_sign_idx: int, lons: Dict[str, float], *,
strength_scope: Optional[str] = None) -> Dict[str, Any]:
profile = SEED_PROFILE_ALIASES.get(profile, profile)
seventh = (lagna_sign_idx + 6) % 12
if profile == SEED_PROFILE:
result = seed_comparison(lagna_sign_idx, lons, strength_scope=strength_scope)
return {"status": "selected" if result["status"] == "selected" else "blocked",
"sign_idx": result.get("selected_sign_idx"), "reason": result.get("reason"),
"level": result.get("strength_level_decided")}
if profile != EMPTY_SIGN_SEED_PROFILE:
raise ValueError(f"unknown seed profile: {profile}")
result = nd.select_narayana_seed_sign(lagna_sign_idx, lons, strength_profile=EMPTY_SIGN_SEED_PROFILE)
return {"status": "selected" if result["status"] == "selected" else "blocked",
"sign_idx": result.get("selected_sign_idx"), "reason": result.get("reason"), "level": None}
def _sign_years_under(sign_idx: int, lons: Dict[str, float], *, years: str, dual: str,
strength_scope: Optional[str] = None) -> Dict[str, Any]:
"""Lord and years of one MD sign with the named years / dual-lord profiles."""
years = YEARS_PROFILE_ALIASES.get(years, years)
if years == YEARS_PROFILE and dual == DUAL_LORD_PROFILE:
period = rath_sign_period(sign_idx, lons, strength_scope=strength_scope)
return {"lord": period["lord"], "years": period["years"],
"base_years": None if period["period"] is None else period["period"]["base_years"],
"dignity_adjustment": None if period["period"] is None else period["period"]["dignity_adjustment"]}
if dual == DUAL_LORD_PROFILE:
decision = resolve_dual_lord(sign_idx, lons, strength_scope=strength_scope)
lords = [decision["lord"]] if decision.get("lord") else (
list(_DUAL_PAIRS[sign_idx]) if sign_idx in _DUAL_PAIRS and decision.get("period") else [])
elif dual == "upstream_jaimini_dual_lord_source_v1":
lords = [nd._resolve_narayana_lord(sign_idx, lons, dual_lord_profile="jaimini_dual_lord_source_v1")]
else:
lords = [SIGN_LORDS[SIGNS[sign_idx]]]
values = []
for lord in lords:
lord_sign = nd._get_planet_sign(lord, lons)
if lord_sign is None:
lord_sign = sign_idx
if years == YEARS_PROFILE:
row = rath_period_years(sign_idx, lord, lord_sign)
values.append((row["years"], row["base_years"], row["dignity_adjustment"]))
else:
profile = LEGACY_GRAHA_YEARS_PROFILE if years == LEGACY_GRAHA_YEARS_PROFILE else "legacy_forward_v0"
value, adjustment = nd.calculate_narayana_period_years(sign_idx, lord, lord_sign, profile=profile)
values.append((value, nd.calculate_narayana_duration(sign_idx, lord_sign, profile="jaimini_odd_footed_v1"
if profile != "legacy_forward_v0" else profile), adjustment))
if not values or len({v[0] for v in values}) != 1:
return {"lord": None, "years": None, "base_years": None, "dignity_adjustment": None}
return {"lord": lords[0] if len(lords) == 1 else None, "years": values[0][0],
"base_years": values[0][1], "dignity_adjustment": values[0][2]}
def _running_age(rows: List[Dict[str, Any]], age: Optional[float]) -> Optional[Dict[str, Any]]:
"""Half-open [start, end): a 0-year row is never the running one (N3)."""
if age is None:
return None
return next((row for row in rows if row["start_age"] <= age < row["end_age"]), None)
def branch_under(lagna_sign_idx: int, planet_lons: Dict[str, float], current_age: Optional[float], *,
seed: str = SEED_PROFILE, years: str = YEARS_PROFILE, dual: str = DUAL_LORD_PROFILE,
ad: str = AD_DIRECTION_PROFILE, saturn_ketu: str = SATURN_KETU_DEFAULT,
strength_scope: Optional[str] = None) -> Dict[str, Any]:
"""Running MD / AD with each step on the named profile (one-step swaps for the comparisons).
Ages are unrounded floats on the same 365.25-day axis as the product rows.
R2 local propagation: an unresolved MD length blocks only that segment's end and
later ages. When `current_age` falls before that segment the branch is still
`selected` (with `years_unresolved_from`); otherwise it is blocked at `years`.
An unresolved AD start blocks only the AD (`ad_status: blocked`), never the MD.
"""
ad = AD_PROFILE_ALIASES.get(ad, ad)
lons = _grahas(planet_lons)
picked = _seed_under(seed, lagna_sign_idx, lons, strength_scope=strength_scope)
if picked["status"] != "selected":
return {"status": "blocked", "step": "seed", "reason": picked.get("reason") or "seed_undecided"}
order = md_order(picked["sign_idx"], lons, saturn_ketu=saturn_ketu)
if order["status"] != "selected":
return {"status": "blocked", "step": "seed", "reason": order["reason"],
"seed_sign": SIGNS[picked["sign_idx"]]}
rows: List[Dict[str, Any]] = []
cursor = 0.0
unresolved: Optional[Dict[str, Any]] = None
for sign_idx in order["order"]:
value = _sign_years_under(sign_idx, lons, years=years, dual=dual, strength_scope=strength_scope)
if value["years"] is None:
# 原值:任一宫年数定不出 → 整个分支 blocked(step years)。
# 新值:只截断该宫及之后;之前的大运照常给当前段。原因:占星师 2026-11-08 第六轮 R2。
unresolved = {"sign": SIGNS[sign_idx], "start_age": cursor}
break
rows.append({"sign": SIGNS[sign_idx], "sign_idx": sign_idx, "lord": value["lord"], "years": value["years"],
"start_age": cursor, "end_age": cursor + value["years"], "cycle_index": 1})
cursor += value["years"]
if unresolved is None:
for first in list(rows):
second_years = 12 - first["years"]
rows.append({**first, "years": second_years, "start_age": cursor, "end_age": cursor + second_years,
"cycle_index": 2})
cursor += second_years
out: Dict[str, Any] = {"status": "selected", "seed_sign": SIGNS[picked["sign_idx"]],
"md_years": [(row["sign"], row["years"]) for row in rows[:12]]}
if unresolved is not None:
out["years_unresolved_from"] = unresolved
if current_age is None or current_age >= unresolved["start_age"]:
return {"status": "blocked", "step": "years", "reason": "years_undecided", "sign": unresolved["sign"],
"seed_sign": SIGNS[picked["sign_idx"]], "years_unresolved_from": unresolved}
md = _running_age(rows, current_age)
if md is None:
return {**out, "md": None, "ad": None}
out.update({"md": md["sign"], "md_years_running": md["years"], "md_start_age": md["start_age"],
"md_end_age": md["end_age"], "md_lord": md["lord"], "md_cycle": md["cycle_index"]})
source_ad = ad if ad in AD_PROFILES else AD_DIRECTION_PROFILE
adr = antardasha({**md, "period_key": "branch"}, lons, ad_profile=source_ad, saturn_ketu=saturn_ketu,
strength_scope=strength_scope)
if adr.get("status") != "selected":
return {**out, "ad": None, "ad_status": "blocked", "ad_reason": adr.get("reason")}
rule = adr["antardasha_start_rule"]
start = SIGNS.index(rule["start_sign"])
if ad in AD_PROFILES:
ad_rows = adr["rows"]
direction = rule["direction"]["direction"]
else:
direction = ad_profile_direction(ad, md["sign_idx"], start, lons)["direction"]
step = 1 if direction == "zodiacal" else -1
span = md["years"] / 12.0
ad_rows = [{"sign": SIGNS[(start + step * index) % 12], "start_age": md["start_age"] + span * index,
"end_age": md["end_age"] if index == 11 else md["start_age"] + span * (index + 1)}
for index in range(12)]
running_ad = _running_age(ad_rows, current_age)
return {**out, "ad": running_ad["sign"] if running_ad else None, "ad_status": "selected",
"ad_start_sign": rule["start_sign"], "ad_direction": direction}
def profile_steps(lagna_sign_idx: int, planet_lons: Dict[str, float], current_age: Optional[float], *,
birth_moment: bool = True, ad_profile: Optional[str] = None,
strength_scope: Optional[str] = None) -> Dict[str, Any]:
"""Each named step: its source profile, status and one-step-swap comparisons.
`determined` = the source profile decides and no `comparison` profile changes
the running MD / AD; `disputed` = one does (named in `differs_on`);
`blocked` = the source profile cannot decide (no plausible value is picked).
"""
config = profile_config(ad_profile=ad_profile, strength_scope=strength_scope)
defaults = {"ad": config["ad_direction"], "strength_scope": config["strength_scope"]}
base = branch_under(lagna_sign_idx, planet_lons, current_age, **defaults)
steps: Dict[str, Any] = {}
for name in PROFILE_STEPS:
spec = STEP_PROFILES[name]
step: Dict[str, Any] = {"profile": spec["profile"], "source": spec["source"], "rule": spec["rule"],
"comparisons": []}
if name == "ad_direction":
step["profile"] = config["ad_direction"]
for key in ("convention", "profile_status", "default_choice"):
if key in spec:
step[key] = spec[key]
if name == "start":
step["status"] = "determined" if birth_moment else "blocked"
if not birth_moment:
step["reason"] = "birth_moment_not_supplied"
steps[name] = step
continue
for key, kind, note, param in spec["comparisons"]:
if name == "ad_direction" and key == config["ad_direction"]:
key = AD_DIRECTION_PROFILE if key != AD_DIRECTION_PROFILE else AD_PROFILE_START_PARITY
other = branch_under(lagna_sign_idx, planet_lons, current_age, **{**defaults, param: key})
row = {"profile": key, "kind": kind, "note": note, "status": other["status"]}
if other["status"] == "selected":
row.update({"md": other.get("md"), "ad": other.get("ad"), "seed_sign": other.get("seed_sign")})
if name == "years" or name == "dual_lord":
row["md_years"] = other.get("md_years")
else:
row["reason"] = other.get("reason")
row["differs"] = (other["status"] != base["status"] or (other.get("md"), other.get("ad")) != (base.get("md"), base.get("ad")))
step["comparisons"].append(row)
steps[name] = step
if base["status"] != "selected":
blocked = base["step"]
for name in ("seed", "years", "dual_lord", "ad_start", "ad_direction"):
steps[name]["status"] = ("blocked" if name == blocked or (blocked == "years" and name == "dual_lord")
else "not_reached" if PROFILE_STEPS.index(name) > PROFILE_STEPS.index(blocked)
else "determined")
steps[blocked]["reason"] = base.get("reason")
if blocked == "years":
steps["years"]["sign"] = base.get("sign")
steps["dual_lord"]["reason"] = "dual_lord_undecided_for_sign_years"
steps["dual_lord"]["sign"] = base.get("sign")
else:
for name in ("seed", "years", "dual_lord", "ad_start", "ad_direction"):
differs = [row["profile"] for row in steps[name]["comparisons"] if row["kind"] == "comparison" and row["differs"]]
steps[name]["status"] = "disputed" if differs else "determined"
if differs:
steps[name]["differs_on"] = differs
if base.get("md") is None:
steps["ad_start"]["status"] = "not_applicable"
steps["ad_direction"]["status"] = "not_applicable"
elif base.get("ad_status") != "selected":
# 原值:小运未决一律记 ad_direction blocked。
# 新值:土星 / 计都同在大运宫 → ad_direction blocked(起点已定);其余(取强比较或其宫主未决)→
# ad_start blocked,ad_direction not_reached。原因:占星师 2026-11-09 第七轮回复 R2 选 D;产品负责人同意:小运起点(大运宫对第 7 宫取强)与小运方向是两步,回答要点名对的那一步。
reason = base.get("ad_reason") or "antardasha_not_selected"
if reason == SATURN_KETU_BLOCKED:
steps["ad_direction"]["status"] = "blocked"
steps["ad_direction"]["reason"] = reason
else:
steps["ad_start"]["status"] = "blocked"
steps["ad_start"]["reason"] = reason
steps["ad_direction"]["status"] = "not_reached"
if base.get("years_unresolved_from"):
# R2: the running MD is earlier than the unresolved length; later absolute dates are blocked.
later = base["years_unresolved_from"]
for name in ("years", "dual_lord"):
steps[name]["status"] = "partially_blocked"
steps[name]["reason"] = "dual_lord_undecided_for_sign_years"
steps[name]["sign"] = later["sign"]
steps[name]["blocked_from_age"] = later["start_age"]
return {"schema": "narayana_profile_steps.v1",
"ruling": "astrologer round 5, 2026-11-08, item 1 (B3/B4); item reply N1-N5; round 6 R1 / R2",
"step_profiles": dict(config),
"branch": {key: base.get(key) for key in ("status", "seed_sign", "md", "ad", "md_lord", "ad_start_sign", "ad_direction")},
"steps": steps}
# ── R2 option D: named candidate branches where a step is unresolved ─────────
#
# 占星师 2026-11-09 第七轮回复 §1(R2 选 D;产品负责人同意,BUG-1829 / BUG-1830):
# - the same strength rule at the seed, the AD start and p.43 (d) (STRENGTH_SCOPE_ALL, the default);
# - where a step is unresolved, the named candidates stay as separate branches, each with a
# `branch_id` and its preceding assumptions; the determined parts stay where they are:
# seed (Lagna / 7th) or seed order (Saturn + Ketu in the seed sign) unresolved -> one
# timeline branch per candidate, each with its own full MD sequence and dates;
# one MD length unresolved (p.43 dual lords) -> one timeline branch per length; the dated
# MD rows before it stay in the main `mahadasha`; later dates are per branch;
# AD start (MD sign vs 7th, its lord) or AD direction (Saturn + Ketu in the MD sign)
# unresolved -> one AD branch per candidate for that MD; the MD and its dates stay;
# - branches are never spliced into one timeline: every row of a branch comes from that
# branch's own assumptions;
# - more candidates than the enumeration cap -> `candidates_exhausted = False` (「候选未穷尽」),
# never a silent cut to two;
# - candidates never enter unique scoring or auto-rectification (`used_for_scoring = False`);
# - the old skip-Rule-3 scope `seed_only_v0` is only a visible conditional legacy branch
# (`legacy_conditional_branch`, 「假设跳过 Rule 3 时的结果」): it never overrides the main
# status and never adds an independent vote.
BRANCH_SCHEMA = "narayana_branches.v1"
BRANCH_ENUMERATION_CAP = 16
BRANCH_WINDOW_YEARS = 30.0
BRANCH_STEP_ZH = {"seed": "起运宫", "seed_order": "起运方向", "md_length": "大运年长", "ad_start": "小运起点",
"ad_direction": "小运方向"}
LEGACY_CONDITIONAL_LABEL = "假设跳过 Rule 3 时的结果"
LEGACY_CONDITIONAL_LABEL_EN = "result if Rule 3 is skipped below own sign (conditional legacy branch)"
def _seed_order_candidates(seed_sign_idx: int, planet_lons: Dict[str, float], saturn_ketu: str) -> List[Tuple[Optional[str], List[int]]]:
"""(token, MD sign order) per candidate; one entry with token None when the order is determined."""
order = md_order(seed_sign_idx, planet_lons, saturn_ketu=saturn_ketu)
if order["status"] == "selected":
return [(None, order["order"])]
# Saturn and Ketu both in the seed sign: Table 12 (Ketu) and Table 11 (Saturn) stay named candidates.
return [("ketu_in_start_sign", _rath_ketu_table12_sequence(seed_sign_idx)),
("saturn_in_start_sign", nd.build_narayana_sign_sequence(seed_sign_idx, profile="rath_saturn_table11_v1"))]
def _timeline_rows(order: List[int], planet_lons: Dict[str, float], forced: Dict[int, Dict[str, Any]], *,
strength_scope: str) -> Tuple[List[Dict[str, Any]], Optional[Dict[str, Any]]]:
"""Dated MD rows (two cycles) with `forced` lengths; stops at the first unresolved length."""
rows: List[Dict[str, Any]] = []
cursor = 0.0
for position, sign_idx in enumerate(order, start=1):
sign_period = rath_sign_period(sign_idx, planet_lons, strength_scope=strength_scope)
lord, years = sign_period["lord"], sign_period["years"]
if years is None:
if sign_idx not in forced:
decision = sign_period["decision"]
return rows, {"sign_idx": sign_idx, "position": position,
"reason": decision.get("reason") or "dual_lord_unresolved",
"length_branches": decision.get("length_branches") or []}
lord, years = forced[sign_idx]["lord"], forced[sign_idx]["years"]
rows.append({"sign": SIGNS[sign_idx], "sign_idx": sign_idx, "lord": lord, "years": years, "cycle_index": 1,
"start_age": cursor, "end_age": cursor + years, "zero_duration": years == 0})
cursor += years
for first in list(rows):
years = 12 - first["years"]
rows.append({**first, "years": years, "cycle_index": 2, "start_age": cursor, "end_age": cursor + years,
"zero_duration": years == 0})
cursor += years
return rows, None
def ad_candidates(md_row: Dict[str, Any], planet_lons: Dict[str, float], *,
ad_profile: str = AD_PROFILE_MD_PARITY, saturn_ketu: str = SATURN_KETU_DEFAULT,
strength_scope: Optional[str] = None) -> Dict[str, Any]:
"""The named AD candidates of one dated MD whose AD start or direction is unresolved.
`status: selected` (nothing unresolved, no candidates) or `unresolved` with one
entry per candidate (stronger sign x its lord x direction), each with its twelve
equal rows. Same rules as `antardasha`; never picks one.
"""
ad_profile = AD_PROFILE_ALIASES.get(ad_profile, ad_profile)
scope = strength_scope or STRENGTH_SCOPE_DEFAULT
md_sign_idx = md_row["sign_idx"]
seventh = (md_sign_idx + 6) % 12
main = antardasha(md_row, planet_lons, ad_profile=ad_profile, saturn_ketu=saturn_ketu, strength_scope=scope)
if main["status"] == "selected":
return {"status": "selected", "candidates": []}
comparison = compare_signs(md_sign_idx, seventh, planet_lons, strength_scope=scope)
steps: List[str] = []
if comparison["status"] == "selected":
strongers = [comparison["selected_sign_idx"]]
else:
strongers = [md_sign_idx, seventh]
steps.append("ad_start")
out: List[Dict[str, Any]] = []
for stronger in strongers:
decision = resolve_dual_lord(stronger, planet_lons, strength_scope=scope)
lords = [decision["lord"]] if decision.get("lord") else list(_DUAL_PAIRS.get(stronger, ()))
for lord in lords:
start = nd._get_planet_sign(lord, planet_lons)
if start is None:
continue
picked = ad_profile_direction(ad_profile, md_sign_idx, start, planet_lons, saturn_ketu=saturn_ketu)
if picked["status"] == "selected":
directions = [(None, picked["direction"])]
else:
usual = picked.get("usual_direction") or "zodiacal"
directions = [("ketu_in_md_sign", _flip(usual)), ("saturn_in_md_sign", "zodiacal")]
for exception, direction in directions:
tokens = []
if len(strongers) > 1:
tokens.append(f"start={SIGNS[stronger]}")
if len(lords) > 1:
tokens.append(f"lord={lord}")
if exception:
tokens.append(f"dir={exception}")
step = 1 if direction == "zodiacal" else -1
rows = _equal_rows(md_row, [(start + step * index) % 12 for index in range(12)],
f"{ad_profile}:{direction}:candidate")
out.append({"tokens": tokens, "stronger_sign": SIGNS[stronger], "lord": lord,
"start_sign": SIGNS[start], "direction": direction, "exception": exception,
"rows": rows})
if not steps and any(token.startswith("lord=") for c in out for token in c["tokens"]):
steps.append("ad_start") # stronger sign decided, its dual lord unresolved
if any(c["exception"] for c in out):
steps.append("ad_direction")
return {"status": "unresolved", "reason": main.get("reason"), "steps": steps or ["ad_start"],
"candidates": out}
def _assumption_token(assumption: Dict[str, Any]) -> str:
step = assumption["step"]
if step == "seed":
return f"seed={assumption['value']}"
if step == "seed_order":
return f"order={assumption['value']}"
if step == "md_length":
return f"len:{assumption['md_sign']}={assumption.get('lord')}:{assumption.get('years')}"
return f"{step}={assumption['value']}"
def _overlaps(row: Dict[str, Any], window: Optional[Tuple[float, float]]) -> bool:
if window is None:
return True
return row["start_age"] < window[1] and row["end_age"] > window[0] and row["end_age"] > row["start_age"]
def narayana_branches(lagna_sign_idx: int, planet_lons: Dict[str, float], *,
current_age: Optional[float] = None, strength_scope: Optional[str] = None,
ad_profile: Optional[str] = None, saturn_ketu: str = SATURN_KETU_DEFAULT,
window_years: float = BRANCH_WINDOW_YEARS,
cap: int = BRANCH_ENUMERATION_CAP) -> Dict[str, Any]:
"""R2 option D: every named candidate branch of one chart (see the block comment above).
Timeline branches (seed / seed order / MD length) carry their own MD rows; AD branches
carry the twelve ADs of one MD. With `current_age`, AD branches and AD rows are listed for
the MDs that overlap [current_age, current_age + window_years) only. Ages are unrounded.
"""
lons = _grahas(planet_lons)
scope = strength_scope or STRENGTH_SCOPE_DEFAULT
ad_profile = AD_PROFILE_ALIASES.get(ad_profile or AD_DIRECTION_PROFILE, ad_profile or AD_DIRECTION_PROFILE)
window = None if current_age is None else (float(current_age), float(current_age) + float(window_years))
seventh = (lagna_sign_idx + 6) % 12
seed = seed_comparison(lagna_sign_idx, lons, strength_scope=scope)
branches: List[Dict[str, Any]] = []
determined: List[str] = []
def add(item: Dict[str, Any]) -> None:
branches.append(item)
def ad_branches(rows: List[Dict[str, Any]], parent: Optional[str], assumptions: List[Dict[str, Any]]) -> None:
for md in rows:
if md["zero_duration"] or not _overlaps(md, window):
continue
found = ad_candidates(md, lons, ad_profile=ad_profile, saturn_ketu=saturn_ketu, strength_scope=scope)
if found["status"] == "selected":
continue
md_key = f"ad:{md['cycle_index']}:{md['sign']}"
for candidate in found["candidates"]:
token = ",".join(candidate["tokens"]) or "candidate"
own = {"step": found["steps"][0], "md_sign": md["sign"], "cycle_index": md["cycle_index"],
"value": token}
add({"branch_id": "/".join(part for part in (parent, f"{md_key}:{token}") if part),
"kind": "ad", "parent_branch_id": parent, "unresolved_step": found["steps"][0],
"unresolved_steps": list(found["steps"]), "reason": found.get("reason"),
"md_sign": md["sign"], "md_cycle_index": md["cycle_index"],
"md_start_age": md["start_age"], "md_end_age": md["end_age"], "md_lord": md["lord"],
"candidate": {key: candidate[key] for key in ("stronger_sign", "lord", "start_sign",
"direction", "exception")},
"assumptions": [*assumptions, own], "ad_rows": candidate["rows"],
"used_for_scoring": False})
if seed["status"] == "selected":
seeds: List[Tuple[Optional[str], int]] = [(None, seed["selected_sign_idx"])]
determined.append("seed_common_field" if seed.get("seed_common_field") else "seed")
else:
seeds = [(SIGNS[idx], idx) for idx in (lagna_sign_idx, seventh)]
timeline_count = 0
main_rows: List[Dict[str, Any]] = []
for seed_token, seed_idx in seeds:
base_assumptions = ([{"step": "seed", "value": seed_token, "reason": seed.get("reason")}]
if seed_token else [])
for order_token, order in _seed_order_candidates(seed_idx, lons, saturn_ketu):
assumptions = list(base_assumptions)
if order_token:
assumptions.append({"step": "seed_order", "seed_sign": SIGNS[seed_idx], "value": order_token,
"reason": SATURN_KETU_BLOCKED})
stack: List[Tuple[List[Dict[str, Any]], Dict[int, Dict[str, Any]]]] = [(assumptions, {})]
while stack:
these, forced = stack.pop(0)
rows, pending = _timeline_rows(order, lons, forced, strength_scope=scope)
if pending is not None:
for branch in pending["length_branches"]:
stack.append(([*these, {"step": "md_length", "md_sign": SIGNS[pending["sign_idx"]],
"value": f"lord={branch.get('lord')},years={branch.get('years')}",
"lord": branch.get("lord"), "years": branch.get("years"),
"reason": pending["reason"]}],
{**forced, pending["sign_idx"]: {"lord": branch.get("lord"),
"years": branch.get("years")}}))
if not these and not forced:
main_rows = rows # the dated rows before the unresolved length stay in the main timeline
continue
if not these:
main_rows = rows # fully determined timeline: no timeline branch
continue
timeline_count += 1
branch_id = "/".join(_assumption_token(a) for a in these)
first_dependent = 0
if these[0]["step"] == "md_length":
sign = these[0]["md_sign"]
first_dependent = next(i for i, row in enumerate(rows) if row["sign"] == sign and row["cycle_index"] == 1)
shown = rows[first_dependent:]
# ADs this branch determines itself (no further candidate), for its MDs in the window.
own_ads: List[Dict[str, Any]] = []
for md in shown:
if md["zero_duration"] or window is None or not _overlaps(md, window):
continue
found = antardasha(md, lons, ad_profile=ad_profile, saturn_ketu=saturn_ketu, strength_scope=scope)
if found["status"] == "selected":
own_ads.extend({**row, "parent_cycle_index": md["cycle_index"]} for row in found["rows"]
if _overlaps(row, window))
add({"branch_id": branch_id, "kind": "timeline", "parent_branch_id": None, "ad_rows": own_ads,
"unresolved_step": these[0]["step"],
"unresolved_steps": sorted({a["step"] for a in these}, key=list(BRANCH_STEP_ZH).index),
"reason": these[0].get("reason"), "seed_sign": SIGNS[seed_idx],
"assumptions": these, "md_rows": shown, "md_rows_from_index": first_dependent,
"used_for_scoring": False})
ad_branches(rows[first_dependent:], branch_id, these)
if main_rows:
determined.append("md_dates_before_unresolved" if timeline_count else "md_timeline")
ad_branches(main_rows, None, [])
total = len(branches)
exhausted = total <= cap
return {"schema": BRANCH_SCHEMA, "strength_scope": scope, "ad_profile": ad_profile,
"window_age": list(window) if window else None,
"enumeration_cap": cap, "branch_count": total, "emitted_count": min(total, cap),
"candidates_exhausted": exhausted, "timeline_branch_count": timeline_count,
"determined": determined, "used_for_scoring": False, "unique_scoring": False,
"seed_common_field": seed.get("seed_common_field"),
"branches": branches[:cap]}
def legacy_conditional_branch(lagna_sign_idx: int, planet_lons: Dict[str, float], *,
current_age: Optional[float] = None, ad_profile: Optional[str] = None,
saturn_ketu: str = SATURN_KETU_DEFAULT) -> Dict[str, Any]:
"""The old skip-Rule-3 scope (`seed_only_v0`) as a visible conditional branch only (R2 option D).
Comparison only: `overrides_main_status` and `independent_vote` are always False.
"""
ad = AD_PROFILE_ALIASES.get(ad_profile or AD_DIRECTION_PROFILE, ad_profile or AD_DIRECTION_PROFILE)
branch = branch_under(lagna_sign_idx, planet_lons, current_age, ad=ad, saturn_ketu=saturn_ketu,
strength_scope=STRENGTH_SCOPE_SEED_ONLY)
return {"label": LEGACY_CONDITIONAL_LABEL, "label_en": LEGACY_CONDITIONAL_LABEL_EN,
"kind": "conditional_legacy_branch", "strength_scope": STRENGTH_SCOPE_SEED_ONLY,
"assumption": "rule3_tie_below_own_passed_through",
"status": branch.get("status"), "seed_sign": branch.get("seed_sign"),
"md": branch.get("md"), "md_start_age": branch.get("md_start_age"), "md_end_age": branch.get("md_end_age"),
"ad": branch.get("ad"), "reason": branch.get("reason") or branch.get("ad_reason"),
"overrides_main_status": False, "independent_vote": False, "used_for_scoring": False}