Files
Jyotisha/scripts/rectification_purpose_gate/native.py
T

190 lines
8.6 KiB
Python

"""Offline adapter from native chart and Dasha calculations to scope evidence."""
from __future__ import annotations
from datetime import datetime, timedelta
from math import isfinite
from scripts.chart_choice import boundaries
from scripts.active_rectification_event_engine import _narayana_antardasha_table, _narayana_periods
from scripts.chart_dasha import birth_moment
from scripts.narayana_legacy_label import NARAYANA_YEAR_DAYS
# The chart-choice module initializes the native scripts import path.
import dasha_analyzer
import domain_calculation_service
import jaimini
from .scope import fingerprint, profile_clock, stamp
NATIVE_METHOD_VERSION = "purpose-native-v1"
ARUDHAS = frozenset({"A1", "A7", "A10", "UL"})
DIVISIONS = frozenset({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 16, 20, 24, 27, 30, 40, 45, 60})
ANGLE_DIMENSIONS = frozenset({"lagna_nakshatra", "moon_sign", "moon_nakshatra"})
def division_of(layer: str) -> int | None:
if layer.startswith("D") and layer[1:].isdigit():
division = int(layer[1:])
if division in DIVISIONS:
return division
return None
def _output(value, method: str, raw_ref: str, dependencies: list[str]) -> dict:
return {
"status": "executed" if value is not None else "blocked",
"reason": None if value is not None else "method_unresolved",
"value": value, "method_id": method, "result_ref": raw_ref,
"dependencies": dependencies,
}
def _window(forecast: dict) -> tuple[datetime, datetime]:
return stamp(forecast["start"]), stamp(forecast["end"])
def _intersects(start, end, forecast) -> bool:
return start < forecast[1] and end > forecast[0] and start < end
def _period(key, parent, level, lord, start, end) -> dict:
return {
"period_id": key, "parent_period_id": parent, "level": level,
"lord": lord, "start": start.isoformat(), "end": end.isoformat(),
}
def _vimshottari(birth, moon, forecast, depth, reference) -> dict:
periods, _, _, _ = birth_moment.mahadashas(birth, moon, through=forecast[1])
relevant = []
for index, md in enumerate(periods):
if not _intersects(md["start"], md["end"], forecast):
continue
md_key = f"MD:{index}:{md['lord']}"
relevant.append(_period(md_key, None, "MD", md["lord"], md["start"], md["end"]))
if depth < 2:
continue
for ad in birth_moment.split_period(md):
if not _intersects(ad["start"], ad["end"], forecast):
continue
ad_key = f"{md_key}/AD:{ad['lord']}"
relevant.append(_period(ad_key, md_key, "AD", ad["lord"], ad["start"], ad["end"]))
if depth < 3:
continue
for pd in birth_moment.split_period(ad):
if _intersects(pd["start"], pd["end"], forecast):
relevant.append(_period(f"{ad_key}/PD:{pd['lord']}", ad_key, "PD",
pd["lord"], pd["start"], pd["end"]))
complete = bool(relevant) and forecast[0] >= birth and periods[-1]["end"] >= forecast[1]
return {**_output("native_periods" if complete else None, "vimshottari_birth_moment", reference,
["candidate_at", "moon_longitude", "dasha_profile"]), "periods": relevant}
def _narayana(birth, asc_sign, planets, forecast, depth, reference) -> dict:
md_rows = _narayana_periods(asc_sign, planets)
ad_rows = _narayana_antardasha_table(md_rows, planets) if depth > 1 else None
def at(age):
return birth + timedelta(days=float(age) * NARAYANA_YEAR_DAYS)
complete = bool(md_rows) and forecast[0] >= birth
relevant = []
for md in md_rows or []:
start, end = at(md["start_age"]), at(md["end_age"])
if not _intersects(start, end, forecast):
continue
md_key = f"MD:{md['period_key']}"
relevant.append(_period(md_key, None, "MD", md["sign_idx"], start, end))
if depth < 2:
continue
children = (ad_rows or {}).get(str(md["period_key"]))
if not children:
complete = False
for ad in children or []:
ad_start, ad_end = at(ad["start_age"]), at(ad["end_age"])
if _intersects(ad_start, ad_end, forecast):
relevant.append(_period(f"{md_key}/AD:{ad['sign_idx']}", md_key, "AD",
ad["sign_idx"], ad_start, ad_end))
complete = complete and bool(relevant) and at(md_rows[-1]["end_age"]) >= forecast[1]
return {**_output("native_periods" if complete else None, "narayana_rath", reference,
["candidate_at", "lagna_sign", "planet_longitudes", "dasha_profile"]), "periods": relevant}
def _supported(profile: dict) -> bool:
return (profile.get("house_system", "whole_sign") == "whole_sign"
and profile.get("varga_mode", "classical_local") == "classical_local"
and profile.get("dasha_profile", "website_native") == "website_native"
and profile.get("year_days", NARAYANA_YEAR_DAYS) == NARAYANA_YEAR_DAYS)
def _chart(at, profile):
local = profile_clock(at, profile)
return domain_calculation_service.compute_chart({
"year": local.year, "month": local.month, "day": local.day,
"hour": local.hour, "minute": local.minute, "second": local.second,
"lat": profile["lat"], "lon": profile["lon"],
"tz": local.utcoffset().total_seconds() / 3600,
"ayanamsa": profile["ayanamsa"], "node_mode": profile["node_mode"],
})
def native_scope_compute(scope: dict):
"""Make the candidate callback used by the offline CLI and real fixtures."""
policy = scope["policy"]
required = policy["required_layers"]
forecast_data = scope["purpose_scope"]["forecast_window"]
forecast = _window(forecast_data) if forecast_data is not None else None
def compute(at: datetime, branch: str) -> dict:
at = stamp(at)
profile = scope["profiles"][branch]
packet = {"candidate_at": at.isoformat(), "branch_id": branch, "profile": profile, "outputs": {}}
if not _supported(profile):
return {**packet, "method_unresolved": True}
chart = _chart(at, profile)
asc = float(chart["ascendant"]["lon"])
planets = {
name: float(item["lon"]) for name, item in chart["planets"].items()
if isinstance(item, dict) and isinstance(item.get("lon"), (int, float)) and isfinite(item["lon"])
}
speeds = {
name: float(item["speed"]) for name, item in chart["planets"].items()
if isinstance(item, dict) and isinstance(item.get("speed"), (int, float)) and isfinite(item["speed"])
}
moon = planets.get("Moon")
ref = "native:" + fingerprint({"profile": profile, "at": at.isoformat(), "ascendant": asc, "planets": planets})
arudhas = jaimini.calc_arudha_padas(int(asc // 30), planets)["padas"] if ARUDHAS.intersection(required) else {}
values = {
"lagna_nakshatra": dasha_analyzer.lon_to_nakshatra(asc)[0][0],
"moon_nakshatra": dasha_analyzer.lon_to_nakshatra(moon)[0][0] if moon is not None else None,
"moon_sign": int(moon // 30) if moon is not None else None,
"D60": boundaries.varga_sign(asc, 60),
}
outputs = {
layer: _output(value, "swisseph_longitude_sectors", ref, ["candidate_at", "profile"])
for layer, value in values.items()
}
for layer in required:
division = division_of(layer)
if division is not None:
outputs[layer] = _output(boundaries.varga_sign(asc, division), "native_varga_ascendant", ref,
["ascendant_longitude", "varga_mode"])
elif layer in ARUDHAS:
pada = arudhas.get(layer)
outputs[layer] = _output(pada.get("sign_idx") if pada else None, "native_arudha", ref,
["lagna_sign", "planet_longitudes"])
elif layer == "Vimshottari" and forecast and moon is not None:
outputs[layer] = _vimshottari(at, moon, forecast, policy["vimshottari_depth"], ref)
elif layer == "Narayana" and forecast:
outputs[layer] = _narayana(at, int(asc // 30), planets, forecast, policy["narayana_depth"], ref)
return {
**packet, "outputs": outputs,
"raw": {"ascendant_longitude": asc, "moon_longitude": moon, "planet_longitudes": planets,
"planet_speeds": speeds,
"chart_ref": ref, "native_adapter_version": NATIVE_METHOD_VERSION,
"calculation_contract": chart.get("calculation_contract", chart.get("contract"))},
}
return compute