449 lines
18 KiB
Python
449 lines
18 KiB
Python
"""Native boundary providers with explicit coverage and resolution receipts."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import timedelta
|
|
from functools import cache
|
|
from itertools import pairwise
|
|
from math import floor, isfinite
|
|
|
|
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 .native import ANGLE_DIMENSIONS, ARUDHAS, division_of
|
|
from .scan import BoundaryMethodUnavailable
|
|
from .scope import SECOND, range_limits, stamp
|
|
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)
|
|
|
|
|
|
def _grid(start, end, step):
|
|
while start < end:
|
|
yield start
|
|
start = min(end, start + step)
|
|
yield end
|
|
|
|
|
|
def _details(method, points, boundaries, *, bounded, reason=None, basis=None):
|
|
max_gap = max(((right - left).total_seconds() for left, right in zip(points, points[1:])), default=0)
|
|
return {
|
|
"state": "policy_covered" if bounded else "sampled_only",
|
|
"method_id": method, "boundaries": boundaries, "resolution_seconds": 1,
|
|
"max_unchecked_gap_seconds": max_gap,
|
|
"boundary_error_seconds": 1 if boundaries else 0, "reason": reason,
|
|
**({"basis": basis} if bounded and basis else {}),
|
|
}
|
|
|
|
|
|
def _bisect_change(left, right, changes):
|
|
while right - left > SECOND:
|
|
mid = left + SECOND * (int((right - left).total_seconds()) // 2)
|
|
if changes(mid):
|
|
right = mid
|
|
else:
|
|
left = mid
|
|
return right
|
|
|
|
|
|
def _longitude_delta(left, right) -> float:
|
|
return (right - left + 180) % 360 - 180
|
|
|
|
|
|
def _ascending_enough(left, right) -> bool:
|
|
return 0 <= _longitude_delta(left, right) < 2.0
|
|
|
|
|
|
def _longitude(row: dict, key: str) -> float:
|
|
value = (row.get("raw") or {}).get(key)
|
|
if value is None:
|
|
if row.get("method_unresolved"):
|
|
raise BoundaryMethodUnavailable("native_profile_not_supported")
|
|
raise RuntimeError("native_longitude_unavailable")
|
|
return float(value)
|
|
|
|
|
|
def _varga_provider(layer, division, profiles):
|
|
def provider(item, sample):
|
|
start, end = range_limits(item)
|
|
branch = item["branch_id"]
|
|
profile = profiles[branch]
|
|
req = ChartRequest(start.date().isoformat(), profile["lat"], profile["lon"], 0,
|
|
profile["ayanamsa"], profile["node_mode"])
|
|
|
|
def longitude(at):
|
|
return _longitude(sample(at, branch), "ascendant_longitude")
|
|
|
|
grid = {at: longitude(at) for at in _grid(start, end, MINUTE)}
|
|
points = list(grid)
|
|
ordinary_latitude = abs(profile["lat"]) <= 60
|
|
forward = all(_ascending_enough(left, right) for left, right in pairwise(grid.values()))
|
|
times = set()
|
|
if ordinary_latitude and forward:
|
|
chunks = _grid(start, end, CHUNK)
|
|
for left, right in pairwise(chunks):
|
|
for line in find_lines(req, left, right, (division,), longitude_at=longitude):
|
|
if layer in line.flips:
|
|
times.add(line.at)
|
|
else:
|
|
times.update(_discover_changes(points, lambda at: sample(at, branch)["outputs"].get(layer, {}).get("value")))
|
|
|
|
verified = all(
|
|
sample(at - SECOND, branch)["outputs"][layer]["value"] != sample(at, branch)["outputs"][layer]["value"]
|
|
for at in times
|
|
)
|
|
return _details("ascendant_degree_crossing", points, sorted(times),
|
|
bounded=ordinary_latitude and forward and verified,
|
|
reason=None if ordinary_latitude and forward and verified else "scan_incomplete")
|
|
|
|
return provider
|
|
|
|
|
|
def _sector_provider(layer, profiles):
|
|
longitude_key = "ascendant_longitude" if layer == "lagna_nakshatra" else "moon_longitude"
|
|
span = 30 if layer == "moon_sign" else 360 / 27
|
|
|
|
def provider(item, sample):
|
|
start, end = range_limits(item)
|
|
branch = item["branch_id"]
|
|
|
|
def longitude(at):
|
|
return _longitude(sample(at, branch), longitude_key)
|
|
|
|
grid = {at: longitude(at) for at in _grid(start, end, MINUTE)}
|
|
cuts = set()
|
|
bounded = longitude_key == "moon_longitude" or abs(profiles[branch]["lat"]) <= 60
|
|
for (left, left_lon), (right, right_lon) in pairwise(grid.items()):
|
|
if not _ascending_enough(left_lon, right_lon):
|
|
bounded = False
|
|
continue
|
|
if right_lon < left_lon:
|
|
right_lon += 360
|
|
for index in range(floor(left_lon / span) + 1, floor(right_lon / span) + 1):
|
|
target = index * span
|
|
cuts.add(_bisect_change(left, right, lambda at: left_lon + (longitude(at) - left_lon + 180) % 360 - 180 >= target))
|
|
verified = all(
|
|
sample(at - SECOND, branch)["outputs"][layer]["value"] != sample(at, branch)["outputs"][layer]["value"]
|
|
for at in cuts
|
|
)
|
|
return _details("longitude_degree_crossing", list(grid), sorted(cuts), bounded=bounded and verified,
|
|
reason=None if bounded and verified else "scan_incomplete")
|
|
|
|
return provider
|
|
|
|
|
|
def _discover_changes(points, value_at):
|
|
cuts = []
|
|
for left, right in pairwise(points):
|
|
before, after = value_at(left), value_at(right)
|
|
if before is None or after is None or before == after:
|
|
continue
|
|
|
|
def changed(at):
|
|
value = value_at(at)
|
|
if value is None:
|
|
raise LookupError("breakpoint_value_unavailable")
|
|
return value != before
|
|
|
|
try:
|
|
cuts.append(_bisect_change(left, right, changed))
|
|
except LookupError:
|
|
continue
|
|
return cuts
|
|
|
|
|
|
def _midpoint(left, right):
|
|
return left + SECOND * (int((right - left).total_seconds()) // 2)
|
|
|
|
|
|
def _with_midpoints(points):
|
|
return sorted(set(points) | {_midpoint(left, right) for left, right in pairwise(points)})
|
|
|
|
|
|
def _segment_probes(start, end, boundaries, grid):
|
|
edges = (start, *boundaries, end + SECOND)
|
|
for left, after in pairwise(edges):
|
|
right = after - SECOND
|
|
interior = {at for at in grid if left < at < right}
|
|
probes = set(_with_midpoints(sorted({left, right} | interior)))
|
|
probes.add(_midpoint(left, right))
|
|
yield sorted(probes)
|
|
|
|
|
|
def _planet_longitude(row, name):
|
|
value = (row.get("raw") or {}).get("planet_longitudes", {}).get(name)
|
|
if not isinstance(value, (int, float)) or not isfinite(value):
|
|
raise BoundaryMethodUnavailable("planet_longitude_unavailable")
|
|
return value % 360
|
|
|
|
|
|
def _one_direction(values):
|
|
deltas = [_longitude_delta(left, right) for left, right in pairwise(values)]
|
|
return (all(0 <= delta < 2 for delta in deltas) or
|
|
all(-2 < delta <= 0 for delta in deltas))
|
|
|
|
|
|
def _planet_direction(rows, name):
|
|
values = [_planet_longitude(row, name) for row in rows]
|
|
if not _one_direction(values):
|
|
return False
|
|
speeds = [(row.get("raw") or {}).get("planet_speeds", {}).get(name) for row in rows]
|
|
if not all(isinstance(speed, (int, float)) and isfinite(speed) for speed in speeds):
|
|
return False
|
|
if all(speed == 0 for speed in speeds):
|
|
return all(value == values[0] for value in values)
|
|
if not (all(speed > 0 for speed in speeds) or all(speed < 0 for speed in speeds)):
|
|
return False
|
|
return all(_longitude_delta(a, b) * speeds[0] > 0 for a, b in pairwise(values))
|
|
|
|
|
|
def _sign_layout_factory(profiles):
|
|
@cache
|
|
def layout(start, end, branch, sample):
|
|
profile = profiles[branch]
|
|
grid = list(_grid(start, end, MINUTE))
|
|
probes = _with_midpoints(grid)
|
|
if abs(profile["lat"]) > 60:
|
|
return grid, [], False
|
|
|
|
observed = {}
|
|
|
|
def row(at):
|
|
if at not in observed:
|
|
observed[at] = sample(at, branch)
|
|
return observed[at]
|
|
|
|
def asc(at):
|
|
return _longitude(row(at), "ascendant_longitude")
|
|
|
|
try:
|
|
rows = [row(at) for at in probes]
|
|
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):
|
|
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:
|
|
def sign(at):
|
|
return int(_planet_longitude(row(at), name) // 30)
|
|
|
|
cuts.update(_discover_changes(probes, sign))
|
|
except BoundaryMethodUnavailable:
|
|
return grid, [], False
|
|
|
|
checked = [observed[at] for at in sorted(observed)]
|
|
bounded = all(_planet_direction(checked, name) for name in GRAHAS)
|
|
return grid, sorted(cuts), bounded
|
|
|
|
return layout
|
|
|
|
|
|
def _executed_output(sample, at, branch, layer):
|
|
output = sample(at, branch)["outputs"].get(layer)
|
|
return output if output and output["status"] == "executed" else None
|
|
|
|
|
|
def _arudha_provider(layer, sign_layout):
|
|
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:
|
|
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),
|
|
bounded=False, reason="scan_incomplete")
|
|
|
|
return provider
|
|
|
|
|
|
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.
|
|
for before, after in pairwise(rows):
|
|
ranges = []
|
|
for name in GRAHAS:
|
|
a, b = (_planet_longitude(row, name) % 30 for row in (before, after))
|
|
if name == "Ketu":
|
|
a, b = 30 - a, 30 - b
|
|
ranges.append((min(a, b), max(a, b)))
|
|
if any(left[1] >= right[0] for left, right in pairwise(sorted(ranges))):
|
|
return False
|
|
return True
|
|
|
|
|
|
def _translated_periods(before, after, shift, forecast_limits):
|
|
lo, hi = forecast_limits
|
|
if not all(start < hi and end > lo and start < end
|
|
for periods in (before, after) for _, start, end in periods.values()):
|
|
return False
|
|
for key in before.keys() | after.keys():
|
|
if key not in before or key not in after:
|
|
# A period can be omitted only when the same translated interval
|
|
# lies outside the forecast window at the other probe.
|
|
_, start, end = (after if key in after else before)[key]
|
|
delta = -shift if key in after else shift
|
|
if start + delta < hi and end + delta > lo:
|
|
return False
|
|
continue
|
|
a, a_start, a_end = before[key]
|
|
b, b_start, b_end = after[key]
|
|
identity = ("lord", "level", "parent_period_id", "direction")
|
|
if (any(a.get(field) != b.get(field) for field in identity)
|
|
or abs(b_start - a_start - shift) > DATE_ROUNDING
|
|
or abs(b_end - a_end - shift) > DATE_ROUNDING):
|
|
return False
|
|
return True
|
|
|
|
|
|
def _timing_transitions(points, value):
|
|
cuts = []
|
|
for left, right in pairwise(points):
|
|
before, after = value(left), value(right)
|
|
while before != after:
|
|
edge = _bisect_change(left, right, lambda at: value(at) != before)
|
|
cuts.append(edge)
|
|
left, before = edge, value(edge)
|
|
return cuts
|
|
|
|
|
|
def _timing_provider(layer, forecast, granularity, sign_layout, moon_layout):
|
|
vim = layer == "Vimshottari"
|
|
forecast_limits = stamp(forecast["start"]), stamp(forecast["end"])
|
|
depth = {"year": 1, "month": 2, "day": 3}[granularity]
|
|
shortest_vim = timedelta(days=365.25 * 120 * (min(VIMSHOTTARI_YEARS.values()) / 120) ** depth)
|
|
|
|
def valid_pairs(points, periods, moon_longitude):
|
|
for left, right in pairwise(points):
|
|
a, b = periods(left), periods(right)
|
|
if vim:
|
|
common = sorted(a.keys() & b.keys())
|
|
if not common:
|
|
return False
|
|
shift = b[common[0]][1] - a[common[0]][1]
|
|
# A hidden period cannot enter and leave between two probes
|
|
# when the translation is shorter than the shortest period.
|
|
moon_delta = _longitude_delta(moon_longitude(left), moon_longitude(right))
|
|
if not (0 < moon_delta < 2 and -shortest_vim < shift <= timedelta(0)):
|
|
return False
|
|
else:
|
|
shift = right - left
|
|
if not _translated_periods(a, b, shift, forecast_limits):
|
|
return False
|
|
return True
|
|
|
|
def provider(item, sample):
|
|
start, end = range_limits(item)
|
|
branch = item["branch_id"]
|
|
|
|
@cache
|
|
def output(at):
|
|
return _executed_output(sample, at, branch, layer)
|
|
|
|
@cache
|
|
def value(at):
|
|
row = output(at)
|
|
return period_signature(row, forecast, granularity) if row else None
|
|
|
|
@cache
|
|
def periods(at):
|
|
row = output(at)
|
|
return output_periods(row) if row else {}
|
|
|
|
if end - start <= SECOND * TIMING_EXACT_SECONDS:
|
|
grid = list(_grid(start, end, SECOND))
|
|
cuts = _discover_changes(grid, value)
|
|
complete = all(map(value, grid))
|
|
return _details("native_period_windows_per_second", grid, cuts, bounded=complete,
|
|
reason=None if complete else "method_unresolved")
|
|
|
|
if vim:
|
|
moon = moon_layout(item, sample)
|
|
grid = list(_grid(start, end, MINUTE))
|
|
forced = moon["boundaries"]
|
|
bounded = moon["state"] == "policy_covered"
|
|
else:
|
|
grid, forced, bounded = sign_layout(start, end, branch, sample)
|
|
cuts = []
|
|
reason = "scan_incomplete"
|
|
if bounded:
|
|
for points in _segment_probes(start, end, forced, grid):
|
|
if not all(map(value, points)):
|
|
reason = "method_unresolved"
|
|
bounded = False
|
|
break
|
|
if not vim and not _degree_order_fixed([sample(at, branch) for at in points]):
|
|
reason = "degree_order_unresolved"
|
|
bounded = False
|
|
break
|
|
checked = set(points)
|
|
|
|
def observe(at):
|
|
checked.add(at)
|
|
return value(at)
|
|
|
|
found = _timing_transitions(points, observe)
|
|
ordered = sorted(checked)
|
|
if not all(map(value, ordered)):
|
|
reason = "method_unresolved"
|
|
bounded = False
|
|
break
|
|
|
|
def moon_longitude(at):
|
|
return _longitude(sample(at, branch), "moon_longitude")
|
|
|
|
if not valid_pairs(ordered, periods, moon_longitude):
|
|
bounded = False
|
|
break
|
|
cuts.extend(found)
|
|
if not bounded:
|
|
fallback = _discover_changes(sorted(set(grid) | set(forced)), value)
|
|
return _details("native_period_windows_minute_sampling", grid, sorted(set(cuts + fallback)),
|
|
bounded=False, reason=reason)
|
|
cuts.extend(at for at in forced if value(at - SECOND) != value(at))
|
|
method = "moon_monotone_minute_grid_bisection" if vim else "sign_segments_minute_grid_bisection"
|
|
basis = ("vimshottari_boundaries_monotone_in_moon_longitude" if vim else
|
|
"narayana_periods_fixed_within_sign_segment")
|
|
return _details(method, grid, sorted(set(cuts)), bounded=True, basis=basis)
|
|
|
|
return provider
|
|
|
|
|
|
def native_boundary_providers(scope: dict) -> dict:
|
|
profiles = scope["profiles"]
|
|
purpose = scope["purpose_scope"]
|
|
sign_layout = _sign_layout_factory(profiles)
|
|
moon_layout = _sector_provider("moon_nakshatra", profiles)
|
|
providers = {}
|
|
for layer in scope["policy"]["required_layers"]:
|
|
division = division_of(layer)
|
|
if division is not None:
|
|
providers[layer] = _varga_provider(layer, division, profiles)
|
|
elif layer in ANGLE_DIMENSIONS:
|
|
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 TIMING_OUTPUTS and purpose["forecast_window"] is not None:
|
|
providers[layer] = _timing_provider(layer, purpose["forecast_window"], purpose["granularity"],
|
|
sign_layout, moon_layout)
|
|
return providers
|