PTZ — сохранить импульс при той же скорости камеры #5

Open
YaroslavKartashov wants to merge 1 commits from feature/ptz-native-floor-continuation into feature/ptz-zoom-zero-decision

1
.gitattributes vendored

@ -1 +1,2 @@
integration/ptz_zoom_zero_decision/server.patch text eol=lf -whitespace integration/ptz_zoom_zero_decision/server.patch text eol=lf -whitespace
integration/ptz_native_floor_continuation/server.patch text eol=lf -whitespace

@ -0,0 +1,9 @@
# Продолжение импульса при той же скорости камеры
У уже начавшегося импульса TRACK дробная команда на следующем кадре может стать меньше исходной, сохраняя ту же целую скорость камеры. Сравнение дробей прерывает такой импульс. Патч разрешает продолжение только после повторной проверки кадра, владельца, исходного запроса и таймера. Камера получает ту же скорость до прежнего срока. При снижении целой скорости, запрете или смене владельца действует прежняя остановка.
В журналах PTZ19 и PTZ21 ветка `pending_native_floor` сработала после 91 и 95 мс при native 10 и минимуме доставки 238 мс. При сохранённых настройках альтернативные условия дают другие ветки. Дробные значения команд в этих записях отсутствуют. Офлайн-повтор использует синтетические 0,106 → 0,103 при зарегистрированных скоростях и длительностях.
Прошли по 16 тестов на исходном коде и кандидате. Офлайн-повтор проверяет неизменность номинального и жёсткого сроков, а также остановку при снижении до native 9, отзыве разрешения, смене запроса и других запретах. Прямой и обратный патчи проверены побайтно. Патч рассчитан на серверный код PR №4 с хешами из `pins.json`.
Для проверки используйте команду из соседнего пакета `ptz_zoom_zero_decision` и добавьте после `RESULT_JSON` путь к телеметрии PR №4 и режим `baseline` или `fixed`. Исходный снимок телеметрии остаётся в локальном рабочем контуре.

@ -0,0 +1,12 @@
{
"requires": "PTZ zoom decision PR #4",
"files": {
"ptz_tracker_modular/postprocess.py": {
"before": "8eb5f6beb79141ef1f1ce9dbad3577006821202557a87c7195e770bbba7b4ba3",
"after": "376f705fb3be06ab04afc1ebb718cb71a2c27a67987023b099f5d921148b64ad"
}
},
"unchanged": {
"ptz_tracker_modular/ptz_io.py": "13d31539193b1a773a5d1db2187cc2a0c8db67d0aacaad89082face64df07499"
}
}

@ -0,0 +1,37 @@
--- a/ptz_tracker_modular/postprocess.py
+++ b/ptz_tracker_modular/postprocess.py
@@ -4619,10 +4619,33 @@
if useful_cmd > 0.0:
# A useful-pulse caller revalidates its entire framing envelope on
# every frame. Never turn one accepted pulse into 10 -> 5 -> 1.
+ below_useful = float(zoom_cmd) < useful_cmd - 1e-9
+ same_native = False
+ if below_useful and (
+ pulse_kind == st.get("zoom_step_pending_kind") == "normal"
+ and pulse_timing is not None
+ and optics_observed_now is not None
+ and max(float(now), float(optics_observed_now)) < pulse_until
+ and not st.get("zoom_stop_obligation_active", False)
+ and st.get("zoom_step_stop_started", False)
+ and st.get("zoom_step_stop_timer") is not None
+ and st.get("zoom_step_stop_source") == "track"
+ and st.get("zoom_step_stop_direction") == 1
+ and st.get("zoom_step_stop_generation") == st.get("ptz_generation")
+ ):
+ # A newly authorized fraction in the same native bucket
+ # sends the same lens speed for the original owned pulse.
+ native = _zoom_speed_to_int(useful_cmd)
+ same_native = (
+ 10 <= native <= 12
+ and _zoom_speed_to_int(zoom_cmd) == native
+ and _zoom_speed_to_int(pulse_floor) == native
+ and _zoom_native_pending_matches(st, native)
+ )
if (
not math.isfinite(float(pulse_floor))
or float(pulse_floor) <= 0.0
- or float(zoom_cmd) < useful_cmd - 1e-9
+ or (below_useful and not same_native)
or float(getattr(config, "ZOOM_STEP_MAX_IN_CMD", 0.12)) < useful_cmd
):
_finish_zoom_step(st, now, stable_key=stable_key)

@ -0,0 +1,11 @@
{
"baseline_tests": 16,
"candidate_tests": 16,
"matched_real_stop_windows": 2,
"fractional_frame_inputs": "synthetic",
"original_nominal_and_hard_deadlines_preserved": true,
"matched_earlier_worker_cases": 19,
"unchanged_controller_frames": 23,
"exact_patch_round_trip": true,
"real_device_or_model_access": false
}

