Files
Jyotisha/scripts/chart_dasha/timeline_boundaries.py
T

135 lines
6.1 KiB
Python

#!/usr/bin/env python3
"""One boundary rule and one continuity check for every exposed period table.
占星师第三轮审查 2026-11-07 (item 10 of her review): two adjacent periods
both shown as "12 月 8 日" do not prove the underlying timeline has no hole.
Every dasha / Mudda / Narayana / annual period table we expose follows one
rule -- start inclusive, end exclusive -- and is checked on its full
timestamps: each segment's end must equal the next segment's start.
Inputs may be datetimes, ISO strings (with or without offset), package
``instant`` dicts (``{"utc": ..., "jd_ut": ...}``) or Julian days. Aware and
naive values are never compared with each other; such a table is reported as
``not_comparable`` instead of being guessed.
"""
from __future__ import annotations
from datetime import datetime, timedelta, timezone
from typing import Any, Iterable
BOUNDARY_RULE = "start_inclusive_end_exclusive"
BOUNDARY_RULE_TEXT = "Each period starts at its start instant (inclusive) and ends just before its end instant (exclusive)."
BOUNDARY_RULE_TEXT_ZH = "每段从起点时刻起算(含),到终点时刻前结束(不含);下一段从同一时刻开始。"
# Producers write seconds with microseconds; anything at or below this is the
# same instant. Larger mismatches are reported with their size.
DEFAULT_TOLERANCE_SECONDS = 1.0
_JD_UNIX_EPOCH = 2440587.5
def parse_instant(value: Any) -> datetime | None:
"""A boundary value as a datetime (aware when the source carries a zone)."""
if isinstance(value, datetime):
return value
if isinstance(value, dict):
if isinstance(value.get("jd_ut"), (int, float)) and not isinstance(value.get("jd_ut"), bool):
return _from_jd(float(value["jd_ut"]))
for key in ("utc", "local", "at", "instant"):
if value.get(key) is not None:
return parse_instant(value[key])
return None
if isinstance(value, (int, float)) and not isinstance(value, bool):
return _from_jd(float(value)) if value > 1_000_000 else None
if isinstance(value, str) and len(value) >= 10:
text = value.strip().replace("Z", "+00:00")
try:
return datetime.fromisoformat(text)
except ValueError:
return None
return None
def _from_jd(jd_ut: float) -> datetime:
return datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(days=jd_ut - _JD_UNIX_EPOCH)
def check_continuity(
rows: Iterable[Any],
*,
start_key: str = "start",
end_key: str = "end",
label: str | None = None,
expected_start: Any = None,
expected_end: Any = None,
tolerance_seconds: float = DEFAULT_TOLERANCE_SECONDS,
) -> dict[str, Any]:
"""Check that consecutive rows meet exactly: ``rows[i].end == rows[i+1].start``.
``expected_start`` / ``expected_end`` (optional) are the window the table
claims to cover; a first start after it or a last end before it is a gap
at the edge. Returns ``status`` ``continuous`` / ``discontinuous`` /
``not_comparable`` / ``insufficient`` with every gap and overlap.
"""
items = [row for row in rows if isinstance(row, dict)]
out: dict[str, Any] = {"rule": BOUNDARY_RULE, "segments": len(items)}
if label:
out["table"] = label
spans = []
for index, row in enumerate(items):
start, end = parse_instant(row.get(start_key)), parse_instant(row.get(end_key))
if start is None or end is None:
out.update(status="insufficient", reason=f"row_{index}_boundary_unparsed")
return out
spans.append((start, end))
edges = [parse_instant(expected_start), parse_instant(expected_end)]
instants = [moment for span in spans for moment in span] + [moment for moment in edges if moment is not None]
if len({moment.tzinfo is None for moment in instants}) > 1:
out.update(status="not_comparable", reason="aware_and_naive_boundaries_mixed")
return out
if not spans:
out.update(status="insufficient", reason="no_rows")
return out
def seconds(a: datetime, b: datetime) -> float:
return round((b - a).total_seconds(), 3)
gaps: list[dict[str, Any]] = []
overlaps: list[dict[str, Any]] = []
reversed_rows = [index for index, (start, end) in enumerate(spans) if end < start]
for index in range(len(spans) - 1):
end, next_start = spans[index][1], spans[index + 1][0]
delta = seconds(end, next_start)
if abs(delta) <= tolerance_seconds:
continue
entry = {"after_index": index, "end": end.isoformat(), "next_start": next_start.isoformat(), "seconds": delta}
(gaps if delta > 0 else overlaps).append(entry)
if edges[0] is not None and abs(seconds(edges[0], spans[0][0])) > tolerance_seconds:
delta = seconds(edges[0], spans[0][0])
(gaps if delta > 0 else overlaps).append(
{"edge": "window_start", "expected": edges[0].isoformat(), "first_start": spans[0][0].isoformat(), "seconds": delta})
if edges[1] is not None and abs(seconds(spans[-1][1], edges[1])) > tolerance_seconds:
delta = seconds(spans[-1][1], edges[1])
(gaps if delta > 0 else overlaps).append(
{"edge": "window_end", "last_end": spans[-1][1].isoformat(), "expected": edges[1].isoformat(), "seconds": delta})
out.update(
status="continuous" if not (gaps or overlaps or reversed_rows) else "discontinuous",
first_start=spans[0][0].isoformat(),
last_end=spans[-1][1].isoformat(),
gaps=gaps,
overlaps=overlaps,
tolerance_seconds=tolerance_seconds,
)
if reversed_rows:
out["reversed_rows"] = reversed_rows
return out
def summarize(checks: Iterable[dict[str, Any]]) -> dict[str, Any]:
"""One line over several checks: which tables are not continuous."""
checks = [check for check in checks if isinstance(check, dict)]
bad = [check.get("table") or f"#{index}" for index, check in enumerate(checks)
if check.get("status") not in ("continuous",)]
return {"rule": BOUNDARY_RULE, "tables_checked": len(checks),
"status": "continuous" if not bad else "discontinuous_or_unchecked", "tables_not_continuous": bad}