Files
Jyotisha/scripts/yoga_expression_paths.py
T

553 lines
41 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.
"""Source-bounded expression adapter for the existing Yoga interpretation pack.
Consumes calculated modules, never life history. No score, event probability,
replacement Yoga detector, period generator, or external service is used here.
"""
from __future__ import annotations
from itertools import combinations
try:
from .yoga_engine import YogaContext, SIGNS, SIGN_LORDS
except ImportError:
from yoga_engine import YogaContext, SIGNS, SIGN_LORDS
PVR = 'P.V.R. Narasimha Rao, Vedic Astrology: An Integrated Approach (2000; 2010 distribution)'
PLANETS = ('Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn')
TOPICS = {'career': (10,), 'resources': (2, 11), 'relationships': (7,),
'learning': (5, 9), 'home': (4,)}
ZH = dict(zip(PLANETS + ('Rahu', 'Ketu'),
('太阳', '月亮', '火星', '水星', '木星', '金星', '土星', '罗睺', '计都')))
def pair(en, zh):
return {'en': en, 'zh': zh}
def _functional_role(functional, planet):
"""Preserve native method/status; list order must not arbitrate conflicts."""
roles = [role for key, role in (
('functional_benefics', 'favourable'),
('functional_malefics', 'challenging'),
('functional_neutrals', 'mixed/neutral')) if planet in (functional.get(key) or [])]
status = (functional.get('planet_status') or {}).get(planet)
unavailable = {'blocked', 'not_implemented', 'evaluation_error', 'not_executed', 'error'}
if status in unavailable or functional.get('status') in unavailable:
role = 'not assessed'
elif len(roles) > 1:
role = 'conflicting classifications'
else:
role = roles[0] if roles else 'not assessed'
return {'role': role, 'reported_roles': roles, 'planet_status': status,
'profile': functional.get('profile'), 'source': functional.get('source'),
'role_basis': (functional.get('role_basis') or {}).get(planet),
'owned_houses': (functional.get('owned_houses') or {}).get(planet)}
def _valid_position(row):
return isinstance(row, dict) and row.get('sign') in SIGNS
def _context(positions, asc):
if asc not in SIGNS:
return None
# The reference changes the houses, never the supplied ecliptic positions.
return YogaContext({p: {**r, 'house': (SIGNS.index(r['sign']) - SIGNS.index(asc)) % 12 + 1}
for p, r in positions.items() if _valid_position(r)}, asc)
def relation_branches(ctx, a, b):
"""PVR 11.7.1 alternatives; directed contacts are retained, not voted."""
if not ctx or a == b or a not in ctx.planets or b not in ctx.planets:
return {'conjunction': None, 'mutual_aspect': None, 'exchange': None,
'a_to_b': None, 'b_to_a': None}
ab, ba = ctx.parashari_aspect(a, b), ctx.parashari_aspect(b, a)
return {'conjunction': ctx.sign_of(a) == ctx.sign_of(b),
'mutual_aspect': ab and ba,
'exchange': SIGN_LORDS[ctx.sign_of(a)] == b and SIGN_LORDS[ctx.sign_of(b)] == a,
'a_to_b': ab, 'b_to_a': ba}
def chain_state(rows):
"""Classify an already calculated chain; never invent its missing tail."""
if not rows:
return 'missing'
seen = set()
for i, row in enumerate(rows):
p, q = row.get('planet'), row.get('dispositor')
if not p or not q or (i and p != rows[i-1].get('dispositor')):
return 'missing'
seen.add(p)
if q == p:
return 'own_sign_terminal' if i == len(rows)-1 else 'inconsistent'
if q in seen:
return 'cycle' if i == len(rows)-1 else 'inconsistent'
return 'truncated'
def partial_raja(ctx, karakas):
"""PVR 11.7.3(1), not a general licence for arbitrary partial Yogas."""
ak = (karakas.get('AK') or {}).get('planet')
pk = (karakas.get('PK') or {}).get('planet')
first = None if not ctx or ak == pk or ak not in ctx.planets or pk not in ctx.planets else ctx.sign_of(ak) == ctx.sign_of(pk)
l1, l5 = (ctx.lord_of_house(1), ctx.lord_of_house(5)) if ctx else (None, None)
second = None if not ctx or l1 == l5 or l1 not in ctx.planets or l5 not in ctx.planets else ctx.sign_of(l1) == ctx.sign_of(l5)
state = ('full' if first is True and second is True else
'source_partial' if first is True or second is True else
'unknown' if first is None or second is None else 'not_met')
return {'status': state, 'checks': {'AK_PK_conjunction': first, 'L1_L5_conjunction': second},
'participants': [p for p in (ak, pk, l1, l5) if p],
'partial_permission': 'PVR 11.7.3(1) only'}
def _row(kind, title, topic, scope, state, facts, meaning, boundary, source, **extra):
return dict(kind=kind, title=title, topic=topic, scope=scope, state=state,
facts=facts, meaning=meaning, boundary=boundary, source=source, **extra)
def _position(ctx, p):
if not ctx or p not in ctx.planets:
return f'{p}: position unavailable'
return f'{p}: {ctx.sign_of(p)}, house {ctx.house_of(p)}'
def _period_rows(dasha):
current = dasha.get('current_dasha') or {}
rows = []
for level, row in [('MD', current), ('AD', current.get('antardasha') or {})]:
if isinstance(row, dict) and row.get('lord'):
rows.append({'level': level, 'lord': row['lord'],
'start': row.get('start_datetime') or row.get('start'),
'end': row.get('end_datetime') or row.get('end')})
ad = current.get('antardasha') or {}
for row in ad.get('pratyantar_dasha_timeline') or []:
if row.get('is_current') is True:
rows.append({'level': 'PD', 'lord': row.get('lord'),
'start': row.get('start_datetime') or row.get('start'),
'end': row.get('end_datetime') or row.get('end')})
return rows
def build_expression_paths(modules, pages=()):
"""Enrich the existing pack using named-source relations and native outputs.
Missing input is local to a path. Method disagreements, common witnesses,
and stage-specific scope remain visible. No user narrative is consumed.
"""
modules = modules or {}
chart = modules.get('chart') or {}
positions = chart.get('planets') or {}
asc = (chart.get('ascendant') or {}).get('sign')
ctx = _context(positions, asc)
rows = []
periods = _period_rows(modules.get('dasha') or {})
functional = modules.get('functional_benefic_malefic') or {}
strength = (modules.get('shadbala') or {}).get('planets') or {}
links = modules.get('inter_chart_linkage') or {}
chains = modules.get('dispositor_chains') or {}
natal = pair('Natal D1, ascendant reference', '本命D1,出生上升参考点')
no_outcome = pair('This describes capacity or thematic support, not an event, amount, rank or guarantee of completion.',
'这里说明能力或主题支持,不确定事件、金额、等级,也不保证完成。')
# A source-explicit non-match is useful: absence from a detected-only list
# cannot otherwise distinguish a failed condition from an unexecuted rule.
for p, name in [('Mars', 'Ruchaka'), ('Mercury', 'Bhadra'), ('Jupiter', 'Hamsa'),
('Venus', 'Malavya'), ('Saturn', 'Sasa')]:
angular = None if not ctx or p not in ctx.planets else ctx.house_of(p) in (1, 4, 7, 10)
dignity = None if angular is None else ctx.is_own_sign(p) or ctx.is_exalted(p)
state = 'unknown' if angular is None else 'full' if angular and dignity else 'not_met'
rows.append(_row('mahapurusha_definition', pair(name+' Yoga', name+' Yoga'), 'capacity', natal, state,
[pair(_position(ctx, p), _position(ctx, p)),
pair(f'Angular house: {angular}; own sign or exaltation: {dignity}.',
f'角宫:{angular};入庙或入旺:{dignity}。')],
pair('The two required conditions are evaluated separately. A favourable dignity alone is not this named Yoga.',
'两项必要条件分别核对;仅有有利尊贵状态不等于此具名格局。'),
pair('Failure of this definition does not establish absence of the planet’s abilities. Other reference-point definitions are separate.',
'此定义未满足不等于该星没有能力;其他参考点定义须另列。'),
PVR+' §11.4, printed pp.117–118; PDF pp.129–130', participants=[p],
checks={'angular': angular, 'dignity': dignity}, partial_permission=False))
karakas = (((modules.get('jaimini') or {}).get('chara_karaka_standard') or {}).get('karakas') or {})
partial = partial_raja(ctx, karakas)
rows.append(_row('source_partial', pair('Two-group Raja combination', '两组条件的Raja组合'), 'career', natal,
partial['status'], [pair(f'{k}: {v}', f'{k}: {v}') for k,v in partial['checks'].items()] +
[pair(_position(ctx,p), _position(ctx,p)) for p in dict.fromkeys(partial['participants'])],
pair('This specific source permits limited expression when either the AK–PK conjunction or the ascendant-lord–fifth-lord conjunction is present; both groups are required for the full form.',
'此处来源明确允许:AK与PK合相、上升主与五宫主合相,两组中至少一组存在时可讨论有限表现;完整形式须两组均满足。'),
pair('No effect percentage is assigned. Missing the other group does not licence the full traditional result; this permission does not extend to other Yogas.',
'不分配效果百分比;缺另一组不能引用完整果报,也不把此许可推广到其他格局。'),
PVR+' §11.7.3(1), printed p.137; PDF p.149', **{k:v for k,v in partial.items() if k!='status'}))
# PVR's legal OR branches, grouped by physical pair, not by role count.
def raja_paths(reference, scope):
rc = _context(positions, reference)
if not rc:
return
groups = {}
for h1 in (1,4,7,10):
for h2 in (1,5,9):
a,b = rc.lord_of_house(h1),rc.lord_of_house(h2)
if a == b: # yogakaraka is a role, not self-conjunction
continue
key = tuple(sorted((a,b)))
groups.setdefault(key, []).append((h1,h2))
for (a,b), roles in groups.items():
branches = relation_branches(rc,a,b)
matched = [k for k in ('conjunction','mutual_aspect','exchange') if branches[k] is True]
if not matched:
continue
role_text = '; '.join(f'{x}/{y}' for x,y in roles)
rows.append(_row('raja_alternative', pair(f'{a}–{b}: Raja association', f'{a}–{b}:Raja联系'),
'career', scope, 'full', [pair(_position(rc,p),_position(rc,p)) for p in (a,b)] +
[pair(f'Quadrant/trine lordships: {role_text}. Satisfied alternatives: {", ".join(matched)}. {a} → {b}: {branches["a_to_b"]}; {b} → {a}: {branches["b_to_a"]}.',
f'角宫/三方宫主职责:{role_text}。满足分支:{", ".join(matched)}。{a} → {b}:{branches["a_to_b"]};{b} → {a}:{branches["b_to_a"]}。')],
pair('A source-permitted alternative establishes this association without requiring every alternative. The traditional theme is responsibility and influence.',
'满足来源许可的一个替代分支即可形成此联系,不要求全部分支同时满足;传统主题为职责与影响力。'),
pair('Shared planets and multiple lordships describe one relationship, not independent confirmations. This is not a promised appointment or promotion.',
'同一行星的多个宫主身份仍是同一联系,不算独立印证;不承诺任职或晋升。'),
PVR+' §11.7.1, printed pp.133–134; PDF pp.145–146',
participants=[a,b], checks=branches, shared_fact_key=[reference,a,b]))
raja_paths(asc,natal)
# The source names contact with Lagna AND HL/GL. Preserve two explicit
# aspect conventions instead of silently mixing them into one definition.
specials=(modules.get('jaimini') or {}).get('special_lagnas') or {}
for key,topic in [('HL','resources'),('GL','career')]:
target=(specials.get(key) or {}).get('sign')
if ctx and target in SIGNS:
for p in PLANETS:
if p not in ctx.planets:continue
for convention in ('planetary','sign'):
contacts={}
for label,sign in [('Lagna',asc),(key,target)]:
kinds=[]
if ctx.sign_of(p)==sign:kinds.append('occupies')
if SIGN_LORDS[sign]==p:kinds.append('owns')
house=(SIGNS.index(sign)-ctx.asc_idx)%12+1
aspect=(ctx.parashari_aspects_house(p,house) if convention=='planetary' else
SIGNS.index(sign) in ctx._rasi_drishti_sign_indices_from(SIGNS.index(ctx.sign_of(p))))
if aspect:kinds.append('aspects')
contacts[label]=kinds
if not all(contacts.values()):continue
rows.append(_row('yogada_variant',pair(f'{p}: Yogada contact with {key}',f'{p}:联系{key}的Yogada条件'),
topic,natal,'context',
[pair(f'{convention} aspect convention; {p} → Lagna ({asc}): {", ".join(contacts["Lagna"])}; {p} → {key} ({target}): {", ".join(contacts[key])}.',
f'{convention}相照方法;{p} → 上升({asc}):{", ".join(contacts["Lagna"])};{p} → {key}({target}):{", ".join(contacts[key])}。')],
pair('The stated contacts provide a source-related '+('resources' if key=='HL' else 'authority')+' theme. The two aspect conventions are separate comparisons.',
'所列联系提供来源相关的'+('资源' if key=='HL' else '权责')+'主题;两种相照方法分开比较。'),
pair('The passage does not settle the aspect convention here. These variants are not independent confirmations and do not create an event promise.',
'此段尚未裁定相照方法;不同变体不是独立印证,也不承诺事件。'),
PVR+' §13.2, printed pp.167–168; PDF pp.179–180',participants=[p],
shared_fact_key=['Yogada',p,key],method_conflict=True))
nar = modules.get('narayana_dasha') or {}
current = nar.get('current_dasha') or {}
md = current.get('md') or {}
if md.get('sign') in SIGNS:
period_scope = pair(f'Narayana major-period reference: {md["sign"]}; calculated age interval {md.get("start_age")}–{md.get("end_age")} years. This does not alter natal D1.',
f'Narayana主运参考点:{md["sign"]};已计算年龄范围{md.get("start_age")}–{md.get("end_age")}岁,不改变本命D1。')
before=len(rows);raja_paths(md['sign'],period_scope)
for row in rows[before:]:
row['source'] += '; '+PVR+' ch.18, PDF p.251'
row['method_conflict'] = bool(nar.get('comparison_required'))
if row['method_conflict']:
row['facts'].append(pair('Narayana method alternatives remain distinct; this is the selected method, not agreement between all methods.',
'Narayana不同取法仍分列;此处采用所选方法,不代表各方法一致。'))
# Independent topical support. Dignity/capacity and role/direction do not
# become a new named Yoga or a claim that all stages of an event succeed.
for topic, houses in TOPICS.items():
for h in houses:
p = ctx.lord_of_house(h) if ctx else None
if not p or p not in positions:
continue
r=positions[p]; good=ctx.is_own_sign(p) or ctx.is_exalted(p)
facts=[pair(f'House {h} lord; {_position(ctx,p)}.', f'{h}宫主;{_position(ctx,p)}。')]
role_evidence = _functional_role(functional, p)
role = role_evidence['role']
owned = role_evidence['owned_houses']
facts.append(pair(f'Functional role in the selected ownership method: {role}. Owned houses: {owned if owned is not None else "not supplied"}.',
f'所选宫主法下的功能角色:{role};掌管宫位:{owned if owned is not None else "未提供"}。'))
method_names = {
'bphs_ch34_general_with_sign_exceptions_v3': pair(
'BPHS chapter 34, general ownership and sign-specific exceptions',
'《BPHS》第34章:宫主通则及各上升的例外'),
'pvr_table30_v1': pair('PVR Table 30 and its Moon-phase qualification',
'PVR表30及月亮盈亏附注'),
}
method = method_names.get(role_evidence['profile'])
if method:
facts.append(pair(f'Functional-role method: {method["en"]}.',
f'功能角色取法:{method["zh"]}。'))
s=strength.get(p) or {}
if s.get('total_rupas') is not None:
facts.append(pair(f'Shadbala: {s["total_rupas"]} Rupas; stated minimum {s.get("min_required")}. This is capacity, not a probability.',
f'Shadbala:{s["total_rupas"]} Rupas;所列最低要求{s.get("min_required")}。这是力量,不是概率。'))
facts.append(pair(f'Combustion: {r.get("combust", "unknown")}; retrograde: {r.get("retrograde", "unknown")}. Retrograde is not a universal gain or veto.',
f'燃烧:{r.get("combust", "unknown")};逆行:{r.get("retrograde", "unknown")}。逆行不统一加分或否决。'))
av=((modules.get('avasthas') or {}).get(p) or {}).get('avasthas') or {}
for system in ('Bala','Jagrat','Deeptadi'):
state=(av.get(system) or {}).get('state')
if state:
facts.append(pair(f'{system} Avastha: {state}; a planetary-state description, not the person’s age or an event outcome.',
f'{system} Avastha:{state};描述行星状态,不是本人年龄或事件结果。'))
for a in (modules.get('aspects') or {}).get('aspects') or []:
if a.get('planet2')==p and a.get('planet1')!=p:
facts.append(pair(f'Incoming contact: {a.get("planet1")} → {p}, {a.get("aspect_degree")}°, orb {a.get("orb")}°. Its effect is not a universal cancellation of Yoga.',
f'受到的联系:{a.get("planet1")} → {p},{a.get("aspect_degree")}°,容许度{a.get("orb")}°。不统一判为格局取消。'))
for div in {'career':('D10',),'resources':('D2','D11'),'relationships':('D9',),
'learning':('D24',),'home':('D4',)}[topic]:
item=(links.get(p) or {}).get(div)
if not item:
varga=next((v for k,v in (modules.get('varga_full') or {}).items() if k.startswith(div+'_')), {})
item=varga.get(p) if isinstance(varga,dict) else None
if item and item.get('sign'):
facts.append(pair(f'{div}: {p} in {item["sign"]}, house {item.get("house", "not supplied")}; separate divisional scope.',
f'{div}:{p}在{item["sign"]},宫位{item.get("house", "未提供")};属于独立分盘范围。'))
chain=chains.get(p) or [];state=chain_state(chain)
path=' → '.join([x['planet'] for x in chain]+[chain[-1]['dispositor']]) if chain and state!='missing' else 'unavailable'
facts.append(pair(f'Dispositor path: {path}; termination: {state}. A link does not automatically transmit beneficial results.',
f'定位路径:{path};终止状态:{state}。联系不自动传递有利果报。'))
for period in periods:
lord=period['lord'];branches=relation_branches(ctx,lord,p)
relations=[k for k in ('conjunction','mutual_aspect','exchange') if branches[k] is True]
if lord==p or relations or branches['a_to_b'] is True or branches['b_to_a'] is True:
evidence='same planet' if lord==p else ', '.join(relations +
([f'{lord} → {p} aspect'] if branches['a_to_b'] else []) +
([f'{p} → {lord} aspect'] if branches['b_to_a'] else []))
facts.append(pair(f'Vimshottari {period["level"]} {lord}, {period["start"] or "start unavailable"} to {period["end"] or "end unavailable"}: {evidence}. Period association only; manifestation has not been established.',
f'Vimshottari {period["level"]} {lord},{period["start"] or "起日未提供"}至{period["end"] or "止日未提供"}:{evidence}。仅为周期联系,未据此确认兑现。'))
meaning=pair('Own-sign or exalted dignity provides a separate capacity-related support for this house lord, even if a named Yoga is absent.',
'此宫主入庙或入旺,提供独立的能力支持,不依赖某个具名格局是否存在。') if good else pair(
'This house-lord path is retained with mixed or limiting conditions; it is not labelled favourable merely to replace an absent Yoga.',
'此宫主路径保留混合或限制条件,不为替代缺失格局而自动标为有利。')
rows.append(_row('independent_house_path',pair(f'House {h} through {p}', f'{h}宫通过{p}'),topic,natal,
'support_with_limits' if good else 'context',facts,meaning,no_outcome,
PVR+' ch.13 (planetary strength and functional nature), printed pp.166–168; PDF pp.178–180',
participants=[p],result_stage='capacity',shared_fact_key=['D1',p],chain_state=state,
functional_role_evidence=role_evidence))
# Carry the actually computed Argala/Virodhargala pair, not just the word
# "Argala" or the presence of a supporting planet.
for topic,houses in TOPICS.items():
for h in houses:
house=((modules.get('argala') or {}).get('houses') or {}).get(f'house_{h}') or {}
for key,a in (house.get('primary') or {}).items():
if not a.get('planets'):
continue
effective=a.get('effective')
rows.append(_row('argala',pair(f'Intervention toward house {h}',f'对{h}宫的介入'),topic,natal,
'support_with_limits' if effective is True else 'limited' if effective is False else 'unknown',
[pair(f'From relative house {a.get("house_from_reference")}: {", ".join(a["planets"])}; opposing house {a.get("blocked_by_house")}: {", ".join(a.get("blockers") or []) or "none listed"}. Effective under the selected comparison: {effective}.',
f'来自相对{a.get("house_from_reference")}宫:{", ".join(a["planets"])};反阻碍宫{a.get("blocked_by_house")}:{", ".join(a.get("blockers") or []) or "未列星体"}。所选比较下有效:{effective}。')],
pair('This describes access to support or interference, not delivery of a final result.', '这里说明支持能否介入及相应阻碍,不等于最终结果交付。'),
pair('The comparison is method-dependent; removing this obstacle does not remove unrelated restrictions.', '强弱比较依方法而定;解除这项阻碍不等于其他限制消失。'),
'Sanjay Rath, Narayana Dasa, pp.34–36; selected native Argala comparison',
participants=list(a['planets'])+list(a.get('blockers') or []),result_stage='opportunity',
shared_fact_key=['Argala',h,key]))
# Preserve cancellation target and surviving limitations without creating
# an exaltation status or cancelling all contrary evidence.
for page in pages:
raw=(page.get('formation_facts') or {}).get('raw_row') or {}
ev=raw.get('formation_evidence') or {}
if not ev.get('cancellation_reasons') or not ev.get('planet'):
continue
p=ev['planet'];f=page.get('formation_assessment') or {}
rows.append(_row('targeted_mitigation',pair(f'{p}: debilitation mitigation',f'{p}:落陷缓解'),'capacity',natal,
'unknown' if f.get('self_reference_only') or not f.get('unqualified_formation_label_allowed') else 'mitigation',
[pair(_position(ctx,p),_position(ctx,p)),pair(f'Only self-reference: {bool(f.get("self_reference_only"))}.',f'是否仅自我参照:{bool(f.get("self_reference_only"))}。')],
pair('The cancellation conditions concern this planet’s debilitation only. The complete named conditions remain in the Yoga details.',
'取消条件仅针对该星落陷;完整具名条件保留在Yoga详情。'),
pair('Original debilitation, functional duties, combustion and other restrictions remain separate. Mitigation is not exaltation or guaranteed recovery.',
'原始落陷、功能职责、燃烧及其他限制仍须分别保留。缓解不等于入旺或保证恢复。'),
(f.get('source') or {}).get('title','Source not resolved')+' p.'+str((f.get('source') or {}).get('page','unavailable')),
participants=[p],shared_fact_key=['debilitation',p]))
# KP is an independent set of cusp and significator observations. It cannot
# veto a Parashari Yoga, or turn contact into legal marriage or receipt.
kp=modules.get('kp') or {}
for topic,houses in TOPICS.items():
for h in houses:
# Native KP uses integer keys; JSON persistence turns them into
# strings. Both must describe the exact same calculated cusp.
cusp=(kp.get('houses') or {}).get(str(h)) or (kp.get('houses') or {}).get(h) or {}
kl=cusp.get('kp_lords') or {};sub=kl.get('sub_lord')
if not sub:
continue
sig=((kp.get('planets') or {}).get(sub) or {}).get('significators') or {}
group_text='; '.join(f'{key}: '+(', '.join(map(str,val)) if isinstance(val,list) and val else 'none listed' if isinstance(val,list) else str(val)) for key,val in sig.items()) or 'not supplied'
rows.append(_row('kp_parallel',pair(f'KP house {h}: {sub}',f'KP {h}宫:{sub}'),topic,
pair('Natal KP cusp reference; separate house method','本命KP宫头参考点;独立宫位方法'),'context',
[pair(f'Cusp {cusp.get("cusp_longitude")}°; star lord {kl.get("nakshatra_lord")}; sub-lord {sub}; sub-lord significator groups '+group_text+'.',
f'宫头{cusp.get("cusp_longitude")}°;星宿主{kl.get("nakshatra_lord")};次主{sub};次主指示分组'+group_text+'。')],
pair('This is a separate event-oriented reference, not another vote for a natal Yoga.', '这是独立的事件参考,不是本命格局的额外票数。'),
pair('Event eligibility, exact timing and agreement with other methods have not been established by these cusp facts alone.',
'仅凭宫头资料尚不能确认事件条件、精确应期或与其他方法一致。'),
'Krishnamurti Paddhati; calculated cusp-to-cusp significator observations',participants=[sub],result_stage='unassessed'))
annual=modules.get('solar_return') or {}
ty=annual.get('tajika_yogas') or {}
for a in ty.get('interactions') or []:
if not a.get('planets'):
continue
rows.append(_row('annual_contact',pair('Annual planetary contact','年度行星联系'),'annual',
pair(f'Solar-return chart {annual.get("target_year")}; return UT {(annual.get("solar_return") or {}).get("dt_ut","unavailable")}',
f'太阳返照年盘{annual.get("target_year")};返照UT {(annual.get("solar_return") or {}).get("dt_ut","未提供")}'),'context',
[pair(f'{" / ".join(a["planets"])}; aspect {a.get("aspect")}°; residual {a.get("residual")}°; motion {a.get("motion")}; within Deeptamsa {a.get("within_deeptamsa")}.',
f'{" / ".join(a["planets"])};相位{a.get("aspect")}°;余差{a.get("residual")}°;运动{a.get("motion")};在Deeptamsa内{a.get("within_deeptamsa")}。')],
pair('The observed motion describes contact at the return, not completion of an event.', '此运动关系说明返照时的联系,不等于事件完成。'),
pair('Station, sign change, obstruction, third-planet mediation and the relevant event lord must be checked before inferring completion. These contacts do not alter natal Yoga definitions.',
'推断完成前须核对停滞、换座、阻断、第三星转递及所问事项主星;年度联系不改变本命格局。'),
PVR+' ch.29; method differences retained in the annual tables',participants=a['planets'],result_stage='contact_only'))
return {'schema':'jyotish.yoga_expression_paths.v1','rows':rows,'periods':periods,
'status':'computed' if ctx else 'missing_natal_reference',
'life_history_used':False,'outcome_probability':None,
'unresolved_mechanisms':['Yogada aspect conventions compared separately, not adjudicated',
'Full source-specific third-planet Tajika completion and movement sequence',
'Continuous birth-interval stability of these paths',
'Independent predictive calibration'],
'trace_identity':'derived_from_calculated_snapshot_not_original_rule_execution_trace'}
def render_expression_paths(pack, language='en'):
"""Self-contained bilingual customer prose; internal keys are not rendered."""
zh=language=='zh'
def say(value):
text = value.get(language,'') if isinstance(value,dict) else str(value)
glossary = {
'AK_PK_conjunction': ('AK与PK同座', 'AK–PK conjunction'),
'L1_L5_conjunction': ('上升主与五宫主同座', 'Ascendant-lord–fifth-lord conjunction'),
'own_sign_terminal': ('止于自座定位星', 'ends with its own-sign dispositor'),
'truncated': ('路径未追踪到终点', 'chain stops before a verified endpoint'),
'inconsistent': ('记录内部不一致', 'inconsistent chain'),
'missing': ('资料缺失', 'missing information'),
'mutual_aspect': ('互照', 'mutual planetary aspect'),
'conjunction': ('同座', 'conjunction'),
'exchange': ('星座交换', 'sign exchange'),
'cycle': ('循环', 'cycle'),
'True': ('是', 'yes'), 'False': ('否', 'no'), 'None': ('未知', 'unknown'),
}
for term, labels in glossary.items():
text=text.replace(term,labels[0 if zh else 1])
if zh:
vocabulary={
PVR:'P.V.R. Narasimha Rao《印度占星综合方法》(2000年初版,2010年分享本)',
'Sanjay Rath, Narayana Dasa':'Sanjay Rath《Narayana Dasa》',
'selected native Argala comparison':'所选Argala强弱比较法',
'Krishnamurti Paddhati; calculated cusp-to-cusp significator observations':'KP体系;已计算的宫头至宫头指示星观察',
'method differences retained in the annual tables':'方法分歧保留在年度表中',
'(planetary strength and functional nature)':'(行星力量与功能属性)',
'Hayanaratna ch.3 (Gansten translation, 2020), comparison only':'《Hayanaratna》第3章(Gansten 2020英译),仅作方法比较',
'Source not resolved':'来源未确定','unavailable':'未提供',
'printed':'印刷页','PDF pp.':'文件页','PDF p.':'文件页',
'pp.':'页','p.':'页','ch.':'章', 'position unavailable':'位置未提供',
'not supplied':'未提供','none listed':'未列项','not assessed':'未评估','unknown':'未知',
'mixed/neutral':'混合/中性','challenging':'功能不利','favourable':'功能有利',
'conflicting classifications':'分类结果冲突',
'same planet':'同一颗星','planetary':'行星','sign aspect':'星座相照',
'sign相照':'星座相照', 'owns':'掌管','occupies':'占据','aspects':'相照',
'aspect':'相照', 'house':'宫', 'applying':'入相','separating':'离相',
'stationary_relative':'相对停滞','exact':'精确接触',
'Infant':'婴儿态','Awake':'清醒态','Youth':'青年态','Old':'老年态',
}
for word,replacement in vocabulary.items():text=text.replace(word,replacement)
for word,replacement in ZH.items():text=text.replace(word,replacement)
for word,replacement in zip(SIGNS,('白羊座','金牛座','双子座','巨蟹座','狮子座','处女座','天秤座','天蝎座','射手座','摩羯座','水瓶座','双鱼座')):
text=text.replace(word,replacement)
return text
titles={'career':pair('Work and responsibility','事业与职责'), 'resources':pair('Resources and income','资源与收入'),
'relationships':pair('Relationships','关系'), 'learning':pair('Learning','学习'),
'home':pair('Home and foundations','家庭与根基'), 'capacity':pair('Named configurations and capacity','具名格局与能力'),
'annual':pair('Annual contacts and completion limits','年度联系与完成条件')}
states={'full':pair('Required definition satisfied','必要定义已满足'),
'not_met':pair('Required definition not satisfied','必要定义未满足'),
'source_partial':pair('Limited expression explicitly permitted by this source','此来源明确许可有限表现'),
'unknown':pair('Required information or source assessment incomplete','所需资料或来源核对未齐'),
'support_with_limits':pair('Support, with separate limitations','存在支持,限制另列'),
'context':pair('Context, not a favourable verdict','背景资料,并非有利裁决'),
'limited':pair('Support obstructed under this method','此方法下支持受阻'),
'mitigation':pair('Target-specific mitigating conditions','针对特定对象的缓解条件')}
lines=['', '## '+('Yoga作用路径:条件、支持与阶段' if zh else 'Yoga Expression: Conditions, Support and Period Context'), '',
('以下按主题连接实际星盘事实。格局缺失不等于能力缺失;同主题路径不等同完整格局。每项说明自身范围,不相加为总分。同一主题内相同的解释限制只写一次,也适用于后续同类路径。' if zh else
'The following paths connect actual chart facts by theme. Absence of a named Yoga is not absence of ability; another path in the same theme is not equivalent to the complete Yoga. Each path retains its own scope, without a combined score. Within each theme, identical reading limits are stated once and also apply to subsequent paths of the same kind.'), '']
for topic in ('career','resources','relationships','learning','home','capacity','annual'):
selected=[r for r in pack.get('rows',[]) if r['topic']==topic]
if not selected:continue
lines+=['### '+say(titles[topic]),'']
seen_meanings=set();seen_limits=set()
for r in selected:
meaning=say(r['meaning']);limit=say(r['boundary'])
lines+=['#### '+say(r['title']),'',say(states[r['state']])+'. '+(meaning if meaning not in seen_meanings else ''),'',
('范围:' if zh else 'Scope: ')+say(r['scope']),'']
lines += ['- '+say(f) for f in r['facts']]
lines += ['',limit if limit not in seen_limits else '', '', ('来源:' if zh else 'Source: ')+say(r['source'])+'.','']
seen_meanings.add(meaning);seen_limits.add(limit)
if not pack.get('rows'):
lines += ['本节缺少已计算的星盘资料,不能判定成立或不成立。' if zh else 'Calculated chart information is unavailable for this section; neither formation nor non-formation can be established.','']
lines+=['### '+('尚未确定的作用环节' if zh else 'Remaining Interpretive Limits'),'',
('未把Yogada的相照口径、第三星转递的完整运动过程或出生时间连续区间稳定性视为已经核定。具名Yoga详情、原始数值和其他方法结果仍保留。这里的传统解释未经过独立事件预测验证。' if zh else
'A Yogada aspect convention, complete motion-based third-planet transfer, and stability across a continuous birth-time interval have not been established here. The detailed named Yogas, original numerical tables and other method results remain available. These traditional interpretations have not been independently validated as event forecasts.'),'']
return '\n'.join(lines)
def attach_expression_paths(packet):
"""Run after late KP/annual attachment; keep the existing pack as owner."""
pack=((packet.get('worksheets') or {}).get('advanced_systems') or {}).get('yoga_interpretation_pack')
if not isinstance(pack,dict):
raise ValueError('Yoga interpretation pack unavailable')
paths=build_expression_paths((packet.get('raw_full_reading') or {}).get('modules') or {},pack.get('pages',[]))
annual=((packet.get('worksheets') or {}).get('timing_and_predictive_systems') or {}).get('annual_tajika_pack') or {}
named=((annual.get('tajika_yogas') or {}).get('data') or {}).get('rows') or []
return_time=((annual.get('solar_return') or {}).get('data') or {}).get('dt_ut')
# The governed annual producer is richer than the raw two-body kernel.
# Preserve its assistance/obstruction witnesses, never its authority label
# as a licence for an event outcome or a cross-lineage rule merger.
grouped={}
for r in named:
name=r.get('named_yoga');participants=tuple(r.get('planets') or [])
if name not in {'Nakta','Yamaya','Manahoo','Rudda','Dutthotta-Daivira','Duphali-Kutta','Tambira','Gairi-Kamboola'}:
continue
grouped.setdefault((name,participants),[]).append(r)
labels={
'interfering_planet':('Interfering planet','干预星'),
'faster_planet':('Faster planet','较快星'), 'slower_planet':('Slower planet','较慢星'),
'afflicted_planet':('Affected planet','受影响星'), 'helper':('Assisting planet','援助星'),
'mediator':('Mediating planet','中介星'), 'affliction':('Limiting condition','限制条件'),
'inimical_aspect':('Interfering aspect (degrees)','干预相位(度)'),
'aspect_residual':('Aspect residual (degrees)','相位余差(度)'),
'deeptamsa_limit':('Deeptamsa limit (degrees)','Deeptamsa界限(度)'),
}
values={'inimical_tajika_rasi_relation':('unfavourable Tajika sign relationship','Tajika不利星座关系'),
'debilitated':('debilitation','落陷'), 'malefic_tajika_aspect':('malefic Tajika contact','Tajika凶性联系')}
for (name,participants),items in grouped.items():
facts=[pair('Participants: '+', '.join(participants),'参与星:'+', '.join(participants))]
seen=set()
for item in items:
pieces=[];pieces_zh=[]
for key,(en,zh) in labels.items():
if item.get(key) is None:continue
val=item[key];translated=values.get(str(val),(str(val),str(val)))
pieces.append(en+': '+translated[0]);pieces_zh.append(zh+':'+translated[1])
ev=item.get('affliction_evidence') or {}
if ev.get('malefic_planets'):
pieces.append('Contact from '+', '.join(ev['malefic_planets']))
pieces_zh.append('联系来自'+', '.join(ev['malefic_planets']))
key='; '.join(pieces)
if key and key not in seen:
seen.add(key);facts.append(pair(key,';'.join(pieces_zh)))
obstruction=name in {'Manahoo','Rudda'}
paths['rows'].append(_row('annual_process',pair(name+' — '+', '.join(participants),name+' — '+', '.join(participants)),
'annual',pair('Annual Tajika; solar return UT '+str(return_time or 'unavailable'),
'年度Tajika;太阳返照UT '+str(return_time or '未提供')),'context',facts,
pair('The selected annual method records '+('interference or a limiting condition affecting the stated contact.' if obstruction else 'a possible mediated or assisted route between the stated participants.'),
'所选年度方法记录了'+('对所列联系的干预或限制条件。' if obstruction else '所列参与星之间可能的转递或援助路径。')),
pair('This does not cancel unrelated natal support. Source variants, event-lord selection, and the actual order of perfection, station and sign change remain separate; neither completion nor failure is guaranteed.',
'这不取消其他本命支持。来源变体、事项主星以及精确接触、停滞、换座的实际先后须分别核对;不保证完成,也不保证失败。'),
PVR+' ch.29; Hayanaratna ch.3 (Gansten translation, 2020), comparison only',
participants=list(participants),result_stage='completion_condition_not_outcome',
shared_fact_key=['annual',name,list(participants)],source_adjudication_complete=False))
pack['expression_paths']=paths
for key in ('json','ai_evidence_bundle'):
if isinstance((pack.get('exports') or {}).get(key),dict):
pack['exports'][key]['expression_paths']=paths
return packet