Files
Jyotisha/scripts/rectification_purpose_gate/providers.py
T

619 lines
25 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 .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
from .timing import TIMING_OUTPUTS, output_periods, period_signature
MINUTE = timedelta(minutes=1)
CHUNK = timedelta(minutes=MAX_WINDOW_MINUTES - 1)
TIMING_EXACT_SECONDS = 180
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, planets=GRAHAS):
@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 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 planets:
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 planets)
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 _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"]
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(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.
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)
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"]:
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 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)
return providers