You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
136 lines
6.4 KiB
Python
136 lines
6.4 KiB
Python
"""Replay recorded PTZ17 lens transactions and their fresh HFOV samples."""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
from dataclasses import asdict, dataclass
|
|
import json
|
|
import math
|
|
from pathlib import Path
|
|
import re
|
|
from typing import Any
|
|
|
|
|
|
WINDOW_S = 20.0
|
|
MIN_HFOV_CHANGE_RATIO = 0.004
|
|
MAX_STATUS_AGE_S = 0.65
|
|
MIN_PROJECTION_MARGIN = 0.16
|
|
EPISODES = ("1412", "1424", "1428")
|
|
START = re.compile(r"request=(\d+) kind=(\w+) physical start seq=(\d+) pulse=([.\d]+)s hard=([.\d]+)s")
|
|
RESULT = re.compile(r"request=(\d+) result=(\w+) duration=([.\d]+)s min=([.\d]+)s optics=(True|False) reason=(\S+)")
|
|
DECISION = re.compile(r"request=(\d+).*?reason=(\S+) blockers=(\S+)")
|
|
CONFIRMED = re.compile(r"request=(\d+) optics confirmed\b")
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class LensSample:
|
|
time_s: float
|
|
hfov_deg: float
|
|
|
|
|
|
def first_hfov_change(
|
|
baseline: LensSample, samples: list[LensSample], *, from_s: float, until_s: float,
|
|
) -> LensSample | None:
|
|
"""Return the first fresh HFOV narrowing of at least 0.4 percent."""
|
|
return next((
|
|
sample for sample in samples
|
|
if math.isfinite(sample.time_s) and math.isfinite(sample.hfov_deg)
|
|
and 0.0 < sample.hfov_deg < 180.0
|
|
and from_s <= sample.time_s < until_s and sample.time_s > baseline.time_s
|
|
and (baseline.hfov_deg - sample.hfov_deg) / baseline.hfov_deg >= MIN_HFOV_CHANGE_RATIO
|
|
), None)
|
|
|
|
|
|
def make_fixture(path: Path) -> dict[str, Any]:
|
|
report = json.loads(path.read_bytes())
|
|
assert report["status"] == "checked"
|
|
detail = report["detail"]
|
|
assert detail["covers"]
|
|
rows = detail["rows"]
|
|
own_status = [value["early_status"] for value in detail["telemetry"].values() if value["early_status"]]
|
|
assert len(own_status) == 1
|
|
keys = ("[ZOOM DELIVERY]", "[ZOOM DECISION]")
|
|
return {
|
|
"start_utc": report["start"],
|
|
"initial_send_s": detail["axis_commands"]["first"][0][0],
|
|
"rows": {key: [row for row in rows.get(key, []) if 0.0 <= row[0] <= WINDOW_S] for key in keys},
|
|
"status": own_status[0],
|
|
"first_logged_projection_s": next(
|
|
(t for t, row in rows.get("[AIM]", []) if 0.0 <= t <= WINDOW_S
|
|
and float(row.get("approach_margin", -1.0)) >= MIN_PROJECTION_MARGIN), None,
|
|
),
|
|
}
|
|
|
|
|
|
def replay(episode: dict[str, Any]) -> dict[str, Any]:
|
|
samples = [LensSample(*row) for row in episode["status"]]
|
|
assert all(math.isfinite(s.time_s) and 0.0 < s.hfov_deg < 180.0 for s in samples)
|
|
assert samples and samples == sorted(samples, key=lambda sample: sample.time_s)
|
|
requests: dict[int, dict[str, Any]] = {}
|
|
for time_s, line in episode["rows"]["[ZOOM DELIVERY]"]:
|
|
if match := START.search(line):
|
|
request_id, kind, seq, pulse, hard = match.groups()
|
|
assert int(request_id) not in requests
|
|
requests[int(request_id)] = dict(
|
|
request=int(request_id), kind=kind, seq=int(seq), start_s=time_s,
|
|
nominal_s=float(pulse), hard_limit_s=float(hard), final=None,
|
|
explicit_confirmation_s=None, decisions=[],
|
|
)
|
|
elif match := RESULT.search(line):
|
|
request_id, status, duration, minimum, optics, reason = match.groups()
|
|
request = requests[int(request_id)]
|
|
assert request["final"] is None
|
|
request["final"] = dict(
|
|
time_s=time_s, status=status, accounted_duration_s=float(duration),
|
|
required_duration_s=float(minimum), optics_at_finalize=optics == "True", reason=reason,
|
|
)
|
|
elif match := CONFIRMED.search(line):
|
|
requests[int(match[1])]["explicit_confirmation_s"] = time_s
|
|
for time_s, line in episode["rows"]["[ZOOM DECISION]"]:
|
|
if (match := DECISION.search(line)) and int(match[1]) in requests:
|
|
requests[int(match[1])]["decisions"].append(dict(time_s=time_s, reason=match[2], blockers=match[3]))
|
|
|
|
ordered = list(requests.values())
|
|
for index, request in enumerate(ordered):
|
|
start_s = request["start_s"]
|
|
assert 0.0 < request["nominal_s"] <= request["hard_limit_s"] <= 0.4
|
|
until_s = ordered[index + 1]["start_s"] if index + 1 < len(ordered) else math.nextafter(WINDOW_S, math.inf)
|
|
baseline = next((s for s in reversed(samples) if s.time_s < start_s), None)
|
|
measured = None
|
|
if baseline is not None and start_s - baseline.time_s <= MAX_STATUS_AGE_S:
|
|
measured = first_hfov_change(baseline, samples, from_s=start_s, until_s=until_s)
|
|
request["first_status_narrowing"] = asdict(measured) if measured is not None else None
|
|
final = request["final"]
|
|
if final is not None and final["status"] == "confirmed" and request["explicit_confirmation_s"] is None:
|
|
request["explicit_confirmation_s"] = final["time_s"]
|
|
first_confirmed = next((row for row in ordered if row["explicit_confirmation_s"] is not None), None)
|
|
first_s = ordered[0]["start_s"] if ordered else None
|
|
confirm_s = first_confirmed["explicit_confirmation_s"] if first_confirmed else None
|
|
return dict(
|
|
start_utc=episode["start_utc"], status_samples=len(samples),
|
|
first_send_s=episode["initial_send_s"], first_start_s=first_s,
|
|
first_confirmed_request=first_confirmed["request"] if first_confirmed else None,
|
|
first_optics_s=confirm_s,
|
|
startup_to_optics_s=round(confirm_s - first_s, 3) if confirm_s is not None else None,
|
|
first_logged_projection_s=episode["first_logged_projection_s"],
|
|
first_request_projection_at_decision="unknown",
|
|
requests=ordered,
|
|
)
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--session", type=Path, help="Build the fixture from the three bounded observer reports")
|
|
parser.add_argument("--fixture", type=Path, default=Path(__file__).with_name("reference_fixture.json"))
|
|
parser.add_argument("--output", type=Path, default=Path(__file__).with_name("reference_replay.json"))
|
|
args = parser.parse_args()
|
|
if args.session:
|
|
fixture = {key: make_fixture(args.session / f"ref_{key}.json") for key in EPISODES}
|
|
args.fixture.write_text(json.dumps(fixture, indent=2) + "\n", encoding="utf-8")
|
|
fixture = json.loads(args.fixture.read_bytes())
|
|
result = {key: replay(value) for key, value in fixture.items()}
|
|
args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|