#!/usr/bin/env python3 """Chesta Bala profile candidates (BUG-1699, port of upstream shadbala.py). Upstream yinduzhanxing (5fb8379c) exposes, inside ``calc_shadbala() ["method_variants"]``, the Chesta profile it ran, the variant families observed in external engines and books, and on request a profile switch (``raman_luminary_zero``, ``pyjhora_jhora_replay_target``, ``raman_inferior_planet_assignment``) plus a shadow comparison. ``scripts/shadbala.py`` is in the rectification frozen identity (ERR-110; ``production_scoring_files`` of every freeze record), so this port lives in a sidecar, as ``shadbala_display.py`` did for BUG-1546. The default Chesta values and totals are not touched: everything here is added under new ``method_variants`` keys, and a requested profile is reported next to the default result (``chesta_profile_result``), never written over it. The functions copied from upstream keep their names and output shape: ``build_chesta_profile_candidates``, ``resolve_chesta_profile_selection``, ``build_chesta_target_diagnostic``, ``build_chesta_target_preview``, ``build_chesta_shadow_profile_result``, ``calc_chesta_bala_pyjhora_external``. """ from __future__ import annotations import json import logging import os from typing import Dict logger = logging.getLogger(__name__) _script_dir = os.path.dirname(os.path.abspath(__file__)) CHESTA_VARIANT_PACKET_PATH = os.path.join( _script_dir, '..', 'references', 'oracle', 'shadbala_chesta_variant_packet_2026_07_20.json', ) DEFAULT_CHESTA_PROFILE = "bphs_bounded_surya_mean_motion_seeghrochcha" # The variant packet's values belong to its reference chart, not to the chart # being read (BUG-1699; 占星师第三轮审查 2026-11-07). VALUES_SCOPE = "reference_packet_chart_not_this_chart" SEVEN_PLANETS = ("Sun", "Moon", "Mars", "Mercury", "Jupiter", "Venus", "Saturn") # Upstream calc_shadbala() top-level provenance (references/book_rule_packets.json). SOURCE_REFERENCE_PACKETS = ['science_of_light_v1_strength_interpretation_boundary'] INTERPRETATION_BOUNDARY = ( 'Strength describes magnitude; it must be combined with functional role and other chart ' 'evidence before a conclusion.' ) def build_chesta_profile_candidates() -> Dict: """Expose the current Chesta profile and externally observed variant families.""" fallback = { "selected_profile": DEFAULT_CHESTA_PROFILE, "closure_status": "method_variant_requires_source_choice", "candidate_profiles": [ { "profile_id": DEFAULT_CHESTA_PROFILE, "label": "Local bounded BPHS", "closest_reference_families": ["VedAstro", "jyotishganit"], "selection_boundary": "Current local production profile; keeps bounded BPHS/Seeghrochcha structure explicit.", }, { "profile_id": "pyjhora_jhora_replay_target", "label": "PyJHora/JHora replay target", "closest_reference_families": ["PyJHora/JHora"], "selection_boundary": "Replay target only until authoritative Chesta source choice and second public component case close.", }, { "profile_id": "raman_luminary_zero", "label": "Raman Example 56 luminary zero", "closest_reference_families": ["B. V. Raman Graha and Bhava Balas Example 56", "VP Jain published luminary policy"], "selection_boundary": "Executable profile: Sun and Moon Chesta are set to zero; other planets keep the local bounded Seeghrochcha calculation.", }, { "profile_id": "raman_inferior_planet_assignment", "label": "Historical swapped-input comparison", "closest_reference_families": [], "raman_source_supported": False, "selection_boundary": "Legacy identifier retained for reproducibility. Its Mercury/Venus input swap is not supported by Raman articles 95/99/102; do not treat it as the printed Raman method.", }, { "profile_id": "vp_jain_reference_family", "label": "VP Jain reference family", "closest_reference_families": ["VP Jain published/local variants"], "selection_boundary": "Reference-family only; published and local VP Jain fixtures diverge for luminaries and cannot be treated as one truth.", }, ], "planet_rows": [], "boundary": "Chesta Bala remains profile-sensitive until source-cited variant selection closes.", } try: with open(CHESTA_VARIANT_PACKET_PATH, 'r', encoding='utf-8') as handle: packet = json.load(handle) except (OSError, ValueError) as exc: logger.warning("chesta variant packet unavailable: %s", exc.__class__.__name__) return fallback rows = [] for row in packet.get("rows", []): if not isinstance(row, dict): continue rows.append({ "planet": row.get("planet"), "variant_family": row.get("variant_family"), "closure_classification": row.get("closure_classification"), "next_evidence_owner": row.get("next_evidence_owner"), "normalized_values_virupa": row.get("normalized_values_virupa"), # 占星师第三轮审查 2026-11-07: every row says whose values these are, so a # lookup of one planet never reads them as this chart's Chesta. "values_scope": VALUES_SCOPE, "claim_boundary": row.get("claim_boundary"), }) return { "selected_profile": DEFAULT_CHESTA_PROFILE, "closure_status": "method_variant_requires_source_choice", "candidate_profiles": fallback["candidate_profiles"], "planet_rows": rows, "source_packet": "references/oracle/shadbala_chesta_variant_packet_2026_07_20.json", # BUG-1699: the packet rows are the reference chart's values, not this chart's. "planet_rows_scope": "reference_packet_chart_not_recomputed_for_this_chart", "boundary": packet.get("boundary", fallback["boundary"]), } def resolve_chesta_profile_selection(requested_profile: str | None = None) -> Dict: """Resolve requested Chesta profile against currently executable local profiles.""" profiles = build_chesta_profile_candidates() effective_profile = DEFAULT_CHESTA_PROFILE requested = requested_profile or effective_profile executable_profiles = { effective_profile: "Current local executable Chesta profile is the bounded BPHS/Seeghrochcha variant.", "pyjhora_jhora_replay_target": "Optional external PyJHora/JHora replay target. Upstream runs the installed PyJHora package; the product runtime here does not import jhora, so the local Chesta value is kept (chesta_basis pyjhora_not_called_in_product).", "raman_luminary_zero": "Raman Example 56 executable profile sets Sun and Moon Chesta to zero while preserving the local Seeghrochcha calculation for other planets.", "raman_inferior_planet_assignment": "Historical swapped-input comparison for Mercury and Venus; the legacy identifier is retained for reproducibility, but the input swap is not supported by Raman articles 95/99/102.", } if requested in executable_profiles: return { "requested_profile": requested, "effective_profile": requested, "selection_status": "active_local_profile", "truth_status": "parameter_sensitive", "boundary": executable_profiles[requested], "candidate_profiles": profiles.get("candidate_profiles", []), } return { "requested_profile": requested, "effective_profile": effective_profile, "selection_status": "requested_profile_not_executable_yet", "truth_status": "parameter_sensitive", "boundary": "Requested Chesta target profile is visible in evidence contracts, but local executable runtime still uses the bounded BPHS/Seeghrochcha variant until source-cited variant closure is complete.", "candidate_profiles": profiles.get("candidate_profiles", []), } def build_chesta_target_diagnostic(requested_profile: str) -> Dict: """Summarize which planets and variant families block a target Chesta profile.""" profiles = build_chesta_profile_candidates() rows = profiles.get("planet_rows", []) if requested_profile == "pyjhora_jhora_replay_target": priority_families = [ "luminary_chesta_policy_conflict", "mean_motion_seeghrochcha_variant", "formula_or_unit_mismatch", ] priority_planets = ["Sun", "Moon", "Mercury", "Jupiter", "Saturn", "Mars", "Venus"] else: priority_families = sorted({row.get("variant_family") for row in rows if row.get("variant_family")}) priority_planets = [row.get("planet") for row in rows if row.get("planet")] return { "requested_profile": requested_profile, "status": "diagnostic_only", "priority_families": priority_families, "priority_planets": priority_planets, "row_count": len(rows), "boundary": "Target profile diagnostics summarize current evidence hotspots; they do not imply that the requested profile is executable in the local runtime.", } def build_chesta_target_preview(requested_profile: str) -> Dict: """Expose side-by-side local and target-family Chesta reference values.""" profiles = build_chesta_profile_candidates() rows = [] target_key = "jyotishganit" if requested_profile == "pyjhora_jhora_replay_target" else "local" for row in profiles.get("planet_rows", []): normalized = row.get("normalized_values_virupa") or {} rows.append({ "planet": row.get("planet"), "variant_family": row.get("variant_family"), "closure_classification": row.get("closure_classification"), "local_current_virupa": normalized.get("local"), "target_reference_virupa": normalized.get(target_key), "values_scope": VALUES_SCOPE, "target_reference_family": target_key, "claim_boundary": row.get("claim_boundary"), }) return { "requested_profile": requested_profile, "status": "diagnostic_preview", "target_reference_family": target_key, "rows": rows, "boundary": "Preview values are evidence-side comparison aids. They do not make the requested target profile executable in the local runtime.", } def build_chesta_shadow_profile_result(requested_profile: str, results: Dict) -> Dict: """Recompute total virupas with target-preview Chesta values as a shadow compare mode.""" preview = build_chesta_target_preview(requested_profile) rows = [] for row in preview.get("rows", []): planet = row.get("planet") current = results.get(planet) if not isinstance(current, dict): continue local_chesta = float(current.get("chesta_bala", 0.0) or 0.0) target_chesta = float(row.get("target_reference_virupa", local_chesta) or local_chesta) current_total = float(current.get("total_virupas", 0.0) or 0.0) shadow_total = round(current_total - local_chesta + target_chesta, 2) rows.append({ "planet": planet, "local_chesta_virupa": local_chesta, "target_chesta_virupa": target_chesta, "chesta_delta_virupa": round(target_chesta - local_chesta, 2), "current_total_virupas": round(current_total, 2), "shadow_total_virupas": shadow_total, "shadow_total_rupas": round(shadow_total / 60.0, 2), "target_reference_family": row.get("target_reference_family"), "closure_classification": row.get("closure_classification"), "claim_boundary": row.get("claim_boundary"), }) return { "requested_profile": requested_profile, "status": "shadow_compare_only", "rows": rows, "boundary": "Shadow totals swap only the Chesta component using target-preview values. This is compare mode, not formula closure.", } def calc_chesta_bala_pyjhora_external(pname: str, context: Dict) -> float | None: """PyJHora replay target: not called from the product runtime. Upstream imports the AGPL ``jhora`` package here at request time. Product entries in this repository must not import ``jhora`` (``tests/test_runtime_jhora_import_scan.py``); PyJHora replays run only in the external-oracle research scripts. The requested profile is reported, and the local value is kept with ``chesta_basis = pyjhora_not_called_in_product``. """ del pname, context return None def _shadbala_module(): try: import shadbala except ImportError: # pragma: no cover - package import path from scripts import shadbala return shadbala def calc_chesta_bala_for_profile(pname: str, all_planets: Dict, kala: Dict, context: Dict, profile: str | None) -> tuple[float, str]: """Chesta Bala under an executable profile; returns (value, basis). Same dispatch as upstream ``calc_chesta_bala_for_profile`` / ``calc_chesta_bala_precise``. The default branch calls this repository's ``shadbala.calc_chesta_bala_precise`` (BUG-1557 / BUG-1590 Sun and Moon rules included), so the default value equals ``planets.
.chesta_bala``. """ sb = _shadbala_module() effective = resolve_chesta_profile_selection(profile).get("effective_profile") if effective == "pyjhora_jhora_replay_target": value = calc_chesta_bala_pyjhora_external(pname, context) if value is not None: return value, "pyjhora_package" return round(sb.calc_chesta_bala_precise(pname, all_planets, kala, context), 2), "pyjhora_not_called_in_product" if effective == "raman_luminary_zero" and pname in {"Sun", "Moon"}: return 0.0, "raman_luminary_zero" if effective == "raman_inferior_planet_assignment" and pname in {"Mercury", "Venus"}: sun_mean = sb._surya_mean_longitude("Sun", context) planet_mean = sb._surya_mean_longitude(pname, context) # Upstream swap: Seeghrochcha = Sun mean, mean longitude = planet mean. value = sb.chesta_from_longitudes(planet_mean, sb._planet_longitude(pname, all_planets), sun_mean) return round(value, 2), "raman_inferior_planet_assignment_swap" return round(sb.calc_chesta_bala_precise(pname, all_planets, kala, context), 2), "local_default" def build_chesta_profile_result(requested_profile: str, results: Dict, all_planets: Dict | None, context: Dict | None) -> Dict: """Totals under a requested executable profile, next to the default totals.""" selection = resolve_chesta_profile_selection(requested_profile) if selection.get("selection_status") != "active_local_profile": return {"status": "not_executable", "requested_profile": requested_profile, "boundary": selection.get("boundary")} if not isinstance(context, dict) or not isinstance(all_planets, dict): return {"status": "blocked", "requested_profile": requested_profile, "reason": "precise_shadbala_context_required"} rows = [] for planet in SEVEN_PLANETS: current = results.get(planet) if not isinstance(current, dict) or not isinstance(current.get("kala_bala"), dict): continue value, basis = calc_chesta_bala_for_profile(planet, all_planets, current["kala_bala"], context, selection["effective_profile"]) local = float(current.get("chesta_bala", 0.0) or 0.0) total = float(current.get("total_virupas", 0.0) or 0.0) profile_total = round(max(1.0, total - local + value), 2) rows.append({ "planet": planet, "default_chesta_virupa": round(local, 2), "profile_chesta_virupa": value, "chesta_basis": basis, "default_total_virupas": round(total, 2), "profile_total_virupas": profile_total, "profile_total_rupas": round(profile_total / 60.0, 4), }) ranking = [row["planet"] for row in sorted(rows, key=lambda r: r["profile_total_virupas"], reverse=True)] return { "status": "computed", "requested_profile": requested_profile, "effective_profile": selection["effective_profile"], "rows": rows, "ranking": ranking, "boundary": "Requested Chesta profile recomputed for this chart; the default planets.*.chesta_bala and totals are unchanged.", } def attach_chesta_profiles(result: Dict, *, planets: Dict | None = None, context: Dict | None = None, requested_profile: str | None = None) -> Dict: """Add the upstream Chesta profile keys to ``result['method_variants']`` in place.""" if not isinstance(result, dict): return result variants = result.setdefault('method_variants', {}) if not isinstance(variants, dict): return result precise = isinstance(context, dict) or variants.get('chesta') == DEFAULT_CHESTA_PROFILE requested = requested_profile if isinstance(requested_profile, str) and requested_profile.strip() else None selection = resolve_chesta_profile_selection(requested) result.setdefault('source_reference_packets', list(SOURCE_REFERENCE_PACKETS)) result.setdefault('interpretation_boundary', INTERPRETATION_BOUNDARY) variants['chesta_profile_candidates'] = build_chesta_profile_candidates() if precise else None variants['chesta_profile_selection'] = selection if precise else None variants['chesta_target_diagnostic'] = build_chesta_target_diagnostic(requested) if precise and requested else None variants['chesta_target_preview'] = build_chesta_target_preview(requested) if precise and requested else None planet_rows = result.get('planets') if isinstance(result.get('planets'), dict) else {} variants['chesta_shadow_profile_result'] = ( build_chesta_shadow_profile_result(requested, planet_rows) if precise and requested else None ) variants['chesta_profile_result'] = ( build_chesta_profile_result(requested, planet_rows, planets, context) if precise and requested else None ) return result