Produce and verify additional offline purpose-scan layers
This commit is contained in:
@@ -0,0 +1,202 @@
|
||||
"""Native projections for the optional offline purpose layers."""
|
||||
|
||||
from datetime import timezone
|
||||
from functools import cache
|
||||
|
||||
from scripts.chart_choice import boundaries
|
||||
|
||||
# Use the same engines as the native chart adapter.
|
||||
import ashtakavarga
|
||||
import domain_calculation_service
|
||||
import functional_benefics
|
||||
import jaimini
|
||||
import solar_return
|
||||
import yogas_doshas
|
||||
|
||||
from scripts.annual_service import package as annual
|
||||
|
||||
from .scope import profile_clock
|
||||
|
||||
GRAHAS = ("Sun", "Moon", "Mars", "Mercury", "Jupiter", "Venus", "Saturn", "Rahu", "Ketu")
|
||||
PLANET_VARGAS = {f"planet_vargas:D{division}": division for division in (9, 10, 2, 11)}
|
||||
SIGN_LAYERS = frozenset({
|
||||
"house_lords", "lord_placements", "planet_signs", "aspects", "ashtakavarga",
|
||||
"wealth_yogas", "raj_yogas",
|
||||
})
|
||||
LAYER_NAMES = SIGN_LAYERS | PLANET_VARGAS.keys() | {
|
||||
"functional_roles", "venus_jupiter", "chara_karakas", "transit_relations",
|
||||
"annual_chart", "strength_shadbala",
|
||||
}
|
||||
|
||||
|
||||
def _functional_roles(asc_sign, planets, profile):
|
||||
paksha = functional_benefics.moon_paksha_from_planets(planets)
|
||||
result = functional_benefics.derive_functional_benefic_malefic(
|
||||
asc_sign, functional_profile=profile, moon_paksha=paksha,
|
||||
)
|
||||
if result["status"] != "used" or result["blocked_planets"]:
|
||||
return None
|
||||
return {
|
||||
"profile": result["profile"],
|
||||
"benefics": result["functional_benefics"],
|
||||
"malefics": result["functional_malefics"],
|
||||
"neutrals": result["functional_neutrals"],
|
||||
"yogakarakas": result["yogakarakas"],
|
||||
}
|
||||
|
||||
|
||||
def _ashtakavarga(planet_rows, asc_index):
|
||||
result = ashtakavarga.calc_ashtakavarga(planet_rows, asc_index)
|
||||
return {
|
||||
"bav": {
|
||||
name: [house["sav_score"] for house in ashtakavarga._map_to_houses_values(row["bindus"], asc_index).values()]
|
||||
for name, row in result["bav"].items()
|
||||
},
|
||||
"sav": [row["sav_score"] for row in result["house_scores"].values()],
|
||||
}
|
||||
|
||||
|
||||
def _yogas(detector, planet_rows, house_lords):
|
||||
houses = {f"H{i}_Lord": lord for i, lord in house_lords.items()}
|
||||
matches = detector(planet_rows, houses)["yogas"]
|
||||
return {"matches": [
|
||||
{"name": name, "subtype": subtype, "combination": combination}
|
||||
for name, subtype, combination in sorted({
|
||||
(row["type"], row.get("subtype", ""), row.get("combination", "")) for row in matches
|
||||
})
|
||||
]}
|
||||
|
||||
|
||||
def _transit_sky(forecast, ayanamsa, node_mode):
|
||||
start, end = forecast
|
||||
# Only the portions of the annual transit producer that are common to every natal chart.
|
||||
# Its exact conjunction and aspect queries need natal longitudes and are separate outputs.
|
||||
ctx = annual._Context({
|
||||
"birth": {"year": start.year, "month": start.month, "day": start.day,
|
||||
"hour": start.hour, "minute": start.minute, "tz": 0},
|
||||
"observation_date": start.date(), "ayanamsa": ayanamsa, "node_mode": node_mode,
|
||||
})
|
||||
snapshot = annual._slow_transits(ctx, {
|
||||
"status": "computed", "lagna_sign_idx": 0, "moon_sign_idx": 0, "longitudes": {},
|
||||
}, start, end)
|
||||
return [
|
||||
(body, start.isoformat(), annual.SIGNS.index(row["sign"]))
|
||||
for body, row in snapshot["positions_at_range_start"].items()
|
||||
] + [
|
||||
(row["body"], row["instant"]["utc"], annual.SIGNS.index(row["to_sign"]))
|
||||
for row in snapshot["events"] if row["kind"] == "ingress"
|
||||
]
|
||||
|
||||
|
||||
def _annual_charts(at, profile, asc_index, forecast):
|
||||
start, end = forecast
|
||||
birth_year = profile_clock(at, profile).year
|
||||
if start < at:
|
||||
return None
|
||||
with domain_calculation_service.swiss_ephemeris_lock():
|
||||
jd = solar_return._datetime_to_jd_ut(at)
|
||||
# Match calc_solar_return_chart's solver-frame Sun instead of rerunning the natal chart.
|
||||
target = solar_return._get_sun_lon_jd(jd, ayanamsa_name=profile["ayanamsa"])
|
||||
if target is None:
|
||||
return None
|
||||
returns = []
|
||||
for year in range(max(birth_year, start.year - 1), end.year + 1):
|
||||
solar = solar_return.find_solar_return_ut(jd, target, year, ayanamsa_name=profile["ayanamsa"])
|
||||
if solar.get("method") != "swisseph_newton":
|
||||
return None
|
||||
instant = solar["dt_ut"].replace(tzinfo=timezone.utc)
|
||||
if instant < end:
|
||||
returns.append((instant, year))
|
||||
active = [row for row in returns if row[0] <= start]
|
||||
relevant = active[-1:] + [row for row in returns if start < row[0]]
|
||||
charts = []
|
||||
for instant, year in relevant:
|
||||
request = boundaries.ChartRequest(instant.date().isoformat(), profile["lat"], profile["lon"], 0,
|
||||
profile["ayanamsa"], profile["node_mode"])
|
||||
asc = boundaries.ascendant_longitude(request, instant)
|
||||
muntha = solar_return._muntha_from_natal_ascendant(asc_index, year - birth_year)
|
||||
charts.append({"year": year, "ascendant_sign": boundaries.varga_sign(asc, 1),
|
||||
"muntha_sign": muntha["muntha_sign_idx"]})
|
||||
return {"charts": charts} if charts else None
|
||||
|
||||
|
||||
def native_layer_values(required, forecast):
|
||||
layers = LAYER_NAMES.intersection(required)
|
||||
|
||||
@cache
|
||||
def sky(ayanamsa, node_mode):
|
||||
return _transit_sky(forecast, ayanamsa, node_mode)
|
||||
|
||||
def compute(at, profile, chart, asc, planets, ref, output):
|
||||
values = {}
|
||||
if not layers:
|
||||
return values
|
||||
asc_index = boundaries.varga_sign(asc, 1)
|
||||
asc_sign = chart["ascendant"]["sign"]
|
||||
planet_rows = chart["planets"]
|
||||
has_grahas = all(name in planets and planet_rows[name].get("sign") in annual.SIGNS for name in GRAHAS)
|
||||
house_lords = {str(i): chart["houses"].get(f"house_{i}", {}).get("lord") for i in range(1, 13)}
|
||||
has_lords = all(house_lords.values())
|
||||
for layer in sorted(layers):
|
||||
if layer == "house_lords":
|
||||
value, method, dependencies = (house_lords if has_lords else None, "native_d1_house_lords", ["lagna_sign"])
|
||||
elif layer == "lord_placements":
|
||||
value = {i: planet_rows.get(lord, {}).get("house") for i, lord in house_lords.items()}
|
||||
value, method, dependencies = (
|
||||
value if has_lords and all(value.values()) else None, "native_d1_lord_placements",
|
||||
["lagna_sign", "planet_signs"],
|
||||
)
|
||||
elif layer == "planet_signs":
|
||||
value = {name: planet_rows[name]["sign"] for name in GRAHAS} if has_grahas else None
|
||||
method, dependencies = "native_d1_planet_signs", ["planet_longitudes"]
|
||||
elif layer in PLANET_VARGAS:
|
||||
value = {name: boundaries.varga_sign(planets[name], PLANET_VARGAS[layer])
|
||||
for name in GRAHAS} if has_grahas else None
|
||||
method, dependencies = "native_divisional_planet_signs", ["planet_longitudes", "varga_mode"]
|
||||
elif layer == "functional_roles":
|
||||
profile_id = profile.get("functional_profile", functional_benefics.DEFAULT_FUNCTIONAL_PROFILE)
|
||||
value = _functional_roles(asc_sign, planets, profile_id)
|
||||
method, dependencies = "native_functional_roles", ["lagna_sign", "moon_paksha", "functional_profile"]
|
||||
elif layer == "venus_jupiter":
|
||||
value = {
|
||||
name: {key: planet_rows[name][key] for key in ("sign", "house", "status")}
|
||||
for name in ("Venus", "Jupiter")
|
||||
} if has_grahas else None
|
||||
method, dependencies = "native_d1_venus_jupiter", ["lagna_sign", "planet_signs", "planet_degrees_in_sign"]
|
||||
elif layer == "aspects":
|
||||
value = {
|
||||
name: [target for target in range(12)
|
||||
if jaimini._rasi_drishti(boundaries.varga_sign(planets[name], 1), target)]
|
||||
for name in GRAHAS
|
||||
} if has_grahas else None
|
||||
method, dependencies = "native_jaimini_rasi_drishti", ["planet_signs"]
|
||||
elif layer == "chara_karakas":
|
||||
degrees = {name: planets[name] % 30 for name in GRAHAS[:7]} if has_grahas else {}
|
||||
table = jaimini.calc_chara_karaka_7(degrees)["karaka_table"] if degrees else {}
|
||||
value = {role: row["planet"] for role, row in table.items()} or None
|
||||
method, dependencies = "native_chara_karakas_7", ["seven_planet_degrees_in_sign"]
|
||||
elif layer == "ashtakavarga":
|
||||
value = _ashtakavarga(planet_rows, asc_index) if has_grahas else None
|
||||
method, dependencies = "native_ashtakavarga_bav_sav", ["lagna_sign", "planet_signs"]
|
||||
elif layer in ("wealth_yogas", "raj_yogas"):
|
||||
detector = yogas_doshas.calc_dhana_yogas if layer == "wealth_yogas" else yogas_doshas.calc_raj_yogas
|
||||
value = _yogas(detector, planet_rows, house_lords) if has_lords and has_grahas else None
|
||||
method, dependencies = detector.__name__, ["lagna_sign", "planet_signs", "house_lords"]
|
||||
elif layer == "transit_relations":
|
||||
value = {"whole_sign_relations": [
|
||||
{"body": body, "at": instant, "sign": sign, "from_lagna": annual._house(sign, asc_index),
|
||||
"from_moon": annual._house(sign, boundaries.varga_sign(planets["Moon"], 1))}
|
||||
for body, instant, sign in sky(profile["ayanamsa"], profile["node_mode"])
|
||||
]} if forecast and "Moon" in planets else None
|
||||
method, dependencies = "native_whole_sign_slow_transits", ["lagna_sign", "moon_sign", "forecast_window"]
|
||||
elif layer == "annual_chart":
|
||||
value = _annual_charts(at, profile, asc_index, forecast) if forecast else None
|
||||
method, dependencies = (
|
||||
"native_solar_return_and_muntha", ["candidate_at", "natal_sun_longitude", "lagna_sign", "forecast_window", "profile"],
|
||||
)
|
||||
else:
|
||||
value, method, dependencies = None, "shadbala_pending_review", []
|
||||
values[layer] = output(value, method, ref, dependencies)
|
||||
return values
|
||||
|
||||
return compute
|
||||
@@ -15,6 +15,7 @@ import dasha_analyzer
|
||||
import domain_calculation_service
|
||||
import jaimini
|
||||
|
||||
from .layer_values import native_layer_values
|
||||
from .scope import fingerprint, profile_clock, stamp
|
||||
|
||||
NATIVE_METHOD_VERSION = "purpose-native-v1"
|
||||
@@ -135,6 +136,7 @@ def native_scope_compute(scope: dict):
|
||||
required = policy["required_layers"]
|
||||
forecast_data = scope["purpose_scope"]["forecast_window"]
|
||||
forecast = _window(forecast_data) if forecast_data is not None else None
|
||||
layer_values = native_layer_values(required, forecast)
|
||||
|
||||
def compute(at: datetime, branch: str) -> dict:
|
||||
at = stamp(at)
|
||||
@@ -178,6 +180,7 @@ def native_scope_compute(scope: dict):
|
||||
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)
|
||||
outputs.update(layer_values(at, profile, chart, asc, planets, ref, _output))
|
||||
return {
|
||||
**packet, "outputs": outputs,
|
||||
"raw": {"ascendant_longitude": asc, "moon_longitude": moon, "planet_longitudes": planets,
|
||||
|
||||
@@ -11,6 +11,7 @@ from scripts.active_rectification_candidates import MAX_WINDOW_MINUTES
|
||||
from scripts.chart_choice.boundaries import ChartRequest, find_lines
|
||||
from scripts.dasha_common import VIMSHOTTARI_YEARS
|
||||
|
||||
from .layer_values import GRAHAS, PLANET_VARGAS, SIGN_LAYERS
|
||||
from .native import ANGLE_DIMENSIONS, ARUDHAS, division_of
|
||||
from .scan import BoundaryMethodUnavailable
|
||||
from .scope import SECOND, range_limits, stamp
|
||||
@@ -19,7 +20,6 @@ from .timing import TIMING_OUTPUTS, output_periods, period_signature
|
||||
MINUTE = timedelta(minutes=1)
|
||||
CHUNK = timedelta(minutes=MAX_WINDOW_MINUTES - 1)
|
||||
TIMING_EXACT_SECONDS = 180
|
||||
GRAHAS = ("Sun", "Moon", "Mars", "Mercury", "Jupiter", "Venus", "Saturn", "Rahu", "Ketu")
|
||||
DATE_ROUNDING = timedelta(microseconds=2)
|
||||
|
||||
|
||||
@@ -202,7 +202,7 @@ def _planet_direction(rows, name):
|
||||
return all(_longitude_delta(a, b) * speeds[0] > 0 for a, b in pairwise(values))
|
||||
|
||||
|
||||
def _sign_layout_factory(profiles):
|
||||
def _sign_layout_factory(profiles, planets=GRAHAS):
|
||||
@cache
|
||||
def layout(start, end, branch, sample):
|
||||
profile = profiles[branch]
|
||||
@@ -226,14 +226,14 @@ def _sign_layout_factory(profiles):
|
||||
asc_values = [asc(at) for at in probes]
|
||||
if not all(_ascending_enough(a, b) for a, b in pairwise(asc_values)):
|
||||
return grid, [], False
|
||||
if not all(_planet_direction(rows, name) for name in GRAHAS):
|
||||
if not all(_planet_direction(rows, name) for name in planets):
|
||||
return grid, [], False
|
||||
|
||||
req = ChartRequest(start.date().isoformat(), profile["lat"], profile["lon"], 0,
|
||||
profile["ayanamsa"], profile["node_mode"])
|
||||
cuts = {line.at for left, right in pairwise(_grid(start, end, CHUNK))
|
||||
for line in find_lines(req, left, right, (1,), longitude_at=asc)}
|
||||
for name in GRAHAS:
|
||||
for name in planets:
|
||||
def sign(at):
|
||||
return int(_planet_longitude(row(at), name) // 30)
|
||||
|
||||
@@ -242,7 +242,7 @@ def _sign_layout_factory(profiles):
|
||||
return grid, [], False
|
||||
|
||||
checked = [observed[at] for at in sorted(observed)]
|
||||
bounded = all(_planet_direction(checked, name) for name in GRAHAS)
|
||||
bounded = all(_planet_direction(checked, name) for name in planets)
|
||||
return grid, sorted(cuts), bounded
|
||||
|
||||
return layout
|
||||
@@ -253,29 +253,177 @@ def _executed_output(sample, at, branch, layer):
|
||||
return output if output and output["status"] == "executed" else None
|
||||
|
||||
|
||||
def _arudha_provider(layer, sign_layout):
|
||||
def _layer_reader(sample, branch, layer):
|
||||
def value(at):
|
||||
output = _executed_output(sample, at, branch, layer)
|
||||
return output["value"] if output else None
|
||||
|
||||
return value
|
||||
|
||||
|
||||
def _constant(points, value):
|
||||
expected = value(points[0])
|
||||
return expected is not None and all(value(at) == expected for at in points[1:])
|
||||
|
||||
|
||||
def _partition_provider(layer, layout, basis, method="sign_change_enumeration"):
|
||||
def provider(item, sample):
|
||||
start, end = range_limits(item)
|
||||
branch = item["branch_id"]
|
||||
|
||||
def value(at):
|
||||
output = _executed_output(sample, at, branch, layer)
|
||||
return output["value"] if output else None
|
||||
|
||||
grid, candidates, bounded = sign_layout(start, end, branch, sample)
|
||||
if bounded:
|
||||
segments = [set(map(value, points)) for points in _segment_probes(start, end, candidates, grid)]
|
||||
bounded = all(len(values) == 1 and None not in values for values in segments)
|
||||
if bounded:
|
||||
value = _layer_reader(sample, branch, layer)
|
||||
grid, candidates, bounded = layout(start, end, branch, sample)
|
||||
if bounded and all(_constant(points, value)
|
||||
for points in _segment_probes(start, end, candidates, grid)):
|
||||
cuts = [at for at in candidates if value(at - SECOND) != value(at)]
|
||||
return _details("sign_change_enumeration", grid, cuts, bounded=True,
|
||||
basis="arudha_depends_on_signs_only")
|
||||
return _details("minute_grid_then_second_bisection", grid, _discover_changes(grid, value),
|
||||
return _details(method, grid, cuts, bounded=True, basis=basis)
|
||||
probes = sorted(set(_with_midpoints(grid)) | set(candidates))
|
||||
return _details("minute_grid_then_second_bisection", probes, _discover_changes(probes, value),
|
||||
bounded=False, reason="scan_incomplete")
|
||||
|
||||
return provider
|
||||
|
||||
|
||||
def _arudha_provider(layer, sign_layout):
|
||||
return _partition_provider(layer, sign_layout, "arudha_depends_on_signs_only")
|
||||
|
||||
|
||||
def _planet_varga_layout(division):
|
||||
def layout(start, end, branch, sample):
|
||||
grid = list(_grid(start, end, MINUTE))
|
||||
probes = _with_midpoints(grid)
|
||||
rows = {at: sample(at, branch) for at in probes}
|
||||
try:
|
||||
if not all(_planet_direction(list(rows.values()), name) for name in GRAHAS):
|
||||
return grid, [], False
|
||||
cuts = set()
|
||||
for name in GRAHAS:
|
||||
def sector(at):
|
||||
if at not in rows:
|
||||
rows[at] = sample(at, branch)
|
||||
longitude = _planet_longitude(rows[at], name)
|
||||
# The existing varga engine indexes equal parts separately within each sign.
|
||||
sign = int(longitude // 30)
|
||||
return sign * division + int((longitude - sign * 30) / (30 / division))
|
||||
|
||||
cuts.update(_discover_changes(probes, sector))
|
||||
checked = [rows[at] for at in sorted(rows)]
|
||||
bounded = all(_planet_direction(checked, name) for name in GRAHAS)
|
||||
except BoundaryMethodUnavailable:
|
||||
return grid, [], False
|
||||
return grid, sorted(cuts), bounded
|
||||
|
||||
return layout
|
||||
|
||||
|
||||
def _functional_layout(lagna_layout):
|
||||
def layout(start, end, branch, sample):
|
||||
grid, lagna_cuts, lagna_bounded = lagna_layout(start, end, branch, sample)
|
||||
probes = _with_midpoints(grid)
|
||||
|
||||
def elongation(at):
|
||||
row = sample(at, branch)
|
||||
return (_planet_longitude(row, "Moon") - _planet_longitude(row, "Sun")) % 360
|
||||
|
||||
try:
|
||||
speeds = [(sample(at, branch).get("raw") or {}).get("planet_speeds", {}) for at in probes]
|
||||
forward = all(
|
||||
all(isinstance(value, (int, float)) and isfinite(value) for value in pair)
|
||||
and pair[0] > pair[1]
|
||||
for pair in ((row.get("Moon"), row.get("Sun")) for row in speeds)
|
||||
) and all(0 < _longitude_delta(elongation(left), elongation(right)) < 2
|
||||
for left, right in pairwise(probes))
|
||||
cuts = _discover_changes(probes, lambda at: int(elongation(at) // 180))
|
||||
except BoundaryMethodUnavailable:
|
||||
return grid, lagna_cuts, False
|
||||
return grid, sorted(set(lagna_cuts) | set(cuts)), lagna_bounded and forward
|
||||
|
||||
return layout
|
||||
|
||||
|
||||
def _karaka_ranges_separate(before, after):
|
||||
spans = sorted(
|
||||
sorted((_planet_longitude(before, name) % 30, _planet_longitude(after, name) % 30))
|
||||
for name in GRAHAS[:7]
|
||||
)
|
||||
return all(left[1] < right[0] for left, right in pairwise(spans))
|
||||
|
||||
|
||||
def _karaka_provider(sign_layout):
|
||||
def provider(item, sample):
|
||||
start, end = range_limits(item)
|
||||
branch = item["branch_id"]
|
||||
value = _layer_reader(sample, branch, "chara_karakas")
|
||||
grid, sign_cuts, bounded = sign_layout(start, end, branch, sample)
|
||||
checked = {}
|
||||
|
||||
def row(at):
|
||||
if at not in checked:
|
||||
checked[at] = sample(at, branch)
|
||||
return checked[at]
|
||||
|
||||
cuts = set()
|
||||
|
||||
def search(left, right):
|
||||
first, last = value(left), value(right)
|
||||
if first is None or last is None:
|
||||
return False
|
||||
before, after = row(left), row(right)
|
||||
if right - left <= SECOND:
|
||||
if first != last:
|
||||
cuts.add(right)
|
||||
return True
|
||||
mid = _midpoint(left, right)
|
||||
if _karaka_ranges_separate(before, after):
|
||||
row(mid)
|
||||
return first == last == value(mid)
|
||||
left_checked = search(left, mid)
|
||||
right_checked = search(mid, right)
|
||||
return left_checked and right_checked
|
||||
|
||||
if bounded:
|
||||
try:
|
||||
for points in _segment_probes(start, end, sign_cuts, grid):
|
||||
if len(points) == 1 and value(points[0]) is None:
|
||||
bounded = False
|
||||
for left, right in pairwise(points):
|
||||
if not search(left, right):
|
||||
bounded = False
|
||||
segment_rows = [checked[at] for at in sorted(checked) if points[0] <= at <= points[-1]]
|
||||
if not segment_rows:
|
||||
segment_rows = [row(points[0])]
|
||||
if not all(_planet_direction(segment_rows, name) for name in GRAHAS[:7]):
|
||||
bounded = False
|
||||
except BoundaryMethodUnavailable:
|
||||
bounded = False
|
||||
if bounded:
|
||||
cuts.update(at for at in sign_cuts if value(at - SECOND) != value(at))
|
||||
return _details("degree_range_refinement_to_second", sorted(set(grid) | checked.keys()), sorted(cuts),
|
||||
bounded=True, basis="karaka_order_from_in_sign_degrees")
|
||||
probes = sorted(set(grid) | checked.keys() | set(sign_cuts))
|
||||
cuts.update(_discover_changes(probes, value))
|
||||
return _details("degree_range_refinement_to_second", probes, sorted(cuts), bounded=False,
|
||||
reason="degree_order_unresolved")
|
||||
|
||||
return provider
|
||||
|
||||
|
||||
def _sampled_layer(layer, reason):
|
||||
def provider(item, sample):
|
||||
start, end = range_limits(item)
|
||||
points = list(_grid(start, end, MINUTE))
|
||||
value = _layer_reader(sample, item["branch_id"], layer)
|
||||
return _details("minute_grid_then_second_bisection", points, _discover_changes(points, value),
|
||||
bounded=False, reason=reason)
|
||||
|
||||
return provider
|
||||
|
||||
|
||||
def _shadbala_pending(item, sample):
|
||||
start, end = range_limits(item)
|
||||
return {**_details("shadbala_pending_review", [start, end], [], bounded=False, reason="method_unresolved"),
|
||||
"state": "incomplete"}
|
||||
|
||||
|
||||
def _degree_order_fixed(rows):
|
||||
# Narayana's strength and dual-lord rules compare unrounded degrees,
|
||||
# with Ketu measured from the far end of its sign.
|
||||
@@ -432,6 +580,9 @@ def native_boundary_providers(scope: dict) -> dict:
|
||||
profiles = scope["profiles"]
|
||||
purpose = scope["purpose_scope"]
|
||||
sign_layout = _sign_layout_factory(profiles)
|
||||
lagna_layout = _sign_layout_factory(profiles, ())
|
||||
lagna_moon_layout = _sign_layout_factory(profiles, ("Moon",))
|
||||
classical_planet_layout = _sign_layout_factory(profiles, GRAHAS[:7])
|
||||
moon_layout = _sector_provider("moon_nakshatra", profiles)
|
||||
providers = {}
|
||||
for layer in scope["policy"]["required_layers"]:
|
||||
@@ -442,6 +593,25 @@ def native_boundary_providers(scope: dict) -> dict:
|
||||
providers[layer] = moon_layout if layer == "moon_nakshatra" else _sector_provider(layer, profiles)
|
||||
elif layer in ARUDHAS:
|
||||
providers[layer] = _arudha_provider(layer, sign_layout)
|
||||
elif layer in SIGN_LAYERS:
|
||||
layout = lagna_layout if layer == "house_lords" else sign_layout
|
||||
providers[layer] = _partition_provider(layer, layout, "depends_on_signs_only")
|
||||
elif layer in PLANET_VARGAS:
|
||||
providers[layer] = _partition_provider(layer, _planet_varga_layout(PLANET_VARGAS[layer]),
|
||||
"varga_sign_from_planet_longitude", "planet_degree_crossing")
|
||||
elif layer == "functional_roles":
|
||||
providers[layer] = _partition_provider(layer, _functional_layout(lagna_layout),
|
||||
"functional_roles_from_lagna_and_paksha", "lagna_and_paksha_crossing")
|
||||
elif layer == "venus_jupiter":
|
||||
providers[layer] = _sampled_layer(layer, "dignity_depends_on_in_sign_degree")
|
||||
elif layer == "chara_karakas":
|
||||
providers[layer] = _karaka_provider(classical_planet_layout)
|
||||
elif layer == "transit_relations" and purpose["forecast_window"] is not None:
|
||||
providers[layer] = _partition_provider(layer, lagna_moon_layout, "transit_relations_from_natal_lagna_moon")
|
||||
elif layer == "annual_chart" and purpose["forecast_window"] is not None:
|
||||
providers[layer] = _sampled_layer(layer, "solar_return_ascendant_between_samples_unproven")
|
||||
elif layer == "strength_shadbala":
|
||||
providers[layer] = _shadbala_pending
|
||||
elif layer in TIMING_OUTPUTS and purpose["forecast_window"] is not None:
|
||||
providers[layer] = _timing_provider(layer, purpose["forecast_window"], purpose["granularity"],
|
||||
sign_layout, moon_layout)
|
||||
|
||||
@@ -59,7 +59,7 @@ def _union(windows: list[tuple]) -> list[dict]:
|
||||
|
||||
|
||||
def period_envelopes(candidates: list[dict], layer: str, policy_covered: bool) -> list[dict]:
|
||||
"""Keep each observed native window; an empty intersection stays null."""
|
||||
"""Return interval envelopes for proved coverage, and sampled ranges otherwise."""
|
||||
periods = {}
|
||||
for candidate in candidates:
|
||||
output = candidate["outputs"].get(layer)
|
||||
@@ -77,6 +77,7 @@ def period_envelopes(candidates: list[dict], layer: str, policy_covered: bool) -
|
||||
common = _window(max(starts), min(ends)) if complete and max(starts) < min(ends) else None
|
||||
envelopes.append({
|
||||
"period_id": key, "coverage": "all_candidates" if complete else "observed_candidates_only",
|
||||
"scope": "full_interval_envelope" if complete else "sampled_points_range",
|
||||
"earliest_start": min(starts).isoformat(), "latest_start": max(starts).isoformat(),
|
||||
"earliest_end": min(ends).isoformat(), "latest_end": max(ends).isoformat(),
|
||||
"possible_windows": _union(windows), "common_window": common,
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
"""Offline purpose-layer projections, real edge scans, and conservative counterexamples."""
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from functools import cache
|
||||
from itertools import pairwise
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
from scripts.rectification_purpose_gate import __main__ as cli
|
||||
from scripts.rectification_purpose_gate.layer_values import GRAHAS, LAYER_NAMES
|
||||
from scripts.rectification_purpose_gate.native import native_scope_compute
|
||||
from scripts.rectification_purpose_gate.providers import CHUNK, native_boundary_providers
|
||||
from scripts.rectification_purpose_gate.scan import scan_scope
|
||||
from scripts.rectification_purpose_gate.scope import SECOND, build_scope_request, range_limits, stamp
|
||||
from scripts.rectification_purpose_gate.timing import period_envelopes
|
||||
|
||||
START = datetime(2000, 1, 1, tzinfo=timezone.utc)
|
||||
BRANCH = "synthetic"
|
||||
FIXTURE = Path(__file__).with_name("fixtures") / "rectification_purpose_scan_20261116.json"
|
||||
SAMPLED = {"venus_jupiter", "annual_chart"}
|
||||
ASC_EDGE = "2000-01-01T01:37:25+00:00"
|
||||
SKY_EDGE = "2000-01-02T06:12:39+00:00"
|
||||
EDGES = {
|
||||
"house_lords": ASC_EDGE,
|
||||
"lord_placements": ASC_EDGE,
|
||||
"planet_signs": SKY_EDGE,
|
||||
"planet_vargas:D2": "2000-01-01T00:13:32+00:00",
|
||||
"planet_vargas:D9": "2000-01-01T03:32:03+00:00",
|
||||
"planet_vargas:D10": "2000-01-01T00:13:32+00:00",
|
||||
"planet_vargas:D11": "2000-01-01T02:55:56+00:00",
|
||||
"functional_roles": "2000-01-21T04:40:27+00:00",
|
||||
"venus_jupiter": ASC_EDGE,
|
||||
"aspects": SKY_EDGE,
|
||||
"chara_karakas": "2000-01-01T05:33:59+00:00",
|
||||
"ashtakavarga": ASC_EDGE,
|
||||
"wealth_yogas": ASC_EDGE,
|
||||
"raj_yogas": ASC_EDGE,
|
||||
"transit_relations": ASC_EDGE,
|
||||
"annual_chart": "2000-01-01T00:23:22+00:00",
|
||||
}
|
||||
|
||||
|
||||
def _packet(start, end, *, lon=None):
|
||||
packet = json.loads(FIXTURE.read_text(encoding="utf-8"))["vimshottari_date"]["input"]
|
||||
packet["question"].update(
|
||||
granularity="month", forecast_start="2026-01-01T00:00:00+00:00",
|
||||
forecast_end="2027-01-01T00:00:00+00:00", target_boundaries=[],
|
||||
)
|
||||
packet["remaining_ranges"] = [{"start": start.isoformat(), "end": end.isoformat()}]
|
||||
if lon is not None:
|
||||
packet["profiles"]["branches"][BRANCH]["lon"] = lon
|
||||
return packet
|
||||
|
||||
|
||||
def _scope(packet, layers):
|
||||
scope = build_scope_request(packet["question"], packet["original_input"], packet["remaining_ranges"],
|
||||
packet["profiles"], packet["evaluated_at"])
|
||||
# Isolate these producers without changing the question routing policy.
|
||||
scope["policy"]["required_layers"] = sorted(layers)
|
||||
return scope
|
||||
|
||||
|
||||
def _second_edges(sample, item, layer):
|
||||
start, end = range_limits(item)
|
||||
branch = item["branch_id"]
|
||||
points = [start + SECOND * count for count in range(int((end - start) / SECOND) + 1)]
|
||||
values = [sample(at, branch)["outputs"][layer]["value"] for at in points]
|
||||
assert all(value is not None for value in values)
|
||||
return [at for at, (before, after) in zip(points[1:], pairwise(values)) if before != after]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("layer,edge", EDGES.items())
|
||||
def test_real_edges_match_every_second(layer, edge):
|
||||
at = stamp(edge)
|
||||
packet = _packet(at - 120 * SECOND, at + 120 * SECOND, lon=-45 if layer == "functional_roles" else None)
|
||||
scope = _scope(packet, [layer])
|
||||
sample = cache(native_scope_compute(scope))
|
||||
item = scope["plausible_ranges"][0]
|
||||
details = native_boundary_providers(scope)[layer](item, sample)
|
||||
assert details["state"] == ("sampled_only" if layer in SAMPLED else "policy_covered"), details
|
||||
assert details["boundaries"] == _second_edges(sample, item, layer)
|
||||
assert at in details["boundaries"]
|
||||
before, after = sample(at - SECOND, BRANCH), sample(at, BRANCH)
|
||||
left, right = [row["outputs"][layer]["value"] for row in (before, after)]
|
||||
if layer in {"planet_vargas:D9", "planet_vargas:D10"}:
|
||||
assert left["Moon"] != right["Moon"]
|
||||
if layer == "functional_roles":
|
||||
raw = [row["raw"] for row in (before, after)]
|
||||
assert int(raw[0]["ascendant_longitude"] // 30) == int(raw[1]["ascendant_longitude"] // 30)
|
||||
phase = [int(((r["planet_longitudes"]["Moon"] - r["planet_longitudes"]["Sun"]) % 360) // 180) for r in raw]
|
||||
assert phase == [0, 1]
|
||||
assert "Moon" in left["malefics"] and "Moon" in right["neutrals"]
|
||||
if layer == "chara_karakas":
|
||||
assert any(left[role] != right[role] and "Moon" in (left[role], right[role])
|
||||
for role in ("Darakaraka", "Amatyakaraka"))
|
||||
if layer == "annual_chart":
|
||||
assert [row["ascendant_sign"] for row in left["charts"]] != [row["ascendant_sign"] for row in right["charts"]]
|
||||
|
||||
|
||||
def _mock_value(value, layer):
|
||||
return {"status": "executed", "value": value, "method_id": "synthetic", "result_ref": f"test:{layer}"}
|
||||
|
||||
|
||||
def _fake(layer, value, *, geometry=None, ascendant=lambda _: 15):
|
||||
def sample(at, branch):
|
||||
tick = int((at - START) / SECOND)
|
||||
lons = {name: index * 30 + 1 + index * 1.6 for index, name in enumerate(GRAHAS)}
|
||||
speeds = dict.fromkeys(GRAHAS, 0.0)
|
||||
lons["Moon"] += tick * 0.0002
|
||||
speeds["Moon"] = 17.28
|
||||
if geometry:
|
||||
geometry(tick, lons, speeds)
|
||||
asc = ascendant(tick)
|
||||
return {"candidate_at": at.isoformat(), "branch_id": branch, "profile": {},
|
||||
"outputs": {layer: _mock_value(value(tick, lons, asc), layer)},
|
||||
"raw": {"ascendant_longitude": asc, "moon_longitude": lons["Moon"],
|
||||
"planet_longitudes": lons, "planet_speeds": speeds}}
|
||||
|
||||
return cache(sample)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("layer", sorted(LAYER_NAMES - {"strength_shadbala"}))
|
||||
def test_change_without_a_matching_geometric_cut_never_gets_coverage(layer):
|
||||
scope = _scope(_packet(START, START + 120 * SECOND), [layer])
|
||||
sample = _fake(layer, lambda tick, *_: {"value": "before" if tick < 30 else "after"})
|
||||
receipt = native_boundary_providers(scope)[layer](scope["plausible_ranges"][0], sample)
|
||||
assert receipt["state"] == "sampled_only"
|
||||
assert "basis" not in receipt
|
||||
assert receipt["boundaries"] == [START + 30 * SECOND]
|
||||
|
||||
|
||||
def test_karaka_finds_and_separates_two_rank_changes_between_minute_samples():
|
||||
layer = "chara_karakas"
|
||||
scope = _scope(_packet(START, START + 60 * SECOND), [layer])
|
||||
|
||||
def geometry(tick, lons, speeds):
|
||||
lons.update(Moon=33.9 + tick / 240, Sun=4.0, Mars=64.06)
|
||||
speeds["Moon"] = 360
|
||||
|
||||
sample = _fake(layer, lambda tick, lons, asc: sorted(GRAHAS[:7], key=lambda name: lons[name] % 30, reverse=True),
|
||||
geometry=geometry)
|
||||
item = scope["plausible_ranges"][0]
|
||||
details = native_boundary_providers(scope)[layer](item, sample)
|
||||
assert details["state"] == "policy_covered"
|
||||
assert details["boundaries"] == _second_edges(sample, item, layer)
|
||||
assert len(details["boundaries"]) == 2
|
||||
assert all(START < edge < START + 60 * SECOND for edge in details["boundaries"])
|
||||
|
||||
|
||||
def test_retrograde_planet_varga_detects_wrap_in_reverse_direction():
|
||||
layer = "planet_vargas:D9"
|
||||
scope = _scope(_packet(START, START + 60 * SECOND), [layer])
|
||||
|
||||
def geometry(tick, lons, speeds):
|
||||
lons["Rahu"] = (0.025 - tick / 1000) % 360
|
||||
speeds["Rahu"] = -86.4
|
||||
|
||||
sample = _fake(layer, lambda tick, lons, asc: {"Rahu": int(lons["Rahu"] // 30)}, geometry=geometry)
|
||||
item = scope["plausible_ranges"][0]
|
||||
details = native_boundary_providers(scope)[layer](item, sample)
|
||||
assert details["state"] == "policy_covered"
|
||||
assert details["boundaries"] == _second_edges(sample, item, layer) == [START + 26 * SECOND]
|
||||
|
||||
|
||||
def test_shadbala_is_explicitly_unavailable_without_invoking_strength_calculation(monkeypatch):
|
||||
import shadbala
|
||||
|
||||
def unexpected_strength(*args, **kwargs):
|
||||
pytest.fail("The offline purpose scan must never compute Shadbala")
|
||||
|
||||
monkeypatch.setattr(shadbala, "calc_shadbala", unexpected_strength)
|
||||
layer = "strength_shadbala"
|
||||
scope = _scope(_packet(START, START + 60 * SECOND), [layer])
|
||||
compute = native_scope_compute(scope)
|
||||
output = compute(START, BRANCH)["outputs"][layer]
|
||||
assert (output["status"], output["value"], output["method_id"]) == ("blocked", None, "shadbala_pending_review")
|
||||
assessment = scan_scope(scope, compute, native_boundary_providers(scope))
|
||||
receipt = assessment["per_layer_scan_receipts"][0]
|
||||
assert (receipt["state"], receipt["reason"], receipt["method_id"], receipt["boundary_times"]) == (
|
||||
"incomplete", "method_unresolved", "shadbala_pending_review", [],
|
||||
)
|
||||
|
||||
|
||||
def test_scan_deduplicates_boundary_on_the_240_minute_chunk_seam():
|
||||
layer = "D1"
|
||||
scope = _scope(_packet(START, START + timedelta(minutes=240)), [layer])
|
||||
seam = int(CHUNK / SECOND)
|
||||
sample = _fake(layer, lambda tick, lons, asc: int(asc // 30), ascendant=lambda tick: 30 + (tick - seam) / 6000)
|
||||
item = scope["plausible_ranges"][0]
|
||||
details = native_boundary_providers(scope)[layer](item, sample)
|
||||
assert details["boundaries"] == [START + CHUNK]
|
||||
assert details["state"] == "policy_covered"
|
||||
|
||||
|
||||
def test_midnight_range_keeps_the_exact_boundary():
|
||||
layer = "D1"
|
||||
scope = _scope(_packet(START - 4 * SECOND, START + 4 * SECOND), [layer])
|
||||
sample = _fake(layer, lambda tick, lons, asc: int(asc // 30), ascendant=lambda tick: 30 + tick / 6000)
|
||||
item = scope["plausible_ranges"][0]
|
||||
assert native_boundary_providers(scope)[layer](item, sample)["boundaries"] == [START]
|
||||
|
||||
|
||||
def test_disjoint_ranges_do_not_compose_a_bridge_or_duplicate_boundaries():
|
||||
layer = "D1"
|
||||
packet = _packet(START - 4 * SECOND, START + 4 * SECOND)
|
||||
packet["remaining_ranges"].append({"start": (START + 14 * SECOND).isoformat(),
|
||||
"end": (START + 28 * SECOND).isoformat()})
|
||||
scope = _scope(packet, [layer])
|
||||
sample = _fake(layer, lambda tick, lons, asc: int(asc // 30),
|
||||
ascendant=lambda tick: 30 + tick / 6000 if tick < 14 else 60 + (tick - 20) / 6000)
|
||||
bound_profile = scope["profiles"][BRANCH]
|
||||
|
||||
def bound_sample(at, branch):
|
||||
return {**sample(at, branch), "profile": bound_profile}
|
||||
|
||||
result = scan_scope(scope, bound_sample, native_boundary_providers(scope))
|
||||
receipts = result["per_layer_scan_receipts"]
|
||||
assert [r["boundary_times"] for r in receipts] == [[START.isoformat()], [(START + 20 * SECOND).isoformat()]]
|
||||
assert all(r["state"] == "policy_covered" for r in receipts)
|
||||
assert all(not START + 4 * SECOND < stamp(row["candidate_at"]) < START + 14 * SECOND
|
||||
for row in result["candidates"])
|
||||
|
||||
|
||||
def test_ayanamsa_and_node_branches_compare_independently():
|
||||
layer = "planet_signs"
|
||||
at = stamp(SKY_EDGE)
|
||||
packet = _packet(at - 120 * SECOND, at + 120 * SECOND)
|
||||
branches = packet["profiles"]["branches"]
|
||||
branches["alternate"] = {**branches[BRANCH], "ayanamsa": "raman", "node_mode": "true"}
|
||||
bounds = packet["remaining_ranges"][0]
|
||||
packet["remaining_ranges"] = [{**bounds, "branch_id": branch} for branch in branches]
|
||||
scope = _scope(packet, [layer])
|
||||
sample = cache(native_scope_compute(scope))
|
||||
provider = native_boundary_providers(scope)[layer]
|
||||
for item in scope["plausible_ranges"]:
|
||||
details = provider(item, sample)
|
||||
assert details["boundaries"] == _second_edges(sample, item, layer)
|
||||
assert sample(at, BRANCH)["raw"]["planet_longitudes"]["Rahu"] != sample(at, "alternate")["raw"]["planet_longitudes"]["Rahu"]
|
||||
|
||||
|
||||
def test_incomplete_timing_returns_sample_ranges_rather_than_a_full_envelope():
|
||||
layer = "Vimshottari"
|
||||
row = {"period_id": "md", "start": START.isoformat(), "end": (START + 60 * SECOND).isoformat()}
|
||||
output = {**_mock_value("native_periods", layer), "periods": [row]}
|
||||
candidates = [{"candidate_id": "test", "branch_id": BRANCH, "outputs": {layer: output}}]
|
||||
partial, = period_envelopes(candidates, layer, False)
|
||||
assert partial["scope"] == "sampled_points_range" and partial["common_window"] is None
|
||||
complete, = period_envelopes(candidates, layer, True)
|
||||
assert complete["scope"] == "full_interval_envelope" and complete["common_window"] is not None
|
||||
|
||||
|
||||
def test_offline_cli_input_runs_all_layers_within_the_candidate_budget(tmp_path, monkeypatch, capsys):
|
||||
packet_path = tmp_path / "synthetic.json"
|
||||
packet_path.write_text(json.dumps(_packet(START - 1800 * SECOND, START + 1800 * SECOND)), encoding="utf-8")
|
||||
|
||||
def with_layers(*args):
|
||||
scope = build_scope_request(*args)
|
||||
scope["policy"]["required_layers"] = sorted(LAYER_NAMES)
|
||||
return scope
|
||||
|
||||
monkeypatch.setattr(cli, "build_scope_request", with_layers)
|
||||
monkeypatch.setattr(sys, "argv", ["rectification_purpose_gate", "--input", str(packet_path)])
|
||||
assert cli.main() == 0
|
||||
result = json.loads(capsys.readouterr().out)["purpose_assessment"]
|
||||
assert result["budget"]["candidates_computed"] <= result["budget"]["candidate_limit"] == 4000
|
||||
assert not result["budget"]["exhausted"]
|
||||
receipts = {r["layer"]: r for r in result["per_layer_scan_receipts"]}
|
||||
assert receipts.keys() == LAYER_NAMES
|
||||
assert {layer for layer, r in receipts.items() if r["state"] == "sampled_only"} == SAMPLED
|
||||
assert receipts["strength_shadbala"]["state"] == "incomplete"
|
||||
assert all(r["basis"] for layer, r in receipts.items() if layer not in SAMPLED | {"strength_shadbala"})
|
||||
Reference in New Issue
Block a user