Ports her yinduzhanxing 17a135457ec16b621f86dd57ba3926612ce1b9b8 (docs ee34700357): timing_evidence_packets.py (new), kp_monthly_report_packet / theme_support / vimshottari / transits, kp_system, with her tests. The report path (frozen engine, no timing systems supplied) keeps its earlier packet byte for byte; her profile and window run when the caller supplies the periods it already computed (engine tool kp_timing_packet, cached per chart and window). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DbBXp2Vp62Ur3C7yRWQdSq
318 lines
19 KiB
Python
318 lines
19 KiB
Python
"""Normalize routed Dasha and transit structures for professional export.
|
||
|
||
Ported from the astrologer's yinduzhanxing 17a135457ec16b621f86dd57ba3926612ce1b9b8 (handoff/product-parity-20261107;
|
||
docs ee34700357ccd3a80f84dede512b9d829abce06f) for BUG-2333. One product difference: the per-period domain association
|
||
re-expresses her ``_calc_dasa_convergence`` ownership / occupancy rule here (``_period_activations``) instead of calling
|
||
the engine's copy — the product's jyotish_engine.py is frozen and its copy has no Narayana input and reads a
|
||
different Vimshottari record shape. The rule and the output rows are hers.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
from typing import Any
|
||
from datetime import datetime, timedelta
|
||
|
||
|
||
def build_multi_system_window(systems: dict[str, dict], *, start: str, end: str,
|
||
boundary_events: list | None = None) -> dict:
|
||
"""Partition already-computed periods; never generate Dasha orders/dates.
|
||
|
||
Each producer keeps its profile. Missing children and blocked alternatives
|
||
are not replaced by another system or a historical variant.
|
||
"""
|
||
left, right = datetime.fromisoformat(start), datetime.fromisoformat(end)
|
||
if left.tzinfo is not None or right.tzinfo is not None or left >= right:
|
||
raise ValueError('window requires increasing local civil datetimes in one explicit timezone')
|
||
boundaries = {left, right}
|
||
events = []
|
||
for event in boundary_events or []:
|
||
stamp = datetime.fromisoformat(event['timestamp_local'])
|
||
if stamp.tzinfo is not None:
|
||
raise ValueError('boundary events require the same local civil timezone')
|
||
if left <= stamp < right:
|
||
boundaries.add(stamp)
|
||
events.append(event)
|
||
tracks = {}
|
||
for name, source in systems.items():
|
||
source = source or {}
|
||
track = {'profile': {key: source[key] for key in
|
||
('calendar_profile', 'kp_profile', 'year_days', 'dasha_year_days', 'selected_method',
|
||
'duration_profile', 'sequence_profile', 'antardasha_profile', 'profile',
|
||
'antardasha_method', 'calculation_profile', 'source') if key in source},
|
||
'periods': [], 'issues': [], 'required_levels': []}
|
||
tracks[name] = track
|
||
if source.get('applicable') is False:
|
||
track['status'] = 'not_applicable'
|
||
track['reason'] = source.get('applicability_reason') or source.get('reason')
|
||
continue
|
||
if not source or source.get('calculation_status') == 'blocked' or source.get('status') == 'blocked' or source.get('error'):
|
||
track['status'] = 'blocked'
|
||
track['reason'] = source.get('error') or source.get('reason') or 'missing_or_blocked_native_timeline'
|
||
continue
|
||
|
||
def accept(row, level, path):
|
||
if level not in track['required_levels']:
|
||
track['required_levels'].append(level)
|
||
try:
|
||
a = datetime.fromisoformat(row.get('start_datetime') or row['start_date'])
|
||
b = datetime.fromisoformat(row.get('end_datetime') or row['end_date'])
|
||
if a.tzinfo is not None or b.tzinfo is not None or a >= b:
|
||
raise ValueError('invalid_local_interval')
|
||
if b <= left or a >= right:
|
||
return
|
||
if str(row.get('source_formula_status', '')).startswith('blocked') or row.get('status') == 'blocked':
|
||
raise ValueError(row.get('blocked_reason') or 'blocked_period')
|
||
label = row.get('sign') or row.get('lord') or row.get('planet')
|
||
if not label:
|
||
raise ValueError('missing_period_identity')
|
||
track['periods'].append({'level': level, 'label': label, 'source_path': path,
|
||
'start': a.isoformat(), 'end': b.isoformat(), 'raw': row})
|
||
boundaries.update((max(a, left), min(b, right)))
|
||
except (KeyError, TypeError, ValueError) as exc:
|
||
track['issues'].append({'source_path': path, 'reason': str(exc)})
|
||
|
||
if isinstance(source.get('dense_boundaries'), list):
|
||
track['required_levels'] = ['MD', 'AD']
|
||
for index, row in enumerate(source['dense_boundaries']):
|
||
accept(row, row.get('level', 'unknown'), f'dense_boundaries[{index}]')
|
||
elif isinstance(source.get('timeline'), list):
|
||
track['required_levels'] = ['MD', 'AD', 'PD']
|
||
for i, md in enumerate(source['timeline']):
|
||
accept(md, 'MD', f'timeline[{i}]')
|
||
for j, ad in enumerate(md.get('antardasha_timeline', [])):
|
||
accept(ad, 'AD', f'timeline[{i}].antardasha_timeline[{j}]')
|
||
for k, pd in enumerate(ad.get('pratyantar_dasha_timeline', [])):
|
||
accept(pd, 'PD', f'timeline[{i}].antardasha_timeline[{j}].pratyantar_dasha_timeline[{k}]')
|
||
elif isinstance(source.get('dasha_sequence'), list):
|
||
track['required_levels'] = ['MD', 'AD', 'PD']
|
||
for i, md in enumerate(source['dasha_sequence']):
|
||
accept(md, 'MD', f'dasha_sequence[{i}]')
|
||
for j, ad in enumerate(md.get('antardashas', [])):
|
||
accept(ad, 'AD', f'dasha_sequence[{i}].antardashas[{j}]')
|
||
for k, pd in enumerate(ad.get('pratyantar_dashas', [])):
|
||
accept(pd, 'PD', f'dasha_sequence[{i}].antardashas[{j}].pratyantar_dashas[{k}]')
|
||
elif isinstance(source.get('major'), list):
|
||
for key, level in (('major', 'MD'), ('antardasha', 'AD'), ('pratyantardasha', 'PD')):
|
||
if key in source:
|
||
track['required_levels'].append(level)
|
||
for i, row in enumerate(source.get(key, [])):
|
||
accept(row, level, f'{key}[{i}]')
|
||
else:
|
||
track['issues'].append({'reason': 'unsupported_native_calendar_schema'})
|
||
track['status'] = 'available' if track['periods'] else 'blocked'
|
||
|
||
edges = sorted(boundaries)
|
||
segments = []
|
||
for a, b in zip(edges, edges[1:]):
|
||
active = {}
|
||
for name, track in tracks.items():
|
||
periods = [p for p in track['periods'] if datetime.fromisoformat(p['start']) <= a < datetime.fromisoformat(p['end'])]
|
||
by_level = {level: [p['source_path'] for p in periods if p['level'] == level]
|
||
for level in track['required_levels']}
|
||
status = track['status']
|
||
if status == 'available':
|
||
status = ('overlap_conflict' if any(len(paths) > 1 for paths in by_level.values()) else
|
||
'coverage_gap' if any(not paths for paths in by_level.values()) else 'covered')
|
||
active[name] = {'status': status, 'period_references': by_level,
|
||
'path': [{'level': p['level'], 'label': p['label']} for p in periods]}
|
||
segments.append({'start': a.isoformat(), 'end_exclusive': b.isoformat(), 'systems': active,
|
||
'boundary_events': [event for event in events
|
||
if datetime.fromisoformat(event['timestamp_local']) == a]})
|
||
for name, track in tracks.items():
|
||
track['window_coverage'] = 'complete' if track['status'] == 'available' and not track['issues'] and all(
|
||
segment['systems'][name]['status'] == 'covered' for segment in segments) else 'not_certified'
|
||
return {'schema': 'jyotish.multi_system_window.v1', 'start': start, 'end_exclusive': end,
|
||
'tracks': tracks, 'segments': segments, 'boundary_count': len(edges),
|
||
'boundary': 'All supplied native period boundaries inside the requested window, not sampled month starts. Shared segmentation does not imply shared meanings, agreement, event probability or continuous transit/birth-time stability.'}
|
||
|
||
|
||
def build_slow_transit_boundaries(*, start: str, end: str, tz: float,
|
||
ayanamsa: str, node_mode: str, position_mode: str) -> dict:
|
||
"""Reuse native ingress/station roots, chunking longer report intervals."""
|
||
import math
|
||
from scripts.transit_search import find_profiled_sign_ingresses, find_stations
|
||
left, right = datetime.fromisoformat(start), datetime.fromisoformat(end)
|
||
if left.tzinfo is not None or right.tzinfo is not None or left >= right:
|
||
raise ValueError('increasing local civil interval required')
|
||
events = []
|
||
cursor = left
|
||
while cursor < right:
|
||
stop = min(cursor + timedelta(days=365), right)
|
||
ingresses = find_profiled_sign_ingresses(cursor.isoformat(), stop.isoformat(), tz=tz,
|
||
ayanamsa=ayanamsa, node_mode=node_mode, position_mode=position_mode)
|
||
events.extend({**row, 'kind': 'sign_ingress'} for row in ingresses['events'])
|
||
for planet in ('Jupiter', 'Saturn'):
|
||
rows = find_stations(planet, cursor.isoformat(), tz, ayanamsa,
|
||
math.ceil((stop-cursor).total_seconds()/86400), position_mode=position_mode)
|
||
events.extend({**row, 'kind': 'station'} for row in rows
|
||
if datetime.fromisoformat(row['timestamp_local']) < stop)
|
||
cursor = stop
|
||
return {'status': 'executed', 'events': sorted(events, key=lambda row: row['timestamp_local']),
|
||
'profile': {'tz': tz, 'ayanamsa': ayanamsa, 'node_mode': node_mode, 'position_mode': position_mode},
|
||
'scope': 'Jupiter/Saturn/node sign ingresses and Jupiter/Saturn stations; not all transits or event triggers.'}
|
||
|
||
|
||
_SIGNS = ('Aries', 'Taurus', 'Gemini', 'Cancer', 'Leo', 'Virgo', 'Libra', 'Scorpio', 'Sagittarius', 'Capricorn',
|
||
'Aquarius', 'Pisces')
|
||
_SIGN_LORDS = {'Aries': 'Mars', 'Taurus': 'Venus', 'Gemini': 'Mercury', 'Cancer': 'Moon', 'Leo': 'Sun',
|
||
'Virgo': 'Mercury', 'Libra': 'Venus', 'Scorpio': 'Mars', 'Sagittarius': 'Jupiter',
|
||
'Capricorn': 'Saturn', 'Aquarius': 'Saturn', 'Pisces': 'Jupiter'}
|
||
# Her _calc_dasa_convergence house_themes_map (yinduzhanxing ee347003 jyotish_engine.py).
|
||
HOUSE_THEMES = {1: 'self_health', 2: 'wealth_family', 3: 'communication_skill', 4: 'home_mother',
|
||
5: 'creativity_children', 6: 'health_service', 7: 'marriage_partnership', 8: 'transformation',
|
||
9: 'fortune_dharma', 10: 'career_status', 11: 'gains_wishes', 12: 'loss_spirituality'}
|
||
_NATIVE_ADAPTERS = {'narayana': ('Narayana', 'sign'), 'chara': ('Chara Dasha', 'sign'), 'yogini': ('Yogini', 'planet'),
|
||
'ashtottari': ('Ashtottari', 'planet'), 'natal_vimshottari': ('Vimshottari', 'planet')}
|
||
|
||
|
||
def _period_activations(system: str, label: str, lons: dict, asc_idx: int) -> dict:
|
||
"""Her convergence rule for one period: a sign period activates the house it occupies (whole sign from the natal
|
||
lagna); a planet period activates the houses its lord owns and the house it occupies. No counts or levels."""
|
||
name, kind = _NATIVE_ADAPTERS[system]
|
||
out: dict = {}
|
||
for house, domain in HOUSE_THEMES.items():
|
||
target_sign = _SIGNS[(asc_idx + house - 1) % 12]
|
||
rows = []
|
||
if kind == 'sign':
|
||
if label in _SIGNS and (_SIGNS.index(label) - asc_idx) % 12 + 1 == house:
|
||
rows.append({'system': name, 'sign': label, 'reason': f'{name} sign {label} occupies house {house}.'})
|
||
else:
|
||
if label == _SIGN_LORDS[target_sign]:
|
||
rows.append({'system': name, 'planet': label, 'reason': f'{label}是{house}宫({target_sign})的宫主星'})
|
||
if label in lons and (int(lons[label] / 30) % 12 - asc_idx) % 12 + 1 == house:
|
||
rows.append({'system': name, 'planet': label, 'reason': f'{label}落在{house}宫'})
|
||
if rows:
|
||
out[domain] = {'house': house, 'activations': rows}
|
||
return out
|
||
|
||
|
||
def build_segment_domain_evidence(window: dict, *, natal_chart: dict, natal_kp: dict) -> dict:
|
||
"""Re-evaluate native domain associations at every supplied period change.
|
||
|
||
No feedback, majority score, event direction or new Dasha formula is used.
|
||
KP significators retain their own cusps; sign/planet periods use natal D1.
|
||
"""
|
||
from scripts.kp_monthly_theme_support import _planet_house_evidence, _DOMAIN_HOUSES
|
||
asc = (natal_chart.get('ascendant') or {}).get('lon')
|
||
if asc is None:
|
||
asc = (natal_chart.get('ascendant') or {}).get('degree_raw')
|
||
lons = {name: row.get('lon', row.get('degree_raw'))
|
||
for name, row in (natal_chart.get('planets') or {}).items() if isinstance(row, dict)}
|
||
lons = {name: value for name, value in lons.items() if isinstance(value, (int, float))}
|
||
segments = []
|
||
for segment in window.get('segments', []):
|
||
evidence = []
|
||
unavailable = []
|
||
for system, state in segment['systems'].items():
|
||
if state['status'] != 'covered':
|
||
unavailable.append({'system': system, 'status': state['status']})
|
||
continue
|
||
for period in state['path']:
|
||
label, level = period['label'], period['level']
|
||
refs = state['period_references'].get(level, [])
|
||
if system == 'kp_vimshottari':
|
||
for domain, houses in _DOMAIN_HOUSES.items():
|
||
association = _planet_house_evidence(natal_kp, label, houses)
|
||
evidence.append({'system': system, 'level': level, 'period': label,
|
||
'domain': domain, 'source_paths': refs, 'evidence': association})
|
||
continue
|
||
if asc is None or not lons:
|
||
unavailable.append({'system': system, 'status': 'natal_structure_missing'})
|
||
continue
|
||
# The existing checker is evaluated one period at a time so
|
||
# children of sign/conditional systems are not silently lost.
|
||
if system not in _NATIVE_ADAPTERS:
|
||
unavailable.append({'system': system, 'status': 'domain_adapter_not_implemented'})
|
||
continue
|
||
for domain, row in _period_activations(system, label, lons, int(asc // 30)).items():
|
||
evidence.append({'system': system, 'level': level, 'period': label,
|
||
'domain': domain, 'house': row['house'], 'source_paths': refs,
|
||
'evidence': row['activations']})
|
||
segments.append({'start': segment['start'], 'end_exclusive': segment['end_exclusive'],
|
||
'boundary_events': segment.get('boundary_events', []),
|
||
'associations': evidence, 'unavailable': unavailable})
|
||
return {'schema': 'jyotish.segment_domain_evidence.v1', 'segments': segments,
|
||
'scope': 'Native occupancy/ownership and separate KP significator associations, not full domain interpretation.',
|
||
'outcome_direction': 'not_adjudicated', 'probability': None,
|
||
'remaining': ['varga_strength_yoga_synthesis', 'event_specific_counterevidence',
|
||
'continuous_transits', 'birth_interval_stability', 'independent_validation']}
|
||
|
||
|
||
def render_segment_domain_evidence(packet: dict) -> list[str]:
|
||
"""Lossless stage association index for the technical report appendix."""
|
||
rows = packet.get('segments', [])
|
||
if not rows:
|
||
return []
|
||
lines = ['#### 多体系阶段依据', '',
|
||
'以下是各阶段的周期关联,不能仅凭关联数量判断吉凶;具体结果仍需结合分盘、强度及制约条件。', '',
|
||
'| 起点(含) | 终点(不含) | 周期及领域依据 | 行运变化 |',
|
||
'|---|---|---|---|']
|
||
def cell(value):
|
||
return str(value).replace('|', '\\|').replace('\n', ' ')
|
||
for row in rows:
|
||
descriptions = []
|
||
for item in row['associations']:
|
||
if item['system'] == 'kp_vimshottari':
|
||
evidence = item['evidence']
|
||
content = f"{item['domain']}:相关宫位{evidence['domain_houses']};资料{evidence['status']}"
|
||
else:
|
||
content = ';'.join(e.get('reason', '') for e in item['evidence'])
|
||
descriptions.append(f"{item['system']} {item['level']} {item['period']}:{content}")
|
||
descriptions.extend(f"{item['system']}:{item['status']}" for item in row['unavailable'])
|
||
changes = [f"{e.get('planet')} {e.get('kind')} {e.get('direction_after', '')}"
|
||
for e in row.get('boundary_events', [])]
|
||
lines.append('| ' + ' | '.join(map(cell, (row['start'], row['end_exclusive'],
|
||
';'.join(descriptions), ';'.join(changes)))) + ' |')
|
||
return lines + ['']
|
||
|
||
|
||
def build_transit_evidence_packet(
|
||
transit: dict[str, Any] | None,
|
||
calculation_profile: dict[str, Any] | None,
|
||
) -> dict[str, Any]:
|
||
transit = transit if isinstance(transit, dict) else {}
|
||
return {
|
||
"status": "computed_pending_validation" if transit else "blocked",
|
||
"inputs": {"calculation_profile": calculation_profile if isinstance(calculation_profile, dict) else {}},
|
||
"raw_results": transit,
|
||
"derived_results": {
|
||
"outcomes": {"status": "blocked", "reason": "Transit events are calculations, not outcome evidence."},
|
||
},
|
||
"external_evidence": {"status": "pending", "reason": "Transit event and duration parity require field-level validation."},
|
||
"limitations": ["No event outcome is inferred from a transit record alone."],
|
||
}
|
||
|
||
|
||
def build_timing_evidence_packet(
|
||
vimshottari: dict[str, Any] | None,
|
||
narayana: dict[str, Any] | None,
|
||
transit: dict[str, Any] | None,
|
||
calculation_profile: dict[str, Any] | None,
|
||
*,
|
||
chara_dasha: dict[str, Any] | None = None,
|
||
ashtottari: dict[str, Any] | None = None,
|
||
) -> dict[str, Any]:
|
||
vimshottari = vimshottari if isinstance(vimshottari, dict) else {}
|
||
narayana = narayana if isinstance(narayana, dict) else {}
|
||
transit = transit if isinstance(transit, dict) else {}
|
||
chara_dasha = chara_dasha if isinstance(chara_dasha, dict) else {}
|
||
ashtottari = ashtottari if isinstance(ashtottari, dict) else {}
|
||
available = any((vimshottari, narayana, transit, chara_dasha, ashtottari))
|
||
return {
|
||
"status": "computed_pending_validation" if available else "blocked",
|
||
"inputs": {"calculation_profile": calculation_profile if isinstance(calculation_profile, dict) else {}},
|
||
"raw_results": {
|
||
"vimshottari": vimshottari,
|
||
"narayana_dasha": narayana,
|
||
"transit": transit,
|
||
"chara_dasha": chara_dasha,
|
||
"ashtottari": ashtottari,
|
||
},
|
||
"derived_results": {
|
||
"chara_dasha": {"status": "available_pending_validation" if chara_dasha else "blocked", "reason": "Routed Chara Dasha raw structure." if chara_dasha else "Chara Dasha producer is not yet routed into the unified archive."},
|
||
"ashtottari": {"status": "available_pending_validation" if ashtottari else "blocked", "reason": "Routed Ashtottari raw structure." if ashtottari else "Ashtottari applicability and producer are not yet routed into the unified archive."},
|
||
"event_assertions": {"status": "blocked", "reason": "Computed time windows do not establish future event outcomes."},
|
||
},
|
||
"external_evidence": {"status": "pending", "reason": "Each timing system requires independent field-level validation."},
|
||
"limitations": ["Raw time boundaries are retained without deterministic event interpretation."],
|
||
}
|