Files
Jyotisha/scripts/raman_sahams.py
ClaudeandClaude Opus 5.5 8ed5b5f3c9 feat(engine): port upstream skill calculation fixes into the engine (BUG-1699)
- affliction_evidence / career_semantic_profile / career_analysis (functional
  roles, affliction signals, user-industry gate)
- sade_sati.build_saturn_cycle_timeline with bisected ingress moments
  (FLG_SIDEREAL frame, BUG-1275)
- Chesta profile candidates and PL9 AV cell profile as sidecars
  (shadbala.py / ashtakavarga.py stay frozen, ERR-110)
- Raman Sahams in the annual pack; book rule packets + admission gate
- consultation_native_layers: affliction_evidence, career_analysis,
  sade_sati_timeline, shadbala_chesta_profiles, book_rules,
  annual_tajika.raman_sahams

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

264 lines
13 KiB
Python

"""Source-backed Raman Saham candidate producer for annual report comparison."""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
SIGNS = ("Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo", "Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces")
SIGN_LORDS = {"Aries": "Mars", "Taurus": "Venus", "Gemini": "Mercury", "Cancer": "Moon", "Leo": "Sun", "Virgo": "Mercury", "Libra": "Venus", "Scorpio": "Mars", "Sagittarius": "Jupiter", "Capricorn": "Saturn", "Aquarius": "Saturn", "Pisces": "Jupiter"}
RULES_PATH = Path(__file__).resolve().parents[1] / "references" / "raman_saham_rules.json"
HOUSE_OPERAND_MODES = {"explicit_cusp", "whole_sign_derived", "whole_sign_madhya"}
ZODIACAL_ORDER_MODES = {"source_backed", "source_backed_sign", "inverted"}
OUTPUT_LABEL_MAPPINGS = {
"native": {},
"pl9_bandhu_vanik_swapped": {"Bandhu": "Vanik", "Vanik": "Bandhu"},
}
FORMULA_PROFILES = {"raman", "pl9_p130_observed"}
PL9_P130_FORMULA_OVERRIDES: dict[str, dict[str, Any]] = {
"Asha": {"operands": ["Venus", "Saturn", "Ascendant"], "day_night_same": True},
"Gaurava": {"operands": ["Jupiter", "Punya", "Ascendant"], "day_night_same": True},
"Roga": {"operands": ["Moon", "Saturn", "Ascendant"], "day_night_same": True},
"Mrityu": {"operands": ["House8Cusp", "Moon", "Saturn"], "day_night_same": True},
"Paradesa": {"operands": ["House9Cusp", "House9Lord", "Ascendant"], "day_night_same": True},
"Artha": {"operands": ["House2Cusp", "House2Lord", "Ascendant"], "day_night_same": True},
"Paradara": {"operands": ["Venus", "Sun", "Ascendant"], "day_night_same": True, "exception_policy": "always"},
"Karyasiddhi": {"operands": ["Saturn", "Moon", "Jupiter"], "day_night_same": True, "exception_policy": "always"},
"Vivaha": {"operands": ["Venus", "Saturn", "Ascendant"], "day_night_same": True},
"Santapa": {"operands": ["Saturn", "Moon", "House6Cusp"], "day_night_same": True},
"Sraddha": {"operands": ["Venus", "Mars", "Ascendant"], "day_night_same": True},
"Preeti": {"operands": ["Vidya", "Punya", "Ascendant"], "day_night_same": True},
"Jadya": {"operands": ["Saturn", "Mars", "Mercury"], "day_night_same": True, "exception_policy": "never"},
"Vyapara": {"operands": ["Mars", "Mercury", "Ascendant"], "day_night_same": True},
"Jalapathana": {"operands": ["Saturn", "Cancer15", "Ascendant"], "day_night_same": True, "exception_policy": "never"},
"Labha": {"operands": ["House11Cusp", "House11Lord", "Ascendant"], "day_night_same": True},
}
def _rules() -> list[tuple[str, list[str], bool]]:
raw = json.loads(RULES_PATH.read_text(encoding="utf-8"))
return [(str(row[0]), list(row[1]), len(row) > 2 and row[2] == "same") for row in raw["rules"]]
def build_raman_sahams(
planet_lons: dict[str, float],
ascendant: float,
*,
is_daytime: bool,
annual_houses: dict[str, Any] | None = None,
annual_ascendant_override: float | None = None,
zodiacal_order_mode: str = "source_backed",
house_operand_mode: str = "explicit_cusp",
output_label_mode: str = "native",
formula_profile: str = "raman",
observed_saham_longitudes: dict[str, float] | None = None,
profile_id: str | None = None,
) -> dict[str, Any]:
"""Calculate only formulas whose declared operands are available.
House-cusp formulas intentionally remain blocked until the annual-house
producer supplies an explicitly profiled cusp set.
"""
planets = {name: float(value) % 360 for name, value in planet_lons.items() if isinstance(value, (int, float))}
ascendant = float(ascendant) % 360
if zodiacal_order_mode not in ZODIACAL_ORDER_MODES:
raise ValueError("zodiacal_order_mode must be source_backed, source_backed_sign, or inverted")
if house_operand_mode not in HOUSE_OPERAND_MODES:
raise ValueError("house_operand_mode must be explicit_cusp, whole_sign_derived, or whole_sign_madhya")
if output_label_mode not in OUTPUT_LABEL_MAPPINGS:
raise ValueError("output_label_mode must be native or pl9_bandhu_vanik_swapped")
if formula_profile not in FORMULA_PROFILES:
raise ValueError("formula_profile must be raman or pl9_p130_observed")
observed_longitudes = {}
if observed_saham_longitudes is not None:
if not isinstance(observed_saham_longitudes, dict):
raise ValueError("observed_saham_longitudes must be an object when supplied")
observed_longitudes = {
str(name): float(value) % 360.0
for name, value in observed_saham_longitudes.items()
if isinstance(value, (int, float))
}
if annual_ascendant_override is not None and not isinstance(annual_ascendant_override, (int, float)):
raise ValueError("annual_ascendant_override must be numeric when supplied")
effective_ascendant = (
float(annual_ascendant_override) % 360
if annual_ascendant_override is not None
else ascendant
)
annual_saham_profile = {
"id": profile_id or "native_raman",
"annual_ascendant_source": "explicit_external_override" if annual_ascendant_override is not None else "native_solar_return",
"annual_ascendant_longitude": round(effective_ascendant, 6),
"zodiacal_order_mode": zodiacal_order_mode,
"annual_house_operand_mode": house_operand_mode,
"annual_house_cusp_policy": _annual_house_cusp_policy(house_operand_mode),
"output_label_mode": output_label_mode,
"formula_profile": formula_profile,
"observed_saham_longitude_count": len(observed_longitudes),
}
house_profile = _annual_house_profile(annual_houses, effective_ascendant, house_operand_mode)
computed: dict[str, float] = {}
rows: list[dict[str, Any]] = []
output_label_mapping = OUTPUT_LABEL_MAPPINGS[output_label_mode]
for name, operands, day_night_same in _rules():
formula_profile_source = "raman"
exception_policy = "standard"
if formula_profile == "pl9_p130_observed" and name in PL9_P130_FORMULA_OVERRIDES:
override = PL9_P130_FORMULA_OVERRIDES[name]
operands = list(override["operands"])
day_night_same = bool(override.get("day_night_same", day_night_same))
exception_policy = str(override.get("exception_policy", "standard"))
formula_profile_source = "pl9_p130_observed"
selected = list(operands)
if not is_daytime and not day_night_same:
selected[0], selected[1] = selected[1], selected[0]
try:
first, second, third = (_operand(value, planets, effective_ascendant, computed, house_profile) for value in selected)
except KeyError as exc:
rows.append({
"name": output_label_mapping.get(name, name), "source_name": name, "status": "blocked",
"reason": str(exc.args[0]), "formula_operands": selected,
"output_name_mapping": output_label_mode, "formula_profile": formula_profile,
"formula_profile_source": formula_profile_source,
})
continue
base = (first - second + third) % 360
# The formula is A - B + C. The traditional exception checks whether
# C occurs on the forward zodiacal arc from B to A, not A to B.
if zodiacal_order_mode == "source_backed_sign":
between = _is_sign_between_b_to_a(first, second, third)
exception = not between
else:
between = second <= third <= first if second <= first else third >= second or third <= first
exception = not between if zodiacal_order_mode == "source_backed" else between
if exception_policy == "never":
exception = False
if exception_policy == "always":
exception = True
longitude = (base + 30.0) % 360 if exception else base
computed[name] = longitude
output_name = output_label_mapping.get(name, name)
replay_longitude = observed_longitudes.get(output_name, observed_longitudes.get(name))
row_status = "rule_backed_parameter_sensitive"
if replay_longitude is not None:
longitude = replay_longitude
row_status = "source_observed_replay"
rows.append({
"name": output_name, "source_name": name, "longitude": round(longitude, 6), "sign": SIGNS[int(longitude // 30)], "degree_in_sign": round(longitude % 30, 6),
"status": row_status, "formula_operands": selected,
"formula_variant": "day" if is_daytime else "night_swapped", "zodiacal_order_exception_applied": exception,
"exception_policy": exception_policy,
"base_longitude_before_exception": round(base, 6), "formula_source": RULES_PATH.relative_to(RULES_PATH.parents[1]).as_posix(),
"annual_house_profile": house_profile.get("profile"), "annual_house_operand_mode": house_operand_mode,
"zodiacal_order_mode": zodiacal_order_mode, "output_name_mapping": output_label_mode,
"formula_profile": formula_profile, "formula_profile_source": formula_profile_source,
"observed_replay_applied": replay_longitude is not None,
"annual_saham_profile_id": annual_saham_profile["id"],
})
return {
"schema": "jyotish.raman_sahams.v1", "status": "partial_verified", "is_daytime": is_daytime,
"annual_house_profile": house_profile.get("profile"), "annual_saham_profile": annual_saham_profile,
"rows": rows,
"boundary": "Requires field comparison before vendor-parity or event claims. An explicit external Ascendant override is a replay candidate, not vendor parity.",
}
def _operand(value: str, planets: dict[str, float], ascendant: float, computed: dict[str, float], house_profile: dict[str, Any]) -> float:
if value == "Ascendant":
return ascendant
if value == "AscendantLord":
return _planet_for_sign(ascendant, planets)
if value == "SunSignLord":
return _planet_for_sign(planets["Sun"], planets)
if value == "Cancer15":
return 105.0
if value.startswith("House"):
try:
suffix = value.removeprefix("House")
digits = "".join(character for character in suffix if character.isdigit())
house_number = int(digits)
house = house_profile["houses"][house_number]
except (KeyError, TypeError, ValueError):
raise KeyError(f"{value}_requires_profiled_annual_house_cusp") from None
if value.endswith("Cusp"):
return house["cusp_longitude"]
if value.endswith("Lord"):
return planets[house["lord"]]
if value in computed:
return computed[value]
if value in planets:
return planets[value]
raise KeyError(f"{value}_missing")
def _planet_for_sign(longitude: float, planets: dict[str, float]) -> float:
lord = SIGN_LORDS[SIGNS[int(longitude % 360 // 30)]]
if lord not in planets:
raise KeyError(f"{lord}_missing_for_sign_lord")
return planets[lord]
def _is_sign_between_b_to_a(first: float, second: float, third: float) -> bool:
"""PyJHora/JHora-compatible Saham exception check by sign, not degree."""
first_sign = int(first % 360 // 30)
second_sign = int(second % 360 // 30)
third_sign = int(third % 360 // 30)
for number in range(second_sign, second_sign + 11):
next_sign = (number + 1) % 12
if next_sign == third_sign:
return True
if next_sign == first_sign:
break
return False
def _annual_house_profile(annual_houses: dict[str, Any] | None, ascendant: float, house_operand_mode: str) -> dict[str, Any]:
"""Normalize only an explicitly passed annual house profile."""
if house_operand_mode in {"whole_sign_derived", "whole_sign_madhya"}:
houses = {}
ascendant_sign_start = int(float(ascendant) % 360 // 30) * 30.0
for number in range(1, 13):
if house_operand_mode == "whole_sign_madhya":
cusp = (ascendant_sign_start + 15.0 + (number - 1) * 30.0) % 360
else:
cusp = (float(ascendant) + (number - 1) * 30.0) % 360
houses[number] = {
"cusp_longitude": cusp,
"lord": SIGN_LORDS[SIGNS[int(cusp // 30)]],
}
profile = (
"whole_sign_madhya_from_annual_ascendant_sign"
if house_operand_mode == "whole_sign_madhya"
else "whole_sign_derived_from_annual_ascendant"
)
return {"profile": profile, "houses": houses}
rows = annual_houses if isinstance(annual_houses, dict) else {}
houses: dict[int, dict[str, Any]] = {}
for number in range(1, 13):
row = rows.get(f"house_{number}") if isinstance(rows.get(f"house_{number}"), dict) else rows.get(number)
if not isinstance(row, dict):
continue
try:
houses[number] = {
"cusp_longitude": float(row["cusp_degree"]) % 360,
"lord": str(row["lord"]),
}
except (KeyError, TypeError, ValueError):
continue
return {
"profile": "annual_solar_return_cusp_profile" if len(houses) == 12 else None,
"houses": houses,
}
def _annual_house_cusp_policy(house_operand_mode: str) -> str:
if house_operand_mode == "whole_sign_derived":
return "whole_sign_derived_from_annual_ascendant"
if house_operand_mode == "whole_sign_madhya":
return "whole_sign_madhya_from_annual_ascendant_sign"
return "explicit_annual_house_cusps"