Files
jesse-ux d92cad065e
Independent Staging Quality Gate / validate-frontend (pull_request) Failing after 3m18s
Independent Staging Quality Gate / validate-python (pull_request) Successful in 6m54s
Independent Staging Quality Gate / publish (pull_request) Skipped
feat(ondemand): add native dasha calculation for a requested date
2026-11-11 15:14:06 +08:00

257 lines
11 KiB
Python
Raw Permalink 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.
"""按需读取指定日的 Vimshottari 和 Narayana 原生运限(#177,BUG-1820)。"""
from __future__ import annotations
from datetime import datetime, timedelta
from importlib import import_module
from typing import Any
from . import contract
from .contract import OnDemandInputError
from .varga import _validate_birth
if __package__ == 'ondemand_calc': # direct scripts/ execution
import narayana_legacy_label as label
import narayana_rath as nr
from chart_dasha import birth_moment
else:
from scripts import narayana_legacy_label as label
from scripts import narayana_rath as nr
from scripts.chart_dasha import birth_moment
TOOL = 'dasha_date'
DEPTHS = ('md', 'ad', 'pd')
def _engine():
return import_module('jyotish_engine' if __package__ == 'ondemand_calc' else 'scripts.jyotish_engine')
def _inputs(body: dict[str, Any]) -> tuple[datetime, datetime, str, dict[str, Any]]:
if not isinstance(body, dict):
raise OnDemandInputError('body must be an object')
birth = _validate_birth(body)
try:
birth_at = datetime(*(birth[key] for key in ('year', 'month', 'day', 'hour', 'minute', 'second')))
except ValueError as exc:
raise OnDemandInputError('birth.day must be a valid calendar day', 'birth.day') from exc
day_value = body.get('date')
day = contract.parse_date(day_value)
if not isinstance(day_value, str) or day.date().isoformat() != day_value:
raise OnDemandInputError('date must be YYYY-MM-DD', 'date')
if not 1900 <= day.year <= 2150:
raise OnDemandInputError('date must be between 1900 and 2150', 'date')
depth = body.get('depth', 'pd')
if depth not in DEPTHS:
raise OnDemandInputError('depth must be md, ad, or pd', 'depth')
# The natal ephemeris and engine timestamps use the birth zone offset.
common = contract.validate_common({**birth, 'date': birth_at.date().isoformat()})
return birth_at, day, depth, contract.resolve_profile(body, common)
def _vim_period(row: dict[str, Any], cycle: int) -> dict[str, Any]:
return {
**row,
'cycle_index': cycle,
'parent_period_start': row.get('parent_period_start', row['start']),
'visible_period_start': row.get('visible_period_start', row['start']),
}
def _vimshottari(
birth_at: datetime, day: datetime, moon: float, tz: float, depth: str,
) -> dict[str, Any]:
day_text = day.date().isoformat()
timeline = birth_moment.compute_vimshottari_timeline(
birth_dt=birth_at, moon_lon=moon, current_date=day,
)
periods = birth_moment.sub_period_timeline(birth_at, moon, through=day, tz_hours=tz)
current = next(
((md, dated) for md, dated in zip(timeline['periods'], periods, strict=True)
if md['start'] <= day_text < md['end']),
None,
)
if current is None:
return {}
md, dated_md = current
cycle = md.get('cycle', 1)
row = {key: value for key, value in dated_md.items() if key != 'antardashas'}
result = {'md': _vim_period({**md, **row}, cycle)}
result['md']['visible_period_start'] = dated_md['antardashas'][0]['start']
if depth == 'md':
return result
ad = next((row for row in dated_md['antardashas'] if row['start'] <= day_text < row['end']), None)
if ad is None:
return result
result['ad'] = _vim_period({key: value for key, value in ad.items() if key != 'pratyantardashas'}, cycle)
if depth == 'pd':
pd = next((row for row in ad['pratyantardashas'] if row[1] <= day_text < row[2]), None)
if pd is not None:
lord, start, end, start_ts, end_ts, *parent_start = pd
result['pd'] = _vim_period({
'lord': lord, 'start': start, 'end': end, 'start_ts': start_ts, 'end_ts': end_ts,
'parent_period_start': parent_start[0] if parent_start else start,
}, cycle)
return result
def _active_age_row(rows: list[dict[str, Any]], age: float) -> dict[str, Any] | None:
return next((row for row in rows if not row.get('zero_duration') and row['start_age'] <= age < row['end_age']), None)
def _dated_row(row: dict[str, Any], birth_at: datetime) -> dict[str, Any]:
return {
**row,
'start_date': label.age_to_date(birth_at, row['start_age']),
'end_date': label.age_to_date(birth_at, row['end_age']),
}
def _branch_at_age(
branch: dict[str, Any], age: float, birth_at: datetime, exhausted: bool,
) -> dict[str, Any] | None:
if branch['kind'] == 'ad':
md = {
'sign': branch['md_sign'], 'lord': branch['md_lord'], 'cycle_index': branch['md_cycle_index'],
'start_age': branch['md_start_age'], 'end_age': branch['md_end_age'],
}
if not md['start_age'] <= age < md['end_age']:
return None
else:
md = _active_age_row(branch['md_rows'], age)
if md is None:
return None
result = {**branch, 'md': _dated_row(md, birth_at), 'candidates_exhausted': exhausted}
ad = _active_age_row(branch['ad_rows'], age)
if ad is not None:
result['ad'] = _dated_row(ad, birth_at)
return result
def _narayana(
asc: int, longitudes: dict[str, float], birth_at: datetime, day: datetime,
) -> tuple[dict[str, Any], list[dict[str, str]]]:
# Match the report's reference clock. On the day of birth the first
# observable moment is birth itself.
reference = max(day, birth_at)
age = label.narayana_age(birth_at, reference)
view = label.rath_narayana_view(asc, longitudes, current_age=age, birth_datetime=birth_at)
config = view['profile_config']
steps = view.get('profile_steps')
if steps is None:
steps = nr.profile_steps(asc, longitudes, age, ad_profile=config['ad_direction'],
strength_scope=config['strength_scope'])
current = view.get('current_dasha') or {}
md, ad = current.get('md'), current.get('ad')
unresolved = {
name: step.get('reason') or step['status']
for name, step in steps['steps'].items() if step['status'] in label.UNRESOLVED_STATUSES
}
if view.get('reason') == nr.SATURN_KETU_BLOCKED:
# The native profile folds blocked seed order into the seed step.
unresolved.pop('seed', None)
unresolved['seed_order'] = view['reason']
raw: dict[str, Any] = {
'algorithm_version': nr.ALGORITHM_VERSION,
'strength_scope': nr.STRENGTH_SCOPE_DEFAULT,
'profile_config': config,
'profile_steps': steps,
'calculation_status': 'blocked',
'unresolved_steps': unresolved,
'branches': [],
'candidates_exhausted': True,
}
gaps = []
if unresolved or not md or not ad:
next_day = day + timedelta(days=1)
branch_data = nr.narayana_branches(
asc, longitudes, current_age=age,
window_years=label.narayana_age(reference, next_day),
strength_scope=config['strength_scope'], ad_profile=config['ad_direction'],
cap=nr.BRANCH_ENUMERATION_CAP,
)
exhausted = branch_data['candidates_exhausted']
raw['branch_schema'] = branch_data['schema']
raw['branches'] = [
candidate for branch in branch_data['branches']
if (candidate := _branch_at_age(branch, age, birth_at, exhausted)) is not None
]
raw['candidates_exhausted'] = exhausted
if not exhausted:
gaps.append({'field': 'narayana.branches', 'reason': 'narayana_candidates_not_exhausted'})
for branch in raw['branches']:
unresolved.setdefault(branch['unresolved_step'], branch.get('reason') or 'blocked')
legacy = view.get('legacy_conditional_branch') or nr.legacy_conditional_branch(
asc, longitudes, current_age=age, ad_profile=config['ad_direction'],
)
if legacy.get('md') is not None or view.get('legacy_conditional_branch'):
raw['legacy_conditional_branch'] = legacy
if md and not md.get('zero_duration'):
raw['md'] = md
raw['ad_status'] = current['ad_status'] if ad else 'blocked'
if ad:
raw['ad'] = ad
else:
raw['ad_reason'] = current.get('ad_reason') or 'antardasha_not_available'
gaps.append({'field': 'narayana.ad', 'reason': raw['ad_reason']})
else:
reason = view.get('reason') or ('years_undetermined' if view.get('years_unresolved') else 'outside_supported_cycles')
gaps.append({'field': 'narayana.md', 'reason': reason})
gaps.extend({'field': f'narayana.profile_steps.{step}', 'reason': reason}
for step, reason in unresolved.items())
if 'md' in raw or raw['branches']:
raw['calculation_status'] = 'partial' if gaps else 'executed'
return raw, gaps
def run(body: dict[str, Any]) -> dict[str, Any]:
try:
birth_at, day, depth, profile = _inputs(body)
except OnDemandInputError as error:
return contract.blocked_envelope(tool=TOOL, body=body, error=error)
except (TypeError, ValueError, OverflowError) as error:
return contract.blocked_envelope(
tool=TOOL, body=body, error=OnDemandInputError(f'input_failed:{type(error).__name__}', 'birth'),
)
requested = {**body, 'depth': depth}
if profile['position_mode'] not in contract.SUPPORTED_POSITION_MODES:
return contract.build_envelope(
tool=TOOL, requested=requested, profile=profile, status='blocked',
gaps=[{'field': 'position_mode', 'reason': 'position_mode_unsupported'}],
)
if day.date() < birth_at.date():
return contract.build_envelope(
tool=TOOL, requested=requested, profile=profile, status='blocked',
gaps=[{'field': 'date', 'reason': 'date_before_birth'}],
)
try:
chart, asc, *_ = _engine().compute_chart_data(
birth_at.year, birth_at.month, birth_at.day, birth_at.hour, birth_at.minute,
profile['lat'], profile['lon'], profile['tz'], node_mode=profile['node_mode'],
second=birth_at.second, ayanamsa_name=profile['ayanamsa'],
)
longitudes = {name: float(chart['planets'][name]['degree_raw']) for name in nr.GRAHAS}
vim = _vimshottari(birth_at, day, longitudes['Moon'], profile['tz'], depth)
narayana, gaps = _narayana(asc, longitudes, birth_at, day)
except Exception as error: # noqa: BLE001 - never leak a partial engine result on failure
return contract.build_envelope(
tool=TOOL, requested=requested, profile=profile, status='blocked',
gaps=[{'field': 'calculation', 'reason': f'engine_failed:{type(error).__name__}'}],
)
missing = [level for level in DEPTHS[:DEPTHS.index(depth) + 1] if level not in vim]
gaps.extend({'field': f'vimshottari.{level}', 'reason': 'period_not_available'} for level in missing)
raw = {
'vimshottari': vim,
'narayana': narayana,
'dual_system_status': ('both_determined' if not missing and 'md' in narayana and 'ad' in narayana
else 'single_system_candidate'),
}
status = 'executed'
if gaps:
status = 'partial' if vim or narayana['calculation_status'] != 'blocked' else 'blocked'
return contract.build_envelope(tool=TOOL, requested=requested, profile=profile, status=status, raw=raw, gaps=gaps)