"""时序防抖:把逐帧观测稳定成可直接下发给 PLC 的判决。 现场难点 -------- * 吊具/箱子在动,单帧结果会跳(尤其"车斗/平板车"边界模糊时); * 起重机振动、逆光、雨雾会造成偶发漏检; * PLC 需要的是"稳定、可联锁"的结果,而不是每帧都变的状态码。 因此这里做三件事: 1. **滑窗投票**:最近 ``window`` 帧(或 ``window_s`` 秒)内同一状态票数达到 ``min_votes`` 且平均置信度达到 ``min_confidence`` 才算候选; 2. **最小驻留**:候选状态要连续保持 ``min_dwell_s`` 才真正提交,避免毛刺。 **冷启动的 UNKNOWN 也走同一套门限**:首帧、复位后的第一帧都不得直接 commit, 必须等票数与驻留同时满足;否则跟踪器一上电就可能把单帧误检当成结果送给 PLC。 3. **保持/丢失**:短暂没有有效观测时先保持上一状态(``hold_s``,此时 ``stable=False`` 提示 PLC "别动作"),超过 ``lost_timeout_s`` 才置 ``UNKNOWN``(PLC 应回安全逻辑)。 状态每次提交变化时 ``seq + 1``,PLC 用它判断"是否有新结果"。 """ from __future__ import annotations import time from collections import deque from typing import Deque, Dict, List, Optional, Tuple from ..config import Config from ..schema import Decision, Observation, SceneState, STATE_LABELS __all__ = ["TemporalVoter"] class TemporalVoter: """滑窗投票 + 最小驻留 + 保持/丢失超时。""" def __init__( self, window: int = 9, window_s: float = 1.0, min_votes: int = 4, min_confidence: float = 0.45, min_dwell_s: float = 0.20, hold_s: float = 0.60, lost_timeout_s: float = 1.50, ) -> None: self.window = max(1, int(window)) self.window_s = max(0.0, float(window_s)) self.min_votes = max(1, int(min_votes)) self.min_confidence = float(min_confidence) self.min_dwell_s = max(0.0, float(min_dwell_s)) self.hold_s = max(0.0, float(hold_s)) self.lost_timeout_s = max(self.hold_s, float(lost_timeout_s)) self._obs: Deque[Tuple[float, int, float]] = deque(maxlen=self.window) self._state: int = int(SceneState.UNKNOWN) self._conf: float = 0.0 self._since: float = 0.0 self._seq: int = 0 self._reason: str = "init" self._last_ts: float = 0.0 self._last_valid_ts: float = 0.0 self._pending: Optional[int] = None self._pending_since: float = 0.0 self._commits: Dict[int, int] = {} # ------------------------------------------------------------- 构造 @classmethod def from_config(cls, cfg: Config) -> "TemporalVoter": d = cfg.section("decision") return cls( window=d.get("window", 9), window_s=d.get("window_s", 1.0), min_votes=d.get("min_votes", 4), min_confidence=d.get("min_confidence", 0.45), min_dwell_s=d.get("min_dwell_s", 0.20), hold_s=d.get("hold_s", 0.60), lost_timeout_s=d.get("lost_timeout_s", 1.50), ) # ------------------------------------------------------------- 属性 @property def state(self) -> int: return self._state @property def seq(self) -> int: return self._seq @property def commit_counts(self) -> Dict[int, int]: return {STATE_LABELS.get(k, str(k)): v for k, v in self._commits.items()} def reset(self) -> None: """复位到初始状态(PLC 下复位命令或重连时调用)。""" self._obs.clear() self._state = int(SceneState.UNKNOWN) self._conf = 0.0 self._since = 0.0 self._reason = "reset" self._pending = None self._pending_since = 0.0 # ------------------------------------------------------------- 主入口 def update(self, obs: Observation) -> Decision: """喂入一帧观测,返回当前判决。""" ts = float(obs.ts) if ts < self._last_ts: # 时钟回拨/乱序,夹紧保证单调 ts = self._last_ts self._last_ts = ts valid = obs.is_valid and float(obs.confidence) >= self.min_confidence if valid: self._obs.append((ts, int(obs.state), float(obs.confidence))) self._last_valid_ts = ts self._prune(ts) candidate, cand_conf = self._vote() changed = False reason = obs.reason if candidate is None: # 没有可信候选:先保持,再超时置 UNKNOWN gap = ts - self._last_valid_ts if self._last_valid_ts > 0 else ts if self._state != int(SceneState.UNKNOWN) and gap > self.lost_timeout_s: changed = self._commit(int(SceneState.UNKNOWN), 0.0, ts, "lost_timeout") elif self._state != int(SceneState.UNKNOWN) and gap > self.hold_s: self._reason = "hold(lost=%.2fs)" % gap else: self._reason = obs.reason or "no_candidate" elif candidate == self._state: self._pending = None self._conf = cand_conf if obs.reason: self._reason = obs.reason else: # 候选与当前状态不同:需要连续驻留 min_dwell_s。 # 注意:这里**不再**给 UNKNOWN 开绿灯。冷启动/复位后的第一帧可能 # 只有一个观测,单帧误检(如箱侧壁被当成车斗门板)必须在驻留门 # 之前就被挡住,不能直接 commit 给 PLC。 if self._pending != candidate: self._pending = candidate self._pending_since = self._candidate_since(candidate, ts) if ( ts - self._pending_since >= self.min_dwell_s and ts > self._pending_since and len(self._obs) >= 2 ): changed = self._commit(candidate, cand_conf, ts, obs.reason or "vote") stable = ( self._state != int(SceneState.UNKNOWN) and (ts - self._since) >= self.min_dwell_s and (ts - self._last_valid_ts) <= self.hold_s ) return Decision( state=int(self._state), confidence=float(self._conf), stable=bool(stable), seq=int(self._seq), since_ts=float(self._since), reason=self._reason, changed=bool(changed), ) # ------------------------------------------------------------- 内部 def _prune(self, now: float) -> None: if self.window_s <= 0: return while self._obs and (now - self._obs[0][0]) > self.window_s: self._obs.popleft() def _vote(self) -> Tuple[Optional[int], float]: """滑窗投票。返回 ``(状态, 平均置信度)``;票数不足返回 ``(None, 0)``。""" if not self._obs: return None, 0.0 stats: Dict[int, List[float]] = {} for _ts, state, conf in self._obs: stats.setdefault(int(state), []).append(float(conf)) best_state = max(stats.keys(), key=lambda s: (len(stats[s]), sum(stats[s]))) confs = stats[best_state] required = min(self.min_votes, len(self._obs)) if len(confs) < required: return None, 0.0 return int(best_state), float(sum(confs) / len(confs)) def _candidate_since(self, candidate: int, now: float) -> float: """候选状态在窗口内连续出现的最早时间戳(没有则用 now)。""" since = now for ts, state, _conf in reversed(self._obs): if int(state) != int(candidate): break since = ts return since def _commit(self, state: int, conf: float, ts: float, reason: str) -> bool: changed = int(state) != int(self._state) if changed: self._state = int(state) self._since = ts self._seq += 1 self._commits[int(state)] = self._commits.get(int(state), 0) + 1 self._conf = float(conf) self._reason = reason or self._reason self._pending = None return changed def current(self) -> Decision: """不喂新观测,取当前判决(用于心跳发布)。""" now = self._last_ts or time.time() stable = ( self._state != int(SceneState.UNKNOWN) and (now - self._since) >= self.min_dwell_s and (now - self._last_valid_ts) <= self.hold_s ) return Decision( state=int(self._state), confidence=float(self._conf), stable=bool(stable), seq=int(self._seq), since_ts=float(self._since), reason=self._reason, changed=False, )