feat(chat): KP dates inside the strip's stretches for career, money and relationship questions — cusp sub lord promise, running lords as significators, Sun / Moon in their stars from a bounded, cached engine tool (BUG-2325)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DbBXp2Vp62Ur3C7yRWQdSq
This commit is contained in:
@@ -0,0 +1,146 @@
|
||||
"""按需计算:KP 推运用的行运星宿主 / 子主时间表(BUG-2325)。
|
||||
|
||||
KP 推运的常规做法:运期主星(大运、小运、细运主星)是这件事的 significator 时,太阳走进它们的星宿(或子)
|
||||
给出月份,月亮走进它们的星宿给出日子,木星走进它们的星宿是更长的背景。本工具只算行运的那一半:
|
||||
一段日期里太阳、月亮、木星每天当地 12:00 的 KP 星宿主(star lord)和子主(sub lord),相同的连续日子合成一段。
|
||||
运期主星和 significator 的比对在问答证据卡里做(frontend/src/lib/chat-kp-timing.ts),这里不读本命盘。
|
||||
|
||||
边界(与协调窗口 2026-11-24 约定,生产机 2 vCPU):
|
||||
- 窗口固定、有上限:最多 MAX_DAYS 天,按天取样(每天一次),不做二分。
|
||||
- 只算三颗星:太阳(星宿主 + 子主)、月亮(只到星宿主,一天之内月亮的子主会换好几次,按天取样没有意义)、
|
||||
木星(星宿主 + 子主)。
|
||||
- KP 岁差(Krishnamurti),在 `temporary_ayanamsa` 里算完即恢复进程原来的岁差。
|
||||
- 结果和本命盘无关,只取决于起始日期、天数、时区和口径,按这几项缓存在进程内(LRU)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from collections import OrderedDict
|
||||
from datetime import timedelta
|
||||
from pathlib import Path
|
||||
from threading import Lock
|
||||
from typing import Any, Dict, List, 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 = 'kp_transit_lords'
|
||||
MAX_DAYS = 400
|
||||
SAMPLE_LOCAL_HOUR = 12.0
|
||||
BODIES: Tuple[Tuple[str, bool], ...] = (('Sun', True), ('Moon', False), ('Jupiter', True))
|
||||
CACHE_MAX_ENTRIES = 64
|
||||
RULES_VERSION = 'kp_transit_lords_v1'
|
||||
|
||||
_CACHE: 'OrderedDict[Tuple[Any, ...], Dict[str, Any]]' = OrderedDict()
|
||||
_CACHE_LOCK = Lock()
|
||||
|
||||
|
||||
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 _kp_helpers():
|
||||
try:
|
||||
from scripts.kp_system import get_kp_lords
|
||||
from scripts.ayanamsa_utils import temporary_ayanamsa
|
||||
except ModuleNotFoundError: # pragma: no cover
|
||||
from kp_system import get_kp_lords # type: ignore[no-redef]
|
||||
from ayanamsa_utils import temporary_ayanamsa # type: ignore[no-redef]
|
||||
return get_kp_lords, temporary_ayanamsa
|
||||
|
||||
|
||||
def cache_key(start: str, days: int, tz: float, node_mode: str) -> Tuple[Any, ...]:
|
||||
"""缓存键:起始日、天数、时区(到 0.01 小时)、交点口径、岁差(固定 KP)、规则版本。与本命盘无关。"""
|
||||
return (start, int(days), round(float(tz), 2), node_mode, 'kp', RULES_VERSION)
|
||||
|
||||
|
||||
def _segments(rows: List[Tuple[str, str, str]], with_sub: bool) -> List[List[str]]:
|
||||
"""按天的 (日期, 星宿主, 子主) 合成 [起, 止(不含), 星宿主, 子主] 段。"""
|
||||
out: List[List[str]] = []
|
||||
for day, star, sub in rows:
|
||||
key = (star, sub if with_sub else '')
|
||||
if out and (out[-1][2], out[-1][3]) == key:
|
||||
continue
|
||||
if out:
|
||||
out[-1][1] = day
|
||||
out.append([day, '', key[0], key[1]])
|
||||
return out
|
||||
|
||||
|
||||
def compute(start: str, days: int, tz: float, node_mode: str = 'mean') -> Dict[str, Any]:
|
||||
"""太阳、月亮、木星每天当地 12:00 的 KP 星宿主 / 子主,合成段。命中缓存时直接返回同一份结果。"""
|
||||
key = cache_key(start, days, tz, node_mode)
|
||||
with _CACHE_LOCK:
|
||||
hit = _CACHE.get(key)
|
||||
if hit is not None:
|
||||
_CACHE.move_to_end(key)
|
||||
return {**hit, 'cache': 'hit'}
|
||||
engine = _engine()
|
||||
get_kp_lords, temporary_ayanamsa = _kp_helpers()
|
||||
if hasattr(engine, '_configure_ephemeris_path'):
|
||||
engine._configure_ephemeris_path() # noqa: SLF001
|
||||
first = contract.parse_date(start, 'start_date')
|
||||
daily: Dict[str, List[Tuple[str, str, str]]] = {name: [] for name, _ in BODIES}
|
||||
with temporary_ayanamsa('kp'):
|
||||
for offset in range(days + 1):
|
||||
day = first + timedelta(days=offset)
|
||||
jd = contract.jd_for_local(day, SAMPLE_LOCAL_HOUR, tz)
|
||||
data, _ayanamsa = engine._calc_sidereal_planets_for_jd( # noqa: SLF001
|
||||
jd, node_mode=node_mode, include_ketu=False, ayanamsa_name='kp',
|
||||
)
|
||||
for name, _with_sub in BODIES:
|
||||
row = data.get(name) or {}
|
||||
lon = row.get('degree_raw', row.get('degree'))
|
||||
if lon is None:
|
||||
continue
|
||||
lords = get_kp_lords(float(lon))
|
||||
daily[name].append((day.strftime('%Y-%m-%d'), str(lords['nakshatra_lord']), str(lords['sub_lord'])))
|
||||
bodies: Dict[str, List[List[str]]] = {}
|
||||
for name, with_sub in BODIES:
|
||||
rows = daily[name]
|
||||
if not rows:
|
||||
continue
|
||||
# The last sampled day only closes the previous segment (the window is [start, start + days)).
|
||||
segments = _segments(rows[:-1], with_sub)
|
||||
if segments:
|
||||
segments[-1][1] = rows[-1][0]
|
||||
bodies[name] = segments
|
||||
result = {
|
||||
'window': {'start': start, 'end': (first + timedelta(days=days)).strftime('%Y-%m-%d'), 'days': days},
|
||||
'sample': f'local {int(SAMPLE_LOCAL_HOUR):02d}:00 daily (tz {tz:+.2f})',
|
||||
'columns': '[from, to (exclusive), star_lord, sub_lord]; Moon sub_lord is empty (day sampling)',
|
||||
'bodies': bodies,
|
||||
'rules_version': RULES_VERSION,
|
||||
}
|
||||
with _CACHE_LOCK:
|
||||
_CACHE[key] = result
|
||||
_CACHE.move_to_end(key)
|
||||
while len(_CACHE) > CACHE_MAX_ENTRIES:
|
||||
_CACHE.popitem(last=False)
|
||||
return {**result, 'cache': 'miss'}
|
||||
|
||||
|
||||
def run(body: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""body:start_date、days(1–400)、lat、lon、tz 或 timezone_id;ayanamsa 必须是 kp。"""
|
||||
try:
|
||||
if not isinstance(body, dict):
|
||||
raise OnDemandInputError('body must be an object')
|
||||
start = contract.parse_date(body.get('start_date'), 'start_date').strftime('%Y-%m-%d')
|
||||
days = int(contract._number(body.get('days'), 'days', 1, MAX_DAYS)) # noqa: SLF001
|
||||
common = contract.validate_common({**body, 'date': start})
|
||||
profile = contract.resolve_profile(body, common)
|
||||
if profile['ayanamsa'] != 'kp':
|
||||
raise OnDemandInputError('ayanamsa must be kp for KP transit lords', 'ayanamsa')
|
||||
except OnDemandInputError as error:
|
||||
return contract.blocked_envelope(tool=TOOL, body=body if isinstance(body, dict) else {}, error=error)
|
||||
raw = compute(start, days, profile['tz'], profile['node_mode'])
|
||||
return contract.build_envelope(tool=TOOL, requested=body, profile=profile, status='executed', raw=raw)
|
||||
@@ -7,7 +7,7 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable, Dict
|
||||
|
||||
from . import dasha_date, prashna, solar_return, transit_date, transit_window, varga
|
||||
from . import dasha_date, kp_transit_lords, prashna, solar_return, transit_date, transit_window, varga
|
||||
from .contract import OnDemandInputError, blocked_envelope
|
||||
|
||||
# 工具名 → run(body) -> envelope
|
||||
@@ -26,6 +26,8 @@ TOOLS: Dict[str, Callable[[Dict[str, Any]], Dict[str, Any]]] = {
|
||||
'varga': varga.run,
|
||||
'dasha_date': dasha_date.run,
|
||||
'prashna': prashna.run, # question_text, question_time, location, ayanamsa
|
||||
# BUG-2325:KP 推运用的太阳、月亮、木星每天的星宿主 / 子主(start_date、days ≤ 400、地点、时区、ayanamsa=kp)。
|
||||
'kp_transit_lords': kp_transit_lords.run,
|
||||
}
|
||||
|
||||
__all__ = ['TOOLS', 'OnDemandInputError', 'ondemand_calc_api']
|
||||
|
||||
Reference in New Issue
Block a user