Add PTZ17 optics replay and bounded focus recovery

feature/ptz17-focus-aware-zoom
Ярослав Карташов 1 week ago
parent 05dcdcd06a
commit 25c94c1e8d

@ -4,7 +4,9 @@
На широком угле кандидат проверяет, может ли уже разрешённый первый обычный импульс native 10 начаться с длительностью до 340 мс и жёстким пределом 400 мс. Для этого нужны текущий кадр OSTrack, свежее подтверждение YOLO, свежая оптика, допустимая скорость в кадре и полная штатная проекция рамки. Повторное разрешение допускает только исходный запрос того же владельца. При запрете базового контроллера запрос остаётся нулевым. Функции модели, тревог и транспорт STOP сохранены. На широком угле кандидат проверяет, может ли уже разрешённый первый обычный импульс native 10 начаться с длительностью до 340 мс и жёстким пределом 400 мс. Для этого нужны текущий кадр OSTrack, свежее подтверждение YOLO, свежая оптика, допустимая скорость в кадре и полная штатная проекция рамки. Повторное разрешение допускает только исходный запрос того же владельца. При запрете базового контроллера запрос остаётся нулевым. Функции модели, тревог и транспорт STOP сохранены.
При HFOV до 18° на PTZ17 оценка резкости проверяет область самой цели. Для решения о паузе подходят рамки с короткой стороной от 20 px. Штатный порог запроса автофокуса остаётся отдельным. Низкая резкость или неоцениваемый кадр удерживают текущее увеличение. Возобновление требует свежего резкого кадра. Пауза относится к новым положительным импульсам, поэтому Pan/Tilt и защитное расширение FOV сохраняют штатные пути. При HFOV до 18° на PTZ17 оценка резкости проверяет область самой цели. Для решения о паузе подходят рамки с короткой стороной от 20 px. Штатный порог размера для автофокуса остаётся 24 px. Низкая резкость или неоцениваемый кадр удерживают текущее увеличение. Для выхода нужны два свежих резких кадра того же владельца с интервалом не более 250 мс. Один резкий отсчёт, дубликат и большой разрыв паузу не снимают. Пауза относится к новым положительным импульсам, поэтому Pan/Tilt и защитное расширение FOV сохраняют штатные пути.
При непрерывных 600 мс неоцениваемой резкости после остановки линзы, свежем подтверждении цели и устойчивом положении рамки кандидат может поставить один восстановительный запрос в штатную очередь автофокуса на владельца трека. Повторный запрос требует смены владельца и соблюдения штатного cooldown. ACK фокуса сам по себе зум не возобновляет.
Повторная проверка на пролёте 14:28 показала, что расширенная область низкоконтрастна и для размытого, и для различимого самолёта. Теперь при непригодной расширенной области проверяется ядро рамки с более строгим порогом. Для этого кандидата задан восьмикратный множитель относительно исходного порога дисперсии лапласиана. Множитель проверен на этой ограниченной выборке и остаётся параметром калибровки. Повторная проверка на пролёте 14:28 показала, что расширенная область низкоконтрастна и для размытого, и для различимого самолёта. Теперь при непригодной расширенной области проверяется ядро рамки с более строгим порогом. Для этого кандидата задан восьмикратный множитель относительно исходного порога дисперсии лапласиана. Множитель проверен на этой ограниченной выборке и остаётся параметром калибровки.
@ -24,3 +26,15 @@
В первом пролёте два коротких импульса 100 и 220 мс не получили отдельного подтверждения оптики. Во втором исходный обычный импульс снят после PUT на фоне `image_motion`, два пробных импульса по 100 мс также остались без оптического подтверждения. Первое подтверждение получено на обычных запросах №3 и №5 соответственно. Первые записанные безопасные проекции в обоих случаях позже первого движения, поэтому изменение длительности из PR №14 ещё не подтверждает выигрыш на этих пролётах. Защитные остановки сохраняются. В первом пролёте два коротких импульса 100 и 220 мс не получили отдельного подтверждения оптики. Во втором исходный обычный импульс снят после PUT на фоне `image_motion`, два пробных импульса по 100 мс также остались без оптического подтверждения. Первое подтверждение получено на обычных запросах №3 и №5 соответственно. Первые записанные безопасные проекции в обоих случаях позже первого движения, поэтому изменение длительности из PR №14 ещё не подтверждает выигрыш на этих пролётах. Защитные остановки сохраняются.
На кадрах второго пролёта PTS 94 и 114 расширенная область вернула `None`. Энергия в ядре рамки составила 142 и 8994 соответственно. При пороге 280 первый кадр удерживает паузу, второй её снимает. Два различимых кадра из пролёта 14:24 проходят проверку. Сопоставление PTS с UTC на уровне отдельных кадров не выполнено. В окнах обоих пролётов журнал не показывает отправку тревоги по WebSocket. На кадрах второго пролёта PTS 94 и 114 расширенная область вернула `None`. Энергия в ядре рамки составила 142 и 8994 соответственно. При пороге 280 первый кадр удерживает паузу, второй её снимает. Два различимых кадра из пролёта 14:24 проходят проверку. Сопоставление PTS с UTC на уровне отдельных кадров не выполнено. В окнах обоих пролётов журнал не показывает отправку тревоги по WebSocket.
## Воспроизводимый эталон первых 20 секунд
`replay_ptz17_reference.py` читает зафиксированные команды, завершения запросов и выборки свежего HFOV из `reference_fixture.json`. Запуск `python replay_ptz17_reference.py` восстанавливает `reference_replay.json`. В журнале время подтверждения и первое наблюдаемое изменение HFOV могут отличаться из-за округления меток и порядка записи. Время измеримого сужения определяется отдельно от подтверждения конкретного запроса.
| TRACK, UTC+7 | Первый старт → первое подтверждение | Первый подтверждённый запрос | Свежие замеры HFOV за 20 с |
| --- | ---: | --- | ---: |
| 14:12:02 | 4,512 с | №3, 340 мс | 257 |
| 14:24:57 | 8,902 с | №3, 340 мс | 259 |
| 14:28:06 | 12,691 с | №5, 220 мс | 253 |
Во всех трёх эпизодах поле зрения оставалось 59° до первого успешного запроса и затем сузилось до 54,12°. Это указывает на отсутствие измеримого сужения на ранних попытках. Из разреженных AIM нельзя восстановить разрешение более длинного первого импульса в момент решения или пересчитать физический контрфактический результат. Данные пригодны для сравнения по номеру запроса, времени первого оптического подтверждения и дальнейшим отметкам 2×/4×/8×. Для сравнения по времени до первого различимого резкого кадра нужна привязка PTS к UTC и покадровая проверка.

