211 lines
8.0 KiB
Python
211 lines
8.0 KiB
Python
"""Native boundary providers with explicit coverage and resolution receipts."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import timedelta
|
|
from itertools import pairwise
|
|
from math import floor
|
|
|
|
from scripts.active_rectification_candidates import MAX_WINDOW_MINUTES
|
|
from scripts.chart_choice.boundaries import ChartRequest, find_lines
|
|
|
|
from .native import ANGLE_DIMENSIONS, ARUDHAS, division_of
|
|
from .scan import BoundaryMethodUnavailable
|
|
from .scope import SECOND, range_limits
|
|
from .timing import TIMING_OUTPUTS, period_signature
|
|
|
|
MINUTE = timedelta(minutes=1)
|
|
CHUNK = timedelta(minutes=MAX_WINDOW_MINUTES - 1)
|
|
TIMING_EXACT_SECONDS = 180
|
|
|
|
|
|
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):
|
|
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,
|
|
}
|
|
|
|
|
|
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 _ascending_enough(left, right) -> bool:
|
|
return 0 <= (right - left + 180) % 360 - 180 < 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 _arudha_provider(layer):
|
|
def provider(item, sample):
|
|
start, end = range_limits(item)
|
|
branch = item["branch_id"]
|
|
observed = set()
|
|
|
|
def value_at(at):
|
|
observed.add(at)
|
|
return sample(at, branch)["outputs"].get(layer, {}).get("value")
|
|
|
|
points = _grid(start, end, MINUTE)
|
|
value_at(start)
|
|
cuts = _discover_changes(points, value_at)
|
|
checked = sorted(observed)
|
|
gap = max((right - left for left, right in pairwise(checked)), default=timedelta(0))
|
|
covered = gap <= SECOND and all(value_at(at) is not None for at in checked)
|
|
return _details("minute_grid_then_second_bisection", checked, cuts,
|
|
bounded=covered, reason=None if covered else "scan_incomplete")
|
|
|
|
return provider
|
|
|
|
|
|
def _timing_provider(layer, forecast, granularity):
|
|
def provider(item, sample):
|
|
start, end = range_limits(item)
|
|
branch = item["branch_id"]
|
|
exact = (end - start).total_seconds() <= TIMING_EXACT_SECONDS
|
|
signatures = {}
|
|
|
|
def value_at(at):
|
|
if at not in signatures:
|
|
output = sample(at, branch)["outputs"].get(layer)
|
|
signatures[at] = period_signature(output, forecast, granularity) if output and output["status"] == "executed" else None
|
|
return signatures[at]
|
|
|
|
value_at(start)
|
|
cuts = _discover_changes(_grid(start, end, SECOND if exact else MINUTE), value_at)
|
|
complete = all(signatures.values())
|
|
return _details("native_period_windows_per_second" if exact else "native_period_windows_minute_sampling",
|
|
sorted(signatures), cuts, bounded=exact and complete,
|
|
reason="method_unresolved" if not complete else None if exact else "scan_incomplete")
|
|
|
|
return provider
|
|
|
|
|
|
def native_boundary_providers(scope: dict) -> dict:
|
|
profiles = scope["profiles"]
|
|
purpose = scope["purpose_scope"]
|
|
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] = _sector_provider(layer, profiles)
|
|
elif layer in ARUDHAS:
|
|
providers[layer] = _arudha_provider(layer)
|
|
elif layer in TIMING_OUTPUTS and purpose["forecast_window"] is not None:
|
|
providers[layer] = _timing_provider(layer, purpose["forecast_window"], purpose["granularity"])
|
|
return providers
|