Compare commits
No commits in common. 'feature/ptz-pr7-zoom-block-reason' and 'main' have entirely different histories.
feature/pt
...
main
@ -1,6 +0,0 @@
|
|||||||
integration/ptz_zoom_zero_decision/server.patch text eol=lf -whitespace
|
|
||||||
integration/ptz_native_floor_continuation/server.patch text eol=lf -whitespace
|
|
||||||
integration/ptz_same_native_diagnostics/server.patch text eol=lf -whitespace
|
|
||||||
integration/ptz_zoom_threshold_diagnostics/server.patch text eol=lf -whitespace
|
|
||||||
integration/ptz_pr7_zoom_block_reason/*.patch text eol=lf -whitespace
|
|
||||||
integration/ptz_pr7_zoom_block_reason/*.py text eol=lf
|
|
||||||
@ -1,12 +0,0 @@
|
|||||||
{
|
|
||||||
"requires": "PTZ zoom decision PR #4",
|
|
||||||
"files": {
|
|
||||||
"ptz_tracker_modular/postprocess.py": {
|
|
||||||
"before": "8eb5f6beb79141ef1f1ce9dbad3577006821202557a87c7195e770bbba7b4ba3",
|
|
||||||
"after": "376f705fb3be06ab04afc1ebb718cb71a2c27a67987023b099f5d921148b64ad"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"unchanged": {
|
|
||||||
"ptz_tracker_modular/ptz_io.py": "13d31539193b1a773a5d1db2187cc2a0c8db67d0aacaad89082face64df07499"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,37 +0,0 @@
|
|||||||
--- 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)
|
|
||||||
@ -1,11 +0,0 @@
|
|||||||
{
|
|
||||||
"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
|
|
||||||
}
|
|
||||||
@ -1,71 +0,0 @@
|
|||||||
--- a/postprocess.py
|
|
||||||
+++ b/postprocess.py
|
|
||||||
@@ -6640,6 +6640,28 @@
|
|
||||||
detector_conf=max(alarm_conf, identity_conf),
|
|
||||||
alarm_eligible=alarm_eligible, cam_idx=cam_idx)
|
|
||||||
alarms.ingest_detection(cam_idx, alarm_eligible)
|
|
||||||
+
|
|
||||||
+
|
|
||||||
+def _log_zoom_block_tick(st, cam, source_seq, zoom, reason, blockers):
|
|
||||||
+ """Count TRACK decisions without taking part in actuator authorization."""
|
|
||||||
+ owner = (st.get("ptz_generation"), st.get("track_started_at"))
|
|
||||||
+ record = st.get("zoom_block_diag")
|
|
||||||
+ if record is None or record["owner"] != owner:
|
|
||||||
+ record = {"owner": owner, "first_positive": False, "total": {}, "before_first": {}}
|
|
||||||
+ st["zoom_block_diag"] = record
|
|
||||||
+ if zoom > 0.0:
|
|
||||||
+ record["first_positive"] = True
|
|
||||||
+ return
|
|
||||||
+ before_first = not record["first_positive"]
|
|
||||||
+ for key in ("total", "before_first") if before_first else ("total",):
|
|
||||||
+ counts = record[key]
|
|
||||||
+ counts[reason] = counts.get(reason, 0) + 1
|
|
||||||
+ logger.info(
|
|
||||||
+ "[ZOOM BLOCK] cam=%s gen=%s track=%s frame=%s zoom_block_reason=%s "
|
|
||||||
+ "before_first_positive_decision=%s blockers=%s counts=%s",
|
|
||||||
+ cam, owner[0], owner[1], source_seq, reason, before_first,
|
|
||||||
+ "+".join(blockers) or "-", json.dumps(record["total"], separators=(",", ":")),
|
|
||||||
+ )
|
|
||||||
|
|
||||||
|
|
||||||
@visual_control.serialized_control
|
|
||||||
@@ -9844,6 +9866,39 @@
|
|
||||||
("brake", final_guard_active),
|
|
||||||
) if blocked)
|
|
||||||
zoom_decision = (source_seq, decision_request, zoom_zero_reason, "+".join(blockers) or "-")
|
|
||||||
+ if (bool(getattr(config, "ZOOM_BLOCK_DIAG_ENABLE", False))
|
|
||||||
+ and cam_idx in getattr(config, "ZOOM_BLOCK_DIAG_CAM_IDS", (8, 10))):
|
|
||||||
+ if zoom_cmd > 0.0:
|
|
||||||
+ _log_zoom_block_tick(st, cam_idx, source_seq, zoom_cmd, "", ())
|
|
||||||
+ else:
|
|
||||||
+ diagnostic_flags = tuple(name for name, active in (
|
|
||||||
+ ("gimbal_brake", final_guard_active),
|
|
||||||
+ ("edge_margin_low", near_edge or edge_recovery_active),
|
|
||||||
+ ("stale_visual", visual_control_stale),
|
|
||||||
+ ("visual_coast", visual_control_coast),
|
|
||||||
+ ("geometry_rearm", not zoom_rearm_ready),
|
|
||||||
+ ("size_controller", not raw_zoom_needed or normal_size_hold),
|
|
||||||
+ ("low_tracker_score", current_track_source == "visual"
|
|
||||||
+ and float(st.get("visual_tracker_score", 0.0) or 0.0)
|
|
||||||
+ < float(getattr(config, "VISUAL_TRACKER_ZOOM_SCORE", 0.42))),
|
|
||||||
+ ("waiting_yolo", current_track_source == "visual" and not zoom_quality_ok
|
|
||||||
+ and visual_zoom_validation_age
|
|
||||||
+ > float(getattr(config, "VISUAL_TRACKER_ZOOM_MAX_UNVALIDATED_SEC", 1.0))),
|
|
||||||
+ ("quality_or_validation", not zoom_quality_ok),
|
|
||||||
+ ("fov_cooldown", not followup_ready),
|
|
||||||
+ ("framing", not zoom_safe),
|
|
||||||
+ ("angular_limit", not zoom_angular_safe),
|
|
||||||
+ ("not_centered", not center_locked_for_zoom),
|
|
||||||
+ ("track_history", not track_stable),
|
|
||||||
+ ("focus_settle", now < float(st.get("focus_settle_until", 0.0) or 0.0)),
|
|
||||||
+ ) if active)
|
|
||||||
+ # size_controller is initialized before any gate is evaluated.
|
|
||||||
+ # Prefer a specific stop stage when one was actually recorded.
|
|
||||||
+ diagnostic_reason = zoom_zero_reason
|
|
||||||
+ if diagnostic_reason in ("size_controller", "permission") and diagnostic_flags:
|
|
||||||
+ diagnostic_reason = diagnostic_flags[0]
|
|
||||||
+ _log_zoom_block_tick(st, cam_idx, source_seq, zoom_cmd,
|
|
||||||
+ diagnostic_reason, diagnostic_flags)
|
|
||||||
dispatch_kwargs = {"force": force_track_ptz}
|
|
||||||
if zoom_decision is not None:
|
|
||||||
dispatch_kwargs["zoom_decision"] = zoom_decision
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
{
|
|
||||||
"before": "776b5b337e5f898e69770fec517c4459560f4cc6adeb951af40ac8f0b2178534",
|
|
||||||
"after": "a9315ef80ca1cc6064088acfba0e854ed4617f3594753663050b13f82dd3c8fa"
|
|
||||||
}
|
|
||||||
@ -1,98 +0,0 @@
|
|||||||
"""Prepare an opt-in observation-only patch for the pinned PR7 controller."""
|
|
||||||
from hashlib import sha256
|
|
||||||
from pathlib import Path
|
|
||||||
import difflib
|
|
||||||
import json
|
|
||||||
import sys
|
|
||||||
|
|
||||||
OUT = Path(__file__).resolve().parent
|
|
||||||
SOURCE = OUT.parent / "ptz_zoom_threshold_maintenance_20261111/postprocess.py"
|
|
||||||
BASE_SHA = "776b5b337e5f898e69770fec517c4459560f4cc6adeb951af40ac8f0b2178534"
|
|
||||||
|
|
||||||
HELPER = '''def _log_zoom_block_tick(st, cam, source_seq, zoom, reason, blockers):
|
|
||||||
"""Count TRACK decisions without taking part in actuator authorization."""
|
|
||||||
owner = (st.get("ptz_generation"), st.get("track_started_at"))
|
|
||||||
record = st.get("zoom_block_diag")
|
|
||||||
if record is None or record["owner"] != owner:
|
|
||||||
record = {"owner": owner, "first_positive": False, "total": {}, "before_first": {}}
|
|
||||||
st["zoom_block_diag"] = record
|
|
||||||
if zoom > 0.0:
|
|
||||||
record["first_positive"] = True
|
|
||||||
return
|
|
||||||
before_first = not record["first_positive"]
|
|
||||||
for key in ("total", "before_first") if before_first else ("total",):
|
|
||||||
counts = record[key]
|
|
||||||
counts[reason] = counts.get(reason, 0) + 1
|
|
||||||
logger.info(
|
|
||||||
"[ZOOM BLOCK] cam=%s gen=%s track=%s frame=%s zoom_block_reason=%s "
|
|
||||||
"before_first_positive_decision=%s blockers=%s counts=%s",
|
|
||||||
cam, owner[0], owner[1], source_seq, reason, before_first,
|
|
||||||
"+".join(blockers) or "-", json.dumps(record["total"], separators=(",", ":")),
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
'''
|
|
||||||
HOOK = ''' if (bool(getattr(config, "ZOOM_BLOCK_DIAG_ENABLE", False))
|
|
||||||
and cam_idx in getattr(config, "ZOOM_BLOCK_DIAG_CAM_IDS", (8, 10))):
|
|
||||||
if zoom_cmd > 0.0:
|
|
||||||
_log_zoom_block_tick(st, cam_idx, source_seq, zoom_cmd, "", ())
|
|
||||||
else:
|
|
||||||
diagnostic_flags = tuple(name for name, active in (
|
|
||||||
("gimbal_brake", final_guard_active),
|
|
||||||
("edge_margin_low", near_edge or edge_recovery_active),
|
|
||||||
("stale_visual", visual_control_stale),
|
|
||||||
("visual_coast", visual_control_coast),
|
|
||||||
("geometry_rearm", not zoom_rearm_ready),
|
|
||||||
("size_controller", not raw_zoom_needed or normal_size_hold),
|
|
||||||
("low_tracker_score", current_track_source == "visual"
|
|
||||||
and float(st.get("visual_tracker_score", 0.0) or 0.0)
|
|
||||||
< float(getattr(config, "VISUAL_TRACKER_ZOOM_SCORE", 0.42))),
|
|
||||||
("waiting_yolo", current_track_source == "visual" and not zoom_quality_ok
|
|
||||||
and visual_zoom_validation_age
|
|
||||||
> float(getattr(config, "VISUAL_TRACKER_ZOOM_MAX_UNVALIDATED_SEC", 1.0))),
|
|
||||||
("quality_or_validation", not zoom_quality_ok),
|
|
||||||
("fov_cooldown", not followup_ready),
|
|
||||||
("framing", not zoom_safe),
|
|
||||||
("angular_limit", not zoom_angular_safe),
|
|
||||||
("not_centered", not center_locked_for_zoom),
|
|
||||||
("track_history", not track_stable),
|
|
||||||
("focus_settle", now < float(st.get("focus_settle_until", 0.0) or 0.0)),
|
|
||||||
) if active)
|
|
||||||
# size_controller is initialized before any gate is evaluated.
|
|
||||||
# Prefer a specific stop stage when one was actually recorded.
|
|
||||||
diagnostic_reason = zoom_zero_reason
|
|
||||||
if diagnostic_reason in ("size_controller", "permission") and diagnostic_flags:
|
|
||||||
diagnostic_reason = diagnostic_flags[0]
|
|
||||||
_log_zoom_block_tick(st, cam_idx, source_seq, zoom_cmd,
|
|
||||||
diagnostic_reason, diagnostic_flags)
|
|
||||||
'''
|
|
||||||
|
|
||||||
|
|
||||||
def build(path):
|
|
||||||
raw = path.read_bytes()
|
|
||||||
if sha256(raw).hexdigest() != BASE_SHA:
|
|
||||||
raise ValueError("Expected pinned PR7 postprocess.py")
|
|
||||||
old = raw.decode()
|
|
||||||
marker = "@visual_control.serialized_control\ndef postprocess_control("
|
|
||||||
anchor = ' dispatch_kwargs = {"force": force_track_ptz}\n'
|
|
||||||
if old.count(marker) != 1 or old.count(anchor) != 1:
|
|
||||||
raise ValueError("Unexpected integration point")
|
|
||||||
new = old.replace(marker, HELPER+marker).replace(anchor,HOOK+anchor)
|
|
||||||
return old,new
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
source = Path(sys.argv[1]) if len(sys.argv) > 1 else SOURCE
|
|
||||||
old,new = build(source)
|
|
||||||
compile(new,"postprocess.py","exec")
|
|
||||||
patch = "".join(difflib.unified_diff(old.splitlines(True),new.splitlines(True),
|
|
||||||
"a/postprocess.py","b/postprocess.py"))
|
|
||||||
(OUT/"pr7_zoom_block_reason.patch").write_bytes(patch.encode())
|
|
||||||
(OUT/"pr7_zoom_block_reason_pins.json").write_text(
|
|
||||||
json.dumps({"before":BASE_SHA,"after":sha256(new.encode()).hexdigest()},indent=2)+"\n",
|
|
||||||
encoding="utf-8")
|
|
||||||
print("Prepared diagnostic patch and hashes")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__=="__main__":
|
|
||||||
main()
|
|
||||||
@ -1,90 +0,0 @@
|
|||||||
"""Verify the pinned PR7 diagnostic patch, its counts and its observation-only hook."""
|
|
||||||
from hashlib import sha256
|
|
||||||
from pathlib import Path
|
|
||||||
from types import SimpleNamespace
|
|
||||||
from unittest.mock import Mock
|
|
||||||
import ast
|
|
||||||
import json
|
|
||||||
import subprocess
|
|
||||||
import sys
|
|
||||||
import tempfile
|
|
||||||
|
|
||||||
from prepare_pr7_diagnostics import BASE_SHA, OUT, SOURCE
|
|
||||||
|
|
||||||
|
|
||||||
def function(tree, name):
|
|
||||||
return next(x for x in tree.body if isinstance(x, ast.FunctionDef) and x.name == name)
|
|
||||||
|
|
||||||
|
|
||||||
def dump(node):
|
|
||||||
return ast.dump(node, include_attributes=False)
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
pins = json.loads((OUT / "pr7_zoom_block_reason_pins.json").read_bytes())
|
|
||||||
patch = str(OUT / "pr7_zoom_block_reason.patch")
|
|
||||||
with tempfile.TemporaryDirectory(dir=OUT) as directory:
|
|
||||||
source = Path(directory)/"postprocess.py"
|
|
||||||
original = Path(sys.argv[1]) if len(sys.argv) > 1 else SOURCE
|
|
||||||
base = original.read_bytes()
|
|
||||||
assert sha256(base).hexdigest()==BASE_SHA
|
|
||||||
source.write_bytes(base)
|
|
||||||
git = ["git","-c","core.autocrlf=false","apply"]
|
|
||||||
subprocess.run([*git,"--whitespace=error",patch],cwd=directory,check=True)
|
|
||||||
after=source.read_bytes()
|
|
||||||
assert sha256(after).hexdigest()==pins["after"]
|
|
||||||
subprocess.run([*git,"-R",patch],cwd=directory,check=True)
|
|
||||||
assert source.read_bytes()==base
|
|
||||||
|
|
||||||
old, new = ast.parse(base), ast.parse(after)
|
|
||||||
proc = function(new,"postprocess_control")
|
|
||||||
control = function(old,"postprocess_control")
|
|
||||||
anchor = next(node for node in ast.walk(proc) if isinstance(node,ast.If)
|
|
||||||
and "ZOOM_BLOCK_DIAG_ENABLE" in dump(node.test))
|
|
||||||
# Removing the optional hook and its sole helper restores the entire AST.
|
|
||||||
for parent in ast.walk(proc):
|
|
||||||
for field,value in ast.iter_fields(parent):
|
|
||||||
if isinstance(value,list) and anchor in value:
|
|
||||||
value.remove(anchor)
|
|
||||||
new.body.remove(function(new,"_log_zoom_block_tick"))
|
|
||||||
assert dump(proc)==dump(control) and dump(old)==dump(new)
|
|
||||||
|
|
||||||
helper=function(ast.parse(after),"_log_zoom_block_tick")
|
|
||||||
log=Mock()
|
|
||||||
env={"json":json,"logger":log}
|
|
||||||
exec(compile(ast.Module(body=[helper],type_ignores=[]),"<diagnostics>","exec"),env)
|
|
||||||
report=env[helper.name]
|
|
||||||
st={"ptz_generation":4,"track_started_at":100.0}
|
|
||||||
state={
|
|
||||||
"config":SimpleNamespace(ZOOM_BLOCK_DIAG_ENABLE=False), "cam_idx":8, "st":st,
|
|
||||||
"source_seq":1,"zoom_cmd":0.,"final_guard_active":False,"near_edge":False,
|
|
||||||
"edge_recovery_active":False,"visual_control_stale":False,"visual_control_coast":False,
|
|
||||||
"zoom_rearm_ready":True,"raw_zoom_needed":True,"normal_size_hold":False,
|
|
||||||
"current_track_source":"visual","visual_zoom_validation_age":0.2,"zoom_quality_ok":True,
|
|
||||||
"followup_ready":True,"zoom_safe":True,"zoom_angular_safe":True,
|
|
||||||
"center_locked_for_zoom":False,"track_stable":False,"now":101.,
|
|
||||||
"zoom_zero_reason":"size_controller","_log_zoom_block_tick":report,
|
|
||||||
}
|
|
||||||
call=compile(ast.Module(body=[anchor],type_ignores=[]),"<hook>","exec")
|
|
||||||
exec(call,state)
|
|
||||||
assert "zoom_block_diag" not in st
|
|
||||||
state["config"].ZOOM_BLOCK_DIAG_ENABLE=True
|
|
||||||
st["visual_tracker_score"]=.8
|
|
||||||
exec(call,state)
|
|
||||||
assert st["zoom_block_diag"]["before_first"]=={"not_centered":1}
|
|
||||||
state.update(zoom_cmd=.10)
|
|
||||||
exec(call,state)
|
|
||||||
assert st["zoom_block_diag"]["first_positive"]
|
|
||||||
state.update(zoom_cmd=0.,zoom_zero_reason="final_brake",final_guard_active=True)
|
|
||||||
exec(call,state)
|
|
||||||
assert st["zoom_block_diag"]["total"]=={"not_centered":1,"final_brake":1}
|
|
||||||
assert st["zoom_block_diag"]["before_first"]=={"not_centered":1}
|
|
||||||
st.update(ptz_generation=5,track_started_at=103.0)
|
|
||||||
exec(call,state)
|
|
||||||
assert st["zoom_block_diag"]["before_first"]=={"final_brake":1}
|
|
||||||
assert log.info.call_count==3
|
|
||||||
print("Round-trip exact, control AST unchanged outside the hook, toggle/phase/owner/count checks passed.")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__=="__main__":
|
|
||||||
main()
|
|
||||||
@ -1,12 +0,0 @@
|
|||||||
{
|
|
||||||
"requires": "PR #5",
|
|
||||||
"files": {
|
|
||||||
"ptz_tracker_modular/postprocess.py": {
|
|
||||||
"before": "376f705fb3be06ab04afc1ebb718cb71a2c27a67987023b099f5d921148b64ad",
|
|
||||||
"after": "d85439504ebf56fc39ee8a883c44b1bfc6db721df938aedc85d6c6484cb97776"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"unchanged": {
|
|
||||||
"ptz_tracker_modular/ptz_io.py": "13d31539193b1a773a5d1db2187cc2a0c8db67d0aacaad89082face64df07499"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,55 +0,0 @@
|
|||||||
--- a/ptz_tracker_modular/postprocess.py
|
|
||||||
+++ b/ptz_tracker_modular/postprocess.py
|
|
||||||
@@ -4577,6 +4577,7 @@
|
|
||||||
pulse_timing: Tuple[float, float] | None = None,
|
|
||||||
optics_observed_now: float | None = None,
|
|
||||||
stop_trace: list[str] | None = None,
|
|
||||||
+ continuation_trace: list[tuple[int, int, float, float, float, float, float]] | None = None,
|
|
||||||
) -> float:
|
|
||||||
"""Break continuous zoom-in into short feedback-controlled steps."""
|
|
||||||
pulse_until = float(st.get("zoom_step_until", 0.0) or 0.0)
|
|
||||||
@@ -4650,6 +4651,12 @@
|
|
||||||
):
|
|
||||||
_finish_zoom_step(st, now, stable_key=stable_key)
|
|
||||||
return _reject_zoom_step("pending_native_floor", stop_trace)
|
|
||||||
+ if same_native and continuation_trace is not None:
|
|
||||||
+ continuation_trace.append((
|
|
||||||
+ st["ptz_generation"], native, float(zoom_cmd), useful_cmd, pulse_until,
|
|
||||||
+ float(st.get("zoom_step_pending_pulse_sec", 0.0) or 0.0),
|
|
||||||
+ float(st.get("zoom_step_pending_hard_sec", 0.0) or 0.0),
|
|
||||||
+ ))
|
|
||||||
zoom_cmd = useful_cmd
|
|
||||||
physical_started = float(st.get("zoom_step_physical_started_at", 0.0) or 0.0)
|
|
||||||
if physical_started > 0.0:
|
|
||||||
@@ -9232,6 +9239,7 @@
|
|
||||||
st["zoom_useful_pulse_reason"] = "wait_response_framing"
|
|
||||||
zoom_zero_reason = "response_framing"
|
|
||||||
gate_stop = [] if decision_request else None
|
|
||||||
+ continuation_trace = [] if decision_request else None
|
|
||||||
zoom_cmd = _gate_zoom_in_pulse(
|
|
||||||
st,
|
|
||||||
# Keep new-request expiry tied to the frame that authorized
|
|
||||||
@@ -9247,6 +9255,7 @@
|
|
||||||
pulse_timing=response_timing,
|
|
||||||
optics_observed_now=zoom_gate_now,
|
|
||||||
stop_trace=gate_stop,
|
|
||||||
+ continuation_trace=continuation_trace,
|
|
||||||
)
|
|
||||||
if gate_stop:
|
|
||||||
zoom_zero_reason = gate_stop[-1]
|
|
||||||
@@ -9788,6 +9797,15 @@
|
|
||||||
cam_idx, prepared_fps, visual_only, max(0., time.time()-now)*1000.,
|
|
||||||
st.get('control_updates', 0), st.get('control_visual_updates', 0))
|
|
||||||
ingest_detection(alarm_eligible)
|
|
||||||
+ if continuation_trace:
|
|
||||||
+ generation, native, proposed, held, until, pulse_sec, hard_sec = continuation_trace[0]
|
|
||||||
+ logger.info(
|
|
||||||
+ "[ZOOM CONTINUE] cam=%s frame=%s request=%s gen=%s reason=same_native "
|
|
||||||
+ "native=%s proposed=%.12g held=%.12g nominal_until=%.6f "
|
|
||||||
+ "pulse=%.3fs hard=%.3fs dispatch_zoom=%.12g",
|
|
||||||
+ cam_idx, source_seq, decision_request, generation, native, proposed,
|
|
||||||
+ held, until, pulse_sec, hard_sec, zoom_cmd,
|
|
||||||
+ )
|
|
||||||
return
|
|
||||||
|
|
||||||
# =========================
|
|
||||||
@ -1,12 +0,0 @@
|
|||||||
{
|
|
||||||
"requires": "PR #6",
|
|
||||||
"files": {
|
|
||||||
"ptz_tracker_modular/postprocess.py": {
|
|
||||||
"before": "d85439504ebf56fc39ee8a883c44b1bfc6db721df938aedc85d6c6484cb97776",
|
|
||||||
"after": "776b5b337e5f898e69770fec517c4459560f4cc6adeb951af40ac8f0b2178534"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"unchanged": {
|
|
||||||
"ptz_tracker_modular/ptz_io.py": "13d31539193b1a773a5d1db2187cc2a0c8db67d0aacaad89082face64df07499"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,314 +0,0 @@
|
|||||||
--- a/ptz_tracker_modular/postprocess.py
|
|
||||||
+++ b/ptz_tracker_modular/postprocess.py
|
|
||||||
@@ -2,6 +2,7 @@
|
|
||||||
import time
|
|
||||||
import math
|
|
||||||
import logging
|
|
||||||
+import json
|
|
||||||
from typing import Any, List, Tuple
|
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
@@ -454,6 +455,7 @@
|
|
||||||
hfov_deg: float,
|
|
||||||
vfov_deg: float,
|
|
||||||
max_error_deg: float | None = None,
|
|
||||||
+ rejection: dict | None = None,
|
|
||||||
) -> bool:
|
|
||||||
"""Allow a lens pulse only when angular steering reserve is available."""
|
|
||||||
max_error = max(
|
|
||||||
@@ -486,7 +488,7 @@
|
|
||||||
float(tilt_error_deg) * float(tilt_rate_deg_s) > 0.0
|
|
||||||
and abs(float(tilt_rate_deg_s)) > max_outward
|
|
||||||
)
|
|
||||||
- return bool(
|
|
||||||
+ allowed = bool(
|
|
||||||
not pan_escaping
|
|
||||||
and not tilt_escaping
|
|
||||||
and abs(float(pan_error_deg)) <= pan_limit
|
|
||||||
@@ -494,6 +496,23 @@
|
|
||||||
and abs(predicted_pan) <= pan_limit
|
|
||||||
and abs(predicted_tilt) <= tilt_limit
|
|
||||||
)
|
|
||||||
+ if not allowed and rejection is not None:
|
|
||||||
+ rejection.update(
|
|
||||||
+ failed=[name for name, failed in (
|
|
||||||
+ ("pan_outward_rate", pan_escaping),
|
|
||||||
+ ("tilt_outward_rate", tilt_escaping),
|
|
||||||
+ ("pan_error", not abs(float(pan_error_deg)) <= pan_limit),
|
|
||||||
+ ("tilt_error", not abs(float(tilt_error_deg)) <= tilt_limit),
|
|
||||||
+ ("predicted_pan", not abs(predicted_pan) <= pan_limit),
|
|
||||||
+ ("predicted_tilt", not abs(predicted_tilt) <= tilt_limit),
|
|
||||||
+ ) if failed],
|
|
||||||
+ pan_error_deg=pan_error_deg, tilt_error_deg=tilt_error_deg,
|
|
||||||
+ pan_rate_deg_s=pan_rate_deg_s, tilt_rate_deg_s=tilt_rate_deg_s,
|
|
||||||
+ predicted_pan_deg=predicted_pan, predicted_tilt_deg=predicted_tilt,
|
|
||||||
+ pan_limit_deg=pan_limit, tilt_limit_deg=tilt_limit,
|
|
||||||
+ outward_rate_limit_deg_s=max_outward, prediction_s=horizon,
|
|
||||||
+ )
|
|
||||||
+ return allowed
|
|
||||||
|
|
||||||
|
|
||||||
def _zoom_probe_used_for_current_track(st: dict) -> bool:
|
|
||||||
@@ -4877,12 +4896,21 @@
|
|
||||||
return min(cap, max(command, minimum)), "useful"
|
|
||||||
|
|
||||||
|
|
||||||
+def _zoom_response_fallback(
|
|
||||||
+ timing: Tuple[float, float], rejection: dict | None, failed: str, **values,
|
|
||||||
+) -> Tuple[float, float]:
|
|
||||||
+ if rejection is not None and timing == (0.0, 0.0):
|
|
||||||
+ rejection.update(check=failed, **values)
|
|
||||||
+ return timing
|
|
||||||
+
|
|
||||||
+
|
|
||||||
def _select_zoom_response_timing(
|
|
||||||
st: dict, *, useful: bool, hfov_deg: float, wide_hfov_deg: float,
|
|
||||||
center_err: float, margin: float, image_rate: float,
|
|
||||||
approach_margin: float | None = None,
|
|
||||||
fast_approach: bool = False,
|
|
||||||
requested_native: int | None = None,
|
|
||||||
+ rejection: dict | None = None,
|
|
||||||
) -> Tuple[float, float]:
|
|
||||||
"""Explore at wide angle; reuse optically proven timing after narrowing.
|
|
||||||
|
|
||||||
@@ -4897,10 +4925,13 @@
|
|
||||||
"""
|
|
||||||
if requested_native is not None:
|
|
||||||
if st.get("zoom_no_effect_blocked", False):
|
|
||||||
- return 0.0, 0.0
|
|
||||||
+ return _zoom_response_fallback((0.0, 0.0), rejection, "no_effect_limit")
|
|
||||||
native = int(requested_native)
|
|
||||||
if not _zoom_native_response_available(st, native, hfov_deg, wide_hfov_deg):
|
|
||||||
- return 0.0, 0.0
|
|
||||||
+ return _zoom_response_fallback(
|
|
||||||
+ (0.0, 0.0), rejection, "native_profile",
|
|
||||||
+ native=native, hfov_deg=hfov_deg, wide_hfov_deg=wide_hfov_deg,
|
|
||||||
+ )
|
|
||||||
proof_native = int(st.get("zoom_response_native_cmd", 0) or 0)
|
|
||||||
retry_native = int(st.get("zoom_response_retry_native_cmd", 0) or 0)
|
|
||||||
legacy_proof10 = native == 10 and proof_native == 0
|
|
||||||
@@ -4923,9 +4954,9 @@
|
|
||||||
try:
|
|
||||||
learned = float(st.get("zoom_response_effective_sec", 0.0) or 0.0)
|
|
||||||
if not math.isfinite(learned):
|
|
||||||
- return 0.0, 0.0
|
|
||||||
+ return _zoom_response_fallback((0.0, 0.0), rejection, "invalid_learned_duration")
|
|
||||||
except (TypeError, ValueError, OverflowError):
|
|
||||||
- return 0.0, 0.0
|
|
||||||
+ return _zoom_response_fallback((0.0, 0.0), rejection, "invalid_learned_duration")
|
|
||||||
fallback = (0.0, 0.0) if learned > base else (base, hard)
|
|
||||||
try:
|
|
||||||
hfov, wide, error, edge, rate = map(float, (hfov_deg, wide_hfov_deg, center_err, margin, image_rate))
|
|
||||||
@@ -4936,14 +4967,20 @@
|
|
||||||
video_lag = float(getattr(config, "AIM_GIMBAL_FF_VIDEO_LATENCY_SEC", 0.45))
|
|
||||||
stop_timeout = float(getattr(config, "PTZ_LENS_STOP_DIRECT_TIMEOUT_SEC", 0.75))
|
|
||||||
if not all(math.isfinite(v) for v in (base, hard, hfov, wide, error, edge, rate, extra, max_pulse, max_hard, ratio, learned, video_lag, stop_timeout)):
|
|
||||||
- return fallback
|
|
||||||
+ return _zoom_response_fallback(fallback, rejection, "invalid_timing_inputs")
|
|
||||||
max_pulse, max_hard, ratio = min(0.34, max_pulse), min(0.40, max_hard), max(0.85, ratio)
|
|
||||||
video_lag, stop_timeout = max(0.0, video_lag), max(0.0, stop_timeout)
|
|
||||||
approach = approach_margin is not None and math.isfinite(approach_margin) and .16 <= approach_margin <= .5
|
|
||||||
+ center_limit = .12 if approach else .065
|
|
||||||
if not (0.0 < hfov <= wide < 180.0
|
|
||||||
- and 0.0 <= error <= (.12 if approach else .065)
|
|
||||||
+ and 0.0 <= error <= center_limit
|
|
||||||
and edge >= 0.30 and 0.0 <= rate <= 0.04):
|
|
||||||
- return fallback
|
|
||||||
+ return _zoom_response_fallback(
|
|
||||||
+ fallback, rejection, "framing",
|
|
||||||
+ hfov_deg=hfov, wide_hfov_deg=wide, center_error=error, center_limit=center_limit,
|
|
||||||
+ margin=edge, margin_min=.30, image_rate=rate, image_rate_max=.04,
|
|
||||||
+ approach_margin=approach_margin,
|
|
||||||
+ )
|
|
||||||
attempts = min(2, max(0, int(st.get("zoom_no_effect_count", 0) or 0)))
|
|
||||||
if hfov >= wide * ratio:
|
|
||||||
pulse = min(max_pulse, max(base + attempts * max(0.0, extra), learned))
|
|
||||||
@@ -4951,7 +4988,13 @@
|
|
||||||
if not (base < learned <= 0.34 and (
|
|
||||||
approach or (error <= 0.04 and edge >= 0.40 and rate <= 0.02)
|
|
||||||
)):
|
|
||||||
- return fallback
|
|
||||||
+ return _zoom_response_fallback(
|
|
||||||
+ fallback, rejection, "narrow_fov",
|
|
||||||
+ hfov_deg=hfov, wide_cutoff_deg=wide * ratio, learned_s=learned,
|
|
||||||
+ base_s=base, learned_max_s=.34, approach=approach,
|
|
||||||
+ approach_margin=approach_margin, center_error=error, center_limit=.04,
|
|
||||||
+ margin=edge, margin_min=.40, image_rate=rate, image_rate_max=.02,
|
|
||||||
+ )
|
|
||||||
# A nominal duration learned at wide FOV may become ineffective
|
|
||||||
# after narrowing (or may have benefited from STOP transport lag).
|
|
||||||
# Repeating it until the no-effect latch fires is not adaptation.
|
|
||||||
@@ -4988,16 +5031,24 @@
|
|
||||||
# increase either configured hard ceiling or the compiled 400ms limit.
|
|
||||||
deadline = min(max_hard, max(hard, pulse + 0.06))
|
|
||||||
if pulse <= base or deadline < pulse or pulse + 1e-9 < learned:
|
|
||||||
- return fallback
|
|
||||||
+ return _zoom_response_fallback(
|
|
||||||
+ fallback, rejection, "duration",
|
|
||||||
+ pulse_s=pulse, base_s=base, hard_s=deadline, learned_s=learned,
|
|
||||||
+ )
|
|
||||||
# Stress the projection with 2x apparent offset/box/rate and include
|
|
||||||
# video lag + STOP network timeout. This is a conservative software
|
|
||||||
# envelope, not a measured bound on this particular lens's zoom rate.
|
|
||||||
# The ordinary enlarged-bbox predictor is also independently checked.
|
|
||||||
- if 2.0 * edge - 0.5 - 2.0 * rate * (deadline + video_lag + stop_timeout) < 0.10:
|
|
||||||
- return fallback
|
|
||||||
+ projected_margin = 2.0 * edge - 0.5 - 2.0 * rate * (deadline + video_lag + stop_timeout)
|
|
||||||
+ if projected_margin < 0.10:
|
|
||||||
+ return _zoom_response_fallback(
|
|
||||||
+ fallback, rejection, "projected_margin",
|
|
||||||
+ projected_margin=projected_margin, margin_min=.10, margin=edge,
|
|
||||||
+ image_rate=rate, hard_s=deadline, video_lag_s=video_lag, stop_timeout_s=stop_timeout,
|
|
||||||
+ )
|
|
||||||
return pulse, deadline
|
|
||||||
except (TypeError, ValueError, OverflowError):
|
|
||||||
- return fallback
|
|
||||||
+ return _zoom_response_fallback(fallback, rejection, "invalid_timing_inputs")
|
|
||||||
|
|
||||||
|
|
||||||
def _apply_zoom_in_minimum(
|
|
||||||
@@ -8516,7 +8567,9 @@
|
|
||||||
tilt_speed = 0.0
|
|
||||||
# === zoom logic (V3): target-size + alpha-beta filter + hysteresis ===
|
|
||||||
state_zoom = int(st.get("zoom_state", 0) or 0)
|
|
||||||
- can_switch = (now - float(st.get("zoom_last_change", 0.0) or 0.0)) >= float(getattr(config, "Z_MIN_SWITCH_INTERVAL", 0.50))
|
|
||||||
+ switch_age = now - float(st.get("zoom_last_change", 0.0) or 0.0)
|
|
||||||
+ switch_interval = float(getattr(config, "Z_MIN_SWITCH_INTERVAL", 0.50))
|
|
||||||
+ can_switch = switch_age >= switch_interval
|
|
||||||
|
|
||||||
gate_dyn = max(0.05, _Z_CENTER_GATE_IN + _Z_CENTER_GATE_SCALE * (1.0 - clipf(w_smooth, 0.0, 1.0)))
|
|
||||||
center_good = measured_center_err < gate_dyn
|
|
||||||
@@ -8766,6 +8819,7 @@
|
|
||||||
pan_rate_deg_s=float(los_pan_rate_deg_s),
|
|
||||||
tilt_rate_deg_s=float(los_tilt_rate_deg_s),
|
|
||||||
)
|
|
||||||
+ angular_rejection = {} if pulse_active else None
|
|
||||||
zoom_angular_safe = followup_ready and _zoom_angular_motion_safe(
|
|
||||||
pan_error_deg=float(los_pan_angle_deg),
|
|
||||||
tilt_error_deg=float(los_tilt_angle_deg),
|
|
||||||
@@ -8774,6 +8828,7 @@
|
|
||||||
hfov_deg=float(hfov_deg),
|
|
||||||
vfov_deg=float(vfov_deg),
|
|
||||||
max_error_deg=float(angular_max),
|
|
||||||
+ rejection=angular_rejection,
|
|
||||||
)
|
|
||||||
if approach_margin is not None and followup_ready:
|
|
||||||
zoom_angular_safe = True
|
|
||||||
@@ -8961,6 +9016,8 @@
|
|
||||||
elif can_switch and int(st.get("zoom_v3_neutral_votes", 0) or 0) >= confirm_frames:
|
|
||||||
next_state = 0
|
|
||||||
|
|
||||||
+ size_votes = (st.get("zoom_v3_in_votes", 0), st.get("zoom_v3_out_votes", 0),
|
|
||||||
+ st.get("zoom_v3_neutral_votes", 0))
|
|
||||||
if next_state != state_zoom:
|
|
||||||
st["zoom_state"] = next_state
|
|
||||||
st["zoom_last_change"] = now
|
|
||||||
@@ -8968,19 +9025,21 @@
|
|
||||||
st["zoom_int"] = 0.0
|
|
||||||
|
|
||||||
err_size = z_target - size_ctrl
|
|
||||||
- if abs(err_size) < float(getattr(config, "Z_DEADBAND", 0.010)):
|
|
||||||
+ size_deadband = float(getattr(config, "Z_DEADBAND", 0.010))
|
|
||||||
+ if abs(err_size) < size_deadband:
|
|
||||||
err_size = 0.0
|
|
||||||
st["zoom_int"] = clipf(float(st.get("zoom_int", 0.0) or 0.0) + err_size * 0.04, -_Z_INT_CLAMP, _Z_INT_CLAMP)
|
|
||||||
zoom_pi = _Z_P * err_size + _Z_I * st["zoom_int"]
|
|
||||||
zoom_ff = _Z_FF_GAIN * (-float(size_rate))
|
|
||||||
- if size_err_abs <= float(getattr(config, "ZOOM_V3_BRAKE_ERR", 0.030)):
|
|
||||||
+ brake_err = float(getattr(config, "ZOOM_V3_BRAKE_ERR", 0.030))
|
|
||||||
+ if size_err_abs <= brake_err:
|
|
||||||
zoom_ff = 0.0
|
|
||||||
zoom_cmd = clipf(zoom_pi + zoom_ff, _Z_SPEED_LIMIT_OUT, _Z_SPEED_LIMIT_IN)
|
|
||||||
zoom_zero_reason = "size_controller"
|
|
||||||
if not out_edge_crit:
|
|
||||||
- brake_err = float(getattr(config, "ZOOM_V3_BRAKE_ERR", 0.030))
|
|
||||||
brake_k = clipf(abs(err_size) / max(1e-6, brake_err), 0.0, 1.0)
|
|
||||||
zoom_cmd *= brake_k
|
|
||||||
+ zoom_before_size_state = zoom_cmd
|
|
||||||
|
|
||||||
if st.get("zoom_lock", False) and not bounded_identification_request:
|
|
||||||
zoom_cmd = min(zoom_cmd, -0.12) if out_edge_effective else 0.0
|
|
||||||
@@ -9005,6 +9064,7 @@
|
|
||||||
if zoom_cmd < 0.0:
|
|
||||||
zoom_cmd = 0.0
|
|
||||||
|
|
||||||
+ zoom_after_size_state = zoom_cmd
|
|
||||||
prev_z = float(st.get("zoom_prev_cmd", 0.0) or 0.0)
|
|
||||||
max_step = float(getattr(config, "ZOOM_V3_CMD_MAX_STEP", 0.04))
|
|
||||||
positive_slew_limit = prev_z + max_step
|
|
||||||
@@ -9018,6 +9078,7 @@
|
|
||||||
and approach_margin is not None and .16 <= approach_margin <= .5):
|
|
||||||
positive_slew_limit = max(positive_slew_limit, min(.12, float(getattr(config, "ZOOM_STEP_MAX_IN_CMD", .12))))
|
|
||||||
zoom_cmd = clipf(zoom_cmd, prev_z - max_step, positive_slew_limit)
|
|
||||||
+ zoom_after_size_slew = zoom_cmd
|
|
||||||
if (prev_z * zoom_cmd) < 0.0 and abs(err_size) < (lock_err_thr * 2.0):
|
|
||||||
sign_cd = float(getattr(config, "ZOOM_V3_SIGN_COOLDOWN_SEC", 0.80))
|
|
||||||
last_flip = float(st.get("zoom_v3_last_sign_flip_t", 0.0) or 0.0)
|
|
||||||
@@ -9038,6 +9099,7 @@
|
|
||||||
zoom_zero_reason = "deadband"
|
|
||||||
zoom_cmd = 0.0
|
|
||||||
|
|
||||||
+ zoom_after_size_minimum = zoom_cmd
|
|
||||||
cmd_mag_est = max(
|
|
||||||
abs(float(pan_speed) + float(pan_rate_ff)),
|
|
||||||
abs(float(tilt_speed) + float(tilt_rate_ff)),
|
|
||||||
@@ -9225,6 +9287,8 @@
|
|
||||||
st["zoom_useful_pulse_reason"] = useful_reason
|
|
||||||
if before_shape > 0.0 and zoom_cmd <= 0.0:
|
|
||||||
zoom_zero_reason = useful_reason
|
|
||||||
+ response_rejection = {} if decision_request and useful_reason == "useful" else None
|
|
||||||
+ timing_native = _zoom_native_timing_request(st, zoom_cmd)
|
|
||||||
response_timing = _select_zoom_response_timing(
|
|
||||||
st, useful=useful_reason == "useful",
|
|
||||||
hfov_deg=float(hfov_deg), wide_hfov_deg=float(shared_wide_hfov),
|
|
||||||
@@ -9232,7 +9296,8 @@
|
|
||||||
margin=float(edge_risk_margin), image_rate=max(float(vel), float(fast_drift)),
|
|
||||||
approach_margin=approach_margin,
|
|
||||||
fast_approach=bool(fast_approach and normal_zoom_quality_ok and pulse_family == "normal"),
|
|
||||||
- requested_native=_zoom_native_timing_request(st, zoom_cmd),
|
|
||||||
+ requested_native=timing_native,
|
|
||||||
+ rejection=response_rejection,
|
|
||||||
)
|
|
||||||
if useful_reason == "useful" and response_timing == (0.0, 0.0):
|
|
||||||
zoom_cmd = 0.0
|
|
||||||
@@ -9259,6 +9324,7 @@
|
|
||||||
)
|
|
||||||
if gate_stop:
|
|
||||||
zoom_zero_reason = gate_stop[-1]
|
|
||||||
+ decision_generation = st.get("ptz_generation")
|
|
||||||
if (
|
|
||||||
probe_start_candidate
|
|
||||||
and zoom_cmd > 0.0
|
|
||||||
@@ -9797,6 +9863,32 @@
|
|
||||||
cam_idx, prepared_fps, visual_only, max(0., time.time()-now)*1000.,
|
|
||||||
st.get('control_updates', 0), st.get('control_visual_updates', 0))
|
|
||||||
ingest_detection(alarm_eligible)
|
|
||||||
+ if zoom_decision is not None and zoom_zero_reason in ("response_framing", "size_controller"):
|
|
||||||
+ if zoom_zero_reason == "response_framing":
|
|
||||||
+ detail = {"native": timing_native, **(response_rejection or {})}
|
|
||||||
+ else:
|
|
||||||
+ detail = dict(
|
|
||||||
+ size=size_ctrl, size_target=z_target, zoom_in_below=z_band_min - _Z_SIGN_HYST,
|
|
||||||
+ size_error=err_size, size_deadband=size_deadband, brake_error=brake_err,
|
|
||||||
+ pi=zoom_pi, feed_forward=zoom_ff, previous_state=state_zoom,
|
|
||||||
+ next_state=next_state, can_switch=can_switch, want_in=want_in, want_out=want_out,
|
|
||||||
+ in_votes=size_votes[0], out_votes=size_votes[1], neutral_votes=size_votes[2],
|
|
||||||
+ confirm_frames=confirm_frames, switch_age_s=switch_age, switch_interval_s=switch_interval,
|
|
||||||
+ can_zoom_in=can_zoom_in, followup_ready=followup_ready, angular_safe=zoom_angular_safe,
|
|
||||||
+ angular=angular_rejection,
|
|
||||||
+ before_state=zoom_before_size_state, after_state=zoom_after_size_state,
|
|
||||||
+ previous_zoom=prev_z, slew_min=prev_z - max_step, slew_max=positive_slew_limit,
|
|
||||||
+ after_slew=zoom_after_size_slew, command_min=_Z_MIN_CMD,
|
|
||||||
+ after_minimum=zoom_after_size_minimum, before_recenter=before_recenter,
|
|
||||||
+ before_ramp=pre_ramp_zoom_cmd, before_shape=before_shape,
|
|
||||||
+ center_error=center_err, center_priority_error=center_prio_err,
|
|
||||||
+ margin=min_margin, center_priority_margin=center_prio_margin,
|
|
||||||
+ )
|
|
||||||
+ logger.info(
|
|
||||||
+ "[ZOOM THRESHOLD] cam=%s frame=%s request=%s gen=%s reason=%s detail=%s",
|
|
||||||
+ cam_idx, source_seq, decision_request, decision_generation, zoom_zero_reason,
|
|
||||||
+ json.dumps(detail, separators=(",", ":"), default=str),
|
|
||||||
+ )
|
|
||||||
if continuation_trace:
|
|
||||||
generation, native, proposed, held, until, pulse_sec, hard_sec = continuation_trace[0]
|
|
||||||
logger.info(
|
|
||||||
@ -1,13 +0,0 @@
|
|||||||
{
|
|
||||||
"requires": "PTZ stop attribution PR #3",
|
|
||||||
"files": {
|
|
||||||
"ptz_tracker_modular/postprocess.py": {
|
|
||||||
"before": "5326c9d3093b7c863310b9c0a7a85010a1a83ff014631a054ac9a16cc31c8fc5",
|
|
||||||
"after": "8eb5f6beb79141ef1f1ce9dbad3577006821202557a87c7195e770bbba7b4ba3"
|
|
||||||
},
|
|
||||||
"ptz_tracker_modular/ptz_io.py": {
|
|
||||||
"before": "3c3f10eaebc2a1c0f67725d6a487bad9e1537b1bb277705fc503c2526c779600",
|
|
||||||
"after": "13d31539193b1a773a5d1db2187cc2a0c8db67d0aacaad89082face64df07499"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,223 +0,0 @@
|
|||||||
"""Reconstruct logged stop boundaries through the installed gate and worker, offline."""
|
|
||||||
from contextlib import ExitStack
|
|
||||||
import ast
|
|
||||||
import hashlib
|
|
||||||
import json
|
|
||||||
import logging
|
|
||||||
import math
|
|
||||||
from pathlib import Path
|
|
||||||
import socket
|
|
||||||
import sys
|
|
||||||
from types import ModuleType, SimpleNamespace
|
|
||||||
import unittest
|
|
||||||
from unittest.mock import patch
|
|
||||||
import importlib.util
|
|
||||||
|
|
||||||
|
|
||||||
WORK = Path(__file__).resolve().parent
|
|
||||||
PP = Path(sys.argv[5])
|
|
||||||
SOURCE, PTZ, INPUT, PRIOR = map(Path,sys.argv[1:5])
|
|
||||||
ROOT = Path(sys.argv[8])
|
|
||||||
BASE = ROOT/'analysis_outputs/visual_probe_20261019'
|
|
||||||
PKG='ptz_tracker_modular'
|
|
||||||
TRACE=[]
|
|
||||||
DETAIL=[]
|
|
||||||
PINS = {PP: sys.argv[6], PTZ: sys.argv[7]}
|
|
||||||
|
|
||||||
def sha(path):
|
|
||||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
|
||||||
|
|
||||||
def load(name,path):
|
|
||||||
spec=importlib.util.spec_from_file_location(name,path)
|
|
||||||
module=importlib.util.module_from_spec(spec)
|
|
||||||
sys.modules[name]=module
|
|
||||||
spec.loader.exec_module(module)
|
|
||||||
return module
|
|
||||||
|
|
||||||
def deny(*args,**kwargs):
|
|
||||||
raise AssertionError('No real network, CUDA, camera RPC, or model access in replay')
|
|
||||||
|
|
||||||
def as_native(value):
|
|
||||||
return math.nextafter(value/100,math.copysign(math.inf,value)) if value else 0.
|
|
||||||
|
|
||||||
def xml_sent(fixture):
|
|
||||||
return [tuple(transport.xml_axis(xml,axis) for axis in ('pan','tilt','zoom')) for xml in fixture.sent]
|
|
||||||
|
|
||||||
def captured():
|
|
||||||
report=json.loads(INPUT.read_text(encoding='utf-8'))
|
|
||||||
assert report['stable'] is True
|
|
||||||
assert report['container']['started_at']=='2026-11-09T06:24:10.287783596Z'
|
|
||||||
for camera, episodes in report['episodes'].items():
|
|
||||||
for episode in episodes:
|
|
||||||
assert episode['short_count']==len(episode['short_examples'])
|
|
||||||
for sample in episode['short_examples']:
|
|
||||||
yield camera,episode,sample
|
|
||||||
|
|
||||||
def sec(value):
|
|
||||||
return float(value.removesuffix('s'))
|
|
||||||
|
|
||||||
class StopBoundary(unittest.TestCase):
|
|
||||||
def fixture(self, cam, kind, native, pulse):
|
|
||||||
fixture=transport.UsefulZoomTransportTests()
|
|
||||||
fixture.setUp()
|
|
||||||
self.addCleanup(fixture.doCleanups)
|
|
||||||
fixture.cam=cam
|
|
||||||
fixture.stack.enter_context(patch.dict(state.ptz_states,{cam:fixture.st}))
|
|
||||||
# Seed each authorized pulse independently. The log gives accounting
|
|
||||||
# duration/minimum and speed, but lacks the original hard-stop deadline.
|
|
||||||
command=as_native(native)
|
|
||||||
allowed=pp._gate_zoom_in_pulse(fixture.st,fixture.wall,command,True,
|
|
||||||
pulse_kind=kind,pulse_floor=command,pulse_timing=(pulse,.4))
|
|
||||||
self.assertGreater(allowed,0)
|
|
||||||
fixture._enqueue(allowed)
|
|
||||||
fixture._flush()
|
|
||||||
self.assertEqual(xml_sent(fixture)[-1][2],native)
|
|
||||||
self.assertTrue(fixture.st['zoom_step_pending'])
|
|
||||||
return fixture
|
|
||||||
|
|
||||||
def test_all_observed_short_deliveries_replay_at_worker(self):
|
|
||||||
for cam,e,row in captured():
|
|
||||||
with self.subTest(camera=cam,request=row['request']):
|
|
||||||
internal={'19':8,'21':10}[cam]
|
|
||||||
pulse=round(sec(row['minimum'])/.7,3)
|
|
||||||
f=self.fixture(internal,row['kind'],int(row['native']),pulse)
|
|
||||||
f._advance(sec(row['duration']))
|
|
||||||
pan,tilt,zoom=row['requested']
|
|
||||||
self.assertEqual(zoom,0)
|
|
||||||
self.assertNotEqual((pan,tilt),(0,0))
|
|
||||||
with self.assertLogs('PTZTracker.PTZ',level='INFO') as logs:
|
|
||||||
# These are the recorded native values already past quantization.
|
|
||||||
seq=int(row['seq'])
|
|
||||||
f.st['ptz_move_seq']=seq
|
|
||||||
queued=ptz_io.MoveTuple(ptz_io.PTZCmd.MOVE,internal,pan,tilt,0,
|
|
||||||
source='track',generation=f.st['ptz_generation'],preset_floor_checked=True,
|
|
||||||
seq=seq,safety_stop=True)
|
|
||||||
state.ptz_cmd_q.put_nowait(queued)
|
|
||||||
self.assertEqual((queued.pan_i,queued.tilt_i,queued.zoom_i),tuple(row['requested']))
|
|
||||||
f._flush()
|
|
||||||
last=xml_sent(f)[-1]
|
|
||||||
self.assertEqual(last,tuple(row['effective']))
|
|
||||||
self.assertEqual(f.st['zoom_step_last_delivery_result'],'short')
|
|
||||||
self.assertEqual(f.st['zoom_in_pulse_count'],0)
|
|
||||||
self.assertAlmostEqual(f.st['zoom_step_last_delivered_sec'],sec(row['duration']))
|
|
||||||
record=next(x for x in logs.output if 'result=short' in x)
|
|
||||||
self.assertIn('stop_effective=(0,0,0)',record)
|
|
||||||
TRACE.append(dict(camera=cam,episode=e['started_at'],complete=e['complete'],
|
|
||||||
source_request=row['request'],kind=row['kind'],native=int(row['native']),
|
|
||||||
logged_s=sec(row['duration']),minimum_s=sec(row['minimum']),requested=row['requested'],
|
|
||||||
replay_effective=last,replay_result=f.st['zoom_step_last_delivery_result'],
|
|
||||||
controller_trigger_recovered=False))
|
|
||||||
|
|
||||||
def test_positive_revalidation_keeps_original_owned_pulse_deadline(self):
|
|
||||||
for cam,native in ((8,10),(10,11)):
|
|
||||||
with self.subTest(cam=cam,native=native):
|
|
||||||
f=self.fixture(cam,'normal',native,.34)
|
|
||||||
hard_deadline=f.st['zoom_step_stop_started_mono']+f.st['zoom_step_stop_timer'].delay
|
|
||||||
origin=f.st['zoom_step_put_started_mono']
|
|
||||||
deadline=f.st['zoom_step_until']
|
|
||||||
request=f.st['zoom_step_physical_request_id']
|
|
||||||
for _ in range(3):
|
|
||||||
f._advance(.045)
|
|
||||||
command=pp._gate_zoom_in_pulse(f.st,f.wall,.12,True,pulse_floor=.12,pulse_timing=(.34,.4))
|
|
||||||
self.assertEqual(ptz_io._zoom_speed_to_int(command),native)
|
|
||||||
f._enqueue(command)
|
|
||||||
f._flush()
|
|
||||||
self.assertEqual(f.st['zoom_step_put_started_mono'],origin)
|
|
||||||
self.assertEqual(f.st['zoom_step_until'],deadline)
|
|
||||||
self.assertEqual(f.st['zoom_step_physical_request_id'],request)
|
|
||||||
self.assertAlmostEqual(f.st['zoom_step_stop_started_mono']+
|
|
||||||
f.st['zoom_step_stop_timer'].delay,hard_deadline,places=6)
|
|
||||||
self.assertLessEqual(hard_deadline-origin,.400001)
|
|
||||||
f._advance(hard_deadline-f.mono)
|
|
||||||
f.st['zoom_step_stop_timer'].fire()
|
|
||||||
self.assertEqual(xml_sent(f)[-1],(0,0,0))
|
|
||||||
|
|
||||||
def test_identical_zero_when_only_vote_fails_or_safety_fails(self):
|
|
||||||
tree=ast.parse((PP).read_bytes())
|
|
||||||
main=next(n for n in tree.body if getattr(n,'name','')=='postprocess_control')
|
|
||||||
expr=next(n.value for n in ast.walk(main) if isinstance(n,ast.Assign)
|
|
||||||
and any(isinstance(target,ast.Name) and target.id=='can_zoom_in' for target in n.targets)
|
|
||||||
and 'zoom_angular_safe' in ast.unparse(n.value))
|
|
||||||
compiled=compile(ast.Expression(expr),'<server can_zoom_in>','eval')
|
|
||||||
for label,changes in (
|
|
||||||
('synthetic_stable_history_only',{'stable_ok':False}),
|
|
||||||
('synthetic_edge_veto',{'near_edge':True}),
|
|
||||||
('synthetic_angular_veto',{'zoom_angular_safe':False}),
|
|
||||||
('synthetic_quality_veto',{'zoom_safe':False}),
|
|
||||||
):
|
|
||||||
with self.subTest(label=label):
|
|
||||||
f=self.fixture(8,'normal',10,.34)
|
|
||||||
f._advance(.110)
|
|
||||||
env=dict(zoom_safe=True,zoom_angular_safe=True,stable_ok=True,
|
|
||||||
zoom_rearm_ready=True,near_edge=False,st={},bounded_identification_request=False,
|
|
||||||
fast_drift=.02,config=config,now=f.wall)
|
|
||||||
can=eval(compiled,{},{**env,**changes})
|
|
||||||
self.assertFalse(can)
|
|
||||||
actual=pp._gate_zoom_in_pulse(f.st,f.wall,.1,can,
|
|
||||||
pulse_floor=.1,pulse_timing=(.34,.4))
|
|
||||||
self.assertEqual(actual,0.)
|
|
||||||
f._enqueue(actual)
|
|
||||||
f._flush()
|
|
||||||
self.assertEqual(xml_sent(f)[-1],(0,0,0))
|
|
||||||
self.assertEqual(f.st['zoom_step_last_delivery_result'],'short')
|
|
||||||
DETAIL.append(dict(label=label,zoom=actual,axes=xml_sent(f)[-1],status='short'))
|
|
||||||
|
|
||||||
def main():
|
|
||||||
import torch
|
|
||||||
import numpy
|
|
||||||
global config,state,ptz_io,pp,transport
|
|
||||||
assert all(sha(path)==expected for path,expected in PINS.items())
|
|
||||||
before=load('prior_replay_fixture',PRIOR)
|
|
||||||
from test_frame_decision import build_cases
|
|
||||||
from test_native_floor import build_floor_cases
|
|
||||||
logging.getLogger('PTZTracker').setLevel(logging.ERROR)
|
|
||||||
with ExitStack() as stack:
|
|
||||||
for owner,name in ((socket.socket,'connect'),(socket.socket,'connect_ex'),
|
|
||||||
(socket,'create_connection'),(torch,'load'),(torch.cuda,'_lazy_init')):
|
|
||||||
stack.enter_context(patch.object(owner,name,deny))
|
|
||||||
stack.enter_context(patch.object(torch.cuda,'is_available',return_value=False))
|
|
||||||
package=ModuleType(PKG)
|
|
||||||
package.__path__=[str(BASE/'geometry_candidate/ptz_tracker_modular'),str(ROOT)]
|
|
||||||
sys.modules[PKG]=package
|
|
||||||
model=ModuleType(PKG+'.model')
|
|
||||||
model.model_shared,model.yolo_forward=object(),deny
|
|
||||||
sys.modules[model.__name__]=model
|
|
||||||
load(PKG+'.visual_control_probe', SOURCE/'visual_control_probe.py')
|
|
||||||
control=load(PKG+'.visual_control',SOURCE/'visual_control.py')
|
|
||||||
ptz_io=load(PKG+'.ptz_io',PTZ)
|
|
||||||
pp=load(PKG+'.postprocess',PP)
|
|
||||||
from ptz_tracker_modular import config,state,visual_tracker
|
|
||||||
values=json.loads((BASE/'zoom_continuation_candidate/runtime_policy_snapshot.json').read_text())['values']
|
|
||||||
for key,value in values.items():
|
|
||||||
stack.enter_context(patch.object(config,key,value,create=True))
|
|
||||||
transport=load('test_zoom_useful_transport',ROOT/'tests/test_zoom_useful_transport.py')
|
|
||||||
before.np,before.torch,before.config,before.state=numpy,torch,config,state
|
|
||||||
before.ptz_io,before.pp,before.tracker,before.control,before.transport=ptz_io,pp,visual_tracker,control,transport
|
|
||||||
suite=unittest.defaultTestLoader.loadTestsFromTestCase(StopBoundary)
|
|
||||||
for name in ('test_geometry_hold_short_delivery_has_exact_synthetic_stop_caller',
|
|
||||||
'test_started_controller_pulse_keeps_hard_stop_after_owner_change',
|
|
||||||
'test_joint_steering_update_cannot_extend_original_started_pulse',
|
|
||||||
'test_visual_age_over_250ms_cannot_move_or_advance_control',
|
|
||||||
'test_detector_age_over_650ms_cannot_refresh_evidence',
|
|
||||||
'test_old_owner_sample_cannot_refresh_or_stop_new_owner',
|
|
||||||
'test_reacquire_does_not_clear_no_effect_limit'):
|
|
||||||
suite.addTest(before.Replay(name))
|
|
||||||
candidate = "zoom_decision" in __import__("inspect").signature(ptz_io.move_ptz).parameters
|
|
||||||
if candidate:
|
|
||||||
suite.addTests(build_cases(before.Replay, pp, ptz_io))
|
|
||||||
suite.addTests(build_floor_cases(StopBoundary, before.Replay, pp, ptz_io, config,
|
|
||||||
Path(sys.argv[10]), sys.argv[11] == "fixed",
|
|
||||||
threshold_diagnostics="--thresholds" in sys.argv[12:]))
|
|
||||||
result=unittest.TextTestRunner(verbosity=2).run(suite)
|
|
||||||
result_file=Path(sys.argv[9])
|
|
||||||
result_file.write_text(json.dumps(dict(passed=result.wasSuccessful(),tests=result.testsRun,
|
|
||||||
observed_expected=len(list(captured())),observed_matched=len(TRACE),telemetry_sha256=sha(INPUT),
|
|
||||||
tested_source_sha256={path.name:pin for path,pin in PINS.items()},observed_rows=TRACE,synthetic=DETAIL,
|
|
||||||
shared_controller_rows={key: rows for key, rows in before.TRACE.items()
|
|
||||||
if not key.startswith(("test_frame_decision", "test_center_history", "test_dropped_move"))},
|
|
||||||
exact_observed_controller_replay=False,real_ptz_or_nn=False,
|
|
||||||
conclusion='The same short-delivery output is compatible with a synthetic admission-only condition and mandatory safety stops. The observed controller trigger and exact deadlines are missing.'),indent=2)+'\n',encoding='utf-8')
|
|
||||||
return not result.wasSuccessful()
|
|
||||||
|
|
||||||
if __name__=='__main__':
|
|
||||||
raise SystemExit(main())
|
|
||||||
@ -1,406 +0,0 @@
|
|||||||
--- a/ptz_tracker_modular/postprocess.py
|
|
||||||
+++ b/ptz_tracker_modular/postprocess.py
|
|
||||||
@@ -4357,6 +4357,7 @@
|
|
||||||
max_image_rate: float,
|
|
||||||
max_outward_rate: float,
|
|
||||||
err_growth_tol: float,
|
|
||||||
+ settled_sample: list[bool] | None = None,
|
|
||||||
) -> bool:
|
|
||||||
"""Return True only after a tight, non-diverging image-space hold.
|
|
||||||
|
|
||||||
@@ -4381,6 +4382,8 @@
|
|
||||||
and outward_rate <= max(0.0, float(max_outward_rate))
|
|
||||||
and non_diverging
|
|
||||||
)
|
|
||||||
+ if settled_sample is not None:
|
|
||||||
+ settled_sample.append(bool(settled))
|
|
||||||
previous_frames = int(st.get(frames_key, 0) or 0)
|
|
||||||
if settled:
|
|
||||||
frames = previous_frames + 1
|
|
||||||
@@ -4411,6 +4414,7 @@
|
|
||||||
vx: float,
|
|
||||||
vy: float,
|
|
||||||
center_gate: float | None = None,
|
|
||||||
+ settled_sample: list[bool] | None = None,
|
|
||||||
) -> bool:
|
|
||||||
return _update_center_lock_state(
|
|
||||||
st,
|
|
||||||
@@ -4436,6 +4440,7 @@
|
|
||||||
max_image_rate=float(getattr(config, "ZOOM_CENTER_LOCK_MAX_IMAGE_RATE", 0.28)),
|
|
||||||
max_outward_rate=float(getattr(config, "ZOOM_CENTER_LOCK_MAX_OUTWARD_RATE", 0.08)),
|
|
||||||
err_growth_tol=float(getattr(config, "ZOOM_CENTER_LOCK_ERR_GROWTH_TOL", 0.018)),
|
|
||||||
+ settled_sample=settled_sample,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@@ -4553,6 +4558,12 @@
|
|
||||||
st["acquire_zoom_prev_err"] = None
|
|
||||||
|
|
||||||
|
|
||||||
+def _reject_zoom_step(reason: str, trace: list[str] | None) -> float:
|
|
||||||
+ if trace is not None:
|
|
||||||
+ trace.append(reason)
|
|
||||||
+ return 0.0
|
|
||||||
+
|
|
||||||
+
|
|
||||||
def _gate_zoom_in_pulse(
|
|
||||||
st: dict,
|
|
||||||
now: float,
|
|
||||||
@@ -4565,6 +4576,7 @@
|
|
||||||
pulse_floor: float = 0.0,
|
|
||||||
pulse_timing: Tuple[float, float] | None = None,
|
|
||||||
optics_observed_now: float | None = None,
|
|
||||||
+ stop_trace: list[str] | None = None,
|
|
||||||
) -> float:
|
|
||||||
"""Break continuous zoom-in into short feedback-controlled steps."""
|
|
||||||
pulse_until = float(st.get("zoom_step_until", 0.0) or 0.0)
|
|
||||||
@@ -4581,15 +4593,15 @@
|
|
||||||
return float(zoom_cmd if can_zoom_in else 0.0)
|
|
||||||
if bool(st.get("zoom_no_effect_blocked", False)):
|
|
||||||
st["zoom_followup_reason"] = "no_effect_limit"
|
|
||||||
- return 0.0
|
|
||||||
+ return _reject_zoom_step("no_effect_limit", stop_trace)
|
|
||||||
if not can_zoom_in:
|
|
||||||
if pulse_until > 0.0 or bool(st.get("zoom_step_pending", False)):
|
|
||||||
_finish_zoom_step(st, now, stable_key=stable_key)
|
|
||||||
- return 0.0
|
|
||||||
+ return _reject_zoom_step("permission", stop_trace)
|
|
||||||
|
|
||||||
if bool(st.get("zoom_step_pending", False)):
|
|
||||||
if bool(st.get("zoom_step_cancel_requested", False)):
|
|
||||||
- return 0.0
|
|
||||||
+ return _reject_zoom_step("cancel_requested", stop_trace)
|
|
||||||
if pulse_timing is not None:
|
|
||||||
try:
|
|
||||||
authorized = tuple(map(float, pulse_timing))
|
|
||||||
@@ -4602,7 +4614,7 @@
|
|
||||||
timing_ok = False
|
|
||||||
if not timing_ok:
|
|
||||||
_finish_zoom_step(st, now, stable_key=stable_key)
|
|
||||||
- return 0.0
|
|
||||||
+ return _reject_zoom_step("pending_timing", stop_trace)
|
|
||||||
useful_cmd = float(st.get("zoom_step_pending_useful_cmd", 0.0) or 0.0)
|
|
||||||
if useful_cmd > 0.0:
|
|
||||||
# A useful-pulse caller revalidates its entire framing envelope on
|
|
||||||
@@ -4614,7 +4626,7 @@
|
|
||||||
or float(getattr(config, "ZOOM_STEP_MAX_IN_CMD", 0.12)) < useful_cmd
|
|
||||||
):
|
|
||||||
_finish_zoom_step(st, now, stable_key=stable_key)
|
|
||||||
- return 0.0
|
|
||||||
+ return _reject_zoom_step("pending_native_floor", stop_trace)
|
|
||||||
zoom_cmd = useful_cmd
|
|
||||||
physical_started = float(st.get("zoom_step_physical_started_at", 0.0) or 0.0)
|
|
||||||
if physical_started > 0.0:
|
|
||||||
@@ -4624,7 +4636,7 @@
|
|
||||||
float(getattr(config, "ZOOM_STEP_MAX_IN_CMD", 0.18)),
|
|
||||||
)
|
|
||||||
_finish_zoom_step(st, now, stable_key=stable_key)
|
|
||||||
- return 0.0
|
|
||||||
+ return _reject_zoom_step("pulse_window_ended", stop_trace)
|
|
||||||
expires_at = float(st.get("zoom_step_pending_expires_at", 0.0) or 0.0)
|
|
||||||
if expires_at > 0.0 and float(now) >= expires_at:
|
|
||||||
_clear_pending_zoom_request(
|
|
||||||
@@ -4633,7 +4645,7 @@
|
|
||||||
reason="delivery_timeout",
|
|
||||||
retry_cooldown=True,
|
|
||||||
)
|
|
||||||
- return 0.0
|
|
||||||
+ return _reject_zoom_step("delivery_timeout", stop_trace)
|
|
||||||
# Keep authorizing the same request until the worker either delivers it
|
|
||||||
# or a newer safety command cancels it. No counters are consumed here.
|
|
||||||
return min(
|
|
||||||
@@ -8614,6 +8626,7 @@
|
|
||||||
)
|
|
||||||
if approach_margin is not None:
|
|
||||||
lock_gate = max(lock_gate, .12)
|
|
||||||
+ center_sample = []
|
|
||||||
center_locked_for_zoom = _update_zoom_center_lock(
|
|
||||||
st,
|
|
||||||
now,
|
|
||||||
@@ -8625,6 +8638,7 @@
|
|
||||||
vx=float(zoom_vx),
|
|
||||||
vy=float(zoom_vy),
|
|
||||||
center_gate=lock_gate,
|
|
||||||
+ settled_sample=center_sample,
|
|
||||||
)
|
|
||||||
|
|
||||||
use_zoom_v3 = bool(getattr(config, "ZOOM_V3_ENABLE", True))
|
|
||||||
@@ -8867,6 +8881,9 @@
|
|
||||||
and now >= float(st.get("focus_settle_until", 0.0) or 0.0)
|
|
||||||
)
|
|
||||||
|
|
||||||
+ center_settled = center_sample[0] if center_sample else None
|
|
||||||
+ track_stable = int(st.get("stable_frames", 0) or 0) >= min_stable
|
|
||||||
+
|
|
||||||
# A safe probe is an explicit bounded identification request, not merely
|
|
||||||
# permission for the ordinary size controller. Without this request a
|
|
||||||
# tiny distant aircraft could pass every probe gate yet never zoom because
|
|
||||||
@@ -8929,6 +8946,7 @@
|
|
||||||
if size_err_abs <= float(getattr(config, "ZOOM_V3_BRAKE_ERR", 0.030)):
|
|
||||||
zoom_ff = 0.0
|
|
||||||
zoom_cmd = clipf(zoom_pi + zoom_ff, _Z_SPEED_LIMIT_OUT, _Z_SPEED_LIMIT_IN)
|
|
||||||
+ zoom_zero_reason = "size_controller"
|
|
||||||
if not out_edge_crit:
|
|
||||||
brake_err = float(getattr(config, "ZOOM_V3_BRAKE_ERR", 0.030))
|
|
||||||
brake_k = clipf(abs(err_size) / max(1e-6, brake_err), 0.0, 1.0)
|
|
||||||
@@ -8936,6 +8954,7 @@
|
|
||||||
|
|
||||||
if st.get("zoom_lock", False) and not bounded_identification_request:
|
|
||||||
zoom_cmd = min(zoom_cmd, -0.12) if out_edge_effective else 0.0
|
|
||||||
+ zoom_zero_reason = "zoom_lock"
|
|
||||||
st["zoom_int"] *= 0.90
|
|
||||||
else:
|
|
||||||
if st["zoom_state"] > 0:
|
|
||||||
@@ -8947,6 +8966,7 @@
|
|
||||||
if normal_size_hold and not out_edge_effective:
|
|
||||||
st["zoom_state"] = 0
|
|
||||||
zoom_cmd = 0.0
|
|
||||||
+ zoom_zero_reason = "size_hold"
|
|
||||||
st["zoom_int"] *= 0.70
|
|
||||||
st["zoom_size_rate"] = float(st.get("zoom_size_rate", 0.0) or 0.0) * 0.6
|
|
||||||
if cruise_active and (not approaching) and (not out_edge_effective) and (not near_react_edge):
|
|
||||||
@@ -8973,6 +8993,7 @@
|
|
||||||
last_flip = float(st.get("zoom_v3_last_sign_flip_t", 0.0) or 0.0)
|
|
||||||
if (now - last_flip) < sign_cd:
|
|
||||||
zoom_cmd = 0.0
|
|
||||||
+ zoom_zero_reason = "sign_cooldown"
|
|
||||||
else:
|
|
||||||
st["zoom_v3_last_sign_flip_t"] = now
|
|
||||||
|
|
||||||
@@ -8983,6 +9004,8 @@
|
|
||||||
elif z_state < 0:
|
|
||||||
zoom_cmd = -_Z_MIN_CMD
|
|
||||||
else:
|
|
||||||
+ if zoom_cmd != 0.0:
|
|
||||||
+ zoom_zero_reason = "deadband"
|
|
||||||
zoom_cmd = 0.0
|
|
||||||
|
|
||||||
cmd_mag_est = max(
|
|
||||||
@@ -8993,10 +9016,14 @@
|
|
||||||
gate_v = float(getattr(config, "Z_VELOCITY_GATE", 0.45))
|
|
||||||
over_v = max(0.0, cmd_mag_est - gate_v)
|
|
||||||
zoom_cmd *= clipf(1.0 - over_v / max(1e-6, gate_v * 1.2), 0.0, 1.0)
|
|
||||||
+ if zoom_cmd == 0.0:
|
|
||||||
+ zoom_zero_reason = "steering_speed"
|
|
||||||
err_gate = float(getattr(config, "Z_ERR_GATE", 0.18))
|
|
||||||
if (max(abs(sm_dx), abs(sm_dy)) > err_gate) and (zoom_cmd > 0.0):
|
|
||||||
over_e = max(0.0, max(abs(sm_dx), abs(sm_dy)) - err_gate)
|
|
||||||
zoom_cmd *= clipf(1.0 - over_e / max(1e-6, err_gate * 1.5), 0.0, 1.0)
|
|
||||||
+ if zoom_cmd == 0.0:
|
|
||||||
+ zoom_zero_reason = "center_error"
|
|
||||||
# Center-first policy: when target is noticeably off-center, prioritize pan/tilt over zoom-in.
|
|
||||||
center_prio_err = float(getattr(config, "ZOOM_CENTER_PRIORITY_ERR", 0.11))
|
|
||||||
center_prio_margin = float(getattr(config, "ZOOM_CENTER_PRIORITY_MARGIN", 0.14))
|
|
||||||
@@ -9007,19 +9034,26 @@
|
|
||||||
zoom_cmd *= clipf(min_margin / max(1e-6, center_prio_margin), 0.0, 1.0)
|
|
||||||
if near_edge and zoom_cmd > 0.0:
|
|
||||||
zoom_cmd = 0.0
|
|
||||||
+ zoom_zero_reason = "near_edge"
|
|
||||||
|
|
||||||
if zoom_cmd > 0.0:
|
|
||||||
vel_ref = float(getattr(config, "ZOOM_IN_SCALE_VEL_REF", 0.22))
|
|
||||||
vel_k = clipf(1.0 - vel / max(1e-6, vel_ref), float(getattr(config, "ZOOM_IN_SCALE_MIN", 0.20)), 1.0)
|
|
||||||
zoom_cmd *= min(zoom_safe_scale, vel_k)
|
|
||||||
-
|
|
||||||
+ if zoom_cmd == 0.0:
|
|
||||||
+ zoom_zero_reason = "framing_scale"
|
|
||||||
+
|
|
||||||
+ before_edge = zoom_cmd
|
|
||||||
zoom_cmd = _apply_predictive_edge_zoom_out(
|
|
||||||
zoom_cmd,
|
|
||||||
risk_margin=edge_risk_margin,
|
|
||||||
react_margin=react_margin,
|
|
||||||
moving_out=moving_out,
|
|
||||||
)
|
|
||||||
+ if before_edge > 0.0 and zoom_cmd <= 0.0:
|
|
||||||
+ zoom_zero_reason = "predictive_edge"
|
|
||||||
recent_zoom_steering = _recent_zoom_steering_active(st, now, zoom_cmd)
|
|
||||||
+ before_recenter = zoom_cmd
|
|
||||||
zoom_cmd = _apply_zoom_recenter_guard(
|
|
||||||
zoom_cmd,
|
|
||||||
center_err=float(center_err),
|
|
||||||
@@ -9027,6 +9061,8 @@
|
|
||||||
recent_zoom=bool(recent_zoom_steering),
|
|
||||||
approach_margin=approach_margin,
|
|
||||||
)
|
|
||||||
+ if before_recenter > 0.0 and zoom_cmd <= 0.0:
|
|
||||||
+ zoom_zero_reason = "recenter"
|
|
||||||
zoom_out_emergency = bool(
|
|
||||||
out_edge_effective
|
|
||||||
or float(min_margin) < float(getattr(config, "Z_SAFETY_EDGE", 0.05))
|
|
||||||
@@ -9114,6 +9150,8 @@
|
|
||||||
request_id_before_gate = int(st.get("zoom_step_request_id", 0) or 0)
|
|
||||||
with _zoom_command_lock(cam_idx):
|
|
||||||
zoom_gate_now = time.time()
|
|
||||||
+ decision_request = int(st.get("zoom_step_physical_request_id", 0) or
|
|
||||||
+ st.get("zoom_step_pending_id", 0) or 0)
|
|
||||||
pulse_family = str(st.get("zoom_step_pending_kind") or pulse_kind)
|
|
||||||
pulse_cap = float(getattr(config, "ZOOM_STEP_MAX_IN_CMD", 0.12))
|
|
||||||
if "probe" in pulse_family:
|
|
||||||
@@ -9142,6 +9180,7 @@
|
|
||||||
proposed_zoom_cmd = max(zoom_cmd, min(pre_ramp_zoom_cmd, pulse_cap, .12))
|
|
||||||
if _zoom_native_response_available(st, _zoom_speed_to_int(proposed_zoom_cmd), hfov_deg, shared_wide_hfov):
|
|
||||||
zoom_cmd = proposed_zoom_cmd
|
|
||||||
+ before_shape = zoom_cmd
|
|
||||||
zoom_cmd, useful_reason = _shape_useful_zoom_pulse(
|
|
||||||
zoom_cmd,
|
|
||||||
can_zoom_in=can_zoom_in,
|
|
||||||
@@ -9154,6 +9193,8 @@
|
|
||||||
approach_margin=approach_margin,
|
|
||||||
)
|
|
||||||
st["zoom_useful_pulse_reason"] = useful_reason
|
|
||||||
+ if before_shape > 0.0 and zoom_cmd <= 0.0:
|
|
||||||
+ zoom_zero_reason = useful_reason
|
|
||||||
response_timing = _select_zoom_response_timing(
|
|
||||||
st, useful=useful_reason == "useful",
|
|
||||||
hfov_deg=float(hfov_deg), wide_hfov_deg=float(shared_wide_hfov),
|
|
||||||
@@ -9166,6 +9207,8 @@
|
|
||||||
if useful_reason == "useful" and response_timing == (0.0, 0.0):
|
|
||||||
zoom_cmd = 0.0
|
|
||||||
st["zoom_useful_pulse_reason"] = "wait_response_framing"
|
|
||||||
+ zoom_zero_reason = "response_framing"
|
|
||||||
+ gate_stop = [] if decision_request else None
|
|
||||||
zoom_cmd = _gate_zoom_in_pulse(
|
|
||||||
st,
|
|
||||||
# Keep new-request expiry tied to the frame that authorized
|
|
||||||
@@ -9180,7 +9223,10 @@
|
|
||||||
pulse_floor=(zoom_cmd if useful_reason == "useful" else 0.0),
|
|
||||||
pulse_timing=response_timing,
|
|
||||||
optics_observed_now=zoom_gate_now,
|
|
||||||
+ stop_trace=gate_stop,
|
|
||||||
)
|
|
||||||
+ if gate_stop:
|
|
||||||
+ zoom_zero_reason = gate_stop[-1]
|
|
||||||
if (
|
|
||||||
probe_start_candidate
|
|
||||||
and zoom_cmd > 0.0
|
|
||||||
@@ -9433,6 +9479,7 @@
|
|
||||||
or visual_control_coast != was_visual_control_coast
|
|
||||||
)
|
|
||||||
if visual_control_coast:
|
|
||||||
+ before_coast = zoom_cmd
|
|
||||||
adj_pan, adj_tilt, zoom_cmd = _bound_visual_coast_commands(
|
|
||||||
st,
|
|
||||||
adj_pan,
|
|
||||||
@@ -9463,7 +9510,11 @@
|
|
||||||
# Appearance continuity is sufficient for bounded steering only.
|
|
||||||
# It never authorizes an alarm without a current detector match.
|
|
||||||
alarm_eligible = False
|
|
||||||
+ if before_coast > 0.0 and zoom_cmd <= 0.0:
|
|
||||||
+ zoom_zero_reason = "visual_coast"
|
|
||||||
elif visual_control_stale:
|
|
||||||
+ if zoom_cmd > 0.0:
|
|
||||||
+ zoom_zero_reason = "visual_stale"
|
|
||||||
# Stale detector validation makes image-space steering unsafe, but a
|
|
||||||
# previously calculated edge-recovery zoom-out only widens the field
|
|
||||||
# of view. Preserve that bounded negative command while cancelling
|
|
||||||
@@ -9532,6 +9583,7 @@
|
|
||||||
# immediately by the forced command below.
|
|
||||||
if float(zoom_cmd) > 0.0:
|
|
||||||
zoom_cmd = 0.0
|
|
||||||
+ zoom_zero_reason = "final_brake"
|
|
||||||
st["zoom_prev_cmd"] = 0.0
|
|
||||||
st["stable_frames"] = 0
|
|
||||||
|
|
||||||
@@ -9673,7 +9725,33 @@
|
|
||||||
_arm_zoom_revalidation_locked(st, time.time(), 'visual_control_expired')
|
|
||||||
stop_ptz(cam_idx, source='stop', generation=int(st.get('ptz_generation', 0) or 0))
|
|
||||||
return
|
|
||||||
- _dispatch_owned_zoom_tracking(cam_idx, _PAN_SIGN * adj_pan, _TILT_SIGN * adj_tilt, zoom_cmd, force=force_track_ptz)
|
|
||||||
+ zoom_decision = None
|
|
||||||
+ if decision_request and zoom_cmd <= 0.0:
|
|
||||||
+ blockers = tuple(name for name, blocked in (
|
|
||||||
+ ("quality", not zoom_quality_ok),
|
|
||||||
+ ("framing", not zoom_safe),
|
|
||||||
+ ("followup", not followup_ready),
|
|
||||||
+ ("angle", not zoom_angular_safe),
|
|
||||||
+ ("center_sample_unknown", center_settled is None),
|
|
||||||
+ ("center_sample", center_settled is False),
|
|
||||||
+ ("center_history", center_settled is True and not center_locked_for_zoom),
|
|
||||||
+ ("track_history", not track_stable),
|
|
||||||
+ ("rearm", not zoom_rearm_ready),
|
|
||||||
+ ("edge", near_edge or edge_recovery_active),
|
|
||||||
+ ("lock", st.get("zoom_lock", False) and not bounded_identification_request),
|
|
||||||
+ ("drift", fast_drift > float(getattr(config, "ZOOM_IN_FAST_DRIFT_MAX", 0.45))),
|
|
||||||
+ ("focus", now < float(st.get("focus_settle_until", 0.0) or 0.0)),
|
|
||||||
+ ("coast", visual_control_coast),
|
|
||||||
+ ("stale", visual_control_stale),
|
|
||||||
+ ("brake", final_guard_active),
|
|
||||||
+ ) if blocked)
|
|
||||||
+ zoom_decision = (source_seq, decision_request, zoom_zero_reason, "+".join(blockers) or "-")
|
|
||||||
+ dispatch_kwargs = {"force": force_track_ptz}
|
|
||||||
+ if zoom_decision is not None:
|
|
||||||
+ dispatch_kwargs["zoom_decision"] = zoom_decision
|
|
||||||
+ _dispatch_owned_zoom_tracking(
|
|
||||||
+ cam_idx, _PAN_SIGN * adj_pan, _TILT_SIGN * adj_tilt, zoom_cmd, **dispatch_kwargs
|
|
||||||
+ )
|
|
||||||
if visual_control.enabled():
|
|
||||||
dispatch_at = time.monotonic()
|
|
||||||
samples = st.setdefault('control_dispatch_samples', [])
|
|
||||||
--- a/ptz_tracker_modular/ptz_io.py
|
|
||||||
+++ b/ptz_tracker_modular/ptz_io.py
|
|
||||||
@@ -1903,10 +1903,11 @@
|
|
||||||
source: Optional[str] = None,
|
|
||||||
generation: Optional[int] = None,
|
|
||||||
preset_floor_checked: bool = False,
|
|
||||||
+ zoom_decision: Optional[Tuple[Optional[int], int, str, str]] = None,
|
|
||||||
) -> None:
|
|
||||||
"""Serialize frame commands with the independent lens hard-stop timer."""
|
|
||||||
with _zoom_command_lock(cam_idx):
|
|
||||||
- _move_ptz_locked(
|
|
||||||
+ queued = _move_ptz_locked(
|
|
||||||
cam_idx,
|
|
||||||
pan,
|
|
||||||
tilt,
|
|
||||||
@@ -1915,6 +1916,15 @@
|
|
||||||
source=source,
|
|
||||||
generation=generation,
|
|
||||||
preset_floor_checked=preset_floor_checked,
|
|
||||||
+ zoom_decision=zoom_decision,
|
|
||||||
+ )
|
|
||||||
+ if zoom_decision is not None and queued is not None:
|
|
||||||
+ cmd_source, generation, seq, native_zoom = queued
|
|
||||||
+ frame, request, reason, blockers = zoom_decision
|
|
||||||
+ logger.info(
|
|
||||||
+ "[ZOOM DECISION] cam=%s frame=%s request=%s source=%s gen=%s seq=%s "
|
|
||||||
+ "queued_zoom=%s reason=%s blockers=%s",
|
|
||||||
+ cam_idx, frame, request, cmd_source, generation, seq, native_zoom, reason, blockers,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1929,7 +1939,8 @@
|
|
||||||
generation: Optional[int] = None,
|
|
||||||
preset_floor_checked: bool = False,
|
|
||||||
hard_stop: bool = False,
|
|
||||||
-) -> None:
|
|
||||||
+ zoom_decision: Optional[Tuple[Optional[int], int, str, str]] = None,
|
|
||||||
+) -> Optional[Tuple[str, int, int, int]]:
|
|
||||||
"""
|
|
||||||
Отправка relative/continuous PTZ-команды.
|
|
||||||
|
|
||||||
@@ -2105,6 +2116,9 @@
|
|
||||||
# The MOVE is already queued. Report watchdog setup separately;
|
|
||||||
# pretending that the MOVE was dropped would corrupt dedupe state.
|
|
||||||
logger.error("[ZOOM WATCHDOG] setup failed cam=%s: %s", cam_idx, exc)
|
|
||||||
+ if zoom_decision is not None:
|
|
||||||
+ return cmd_source, cmd_generation, move_seq, zoom_i
|
|
||||||
+ return None
|
|
||||||
|
|
||||||
|
|
||||||
def stop_ptz(cam_idx: int, *, source: str = "stop", generation: Optional[int] = None) -> None:
|
|
||||||
@@ -2253,6 +2267,7 @@
|
|
||||||
force: bool = False,
|
|
||||||
source: Optional[str] = None,
|
|
||||||
generation: Optional[int] = None,
|
|
||||||
+ zoom_decision: Optional[Tuple[Optional[int], int, str, str]] = None,
|
|
||||||
) -> None:
|
|
||||||
"""
|
|
||||||
Обёртка над move_ptz.
|
|
||||||
@@ -2295,6 +2310,7 @@
|
|
||||||
source=source,
|
|
||||||
generation=generation,
|
|
||||||
preset_floor_checked=True,
|
|
||||||
+ zoom_decision=zoom_decision,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@ -1,71 +0,0 @@
|
|||||||
"""Offline frame-to-queue/ACK tests built on the established fake PTZ worker."""
|
|
||||||
from unittest.mock import patch
|
|
||||||
|
|
||||||
|
|
||||||
def build_cases(replay_base, controller, transport):
|
|
||||||
class FrameDecision(replay_base):
|
|
||||||
def test_frame_decision_joins_protective_stop_ack(self):
|
|
||||||
self.start_pulse()
|
|
||||||
request = self.st["zoom_step_physical_request_id"]
|
|
||||||
with patch.object(controller, "_shape_useful_zoom_pulse",
|
|
||||||
return_value=(0.0, "stale_optics")) as shape:
|
|
||||||
with self.assertLogs("PTZTracker.PTZ", level="INFO") as logs:
|
|
||||||
row = self.tick(.035)
|
|
||||||
self.assertGreater(shape.call_args.args[0], 0.0)
|
|
||||||
decision = self.log_fields(logs, "[ZOOM DECISION]")
|
|
||||||
delivery = self.log_fields(logs, "[ZOOM DELIVERY]")
|
|
||||||
self.assertEqual(decision["frame"], str(row["seq"]))
|
|
||||||
self.assertEqual(decision["request"], str(request))
|
|
||||||
self.assertEqual(decision["reason"], "stale_optics")
|
|
||||||
self.assertEqual(decision["queued_zoom"], "0")
|
|
||||||
self.assertEqual(decision["source"], "track")
|
|
||||||
self.assertEqual(decision["gen"], delivery["stop_gen"])
|
|
||||||
self.assertEqual(decision["seq"], delivery["stop_seq"])
|
|
||||||
self.assertEqual(delivery["request"], str(request))
|
|
||||||
self.assertEqual(delivery["stop_effective"], "(0,0,0)")
|
|
||||||
self.assertEqual(row["sent"][-1], (0, 0, 0))
|
|
||||||
|
|
||||||
def test_center_history_is_distinct_from_current_sample(self):
|
|
||||||
for settled, expected in ((True, "center_history"), (False, "center_sample")):
|
|
||||||
with self.subTest(settled=settled):
|
|
||||||
self.start_pulse()
|
|
||||||
def unsettled(*args, settled_sample, **kwargs):
|
|
||||||
settled_sample.append(settled)
|
|
||||||
return False
|
|
||||||
with patch.object(controller, "_update_zoom_center_lock", side_effect=unsettled):
|
|
||||||
with self.assertLogs("PTZTracker.PTZ", level="INFO") as logs:
|
|
||||||
row = self.tick(.035)
|
|
||||||
decision = self.log_fields(logs, "[ZOOM DECISION]")
|
|
||||||
blockers = decision["blockers"].split("+")
|
|
||||||
self.assertEqual(decision["frame"], str(row["seq"]))
|
|
||||||
self.assertIn(expected, blockers)
|
|
||||||
self.assertNotIn("center_sample" if settled else "center_history", blockers)
|
|
||||||
self.assertEqual(row["sent"][-1], (0, 0, 0))
|
|
||||||
|
|
||||||
def test_dropped_move_does_not_emit_decision(self):
|
|
||||||
with patch.object(transport.state.ptz_cmd_q, "put_nowait", side_effect=RuntimeError("queue full")):
|
|
||||||
with self.assertLogs("PTZTracker.PTZ", level="INFO") as logs:
|
|
||||||
transport.move_ptz_bounded(self.cam, .1, .05, 0., force=True,
|
|
||||||
zoom_decision=(104, 7, "permission", "center_history"))
|
|
||||||
self.assertTrue(any("[PTZ QUEUE] drop" in entry for entry in logs.output))
|
|
||||||
self.assertFalse(any("[ZOOM DECISION]" in entry for entry in logs.output))
|
|
||||||
|
|
||||||
def start_pulse(self):
|
|
||||||
for _ in range(24):
|
|
||||||
row = self.tick(.1)
|
|
||||||
if any(axes[2] > 0 for axes in row["sent"]):
|
|
||||||
self.assertGreater(self.st["zoom_step_physical_request_id"], 0)
|
|
||||||
return
|
|
||||||
self.fail("No authorized zoom pulse in the offline fixture")
|
|
||||||
|
|
||||||
def log_fields(self, logs, tag):
|
|
||||||
entries = [entry for entry in logs.output if tag in entry]
|
|
||||||
self.assertEqual(len(entries), 1, logs.output)
|
|
||||||
return dict(part.split("=", 1) for part in entries[0].split(tag, 1)[1].split()
|
|
||||||
if "=" in part)
|
|
||||||
|
|
||||||
return [FrameDecision(name) for name in (
|
|
||||||
"test_frame_decision_joins_protective_stop_ack",
|
|
||||||
"test_center_history_is_distinct_from_current_sample",
|
|
||||||
"test_dropped_move_does_not_emit_decision",
|
|
||||||
)]
|
|
||||||
@ -1,250 +0,0 @@
|
|||||||
"""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,
|
|
||||||
*, threshold_diagnostics=False):
|
|
||||||
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,
|
|
||||||
patch.object(pp.logger, "info", wraps=pp.logger.info) as log):
|
|
||||||
row = self.tick(.06)
|
|
||||||
events = [call.args for call in log.call_args_list if "[ZOOM CONTINUE]" in call.args[0]]
|
|
||||||
self.assertEqual(len(events), int(fixed))
|
|
||||||
if events:
|
|
||||||
fmt, *values = events[0]
|
|
||||||
self.assertEqual(values[0:2], [self.cam, row["seq"]])
|
|
||||||
self.assertEqual(values[2], self.st["zoom_step_physical_request_id"])
|
|
||||||
self.assertEqual(values[3], self.st["ptz_generation"])
|
|
||||||
self.assertEqual(values[4:8], [10, .103, .106, deadline])
|
|
||||||
self.assertEqual(values[8:11], [.34, .40, .106])
|
|
||||||
self.assertIn("reason=same_native", fmt % tuple(values))
|
|
||||||
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")
|
|
||||||
with patch.object(pp.logger, "info", wraps=pp.logger.info) as log:
|
|
||||||
self.tick(.05, detector=False, score=.1)
|
|
||||||
self.assertFalse(any("[ZOOM CONTINUE]" in call.args[0] for call in log.call_args_list))
|
|
||||||
|
|
||||||
class Thresholds(controller_replay):
|
|
||||||
def begin_normal_pulse(self):
|
|
||||||
self.stack.enter_context(patch.object(config, "ZOOM_PROBE_ENABLE", False))
|
|
||||||
self.stack.enter_context(patch.object(config, "ZOOM_IDENTIFY_ENABLE", False))
|
|
||||||
self.stack.enter_context(patch.dict(config.CAMERA_CONFIG[self.cam], {"zoom_fast_approach": False}))
|
|
||||||
for _ in range(24):
|
|
||||||
row = self.tick(.1)
|
|
||||||
if any(axes[2] > 0 for axes in row["sent"]):
|
|
||||||
return self.st["zoom_step_physical_request_id"]
|
|
||||||
self.fail("Normal pulse did not start")
|
|
||||||
|
|
||||||
def test_response_framing_reports_the_rejected_frame(self):
|
|
||||||
request = self.begin_normal_pulse()
|
|
||||||
select = pp._select_zoom_response_timing
|
|
||||||
|
|
||||||
def with_excess_rate(st, **values):
|
|
||||||
return select(st, **{**values, "image_rate": .041})
|
|
||||||
|
|
||||||
with (patch.object(config, "ZOOM_STEP_PULSE_SEC", .10),
|
|
||||||
patch.object(pp, "_select_zoom_response_timing", side_effect=with_excess_rate),
|
|
||||||
patch.object(pp.logger, "info", wraps=pp.logger.info) as log):
|
|
||||||
row = self.tick(.06)
|
|
||||||
events = [c.args for c in log.call_args_list if "[ZOOM THRESHOLD]" in c.args[0]]
|
|
||||||
self.assertEqual(len(events), 1, (row, log.call_args_list))
|
|
||||||
fmt, cam, frame, logged_request, generation, reason, raw = events[0]
|
|
||||||
self.assertEqual((cam, frame, logged_request, reason),
|
|
||||||
(self.cam, row["seq"], request, "response_framing"))
|
|
||||||
detail = json.loads(raw)
|
|
||||||
self.assertEqual(detail["check"], "framing")
|
|
||||||
self.assertEqual((detail["image_rate"], detail["image_rate_max"]), (.041, .04))
|
|
||||||
self.assertEqual(row["sent"][-1], (0, 0, 0))
|
|
||||||
|
|
||||||
with (patch.object(config, "ZOOM_STEP_PULSE_SEC", .10),
|
|
||||||
patch.object(config, "AIM_GIMBAL_FF_VIDEO_LATENCY_SEC", .45),
|
|
||||||
patch.object(config, "PTZ_LENS_STOP_DIRECT_TIMEOUT_SEC", .75)):
|
|
||||||
for change, check, observed, limit in (
|
|
||||||
({"hfov_deg": 40., "image_rate": .021}, "narrow_fov", "image_rate", "image_rate_max"),
|
|
||||||
({"margin": .35, "image_rate": .04}, "projected_margin", "projected_margin", "margin_min"),
|
|
||||||
):
|
|
||||||
trace = {}
|
|
||||||
inputs = dict(useful=True, hfov_deg=59., wide_hfov_deg=59.,
|
|
||||||
center_err=.01, margin=.45, image_rate=.01)
|
|
||||||
inputs.update(change)
|
|
||||||
state = {"zoom_response_effective_sec": .34}
|
|
||||||
self.assertEqual(select(state, **inputs), (0., 0.))
|
|
||||||
self.assertEqual(select(state, rejection=trace, **inputs), (0., 0.))
|
|
||||||
self.assertEqual(trace["check"], check)
|
|
||||||
if check == "narrow_fov":
|
|
||||||
self.assertGreater(trace[observed], trace[limit])
|
|
||||||
else:
|
|
||||||
self.assertLess(trace[observed], trace[limit])
|
|
||||||
|
|
||||||
def test_size_controller_reports_the_failed_angle_and_zero_stage(self):
|
|
||||||
request = self.begin_normal_pulse()
|
|
||||||
safe = pp._zoom_angular_motion_safe
|
|
||||||
|
|
||||||
def with_excess_pan(**values):
|
|
||||||
return safe(**{**values, "pan_error_deg": 9., "pan_rate_deg_s": 0.})
|
|
||||||
|
|
||||||
with (patch.object(pp, "_zoom_angular_motion_safe", side_effect=with_excess_pan),
|
|
||||||
patch.object(pp, "_zoom_approach_margin", return_value=None),
|
|
||||||
patch.object(config, "Z_DEADBAND", .99),
|
|
||||||
patch.object(config, "ZOOM_V3_CMD_MAX_STEP", .2),
|
|
||||||
patch.object(pp, "_Z_I", 0.),
|
|
||||||
patch.object(pp, "_Z_FF_GAIN", 0.),
|
|
||||||
patch.object(pp.logger, "info", wraps=pp.logger.info) as log):
|
|
||||||
row = self.tick(.06)
|
|
||||||
events = [c.args for c in log.call_args_list if "[ZOOM THRESHOLD]" in c.args[0]]
|
|
||||||
self.assertEqual(len(events), 1, (row, log.call_args_list))
|
|
||||||
fmt, cam, frame, logged_request, generation, reason, raw = events[0]
|
|
||||||
self.assertEqual((cam, frame, logged_request, reason),
|
|
||||||
(self.cam, row["seq"], request, "size_controller"))
|
|
||||||
detail = json.loads(raw)
|
|
||||||
self.assertEqual(detail["angular"]["pan_error_deg"], 9.)
|
|
||||||
self.assertIn("pan_error", detail["angular"]["failed"])
|
|
||||||
self.assertLess(detail["angular"]["pan_limit_deg"], 9.)
|
|
||||||
self.assertEqual((detail["size_error"], detail["after_minimum"]), (0., 0.))
|
|
||||||
self.assertEqual(row["sent"][-1], (0, 0, 0))
|
|
||||||
|
|
||||||
cases = [
|
|
||||||
NativeFloor("test_observed_native10_windows"),
|
|
||||||
NativeFloor("test_stop_vetoes_keep_zero"),
|
|
||||||
FrameFloor("test_track_frame_uses_native_continuation"),
|
|
||||||
]
|
|
||||||
if threshold_diagnostics:
|
|
||||||
cases += [
|
|
||||||
Thresholds("test_response_framing_reports_the_rejected_frame"),
|
|
||||||
Thresholds("test_size_controller_reports_the_failed_angle_and_zero_stage"),
|
|
||||||
]
|
|
||||||
return cases
|
|
||||||
@ -1,9 +0,0 @@
|
|||||||
{
|
|
||||||
"baseline_tests_passed": 10,
|
|
||||||
"candidate_tests_passed": 13,
|
|
||||||
"historical_worker_cases_matched": 19,
|
|
||||||
"shared_controller_frames_identical": 23,
|
|
||||||
"real_camera_or_model_access": false,
|
|
||||||
"patch_apply_and_reverse_byte_exact": true,
|
|
||||||
"historical_decision_reason_recovered": false
|
|
||||||
}
|
|
||||||
Loading…
Reference in New Issue