#!/usr/bin/env python3 """Ashtakavarga explicit score fields and the PL9 cell profile (BUG-1699). Port of upstream yinduzhanxing ``ashtakavarga.py`` (``fad247d4``, ``30b43643``): ``ASHTAKAVARGA_PROFILES``, ``PL9_BAV_CELL_OVERRIDES``, ``_apply_ashtakavarga_profile``, ``score_fields`` and ``_map_to_houses_split``. ``scripts/ashtakavarga.py`` is in the rectification frozen identity (ERR-110), so the profile is applied here on a copy of the standard result. The standard result is never modified: ``score_fields`` is a new key, and the PL9 profile is a separate object returned only on request. The PL9 overrides are cells read from one controlled PL9 9.0 display sample (p51-p53); they are a vendor-display replay profile, not a rule, and the standard BPHS/PVR tables stay the default. """ from __future__ import annotations import copy from typing import Dict, List try: import ashtakavarga as _av except ImportError: # pragma: no cover - package import path from scripts import ashtakavarga as _av SIGNS = _av.SIGNS SEVEN_PLANETS = _av.SEVEN_PLANETS ASHTAKAVARGA_PROFILES = ("standard", "pl9") PL9_BAV_CELL_OVERRIDES = { "Moon": { "Taurus": 4, "Leo": 3, "Sagittarius": 4, "Aquarius": 5, }, "Venus": { "Sagittarius": 4, "Capricorn": 4, }, } PL9_PROFILE_BOUNDARY = ( "PL9-compatible p51-p53 source-bound display profile: fixed BAV cells observed in one controlled " "PL9 9.0 sample. Vendor-display replay only; the standard BPHS/PVR result stays the default and " "the source of every reading." ) def _apply_ashtakavarga_profile(bav_results: Dict, profile: str) -> List[Dict]: """Upstream ``_apply_ashtakavarga_profile``; also returns the cells it changed.""" changed: List[Dict] = [] if profile != "pl9": return changed for planet, overrides in PL9_BAV_CELL_OVERRIDES.items(): row = bav_results.get(planet) bindus = row.get("bindus") if isinstance(row, dict) else None if not isinstance(bindus, list) or len(bindus) != 12: continue for sign, value in overrides.items(): index = SIGNS.index(sign) if bindus[index] != value: changed.append({"planet": planet, "sign": sign, "standard": bindus[index], "pl9": value}) bindus[index] = value row["total"] = sum(bindus) row["valid"] = row["total"] == row.get("expected_total") row["deviation"] = abs(row["total"] - row.get("expected_total", 0)) return changed def _map_to_houses_split(sav: List[int], lagna_sav: List[int], full_sav: List[int], asc_sign_idx: int) -> Dict: """Map explicit Ashtakavarga score fields to houses.""" houses = {} for house_num in range(1, 13): sign_idx = (asc_sign_idx + house_num - 1) % 12 houses[f"house_{house_num}"] = { 'sign': SIGNS[sign_idx], 'sav_house_score': sav[sign_idx], 'lagna_bindus': lagna_sav[sign_idx], 'full_with_lagna_house_score': full_sav[sign_idx], 'external_lifemap_bindus': None, } return houses def _rows(result: Dict) -> tuple[List[int], List[int], List[int]]: bav = result.get('bav') if isinstance(result.get('bav'), dict) else {} sav = [0] * 12 for planet in SEVEN_PLANETS: bindus = (bav.get(planet) or {}).get('bindus') if isinstance(bindus, list) and len(bindus) == 12: for i in range(12): sav[i] += int(bindus[i]) lagna = (bav.get('Lagna') or {}).get('bindus') lagna_sav = [int(v) for v in lagna] if isinstance(lagna, list) and len(lagna) == 12 else [0] * 12 full_sav = [sav[i] + lagna_sav[i] for i in range(12)] return sav, lagna_sav, full_sav def build_score_fields(result: Dict, asc_sign_idx: int) -> Dict: """Upstream ``score_fields`` block, built from the result's own BAV rows.""" sav, lagna_sav, full_sav = _rows(result) sign_score_fields = { SIGNS[i]: { "sav_sign_score": sav[i], "lagna_bindus": lagna_sav[i], "full_with_lagna_score": full_sav[i], "field_boundary": "SAV sign score excludes Lagna; full_with_lagna includes Lagna bindus.", } for i in range(12) } return { 'schema': 'ashtakavarga.score_fields.v1', 'canonical_standard': 'JHora/PyJHora SAV/BAV explicit-field profile', 'field_boundary': ( 'Do not compare SAV house score directly with VedAstro AshtakvargaLifeMap bindu. ' 'Store VedAstro LifeMap under external_lifemap_bindus when supplied.' ), 'sign_scores': sign_score_fields, 'house_scores': _map_to_houses_split(sav, lagna_sav, full_sav, int(asc_sign_idx) % 12), 'external_lifemap_bindus': {}, } def attach_score_fields(result: Dict, asc_sign_idx: int) -> Dict: """Add ``profile`` and ``score_fields`` to a standard result in place (new keys only).""" if isinstance(result, dict) and isinstance(result.get('bav'), dict): result.setdefault('profile', 'standard') result['available_profiles'] = list(ASHTAKAVARGA_PROFILES) result['score_fields'] = build_score_fields(result, asc_sign_idx) return result def calc_ashtakavarga_profile(planets: Dict, asc_sign_idx: int, profile: str = "standard", standard: Dict | None = None) -> Dict: """Upstream ``calc_ashtakavarga(planets, asc, profile)`` without touching the frozen file.""" profile = profile if profile in ASHTAKAVARGA_PROFILES else "standard" base = standard if isinstance(standard, dict) else _av.calc_ashtakavarga(planets, asc_sign_idx) if profile == "standard": return attach_score_fields(base, asc_sign_idx) result = copy.deepcopy(base) bav = result['bav'] changed = _apply_ashtakavarga_profile(bav, profile) sav, lagna_sav, full_sav = _rows(result) assessment = [] for i in range(12): score = sav[i] level = "极吉" if score >= 30 else "吉利" if score >= 28 else "中等" if score >= 25 else "挑战" assessment.append({'sign': SIGNS[i], 'score': score, 'level': level}) sav_total = sum(sav) result['sav'] = { 'scores': {SIGNS[i]: sav[i] for i in range(12)}, 'full_scores_with_lagna': {SIGNS[i]: full_sav[i] for i in range(12)}, 'assessment': assessment, 'total': sav_total, 'expected_total': _av.EXPECTED_SAV_TOTAL, 'valid': sav_total == _av.EXPECTED_SAV_TOTAL, 'deviation': abs(sav_total - _av.EXPECTED_SAV_TOTAL), 'full_total_with_lagna': sum(full_sav), } yoga_pinda = _av.calc_yoga_pinda(bav, planets, asc_sign_idx) result['yoga_pinda'] = yoga_pinda result['shodhya_pinda'] = { pname: { 'rashi_pinda': row['rashi_pinda'], 'graha_pinda': row['graha_pinda'], 'total_pinda': row['yoga_pinda'], 'bindu_at_own_sign': row['bindu_at_own_sign'], } for pname, row in yoga_pinda.get('planets', {}).items() } validation = [] all_valid = True for planet in _av.ALL_SOURCES: row = bav[planet] if not row['valid']: all_valid = False validation.append({ 'planet': planet, 'actual': row['total'], 'expected': row['expected_total'], 'status': "✅" if row['valid'] else f"❌ 偏差{row['deviation']}", }) result['bav_validation'] = validation result['all_bav_valid'] = all_valid ranked = sorted(enumerate(assessment), key=lambda x: x[1]['score'], reverse=True) result['strongest_signs'] = [SIGNS[i] for i, _ in ranked[:3]] result['weakest_signs'] = [SIGNS[i] for i, _ in ranked[-3:]] result['house_scores'] = _av._map_to_houses(assessment, asc_sign_idx) result['house_scores_full'] = _av._map_to_houses_values(full_sav, asc_sign_idx) result['method'] = 'Ashtakavarga八分法(PL9-compatible p51-p53 source-bound profile)' result['profile'] = profile result['pl9_changed_cells'] = changed result['profile_boundary'] = PL9_PROFILE_BOUNDARY result['score_fields'] = build_score_fields(result, asc_sign_idx) return result def build_pl9_profile_summary(standard: Dict, planets: Dict, asc_sign_idx: int) -> Dict: """Compact PL9 replay next to the standard result (for the API on request).""" pl9 = calc_ashtakavarga_profile(planets, asc_sign_idx, "pl9", standard=standard) std_scores = ((standard.get('sav') or {}).get('scores') or {}) if isinstance(standard, dict) else {} return { 'status': 'replay_profile', 'profile': 'pl9', 'changed_cells': pl9.get('pl9_changed_cells', []), 'sav_scores': pl9['sav']['scores'], 'sav_total': pl9['sav']['total'], 'sav_delta_vs_standard': { sign: pl9['sav']['scores'][sign] - int(std_scores.get(sign, 0)) for sign in SIGNS }, 'bav': {planet: pl9['bav'][planet]['bindus'] for planet in PL9_BAV_CELL_OVERRIDES}, 'all_bav_valid': pl9['all_bav_valid'], 'boundary': PL9_PROFILE_BOUNDARY, }