Files
ClaudeandClaude Opus 5.5 8196387efa
Independent Staging Quality Gate / validate-frontend (push) Successful in 5m6s
Independent Staging Quality Gate / validate-python (push) Successful in 6m36s
Independent Staging Quality Gate / publish (push) Successful in 2m57s
fix(ondemand): varga echoes parashara for D2/D3, labels from VARGA_META, no 0-degree fallback (#176 acceptance, BUG-1819)
- D2/D3 without a variant reported classical_local; the brief asks for
  parashara (identical at 3600 sampled points, echo only).
- usage_labels were a hand-written list that disagreed with VARGA_META.area
  for D9 and D11; now taken from VARGA_META.
- a missing engine longitude silently became 0 deg Aries; now blocked.

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

276 lines
13 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.
"""按需计算:指定分盘及其变体(#176,BUG-1819)。
占星师 2026-11-07 Q9 / 2026-11-08 第五轮第 9 条:
- 分盘按需计算,一次可指定多个(本工具 1–6 个);
- 分盘支持**显式变体**(现有变体只有 D2 的 6 种与 D3 的 4 种);
- Q4 原文:D11「不能被说成所有传统一致采用的财富主盘」。
所以用途名只放 `usage_labels`,并带 `tradition_note`;`raw` 里任何一层都不把用途当唯一含义。
分盘星座与度数全部搬自 `scripts/varga.py` 与 `scripts/divisional_charts_extended.py`,
本工具只做校验、调度与改名,不另起算法,也不依赖任何默认值。
"""
from __future__ import annotations
import sys
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, Final, List, Optional
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 = 'varga'
MAX_DIVISIONS = 6
BIRTH_FIELDS = ('year', 'month', 'day', 'hour', 'minute', 'lat', 'lon')
TRADITION_NOTE = '用途标签因传统而异,不是唯一含义'
PLANETS = ('Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn', 'Rahu', 'Ketu')
# D2 / D3 不指定变体时走 calc_all_vargas 的 classical_local,它与 divisional_charts_extended 的
# parashara 变体逐点相同(验收时 0.05°~359.95° 每 0.1° 实测 3600 点 0 处不同),所以按任务书回显 parashara。
DEFAULT_VARIANT_NAME: Final[Dict[int, str]] = {2: 'parashara', 3: 'parashara'}
def _engine():
try:
from scripts import jyotish_engine as module
except ModuleNotFoundError: # pragma: no cover - 直接跑 scripts/
import jyotish_engine as module # type: ignore[no-redef]
return module
def _varga_module():
try:
from scripts import varga as module
except ModuleNotFoundError: # pragma: no cover
import varga as module # type: ignore[no-redef]
return module
def _extended_calculator():
try:
from scripts import divisional_charts_extended as module
except ModuleNotFoundError: # pragma: no cover
import divisional_charts_extended as module # type: ignore[no-redef]
return module.DivisionalChartsCalculator()
def _int_field(value: Any, field: str, low: int, high: int) -> int:
try:
number = int(value)
except (TypeError, ValueError) as exc:
raise OnDemandInputError(f'{field} must be an integer', field) from exc
if number < low or number > high:
raise OnDemandInputError(f'{field} must be between {low} and {high}', field)
return number
def _float_field(value: Any, field: str, low: float, high: float) -> float:
try:
number = float(value)
except (TypeError, ValueError) as exc:
raise OnDemandInputError(f'{field} must be a number', field) from exc
if number < low or number > high:
raise OnDemandInputError(f'{field} must be between {low} and {high}', field)
return number
def _validate_birth(body: Dict[str, Any]) -> Dict[str, Any]:
birth = body.get('birth')
if not isinstance(birth, dict):
raise OnDemandInputError('missing required field: birth', 'birth')
for field in BIRTH_FIELDS:
value = birth.get(field)
if value is None or (isinstance(value, str) and not value.strip()):
raise OnDemandInputError(f'missing required field: birth.{field}', f'birth.{field}')
if birth.get('tz') is None and not birth.get('timezone_id'):
raise OnDemandInputError('missing required field: birth.tz or birth.timezone_id', 'birth.tz')
second = birth.get('second') or 0
return {
'year': _int_field(birth['year'], 'birth.year', 1800, 2200),
'month': _int_field(birth['month'], 'birth.month', 1, 12),
'day': _int_field(birth['day'], 'birth.day', 1, 31),
'hour': _int_field(birth['hour'], 'birth.hour', 0, 23),
'minute': _int_field(birth['minute'], 'birth.minute', 0, 59),
'second': _int_field(second, 'birth.second', 0, 59),
'lat': _float_field(birth['lat'], 'birth.lat', -90.0, 90.0),
'lon': _float_field(birth['lon'], 'birth.lon', -180.0, 180.0),
'tz': None if birth.get('tz') is None else _float_field(birth['tz'], 'birth.tz', -12.0, 14.0),
'timezone_id': str(birth['timezone_id']) if birth.get('timezone_id') else None,
}
def _validate_divisions(body: Dict[str, Any], available: List[int]) -> List[int]:
raw = body.get('divisions')
if not isinstance(raw, list) or not raw:
raise OnDemandInputError('missing required field: divisions', 'divisions')
if len(raw) > MAX_DIVISIONS:
raise OnDemandInputError(f'divisions accepts at most {MAX_DIVISIONS} entries', 'divisions')
divisions: List[int] = []
for item in raw:
text = str(item).strip().upper()
if not text.startswith('D') or not text[1:].isdigit():
raise OnDemandInputError(f'division must look like D9: {item}', 'divisions')
number = int(text[1:])
if number not in available:
raise OnDemandInputError(f'unknown division: {item}', 'divisions')
if number in divisions:
raise OnDemandInputError(f'duplicate division: {item}', 'divisions')
divisions.append(number)
return divisions
def _validate_variants(body: Dict[str, Any], divisions: List[int], variants_by_division: Dict[str, Dict[str, Any]]) -> Dict[int, str]:
raw = body.get('variants')
if raw is None:
return {}
if not isinstance(raw, dict):
raise OnDemandInputError('variants must be an object', 'variants')
out: Dict[int, str] = {}
for key, value in raw.items():
text = str(key).strip().upper()
if not text.startswith('D') or not text[1:].isdigit():
raise OnDemandInputError(f'variants key must look like D2: {key}', 'variants')
number = int(text[1:])
if number not in divisions:
raise OnDemandInputError(f'variants for a division that is not requested: {key}', 'variants')
allowed = variants_by_division.get(f'D{number}', {}).get('variants') or {}
if not allowed:
raise OnDemandInputError(f'division {text} has no variants', 'variants')
name = str(value).strip().lower()
if name not in allowed:
raise OnDemandInputError(
f'unknown_variant:D{number}:allowed={",".join(sorted(allowed))}', 'variants',
)
out[number] = name
return out
def run(body: Dict[str, Any]) -> Dict[str, Any]:
try:
if not isinstance(body, dict):
raise OnDemandInputError('body must be an object')
birth = _validate_birth(body)
if not body.get('ayanamsa') or (isinstance(body.get('ayanamsa'), str) and not body['ayanamsa'].strip()):
raise OnDemandInputError('missing required field: ayanamsa', 'ayanamsa')
varga_module = _varga_module()
available = sorted(int(key) for key in varga_module.VARGA_META if int(key) <= 60)
divisions = _validate_divisions(body, available)
calculator = _extended_calculator()
variants_by_division = calculator.list_available_variants()
variants = _validate_variants(body, divisions, variants_by_division)
date = datetime(birth['year'], birth['month'], birth['day'])
common_input = {
**body,
'date': date.strftime('%Y-%m-%d'),
'lat': birth['lat'], 'lon': birth['lon'],
'tz': birth['tz'], 'timezone_id': birth['timezone_id'],
}
common = contract.validate_common(common_input)
profile = contract.resolve_profile(common_input, common)
except OnDemandInputError as error:
return contract.blocked_envelope(tool=TOOL, body=body, error=error)
except Exception as error: # noqa: BLE001 - 合同外的输入错误也只留缺口
return contract.blocked_envelope(tool=TOOL, body=body,
error=OnDemandInputError(f'input_failed:{type(error).__name__}', 'input'))
requested = dict(body) if isinstance(body, dict) else {}
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'}],
)
try:
engine = _engine()
engine._configure_ephemeris_path() # noqa: SLF001
# 引擎返回 (chart, year, ayanamsa, jd):chart 里是 ascendant / planets / houses / meta。
chart, *_rest = engine.compute_chart_data(
birth['year'], birth['month'], birth['day'], birth['hour'], birth['minute'],
birth['lat'], birth['lon'], profile['tz'],
node_mode=profile['node_mode'], second=birth['second'], ayanamsa_name=profile['ayanamsa'],
)
natal_planets = {name: row for name, row in (chart.get('planets') or {}).items() if name in PLANETS}
ascendant = chart.get('ascendant') or {}
# 引擎没给经度就当引擎失败(blocked),不拿 0° 白羊顶替。
if ascendant.get('lon') is None:
raise KeyError('ascendant.lon')
asc_lon = float(ascendant['lon'])
missing_planets = [name for name in PLANETS if (natal_planets.get(name) or {}).get('degree_raw') is None]
if missing_planets:
raise KeyError(f'planets.degree_raw:{",".join(missing_planets)}')
planet_lons = {name: float(natal_planets[name]['degree_raw']) for name in PLANETS}
# 标准分盘:逐盘调用(calc_all_vargas 支持批量,但逐盘取 meta 更直观)。
standard = {
number: next(iter(varga_module.calc_all_vargas(planet_lons, asc_lon, divisions=[number]).values()))
for number in divisions if number not in variants
}
# calc_all_vargas 只按批返回,多分盘一次算也可,但逐盘取更直观;这里按需再算变体。
variant_rows = {}
for number, name in variants.items():
rows = {}
for planet, longitude in planet_lons.items():
rows[planet] = calculator.calc_varga_with_variant(longitude, number, name)
rows['Ascendant'] = calculator.calc_varga_with_variant(asc_lon, number, name)
variant_rows[number] = rows
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__}'}],
)
gaps: List[Dict[str, str]] = []
division_rows: List[Dict[str, Any]] = []
for number in divisions:
entry: Dict[str, Any] = {'division': f'D{number}'}
if number in variant_rows:
rows = variant_rows[number]
entry['variant'] = variants[number]
entry['ascendant'] = _sign_of(rows.get('Ascendant'))
entry['planets'] = {planet: _sign_of(rows.get(planet)) for planet in PLANETS if planet in rows}
entry['method'] = {'source': 'divisional_charts_extended.calc_varga_with_variant', 'part_size': None}
else:
data = standard.get(number) or {}
meta = data.get('_meta') or {}
entry['variant'] = DEFAULT_VARIANT_NAME.get(number) or str(meta.get('mapping_source') or 'classical_local')
entry['ascendant'] = _sign_of(data.get('Ascendant'))
entry['planets'] = {planet: _sign_of(data.get(planet)) for planet in PLANETS if planet in data}
entry['method'] = {
'source': str(meta.get('mapping_source') or 'classical_local'),
'part_size': meta.get('part_size'),
}
# 用途标签取自 scripts/varga.py 的 VARGA_META[n]['area'],不手写。
area = (varga_module.VARGA_META.get(number) or {}).get('area')
if area:
entry['usage_labels'] = [str(area)]
entry['tradition_note'] = TRADITION_NOTE
if not entry['planets']:
gaps.append({'field': f'divisions.{number}', 'reason': 'division_rows_missing'})
division_rows.append(entry)
raw = {
'natal': {
'ascendant': {'longitude': asc_lon, 'sign': ascendant.get('sign')},
'planets': {name: {'longitude': planet_lons[name], 'sign': natal_planets[name].get('sign')} for name in planet_lons},
},
'divisions': division_rows,
}
status = 'partial' if gaps else 'executed'
return contract.build_envelope(
tool=TOOL, requested=requested, profile=profile, status=status, raw=raw, gaps=gaps,
)
def _sign_of(row: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
if not isinstance(row, dict):
return None
out: Dict[str, Any] = {'sign': row.get('sign')}
for key in ('sign_idx', 'degree_in_sign', 'longitude'):
if row.get(key) is not None:
out[key] = row[key]
return out