90 lines
3.6 KiB
Python
90 lines
3.6 KiB
Python
"""Compare native time windows at the frozen forecast precision."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import timedelta, timezone
|
|
|
|
from .scope import stamp, usable
|
|
|
|
TIMING_OUTPUTS = frozenset({"Vimshottari", "Narayana"})
|
|
|
|
|
|
def output_periods(output: dict) -> dict:
|
|
rows = output.get("periods")
|
|
if not isinstance(rows, list):
|
|
return {}
|
|
periods = {}
|
|
for row in rows:
|
|
start, end = stamp(row["start"]), stamp(row["end"])
|
|
key = row["period_id"]
|
|
if key in periods or end < start:
|
|
raise ValueError("invalid_native_periods")
|
|
periods[key] = (row, start, end)
|
|
return periods
|
|
|
|
|
|
def _bucket(at, granularity, offset):
|
|
local = at.astimezone(offset)
|
|
return (local.year, local.month, local.day)[:{"year": 1, "month": 2, "day": 3}[granularity]]
|
|
|
|
|
|
def period_signature(output: dict, forecast: dict, granularity: str) -> tuple:
|
|
"""Keep identity, endpoint precision, explicit target crossings and direction."""
|
|
offset = timezone(timedelta(seconds=forecast["comparison_offset_seconds"]))
|
|
boundaries = [stamp(forecast["start"]), *map(stamp, forecast["target_boundaries"]), stamp(forecast["end"])]
|
|
return tuple(
|
|
(
|
|
key, row["lord"], row.get("level"), row.get("parent_period_id"), row.get("direction"),
|
|
_bucket(start, granularity, offset), _bucket(end, granularity, offset),
|
|
tuple((start <= target, end <= target) for target in boundaries),
|
|
)
|
|
for key, (row, start, end) in sorted(output_periods(output).items())
|
|
)
|
|
|
|
|
|
def _window(start, end) -> dict:
|
|
return {"start": start.isoformat(), "end": end.isoformat(), "closed_start": True, "closed_end": False}
|
|
|
|
|
|
def _union(windows: list[tuple]) -> list[dict]:
|
|
merged = []
|
|
for start, end in sorted(windows):
|
|
if start == end:
|
|
continue
|
|
if merged and start <= merged[-1][1]:
|
|
merged[-1] = (merged[-1][0], max(merged[-1][1], end))
|
|
else:
|
|
merged.append((start, end))
|
|
return [_window(start, end) for start, end in merged]
|
|
|
|
|
|
def period_envelopes(candidates: list[dict], layer: str, policy_covered: bool) -> list[dict]:
|
|
"""Keep each observed native window; an empty intersection stays null."""
|
|
periods = {}
|
|
for candidate in candidates:
|
|
output = candidate["outputs"].get(layer)
|
|
if output is None:
|
|
continue
|
|
for key, (raw, start, end) in output_periods(output).items():
|
|
periods.setdefault(key, []).append((candidate, output, raw, start, end))
|
|
|
|
envelopes = []
|
|
for key, entries in sorted(periods.items()):
|
|
windows = [(start, end) for _, _, _, start, end in entries]
|
|
starts = [start for start, _ in windows]
|
|
ends = [end for _, end in windows]
|
|
complete = policy_covered and len(entries) == len(candidates) and all(usable(output) for _, output, *_ in entries)
|
|
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",
|
|
"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,
|
|
"by_candidate": [
|
|
{"candidate_id": candidate["candidate_id"], "branch_id": candidate["branch_id"],
|
|
"native_result_ref": output["result_ref"], "period": raw}
|
|
for candidate, output, raw, _, _ in entries
|
|
],
|
|
})
|
|
return envelopes
|