Files
Jyotisha/scripts/ondemand_calc/transit_window.py
T
ClaudeandClaude Opus 5.5 35c87349e3 fix(accept): #174 ingress to_sign/direction and per-time outside-window flags
- to_sign was taken from the JD instead of a longitude, and direction read a
  direct 0° Aries ingress as retrograde; both now come from the step's
  longitudes.
- shadow_entry / shadow_exit / both stations carry outside_requested_window
  as the brief requires; the window end uses the end day's UTC offset.
- 3 regression tests.

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

507 lines
22 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.
"""按需计算:一段时间内的行运变化(#174,BUG-1817)。
占星师 2026-11-07 Q9 / 2026-11-08 第五轮第 9 条:行运窗口要支持**换座、停滞、逆行往返、目标经度**。
数值一律来自引擎的恒星黄经(`jyotish_engine._calc_sidereal_planets_for_jd`),岁差、交点、
位置口径由调用方显式给出;本工具不排本命盘,`natal_point` 要调用方把恒星黄经传进来。
时刻用二分收敛到 ≤ 1 分钟。换座、停滞、目标经度的判定都只看恒星黄经与日速度,不另起算法。
"""
from __future__ import annotations
import sys
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple
from . import contract
from .contract import OnDemandInputError
_SCRIPTS_DIR = Path(__file__).resolve().parents[1]
if str(_SCRIPTS_DIR) not in sys.path:
sys.path.insert(0, str(_SCRIPTS_DIR))
TOOL = 'transit_window'
MAX_WINDOW_DAYS = 366
SEARCH_MARGIN_DAYS = 400
CONVERGENCE_MINUTES = 1
CONVERGENCE_DAYS = CONVERGENCE_MINUTES / 1440.0
PLANETS = ('Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn', 'Rahu', 'Ketu')
STATION_PLANETS = ('Mercury', 'Venus', 'Mars', 'Jupiter', 'Saturn')
EVENT_TYPES = ('ingress', 'station', 'retrograde_loop', 'target_longitude')
COARSE_STEP_HOURS = {'Moon': 6.0, 'default': 24.0}
def _engine():
try:
from scripts import jyotish_engine as engine
except ModuleNotFoundError: # pragma: no cover - 直接跑 scripts/
import jyotish_engine as engine # type: ignore[no-redef]
return engine
def _jd_from_datetime(moment: datetime) -> float:
import swisseph as swe
return swe.julday(
moment.year, moment.month, moment.day,
moment.hour + moment.minute / 60.0 + moment.second / 3600.0,
)
def _local_midnight_jd(day: datetime, tz: float) -> float:
"""当地 00:00 对应的 JD(UT)。"""
return _jd_from_datetime(datetime(day.year, day.month, day.day) - timedelta(hours=tz))
class _Sky:
"""一个区间内按需取恒星黄经与日速度,调用方给的口径固定不变。"""
def __init__(self, engine: Any, profile: Dict[str, Any], planets: Sequence[str]) -> None:
self.engine = engine
self.profile = profile
self.planets = tuple(planets)
if hasattr(engine, '_configure_ephemeris_path'):
engine._configure_ephemeris_path() # noqa: SLF001
self._cache: Dict[float, Dict[str, Dict[str, float]]] = {}
def at(self, jd: float) -> Dict[str, Dict[str, float]]:
key = round(jd, 8)
if key in self._cache:
return self._cache[key]
data, _ayanamsa = self.engine._calc_sidereal_planets_for_jd( # noqa: SLF001
jd,
node_mode=self.profile['node_mode'],
include_ketu=True,
ayanamsa_name=self.profile['ayanamsa'],
)
snapshot: Dict[str, Dict[str, float]] = {}
for name in self.planets:
row = data.get(name)
if not row:
continue
snapshot[name] = {
'lon': float(row.get('degree_raw', row.get('degree', 0.0))),
'speed': float(row.get('speed') or 0.0),
'sign': str(row.get('sign') or ''),
}
self._cache[key] = snapshot
return snapshot
def ayanamsa(self, jd: float) -> float:
data, ayanamsa = self.engine._calc_sidereal_planets_for_jd( # noqa: SLF001
jd,
node_mode=self.profile['node_mode'],
include_ketu=True,
ayanamsa_name=self.profile['ayanamsa'],
)
del data
return float(ayanamsa or 0.0)
def lon(self, planet: str, jd: float) -> Optional[float]:
row = self.at(jd).get(planet)
return None if row is None else row['lon']
def _bisect(predicate: Callable[[float], bool], low: float, high: float,
tolerance: float = CONVERGENCE_DAYS) -> float:
"""在 [low, high] 上找 predicate 从 False 变 True 的位置。"""
lo, hi = low, high
while hi - lo > tolerance:
middle = (lo + hi) / 2.0
if predicate(middle):
hi = middle
else:
lo = middle
return (lo + hi) / 2.0
def _signed_delta(value: float, reference: float) -> float:
"""value - reference,按 0–360 取最短方向(正为顺行方向)。"""
return ((value - reference + 180.0) % 360.0) - 180.0
def _crossed(before: float, after: float, boundary: float) -> bool:
"""从 before 到 after(正向时间)是否跨过 boundary(模 360)。顺行逆行都算。"""
if before == after:
return False
delta = _signed_delta(after, before)
if delta == 0.0:
return False
if delta > 0.0:
return 0.0 < (boundary - before) % 360.0 <= delta
return 0.0 < (before - boundary) % 360.0 <= -delta
def _sign_boundaries(before: float, after: float) -> List[float]:
"""一步之内跨过的所有 30° 整数倍,按行进方向排序。"""
out: List[float] = []
forward = (after - before) % 360.0
if forward == 0.0:
return out
step = 30.0 if forward < 180.0 else -30.0
boundary = ((before // 30.0) + (1 if step > 0 else 0)) * 30.0
travelled = 0.0
guard = 0
while travelled < forward - 1e-9 and guard < 24:
guard += 1
if step > 0:
distance = (boundary - before) % 360.0
if distance > forward:
break
out.append(boundary % 360.0)
travelled = distance
boundary += 30.0
else:
distance = (before - boundary) % 360.0
if distance > (before - after) % 360.0:
break
out.append(boundary % 360.0)
travelled = distance
boundary -= 30.0
return out
def _sign_name(engine: Any, longitude: float) -> str:
signs = getattr(engine, 'SIGNS', None) or []
if not signs:
return ''
return str(signs[int(longitude % 360.0 / 30.0) % 12])
def _utc_stamp(jd: float) -> str:
import swisseph as swe
year, month, day, hour = swe.revjul(jd)
minutes = int(round(hour * 60.0))
return f'{year:04d}-{month:02d}-{day:02d}T{(minutes // 60) % 24:02d}:{minutes % 60:02d}Z'
def _local_parts(jd: float, tz: float) -> Tuple[str, int, int]:
"""当地日期与时分。"""
import swisseph as swe
year, month, day, hour = swe.revjul(jd + tz / 24.0)
minutes = int(round(hour * 60.0))
return f'{year:04d}-{month:02d}-{day:02d}', (minutes // 60) % 24, minutes % 60
def _offset_for_jd(jd: float, tz_fixed: Optional[float], timezone_id: Optional[str]) -> float:
if not timezone_id:
return float(tz_fixed or 0.0)
import swisseph as swe
year, month, day, _hour = swe.revjul(jd + (tz_fixed or 0.0) / 24.0)
return contract.offset_hours(datetime(year, month, day), None, timezone_id)
def _event(engine: Any, sky: _Sky, planet: str, jd: float, kind: str,
tz_fixed: Optional[float], timezone_id: Optional[str]) -> Dict[str, Any]:
row = sky.at(jd).get(planet) or {}
longitude = float(row.get('lon') or 0.0)
offset = _offset_for_jd(jd, tz_fixed, timezone_id)
date_text, hour, minute = _local_parts(jd, offset)
return {
'type': kind,
'planet': planet,
'utc': _utc_stamp(jd),
'local': f'{date_text}T{hour:02d}:{minute:02d}',
'utc_offset_hours': round(offset, 4),
'jd_ut': round(jd, 8),
'longitude': round(longitude, 6),
'sign': _sign_name(engine, longitude),
'degree_in_sign': round(longitude % 30.0, 4),
}
def _sign_index(longitude: float) -> int:
return int(longitude % 360.0 / 30.0) % 12
def _ingress_events(engine: Any, sky: _Sky, planet: str, start_jd: float, end_jd: float,
tz_fixed: Optional[float], timezone_id: Optional[str]) -> List[Dict[str, Any]]:
step = COARSE_STEP_HOURS.get(planet, COARSE_STEP_HOURS['default']) / 24.0
events: List[Dict[str, Any]] = []
jd = start_jd
before = sky.lon(planet, jd)
while jd < end_jd:
nxt = min(jd + step, end_jd)
after = sky.lon(planet, nxt)
if before is None or after is None:
before, jd = after, nxt
continue
if _sign_index(before) != _sign_index(after):
start_sign = _sign_index(before)
at = _bisect(lambda x: _sign_index(sky.lon(planet, x) or before) != start_sign, jd, nxt)
event = _event(engine, sky, planet, at, 'ingress', tz_fixed, timezone_id)
event['from_sign'] = _sign_name(engine, before)
# 验收修正(Claude 2026-11-09):原来 to_sign 用 JD 当黄经取星座、direction 在 0° 白羊处判反;
# 改为按粗扫步末端的黄经取星座,方向按最短角差的正负。
event['to_sign'] = _sign_name(engine, after)
event['direction'] = 'direct' if _signed_delta(after, before) > 0.0 else 'retrograde'
events.append(event)
before, jd = after, nxt
return events
def _station_events(engine: Any, sky: _Sky, planet: str, start_jd: float, end_jd: float,
tz_fixed: Optional[float], timezone_id: Optional[str]) -> List[Dict[str, Any]]:
step = COARSE_STEP_HOURS['default'] / 24.0
events: List[Dict[str, Any]] = []
jd = start_jd
before_row = sky.at(jd).get(planet)
while jd < end_jd:
nxt = min(jd + step, end_jd)
after_row = sky.at(nxt).get(planet)
if not before_row or not after_row:
before_row, jd = after_row, nxt
continue
before_speed = before_row['speed']
after_speed = after_row['speed']
if before_speed == 0.0 or (before_speed < 0) != (after_speed < 0):
at = _bisect(lambda x: (sky.at(x).get(planet, {}).get('speed', 0.0) < 0) != (before_speed < 0), jd, nxt)
event = _event(engine, sky, planet, at, 'station', tz_fixed, timezone_id)
event['station_type'] = 'retrograde' if before_speed >= 0 else 'direct'
event['speed'] = round(float(sky.at(at).get(planet, {}).get('speed', 0.0)), 6)
events.append(event)
before_row, jd = after_row, nxt
return events
def _target_events(engine: Any, sky: _Sky, planet: str, target: float, start_jd: float, end_jd: float,
tz_fixed: Optional[float], timezone_id: Optional[str]) -> List[Dict[str, Any]]:
step = COARSE_STEP_HOURS.get(planet, COARSE_STEP_HOURS['default']) / 24.0
events: List[Dict[str, Any]] = []
jd = start_jd
before = sky.lon(planet, jd)
while jd < end_jd:
nxt = min(jd + step, end_jd)
after = sky.lon(planet, nxt)
if before is None or after is None:
before, jd = after, nxt
continue
if before != after and _crossed(before, after, target):
at = _bisect(lambda x: _crossed(before, sky.lon(planet, x) or before, target), jd, nxt)
event = _event(engine, sky, planet, at, 'target_longitude', tz_fixed, timezone_id)
event['target_longitude'] = round(float(target), 6)
event['direction'] = 'direct' if (after - before) % 360.0 < 180.0 else 'retrograde'
events.append(event)
before, jd = after, nxt
return events
def _retrograde_loops(engine: Any, sky: _Sky, planet: str, start_jd: float, end_jd: float,
tz_fixed: Optional[float], timezone_id: Optional[str],
gaps: List[Dict[str, str]]) -> List[Dict[str, Any]]:
margin = SEARCH_MARGIN_DAYS
stations = _station_events(engine, sky, planet, start_jd - margin, end_jd + margin, tz_fixed, timezone_id)
loops: List[Dict[str, Any]] = []
for index, station in enumerate(stations):
if station.get('station_type') != 'retrograde':
continue
if index + 1 >= len(stations):
continue
direct = stations[index + 1]
if direct.get('station_type') != 'direct':
continue
retro_lon = float(station['longitude'])
direct_lon = float(direct['longitude'])
entry = _find_crossing(engine, sky, planet, direct_lon, station['jd_ut'] - margin * 1.0,
station['jd_ut'], tz_fixed, timezone_id, backwards=True)
exit_ = _find_crossing(engine, sky, planet, retro_lon, direct['jd_ut'],
direct['jd_ut'] + margin * 1.0, tz_fixed, timezone_id, backwards=False)
inside = (start_jd <= station['jd_ut'] <= end_jd) or (start_jd <= direct['jd_ut'] <= end_jd)
if not inside:
continue
for key, value in (('shadow_entry', entry), ('shadow_exit', exit_)):
if value is None:
gaps.append({'field': 'retrograde_loop', 'reason': f'loop_incomplete:{planet}:{key}'})
loops.append({
'planet': planet,
'station_retrograde': station,
'station_direct': direct,
'retrograde_span': [round(direct_lon, 6), round(retro_lon, 6)],
'shadow_entry': entry,
'shadow_exit': exit_,
'outside_requested_window': not (start_jd <= station['jd_ut'] <= end_jd),
})
return loops
def _find_crossing(engine: Any, sky: _Sky, planet: str, longitude: float, low: float, high: float,
tz_fixed: Optional[float], timezone_id: Optional[str],
*, backwards: bool) -> Optional[Dict[str, Any]]:
"""在 [low, high] 内找最后一次(backwards)或第一次(向前)到达 longitude 的时刻。"""
if high <= low:
return None
step = COARSE_STEP_HOURS['default'] / 24.0
found: Optional[float] = None
jd = low
before = sky.lon(planet, jd)
while jd < high:
nxt = min(jd + step, high)
after = sky.lon(planet, nxt)
if before is not None and after is not None and before != after and _crossed(before, after, longitude):
at = _bisect(lambda x: _crossed(before, sky.lon(planet, x) or before, longitude), jd, nxt)
# 向后找「最后一次」到达:从早到晚扫,保留最后一个;向前找「第一次」:命中即停。
found = at
if not backwards:
break
before, jd = after, nxt
if found is None:
return None
return _event(engine, sky, planet, found, 'shadow_crossing', tz_fixed, timezone_id)
def _validate(body: Dict[str, Any]) -> Dict[str, Any]:
if not isinstance(body, dict):
raise OnDemandInputError('body must be an object')
start = contract.parse_date(body.get('start_date'), 'start_date') if body.get('start_date') else None
if start is None:
raise OnDemandInputError('missing required field: start_date', 'start_date')
end = contract.parse_date(body.get('end_date'), 'end_date') if body.get('end_date') else None
if end is None:
raise OnDemandInputError('missing required field: end_date', 'end_date')
if end < start:
raise OnDemandInputError('end_date must be on or after start_date', 'end_date')
if (end - start).days + 1 > MAX_WINDOW_DAYS:
raise OnDemandInputError(f'window must be at most {MAX_WINDOW_DAYS} days', 'end_date')
events = body.get('events')
if not isinstance(events, list) or not events:
raise OnDemandInputError('missing required field: events', 'events')
unknown = [item for item in events if item not in EVENT_TYPES]
if unknown:
raise OnDemandInputError(f'unknown event type: {unknown[0]}', 'events')
planets = body.get('planets')
if planets is None:
planets = list(PLANETS)
if not isinstance(planets, list) or not planets:
raise OnDemandInputError('planets must be a non-empty list', 'planets')
bad = [item for item in planets if item not in PLANETS]
if bad:
raise OnDemandInputError(f'unknown planet: {bad[0]}', 'planets')
target = body.get('target')
if 'target_longitude' in events:
if not isinstance(target, dict):
raise OnDemandInputError('missing required field: target', 'target')
if str(target.get('planet')) not in PLANETS:
raise OnDemandInputError('target.planet must be one of the nine planets', 'target')
has_longitude = target.get('longitude') is not None
has_point = target.get('natal_point') is not None
if not has_longitude and not has_point:
raise OnDemandInputError('target needs longitude or natal_point', 'target')
if has_longitude:
try:
value = float(target['longitude'])
except (TypeError, ValueError) as error:
raise OnDemandInputError('target.longitude must be a number', 'target') from error
if not 0.0 <= value < 360.0:
raise OnDemandInputError('target.longitude must be 0–360', 'target')
if has_point and not isinstance(body.get('natal'), dict):
raise OnDemandInputError('target.natal_point needs natal.points', 'natal')
return {
'start': start,
'end': end,
'planets': list(dict.fromkeys(planets)),
'events': list(dict.fromkeys(events)),
'target': target,
}
def _resolve_target(body: Dict[str, Any], inputs: Dict[str, Any]) -> Tuple[Optional[float], Optional[Dict[str, str]]]:
target = inputs.get('target') or {}
if 'target_longitude' not in inputs['events']:
return None, None
if target.get('longitude') is not None:
return float(target['longitude']), None
name = str(target.get('natal_point'))
points = (body.get('natal') or {}).get('points') if isinstance(body.get('natal'), dict) else None
if not isinstance(points, dict) or name not in points:
return None, {'field': 'target.natal_point', 'reason': f'natal_point_missing:{name}'}
return float(points[name]), None
def run(body: Dict[str, Any]) -> Dict[str, Any]:
try:
inputs = _validate(body)
common = contract.validate_common({**body, 'date': body['start_date']})
profile = contract.resolve_profile({**body, 'date': body['start_date']}, common)
target_longitude, target_gap = _resolve_target(body, inputs)
except OnDemandInputError as error:
return contract.blocked_envelope(tool=TOOL, body=body, error=error)
requested = dict(body)
if target_gap is not None:
return contract.build_envelope(
tool=TOOL, requested=requested, profile=profile, status='blocked', raw={},
gaps=[target_gap],
)
if profile['position_mode'] not in contract.SUPPORTED_POSITION_MODES:
return contract.build_envelope(
tool=TOOL, requested=requested, profile=profile, status='blocked', raw={},
gaps=[{'field': 'position_mode', 'reason': 'position_mode_unsupported'}],
)
tz_fixed = profile['tz'] if not profile.get('timezone_id') else None
timezone_id = profile.get('timezone_id')
try:
engine = _engine()
sky = _Sky(engine, profile, inputs['planets'])
except Exception as error: # noqa: BLE001 - 星历不可用也只留缺口
return contract.build_envelope(
tool=TOOL, requested=requested, profile=profile, status='blocked', raw={},
gaps=[{'field': 'calculation', 'reason': f'engine_failed:{type(error).__name__}'}],
)
start_jd = _local_midnight_jd(inputs['start'], profile['tz'])
end_day = inputs['end'] + timedelta(days=1)
# 验收修正(Claude 2026-11-09):区间终点按终点那天的偏移换算(原来用起始日偏移,跨夏令时差 1 小时)。
end_offset = contract.offset_hours(end_day, None, timezone_id) if timezone_id else profile['tz']
end_jd = _local_midnight_jd(end_day, end_offset)
gaps: List[Dict[str, str]] = []
events: List[Dict[str, Any]] = []
loops: List[Dict[str, Any]] = []
try:
for planet in inputs['planets']:
if 'ingress' in inputs['events']:
events.extend(_ingress_events(engine, sky, planet, start_jd, end_jd, tz_fixed, timezone_id))
if 'station' in inputs['events'] or 'retrograde_loop' in inputs['events']:
if planet in ('Rahu', 'Ketu'):
if 'station' in inputs['events'] or 'retrograde_loop' in inputs['events']:
gaps.append({'field': 'planets', 'reason': f'node_station_not_supported:{planet}'})
elif planet in STATION_PLANETS:
if 'station' in inputs['events']:
events.extend(_station_events(engine, sky, planet, start_jd, end_jd, tz_fixed, timezone_id))
if 'retrograde_loop' in inputs['events']:
loops.extend(_retrograde_loops(engine, sky, planet, start_jd, end_jd, tz_fixed, timezone_id, gaps))
if 'target_longitude' in inputs['events'] and target_longitude is not None and planet == str((inputs['target'] or {}).get('planet')):
events.extend(_target_events(engine, sky, planet, target_longitude, start_jd, end_jd, tz_fixed, timezone_id))
except Exception as error: # noqa: BLE001 - 失败只留缺口,不编任何日期
return contract.build_envelope(
tool=TOOL, requested=requested, profile=profile, status='blocked', raw={},
gaps=[{'field': 'calculation', 'reason': f'engine_failed:{type(error).__name__}'}],
)
events.sort(key=lambda item: item['jd_ut'])
for loop in loops:
for key in ('station_retrograde', 'station_direct'):
stamp = loop.get(key) or {}
loop[f'{key}_outside_window'] = not (start_jd <= float(stamp.get('jd_ut', 0.0)) <= end_jd)
# 验收修正(Claude 2026-11-09):任务书要求落在请求区间外的每个时刻自己标 outside_requested_window。
for key in ('station_retrograde', 'station_direct', 'shadow_entry', 'shadow_exit'):
stamp = loop.get(key)
if isinstance(stamp, dict):
stamp['outside_requested_window'] = not (start_jd <= float(stamp['jd_ut']) <= end_jd)
raw = {
'start_date': inputs['start'].strftime('%Y-%m-%d'),
'end_date': inputs['end'].strftime('%Y-%m-%d'),
'ayanamsa_degrees_at_start': round(sky.ayanamsa(start_jd), 6),
'precision': {
'coarse_step_hours': {planet: COARSE_STEP_HOURS.get(planet, COARSE_STEP_HOURS['default']) for planet in inputs['planets']},
'convergence_minutes': CONVERGENCE_MINUTES,
'search_margin_days': SEARCH_MARGIN_DAYS,
},
'events': events,
'retrograde_loops': loops,
}
status = 'partial' if gaps else 'executed'
return contract.build_envelope(
tool=TOOL, requested=requested, profile=profile, status=status, raw=raw, gaps=gaps,
)