@ -1,6 +1,6 @@
{ {
"base_sha256": "6cf484271ef3659028b0b4d43041addb05102f91d2758ab472d968a52d24e911", "base_sha256": "6cf484271ef3659028b0b4d43041addb05102f91d2758ab472d968a52d24e911",
"candidate_sha256": "da2a970deb041d6dc4897fd58c2efa2943803d46c3af6ddcf92d010a4ca0f589", "candidate_sha256": "26edb69b9d0bd0ae6ad4b9c18ff2f793bcb2a2cf035b38293a3e07d6fc833f8b",
"patch_sha256": "6c6f5ee84f9be3976cf318431cfa505817f2322345215a76ae638873376d14c8", "patch_sha256": "6a563f751871dcadc3c4daf730cc3cfb1ff6fd8edf1f379a2cee01f99302d4de",
"installed": false "installed": false
} }

File diff suppressed because it is too large Load Diff

@ -0,0 +1,390 @@
{
"1412": {
"start_utc": "2026-11-13T07:12:02.328+00:00",
"status_samples": 257,
"first_send_s": 6.041,
"first_start_s": 6.115,
"first_confirmed_request": 3,
"first_optics_s": 10.627,
"startup_to_optics_s": 4.512,
"first_logged_projection_s": 9.869,
"first_request_projection_at_decision": "unknown",
"requests": [
{
"request": 1,
"kind": "normal",
"seq": 5714,
"start_s": 6.115,
"nominal_s": 0.1,
"hard_limit_s": 0.12,
"final": {
"time_s": 6.231,
"status": "delivered_wait_optics",
"accounted_duration_s": 0.191,
"required_duration_s": 0.07,
"optics_at_finalize": false,
"reason": "priority_stop:watchdog"
},
"explicit_confirmation_s": null,
"decisions": [],
"first_status_narrowing": null
},
{
"request": 2,
"kind": "normal",
"seq": 5724,
"start_s": 7.766,
"nominal_s": 0.22,
"hard_limit_s": 0.28,
"final": {
"time_s": 8.086,
"status": "delivered_wait_optics",
"accounted_duration_s": 0.402,
"required_duration_s": 0.154,
"optics_at_finalize": false,
"reason": "priority_stop:watchdog"
},
"explicit_confirmation_s": null,
"decisions": [],
"first_status_narrowing": null
},
{
"request": 3,
"kind": "normal",
"seq": 5736,
"start_s": 10.164,
"nominal_s": 0.34,
"hard_limit_s": 0.4,
"final": {
"time_s": 10.496,
"status": "delivered_wait_optics",
"accounted_duration_s": 0.395,
"required_duration_s": 0.238,
"optics_at_finalize": false,
"reason": "physical_stop"
},
"explicit_confirmation_s": 10.627,
"decisions": [
{
"time_s": 10.481,
"reason": "recenter",
"blockers": "angle"
}
],
"first_status_narrowing": {
"time_s": 10.627,
"hfov_deg": 54.12173440987275
}
},
{
"request": 4,
"kind": "normal",
"seq": 5757,
"start_s": 14.109,
"nominal_s": 0.1,
"hard_limit_s": 0.12,
"final": {
"time_s": 14.182,
"status": "discarded",
"accounted_duration_s": 0.147,
"required_duration_s": 0.07,
"optics_at_finalize": false,
"reason": "priority_stop:cancel_after_put"
},
"explicit_confirmation_s": null,
"decisions": [
{
"time_s": 14.055,
"reason": "recenter",
"blockers": "followup+angle+center_sample"
}
],
"first_status_narrowing": null
},
{
"request": 5,
"kind": "normal",
"seq": 5772,
"start_s": 16.382,
"nominal_s": 0.1,
"hard_limit_s": 0.12,
"final": {
"time_s": 16.419,
"status": "short",
"accounted_duration_s": 0.055,
"required_duration_s": 0.07,
"optics_at_finalize": false,
"reason": "physical_stop"
},
"explicit_confirmation_s": null,
"decisions": [
{
"time_s": 16.399,
"reason": "size_controller",
"blockers": "angle"
}
],
"first_status_narrowing": null
},
{
"request": 6,
"kind": "normal",
"seq": 5778,
"start_s": 17.247,
"nominal_s": 0.34,
"hard_limit_s": 0.4,
"final": {
"time_s": 17.445,
"status": "delivered_wait_optics",
"accounted_duration_s": 0.244,
"required_duration_s": 0.238,
"optics_at_finalize": false,
"reason": "physical_stop"
},
"explicit_confirmation_s": null,
"decisions": [
{
"time_s": 17.401,
"reason": "recenter",
"blockers": "angle"
},
{
"time_s": 17.444,
"reason": "size_controller",
"blockers": "followup+angle+center_history+track_history"
}
],
"first_status_narrowing": null
}
]
},
"1424": {
"start_utc": "2026-11-13T07:24:57.917+00:00",
"status_samples": 259,
"first_send_s": 8.054,
"first_start_s": 8.118,
"first_confirmed_request": 3,
"first_optics_s": 17.02,
"startup_to_optics_s": 8.902,
"first_logged_projection_s": 11.23,
"first_request_projection_at_decision": "unknown",
"requests": [
{
"request": 1,
"kind": "normal",
"seq": 7515,
"start_s": 8.118,
"nominal_s": 0.1,
"hard_limit_s": 0.12,
"final": {
"time_s": 8.245,
"status": "delivered_wait_optics",
"accounted_duration_s": 0.192,
"required_duration_s": 0.07,
"optics_at_finalize": false,
"reason": "priority_stop:watchdog"
},
"explicit_confirmation_s": null,
"decisions": [],
"first_status_narrowing": null
},
{
"request": 2,
"kind": "normal",
"seq": 7536,
"start_s": 12.205,
"nominal_s": 0.22,
"hard_limit_s": 0.28,
"final": {
"time_s": 12.392,
"status": "delivered_wait_optics",
"accounted_duration_s": 0.248,
"required_duration_s": 0.154,
"optics_at_finalize": false,
"reason": "physical_stop"
},
"explicit_confirmation_s": null,
"decisions": [
{
"time_s": 12.379,
"reason": "recenter",
"blockers": "angle+center_sample"
}
],
"first_status_narrowing": null
},
{
"request": 3,
"kind": "normal",
"seq": 7556,
"start_s": 16.563,
"nominal_s": 0.34,
"hard_limit_s": 0.4,
"final": {
"time_s": 17.018,
"status": "delivered_wait_optics",
"accounted_duration_s": 0.47,
"required_duration_s": 0.238,
"optics_at_finalize": false,
"reason": "priority_stop:watchdog"
},
"explicit_confirmation_s": 17.02,
"decisions": [],
"first_status_narrowing": {
"time_s": 17.02,
"hfov_deg": 54.12173440987275
}
},
{
"request": 4,
"kind": "normal",
"seq": 7572,
"start_s": 19.593,
"nominal_s": 0.34,
"hard_limit_s": 0.4,
"final": null,
"explicit_confirmation_s": null,
"decisions": [],
"first_status_narrowing": {
"time_s": 19.901,
"hfov_deg": 46.524147844879025
}
}
]
},
"1428": {
"start_utc": "2026-11-13T07:28:06.389+00:00",
"status_samples": 253,
"first_send_s": 4.227,
"first_start_s": 4.294,
"first_confirmed_request": 5,
"first_optics_s": 16.985,
"startup_to_optics_s": 12.691,
"first_logged_projection_s": 13.713,
"first_request_projection_at_decision": "unknown",
"requests": [
{
"request": 1,
"kind": "normal",
"seq": 8125,
"start_s": 4.294,
"nominal_s": 0.1,
"hard_limit_s": 0.12,
"final": {
"time_s": 4.399,
"status": "discarded",
"accounted_duration_s": 0.172,
"required_duration_s": 0.07,
"optics_at_finalize": false,
"reason": "priority_stop:cancel_after_put"
},
"explicit_confirmation_s": null,
"decisions": [
{
"time_s": 4.235,
"reason": "image_motion",
"blockers": "-"
}
],
"first_status_narrowing": null
},
{
"request": 2,
"kind": "probe",
"seq": 8137,
"start_s": 6.302,
"nominal_s": 0.1,
"hard_limit_s": 0.12,
"final": {
"time_s": 6.448,
"status": "discarded",
"accounted_duration_s": 0.208,
"required_duration_s": 0.07,
"optics_at_finalize": false,
"reason": "priority_stop:watchdog"
},
"explicit_confirmation_s": null,
"decisions": [],
"first_status_narrowing": null
},
{
"request": 3,
"kind": "probe",
"seq": 8157,
"start_s": 10.195,
"nominal_s": 0.1,
"hard_limit_s": 0.12,
"final": {
"time_s": 10.365,
"status": "delivered_wait_optics",
"accounted_duration_s": 0.208,
"required_duration_s": 0.07,
"optics_at_finalize": false,
"reason": "priority_stop:watchdog"
},
"explicit_confirmation_s": null,
"decisions": [
{
"time_s": 10.261,
"reason": "size_controller",
"blockers": "angle"
}
],
"first_status_narrowing": null
},
{
"request": 4,
"kind": "normal",
"seq": 8178,
"start_s": 14.181,
"nominal_s": 0.22,
"hard_limit_s": 0.28,
"final": {
"time_s": 14.273,
"status": "discarded",
"accounted_duration_s": 0.121,
"required_duration_s": 0.154,
"optics_at_finalize": false,
"reason": "priority_stop:cancel_after_put"
},
"explicit_confirmation_s": null,
"decisions": [
{
"time_s": 14.158,
"reason": "recenter",
"blockers": "angle+center_sample"
}
],
"first_status_narrowing": null
},
{
"request": 5,
"kind": "normal",
"seq": 8194,
"start_s": 16.639,
"nominal_s": 0.22,
"hard_limit_s": 0.28,
"final": {
"time_s": 16.942,
"status": "delivered_wait_optics",
"accounted_duration_s": 0.314,
"required_duration_s": 0.154,
"optics_at_finalize": false,
"reason": "priority_stop:watchdog"
},
"explicit_confirmation_s": 16.985,
"decisions": [
{
"time_s": 16.894,
"reason": "size_controller",
"blockers": "angle"
}
],
"first_status_narrowing": {
"time_s": 16.986,
"hfov_deg": 54.12173440987275
}
}
]
}
}

