"""Compare native time windows at the frozen forecast precision.""" from __future__ import annotations from collections import defaultdict from datetime import timedelta, timezone from .scope import LEGACY_POLICY_VERSION, POLICY_VERSION, WINDOW_DURATION_TOLERANCE_DAYS, 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, *, policy_version=LEGACY_POLICY_VERSION): """Compare discrete features. V2 duration tolerance is applied across all observations.""" if policy_version == POLICY_VERSION: return period_observation(output, forecast, granularity)[0] 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 _merged_windows(windows: list[tuple]) -> list[tuple]: 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 merged def _union(windows: list[tuple]) -> list[dict]: return [_window(start, end) for start, end in _merged_windows(windows)] def period_observation(output: dict, forecast: dict, granularity: str) -> tuple[dict, dict]: lo, hi = stamp(forecast["start"]), stamp(forecast["end"]) offset = timezone(timedelta(seconds=forecast["comparison_offset_seconds"])) targets = (lo, *map(stamp, forecast["target_boundaries"]), hi) identity, boundaries = [], [] by_lord = defaultdict(list) for key, (row, start, end) in sorted(output_periods(output).items()): left, right = max(start, lo), min(end, hi) if left >= right: continue lord, level = row["lord"], row.get("level") identity.append((key, lord, level, row.get("parent_period_id"))) boundaries.append(( key, (_bucket(left, granularity, offset), _bucket(right, granularity, offset), tuple((left <= target, right <= target) for target in targets)), )) by_lord[(str(level or ""), str(lord))].append((left, right)) segments, durations = [], {} for key, windows in sorted(by_lord.items()): merged = _merged_windows(windows) segments.append((key, (len(windows), len(merged) - 1))) durations[key] = sum((end - start for start, end in merged), timedelta()) return { "window_presence": bool(identity), "period_identity": identity, "target_boundary_crossing": boundaries, "window_segments_and_gaps": segments, }, durations def period_change_witnesses(observations, granularity: str) -> dict[str, list[str]]: """Return observed birth times for each differing axis, without bucketing durations.""" tolerance = timedelta(days=WINDOW_DURATION_TOLERANCE_DAYS[granularity]) seen = {} limits = {} witnesses = {} for at, (shape, durations) in observations: def compare(axis, key, value): other, other_at = seen.setdefault((axis, key), (value, at)) if value != other and axis not in witnesses: witnesses[axis] = sorted({other_at, at}) compare("window_presence", None, shape["window_presence"]) if not shape["window_presence"]: continue compare("period_identity", None, shape["period_identity"]) for axis in ("target_boundary_crossing", "window_segments_and_gaps"): for key, value in shape[axis]: compare(axis, key, value) for key, duration in durations.items(): low, high = limits.get(key, ((duration, at), (duration, at))) low = min(low, (duration, at)) high = max(high, (duration, at)) limits[key] = (low, high) if high[0] - low[0] > tolerance and "window_total_duration" not in witnesses: witnesses["window_total_duration"] = sorted({low[1], high[1]}) return witnesses def period_envelopes(candidates: list[dict], layer: str, policy_covered: bool) -> list[dict]: """Return interval envelopes for proved coverage, and sampled ranges otherwise.""" 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", "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, "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