@ -169,6 +169,7 @@ def main():
assert all(sha(path)==expected for path,expected in PINS.items()) assert all(sha(path)==expected for path,expected in PINS.items())
before=load('prior_replay_fixture',PRIOR) before=load('prior_replay_fixture',PRIOR)
from test_frame_decision import build_cases from test_frame_decision import build_cases
from test_native_floor import build_floor_cases
logging.getLogger('PTZTracker').setLevel(logging.ERROR) logging.getLogger('PTZTracker').setLevel(logging.ERROR)
with ExitStack() as stack: with ExitStack() as stack:
for owner,name in ((socket.socket,'connect'),(socket.socket,'connect_ex'), for owner,name in ((socket.socket,'connect'),(socket.socket,'connect_ex'),
@ -204,6 +205,9 @@ def main():
candidate = "zoom_decision" in __import__("inspect").signature(ptz_io.move_ptz).parameters candidate = "zoom_decision" in __import__("inspect").signature(ptz_io.move_ptz).parameters
if candidate: if candidate:
suite.addTests(build_cases(before.Replay, pp, ptz_io)) suite.addTests(build_cases(before.Replay, pp, ptz_io))
if len(sys.argv) > 10:
suite.addTests(build_floor_cases(StopBoundary, before.Replay, pp, ptz_io, config,
Path(sys.argv[10]), sys.argv[11] == "fixed"))
result=unittest.TextTestRunner(verbosity=2).run(suite) result=unittest.TextTestRunner(verbosity=2).run(suite)
result_file=Path(sys.argv[9]) result_file=Path(sys.argv[9])
result_file.write_text(json.dumps(dict(passed=result.wasSuccessful(),tests=result.testsRun, result_file.write_text(json.dumps(dict(passed=result.wasSuccessful(),tests=result.testsRun,

@ -0,0 +1,150 @@
"""Replay the observed timing with synthetic intra-native demands."""
import json
from unittest.mock import patch
def build_floor_cases(boundary, controller_replay, pp, ptz_io, config, report_path, fixed):
report = json.loads(report_path.read_bytes())
observed = [
(int(camera), decision)
for camera, episodes in report["episodes"].items()
for episode in episodes
for decision in episode["matched_decisions"]
if decision["reason"] == "pending_native_floor" and decision["result"] == "short"
]
class NativeFloor(boundary):
def seed(self, camera):
f = self.fixture(camera, "normal", 10, .34)
# The observed logs record native 10. This synthetic fraction has
# the same wire representation but a larger controller value.
f.st["zoom_step_pending_useful_cmd"] = .106
return f
def gate(self, f, command=.103, *, can=True, floor=None, timing=(.34, .40),
kind="normal", observed_now=None):
trace = []
value = pp._gate_zoom_in_pulse(
f.st, f.wall, command, can, pulse_kind=kind,
pulse_floor=command if floor is None else floor,
pulse_timing=timing,
optics_observed_now=f.wall if observed_now is None else observed_now,
stop_trace=trace,
)
return value, trace
def test_observed_native10_windows(self):
self.assertEqual(sorted(camera for camera, _ in observed), [19, 21])
for camera, row in observed:
with self.subTest(camera=camera, frame=row["frame"]):
self.assertEqual(row["native"], "10")
self.assertEqual(row["minimum"], "0.238s")
f = self.seed({19: 8, 21: 10}[camera])
timer = f.st["zoom_step_stop_timer"]
request = f.st["zoom_step_physical_request_id"]
deadline = f.st["zoom_step_until"]
hard = f.st["zoom_step_stop_started_mono"] + timer.delay
origin = f.st["zoom_step_put_started_mono"]
f._advance(float(row["duration"].removesuffix("s")))
shaped = f._shape(.103)
self.assertEqual(shaped, .103)
self.assertEqual(ptz_io._zoom_speed_to_int(shaped), 10)
self.assertEqual(ptz_io._zoom_speed_to_int(.106), 10)
with patch.object(config, "ZOOM_STEP_PULSE_SEC", .10):
self.assertEqual(pp._select_zoom_response_timing(
f.st, useful=False, hfov_deg=59., wide_hfov_deg=59.,
center_err=.02, margin=.45, image_rate=.01, requested_native=10
), (.10, .12))
timing = pp._select_zoom_response_timing(
f.st, useful=True, hfov_deg=59., wide_hfov_deg=59.,
center_err=.02, margin=.45, image_rate=.01, requested_native=10
)
self.assertEqual(timing, (.34, .40))
command, trace = self.gate(f, shaped, timing=timing)
self.assertEqual((command, trace), (.106, []) if fixed else (0., ["pending_native_floor"]))
pan, tilt, _ = row["requested"]
f._enqueue(command, pan=pan / 100, tilt=tilt / 100)
f._flush()
if not fixed:
self.assertEqual(f._zooms()[-1], 0)
self.assertEqual(f.st["zoom_step_last_delivery_result"], "short")
self.assertAlmostEqual(f.st["zoom_step_last_delivered_sec"],
float(row["duration"].removesuffix("s")))
continue
self.assertEqual(f._zooms()[-1], 10)
self.assertEqual(f.st["zoom_step_physical_request_id"], request)
self.assertEqual(f.st["zoom_step_until"], deadline)
self.assertEqual(f.st["zoom_step_put_started_mono"], origin)
active_timer = f.st["zoom_step_stop_timer"]
self.assertAlmostEqual(f.st["zoom_step_stop_started_mono"] + active_timer.delay, hard)
self.assertAlmostEqual(hard - origin, .40)
f._advance(hard - f.mono)
active_timer.fire()
self.assertEqual(f._zooms()[-1], 0)
self.assertEqual(f.st["zoom_step_physical_request_id"], 0)
self.assertNotEqual(f.st["zoom_step_last_delivery_result"], "short")
def test_stop_vetoes_keep_zero(self):
for name, state_change, gate_args, expected in (
("below_native10", {}, {"command": .0999999999}, "pending_native_floor"),
("floor_missing", {}, {"floor": 0.}, "pending_native_floor"),
("floor_invalid", {}, {"floor": float("nan")}, "pending_native_floor"),
("shorter_timing", {}, {"timing": (.10, .12)}, "pending_timing"),
("no_timing", {}, {"timing": None}, "pending_native_floor"),
("permission", {}, {"can": False}, "permission"),
("cancel", {"zoom_step_cancel_requested": True}, {}, "cancel_requested"),
("discard", {"zoom_step_discard_on_finalize": True}, {}, "pending_native_floor"),
("no_effect", {"zoom_no_effect_blocked": True}, {}, "no_effect_limit"),
("new_owner", {"ptz_generation": 5}, {}, "pending_native_floor"),
("new_track", {"track_started_at": 91.}, {}, "pending_native_floor"),
("new_request", {"zoom_step_physical_request_id": 7}, {}, "pending_native_floor"),
("no_delivery", {"zoom_step_physical_started_at": 0.}, {}, "pending_native_floor"),
("protective_stop", {"zoom_stop_obligation_active": True}, {}, "pending_native_floor"),
("watchdog_missing", {"zoom_step_stop_timer": None}, {}, "pending_native_floor"),
("watchdog_other_source", {"zoom_step_stop_source": "acquire"}, {}, "pending_native_floor"),
("probe", {"zoom_step_pending_kind": "probe"}, {"kind": "probe"}, "pending_native_floor"),
("reached_nominal_end", {}, {"observed_now": 101.}, "pending_native_floor"),
("real_zero", {}, {"command": 0.}, None),
):
with self.subTest(name=name):
f = self.seed(8)
f._advance(.05)
f.st.update(state_change)
value, trace = self.gate(f, **gate_args)
self.assertEqual(value, 0.)
self.assertEqual(trace, [expected] if expected else [])
f = self.seed(8)
f._advance(.05)
with patch.object(config, "ZOOM_STEP_MAX_IN_CMD", .104):
self.assertEqual(self.gate(f), (0., ["pending_native_floor"]))
class FrameFloor(controller_replay):
def test_track_frame_uses_native_continuation(self):
self.stack.enter_context(patch.object(config, "ZOOM_PROBE_ENABLE", False))
self.stack.enter_context(patch.object(config, "ZOOM_IDENTIFY_ENABLE", False))
shape = pp._shape_useful_zoom_pulse
def fraction(command, **kwargs):
demand = .103 if self.st.get("zoom_step_physical_request_id") else .106
return shape(demand if command > 0. else command, **kwargs)
with patch.object(pp, "_shape_useful_zoom_pulse", side_effect=fraction):
for _ in range(24):
row = self.tick(.1)
if any(axes[2] > 0 for axes in row["sent"]):
break
self.assertEqual(self.st["zoom_step_pending_useful_cmd"], .106)
deadline = self.st["zoom_step_until"]
with patch.object(pp, "_gate_zoom_in_pulse", wraps=pp._gate_zoom_in_pulse) as gate:
row = self.tick(.06)
self.assertEqual(gate.call_args.args[2], .103)
if fixed:
self.assertEqual(self.st["zoom_step_until"], deadline)
self.assertEqual(self.fixture._zooms()[-1], 10)
else:
self.assertEqual(row["sent"][-1], (0, 0, 0))
self.assertEqual(self.st["zoom_step_last_delivery_result"], "short")
return [
NativeFloor("test_observed_native10_windows"),
NativeFloor("test_stop_vetoes_keep_zero"),
FrameFloor("test_track_frame_uses_native_continuation"),
]
Loading…
Cancel
Save