@ -0,0 +1,135 @@
"""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()

@ -18,7 +18,7 @@
cx = (x1 + x2) * 0.5 cx = (x1 + x2) * 0.5
cy = (y1 + y2) * 0.5 cy = (y1 + y2) * 0.5
roi_w = max(16.0, (x2 - x1) * scale) roi_w = max(16.0, (x2 - x1) * scale)
@@ -741,6 +743,106 @@ @@ -741,6 +743,141 @@
return score if math.isfinite(score) else None return score if math.isfinite(score) else None
@ -27,6 +27,9 @@
+ focus_max_hfov_deg: float = 18.0 + focus_max_hfov_deg: float = 18.0
+ focus_min_side_px: int = 20 + focus_min_side_px: int = 20
+ focus_core_only_threshold_scale: float = 8.0 + focus_core_only_threshold_scale: float = 8.0
+ focus_unknown_retry_s: float = 0.60
+ focus_unknown_max_gap_s: float = 0.25
+ focus_recovery_samples: int = 2
+ frame_max_age_s: float = 0.25 + frame_max_age_s: float = 0.25
+ detector_max_age_s: float = 0.65 + detector_max_age_s: float = 0.65
+ first_pulse_s: float = 0.34 + first_pulse_s: float = 0.34
@ -58,28 +61,41 @@
+ +
+ +
+def _ptz17_focus_hold( +def _ptz17_focus_hold(
+ st: dict, *, hfov_deg: float, side_px: int, frame_is_current: bool, + st: dict, *, hfov_deg: float, side_px: int, frame_is_current: bool, captured_at: float,
+) -> str | None: +) -> str | None:
+ """Keep the lens at its current FOV while the settled target is blurry.""" + """Keep the lens at its current FOV while the settled target is blurry."""
+ owner = visual_control.owner(st) + owner = visual_control.owner(st)
+ if owner[2] <= 0.0 or not 0.0 < hfov_deg <= _PTZ17_ZOOM.focus_max_hfov_deg: + if owner[2] <= 0.0 or not 0.0 < hfov_deg <= _PTZ17_ZOOM.focus_max_hfov_deg:
+ st.pop("ptz17_focus_hold", None) + st.pop("ptz17_focus_hold", None)
+ st.pop("ptz17_focus_recovery", None)
+ return None + return None
+ previous = st.get("ptz17_focus_hold") + previous = st.get("ptz17_focus_hold")
+ reason = previous[1] if previous is not None and previous[0] == owner else None + reason = previous[1] if previous is not None and previous[0] == owner else None
+ if not frame_is_current: + if not frame_is_current or not math.isfinite(captured_at):
+ return reason + return reason
+ focus_state = st.get("focus_state") + focus_state = st.get("focus_state")
+ if focus_state == "disabled": + if focus_state == "disabled":
+ reason = None + reason = None
+ elif side_px >= _PTZ17_ZOOM.focus_min_side_px: + elif side_px >= _PTZ17_ZOOM.focus_min_side_px:
+ if focus_state == "sharp": + if focus_state == "sharp" and reason is not None:
+ reason = None + recovery = st.get("ptz17_focus_recovery")
+ votes = 1
+ if recovery is not None and recovery[0] == owner:
+ gap_s = captured_at - recovery[1]
+ if gap_s <= 0.0:
+ return reason
+ if gap_s <= _PTZ17_ZOOM.focus_unknown_max_gap_s:
+ votes += recovery[2]
+ st["ptz17_focus_recovery"] = (owner, captured_at, votes)
+ if votes >= _PTZ17_ZOOM.focus_recovery_samples:
+ reason = None
+ elif focus_state in { + elif focus_state in {
+ "blur_suspected", "blur_fast_suspected", "blur_cooldown", "blur_wait", + "blur_suspected", "blur_fast_suspected", "blur_cooldown", "blur_wait",
+ "unassessable", "requested", "settling", + "unassessable", "requested", "settling",
+ }: + }:
+ reason = str(focus_state) + reason = str(focus_state)
+ if focus_state != "sharp" or side_px < _PTZ17_ZOOM.focus_min_side_px or reason is None:
+ st.pop("ptz17_focus_recovery", None)
+ if reason is not None: + if reason is not None:
+ st["ptz17_focus_hold"] = (owner, reason) + st["ptz17_focus_hold"] = (owner, reason)
+ else: + else:
@ -87,6 +103,25 @@
+ return reason + return reason
+ +
+ +
+def _ptz17_unassessable_retry_ready(st: dict, captured_at: float) -> bool:
+ """Authorize one recovery attempt per track owner after sustained low contrast."""
+ owner = visual_control.owner(st)
+ evidence = st.get("ptz17_focus_unknown")
+ if owner[2] <= 0.0 or not math.isfinite(captured_at):
+ return False
+ if evidence is None or evidence[0] != owner:
+ st["ptz17_focus_unknown"] = (owner, captured_at, captured_at)
+ return False
+ if st.get("ptz17_focus_unknown_attempt") == owner:
+ return False
+ gap_s = captured_at - evidence[2]
+ if gap_s <= 0.0:
+ return False
+ since = captured_at if gap_s > _PTZ17_ZOOM.focus_unknown_max_gap_s else evidence[1]
+ st["ptz17_focus_unknown"] = (owner, since, captured_at)
+ return captured_at - since >= _PTZ17_ZOOM.focus_unknown_retry_s
+
+
+def _ptz17_first_useful_timing( +def _ptz17_first_useful_timing(
+ st: dict, timing: tuple[float, float], *, native: int, normal_onset: bool, + st: dict, timing: tuple[float, float], *, native: int, normal_onset: bool,
+ frame_age_s: float, detector_age_s: float, hfov_deg: float, wide_hfov_deg: float, + frame_age_s: float, detector_age_s: float, hfov_deg: float, wide_hfov_deg: float,
@ -125,7 +160,15 @@
def _clear_focus_low_evidence(st: dict) -> None: def _clear_focus_low_evidence(st: dict) -> None:
st["focus_quality_low_frames"] = 0 st["focus_quality_low_frames"] = 0
st["focus_quality_low_since"] = None st["focus_quality_low_since"] = None
@@ -833,7 +935,11 @@ @@ -761,6 +898,7 @@
center_err: float,
hfov_deg: float,
validation_age: float,
+ allow_unassessable_retry: bool = False,
) -> bool:
"""Measure settled target detail and queue one bounded autofocus request."""
if not bool(getattr(config, "AUTOFOCUS_QUALITY_ENABLE", True)) or not bool(
@@ -833,14 +971,31 @@
_clear_focus_low_evidence(st) _clear_focus_low_evidence(st)
st["focus_last_hfov_deg"] = float(hfov_deg) st["focus_last_hfov_deg"] = float(hfov_deg)
@ -137,8 +180,90 @@
+ ) + )
st["focus_quality_last_eval_at"] = float(now) st["focus_quality_last_eval_at"] = float(now)
st["focus_quality_score"] = score st["focus_quality_score"] = score
+ unknown_retry = False
if score is None: if score is None:
@@ -9537,6 +9643,47 @@ st["focus_state"] = "unassessable"
_clear_focus_low_evidence(st)
- return False
-
+ unknown_retry = (
+ allow_unassessable_retry and cam_idx == _PTZ17_CAM_IDX
+ and 0.0 < hfov_deg <= _PTZ17_ZOOM.focus_max_hfov_deg
+ and 0.0 <= validation_age <= _PTZ17_ZOOM.detector_max_age_s
+ and _ptz17_unassessable_retry_ready(st, now)
+ )
+ if not unknown_retry:
+ return False
+ else:
+ st.pop("ptz17_focus_unknown", None)
+
+ if unknown_retry:
+ return _queue_focus_recovery(cam_idx, st, now, reason="unassessable")
+ assert score is not None
alpha = clipf(float(getattr(config, "AUTOFOCUS_SCORE_EMA_ALPHA", 0.35)), 0.01, 1.0)
previous_ema = st.get("focus_quality_ema")
ema = float(score) if not isinstance(previous_ema, (int, float)) else (
@@ -870,7 +1025,10 @@
if ema >= threshold:
# Keep the independent raw-drop evidence while the deliberately slow
# EMA still describes the previously sharp scene.
- st["focus_state"] = "blur_fast_suspected" if raw_drop else "sharp"
+ ptz17_instant_low = (
+ allow_unassessable_retry and cam_idx == _PTZ17_CAM_IDX and score < threshold
+ )
+ st["focus_state"] = "blur_fast_suspected" if raw_drop or ptz17_instant_low else "sharp"
st["focus_quality_low_frames"] = 0
st["focus_quality_low_since"] = None
else:
@@ -916,12 +1074,19 @@
if not confirmed_low:
return False
+ return _queue_focus_recovery(cam_idx, st, now, reason="quality", score=score, ema=ema)
+
+
+def _queue_focus_recovery(
+ cam_idx: int, st: dict, now: float, *, reason: str,
+ score: float | None = None, ema: float | None = None,
+) -> bool:
request_cd = max(0.5, float(getattr(config, "AUTOFOCUS_REQUEST_COOLDOWN_SEC", 15.0)))
last_request = float(st.get("focus_last_request_at", 0.0) or 0.0)
if last_request > 0.0 and (float(now) - last_request) < request_cd:
st["focus_state"] = "blur_cooldown"
return False
- if not bool(call_autofocus(cam_idx, reason="quality")):
+ if not bool(call_autofocus(cam_idx, reason=reason)):
if str(st.get("focus_state", "")) not in {
"unsupported",
"unsupported_backoff",
@@ -931,6 +1096,8 @@
st["focus_state"] = "blur_wait"
return False
+ if reason == "unassessable":
+ st["ptz17_focus_unknown_attempt"] = visual_control.owner(st)
st["focus_state"] = "requested"
st["focus_last_request_at"] = float(now)
st["focus_settle_until"] = float(now) + max(
@@ -938,12 +1105,11 @@
float(getattr(config, "AUTOFOCUS_SETTLE_HOLD_SEC", 0.80)),
)
_clear_focus_low_evidence(st)
- logger.warning(
- "[FOCUS/QUALITY] cam=%s autofocus requested score=%.1f ema=%.1f",
- cam_idx,
- float(score),
- float(ema),
- )
+ if score is not None and ema is not None:
+ logger.warning("[FOCUS/QUALITY] cam=%s autofocus requested score=%.1f ema=%.1f",
+ cam_idx, score, ema)
+ else:
+ logger.warning("[FOCUS/QUALITY] cam=%s autofocus requested reason=%s", cam_idx, reason)
return True
@@ -9537,6 +9703,48 @@
max(0.0, float(getattr(config, min_key, 0.10))), max(0.0, float(getattr(config, min_key, 0.10))),
) )
zoom_cmd = min(max_effective, max(float(zoom_cmd), min_effective)) zoom_cmd = min(max_effective, max(float(zoom_cmd), min_effective))
@ -163,6 +288,7 @@
+ tilt_cmd=float(tilt_speed) + float(tilt_rate_ff), + tilt_cmd=float(tilt_speed) + float(tilt_rate_ff),
+ zoom_cmd=0.0, center_err=float(center_err), hfov_deg=float(hfov_deg), + zoom_cmd=0.0, center_err=float(center_err), hfov_deg=float(hfov_deg),
+ validation_age=float(visual_control_validation_age), + validation_age=float(visual_control_validation_age),
+ allow_unassessable_retry=True,
+ ) + )
+ ptz17_focus_checked = True + ptz17_focus_checked = True
+ # A small but measurable crop can veto another zoom step. + # A small but measurable crop can veto another zoom step.
@ -178,7 +304,7 @@
+ ) + )
+ ptz17_focus_reason = _ptz17_focus_hold( + ptz17_focus_reason = _ptz17_focus_hold(
+ st, hfov_deg=float(hfov_deg), side_px=min(x2 - x1, y2 - y1), + st, hfov_deg=float(hfov_deg), side_px=min(x2 - x1, y2 - y1),
+ frame_is_current=ptz17_focus_checked, + frame_is_current=ptz17_focus_checked, captured_at=float(now),
+ ) + )
+ if ptz17_focus_reason is not None and zoom_cmd > 0.0: + if ptz17_focus_reason is not None and zoom_cmd > 0.0:
+ zoom_cmd = 0.0 + zoom_cmd = 0.0
@ -186,7 +312,7 @@
if probe_start_candidate and identify_start_candidate: if probe_start_candidate and identify_start_candidate:
pulse_kind = "probe_identify" pulse_kind = "probe_identify"
elif probe_start_candidate: elif probe_start_candidate:
@@ -9645,6 +9792,27 @@ @@ -9645,6 +9853,27 @@
zoom_cmd = 0.0 zoom_cmd = 0.0
st["zoom_useful_pulse_reason"] = "wait_response_framing" st["zoom_useful_pulse_reason"] = "wait_response_framing"
zoom_zero_reason = "response_framing" zoom_zero_reason = "response_framing"
@ -214,7 +340,7 @@
gate_stop = [] if decision_request else None gate_stop = [] if decision_request else None
continuation_trace = [] if decision_request else None continuation_trace = [] if decision_request else None
zoom_cmd = _gate_zoom_in_pulse( zoom_cmd = _gate_zoom_in_pulse(
@@ -9667,6 +9835,9 @@ @@ -9667,6 +9896,9 @@
) )
if predictive_start and zoom_cmd > 0.0 and st["zoom_step_request_id"] > request_id_before_gate: if predictive_start and zoom_cmd > 0.0 and st["zoom_step_request_id"] > request_id_before_gate:
st["predictive_zoom_request"] = st["zoom_step_pending_id"] st["predictive_zoom_request"] = st["zoom_step_pending_id"]
@ -224,7 +350,7 @@
if gate_stop: if gate_stop:
zoom_zero_reason = gate_stop[-1] zoom_zero_reason = gate_stop[-1]
decision_generation = st.get("ptz_generation") decision_generation = st.get("ptz_generation")
@@ -9693,23 +9864,24 @@ @@ -9693,23 +9925,24 @@
elif zoom_cmd < 0.0 and float(size_est) <= max(0.05, zoomed_size_thr * 0.75): elif zoom_cmd < 0.0 and float(size_est) <= max(0.05, zoomed_size_thr * 0.75):
st["was_zoomed_in"] = False st["was_zoomed_in"] = False
@ -266,7 +392,7 @@
st["fallback_done"] = False st["fallback_done"] = False
@@ -10222,6 +10394,8 @@ @@ -10222,6 +10455,8 @@
if getattr(config, "PREDICTIVE_ZOOM_TELEMETRY_DIR", "logs/ptz_zoom"): if getattr(config, "PREDICTIVE_ZOOM_TELEMETRY_DIR", "logs/ptz_zoom"):
blocked = {} blocked = {}
if zoom_cmd <= 0.0 and raw_zoom_needed: if zoom_cmd <= 0.0 and raw_zoom_needed:

@ -0,0 +1,30 @@
from pathlib import Path
import json
import pytest
from replay_ptz17_reference import LensSample, first_hfov_change, replay
@pytest.mark.parametrize("key,start,request_id,confirmation,delay", [
("1412", 6.115, 3, 10.627, 4.512),
("1424", 8.118, 3, 17.020, 8.902),
("1428", 4.294, 5, 16.985, 12.691),
])
def test_replays_observed_first_optics(
key: str, start: float, request_id: int, confirmation: float, delay: float,
) -> None:
fixture = json.loads(Path(__file__).with_name("reference_fixture.json").read_bytes())
result = replay(fixture[key])
assert result["first_start_s"] == start
assert result["first_confirmed_request"] == request_id
assert result["first_optics_s"] == confirmation and result["startup_to_optics_s"] == delay
assert all(row["first_status_narrowing"] is None for row in result["requests"][:request_id - 1])
assert result["requests"][request_id - 1]["first_status_narrowing"]["hfov_deg"] == pytest.approx(54.122, abs=.001)
def test_measurement_does_not_cross_request_boundary() -> None:
assert first_hfov_change(
LensSample(1., 59.), [LensSample(1.1, float("nan")), LensSample(1.2, 58.9), LensSample(1.3, 54.)],
from_s=1.1, until_s=1.3,
) is None
Loading…
Cancel
Save