decision.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. """时序防抖:把逐帧观测稳定成可直接下发给 PLC 的判决。
  2. 现场难点
  3. --------
  4. * 吊具/箱子在动,单帧结果会跳(尤其"车斗/平板车"边界模糊时);
  5. * 起重机振动、逆光、雨雾会造成偶发漏检;
  6. * PLC 需要的是"稳定、可联锁"的结果,而不是每帧都变的状态码。
  7. 因此这里做三件事:
  8. 1. **滑窗投票**:最近 ``window`` 帧(或 ``window_s`` 秒)内同一状态票数达到
  9. ``min_votes`` 且平均置信度达到 ``min_confidence`` 才算候选;
  10. 2. **最小驻留**:候选状态要连续保持 ``min_dwell_s`` 才真正提交,避免毛刺。
  11. **冷启动的 UNKNOWN 也走同一套门限**:首帧、复位后的第一帧都不得直接 commit,
  12. 必须等票数与驻留同时满足;否则跟踪器一上电就可能把单帧误检当成结果送给 PLC。
  13. 3. **保持/丢失**:短暂没有有效观测时先保持上一状态(``hold_s``,此时 ``stable=False``
  14. 提示 PLC "别动作"),超过 ``lost_timeout_s`` 才置 ``UNKNOWN``(PLC 应回安全逻辑)。
  15. 状态每次提交变化时 ``seq + 1``,PLC 用它判断"是否有新结果"。
  16. """
  17. from __future__ import annotations
  18. import time
  19. from collections import deque
  20. from typing import Deque, Dict, List, Optional, Tuple
  21. from ..config import Config
  22. from ..schema import Decision, Observation, SceneState, STATE_LABELS
  23. __all__ = ["TemporalVoter"]
  24. class TemporalVoter:
  25. """滑窗投票 + 最小驻留 + 保持/丢失超时。"""
  26. def __init__(
  27. self,
  28. window: int = 9,
  29. window_s: float = 1.0,
  30. min_votes: int = 4,
  31. min_confidence: float = 0.45,
  32. min_dwell_s: float = 0.20,
  33. hold_s: float = 0.60,
  34. lost_timeout_s: float = 1.50,
  35. ) -> None:
  36. self.window = max(1, int(window))
  37. self.window_s = max(0.0, float(window_s))
  38. self.min_votes = max(1, int(min_votes))
  39. self.min_confidence = float(min_confidence)
  40. self.min_dwell_s = max(0.0, float(min_dwell_s))
  41. self.hold_s = max(0.0, float(hold_s))
  42. self.lost_timeout_s = max(self.hold_s, float(lost_timeout_s))
  43. self._obs: Deque[Tuple[float, int, float]] = deque(maxlen=self.window)
  44. self._state: int = int(SceneState.UNKNOWN)
  45. self._conf: float = 0.0
  46. self._since: float = 0.0
  47. self._seq: int = 0
  48. self._reason: str = "init"
  49. self._last_ts: float = 0.0
  50. self._last_valid_ts: float = 0.0
  51. self._pending: Optional[int] = None
  52. self._pending_since: float = 0.0
  53. self._commits: Dict[int, int] = {}
  54. # ------------------------------------------------------------- 构造
  55. @classmethod
  56. def from_config(cls, cfg: Config) -> "TemporalVoter":
  57. d = cfg.section("decision")
  58. return cls(
  59. window=d.get("window", 9),
  60. window_s=d.get("window_s", 1.0),
  61. min_votes=d.get("min_votes", 4),
  62. min_confidence=d.get("min_confidence", 0.45),
  63. min_dwell_s=d.get("min_dwell_s", 0.20),
  64. hold_s=d.get("hold_s", 0.60),
  65. lost_timeout_s=d.get("lost_timeout_s", 1.50),
  66. )
  67. # ------------------------------------------------------------- 属性
  68. @property
  69. def state(self) -> int:
  70. return self._state
  71. @property
  72. def seq(self) -> int:
  73. return self._seq
  74. @property
  75. def commit_counts(self) -> Dict[int, int]:
  76. return {STATE_LABELS.get(k, str(k)): v for k, v in self._commits.items()}
  77. def reset(self) -> None:
  78. """复位到初始状态(PLC 下复位命令或重连时调用)。"""
  79. self._obs.clear()
  80. self._state = int(SceneState.UNKNOWN)
  81. self._conf = 0.0
  82. self._since = 0.0
  83. self._reason = "reset"
  84. self._pending = None
  85. self._pending_since = 0.0
  86. # ------------------------------------------------------------- 主入口
  87. def update(self, obs: Observation) -> Decision:
  88. """喂入一帧观测,返回当前判决。"""
  89. ts = float(obs.ts)
  90. if ts < self._last_ts: # 时钟回拨/乱序,夹紧保证单调
  91. ts = self._last_ts
  92. self._last_ts = ts
  93. valid = obs.is_valid and float(obs.confidence) >= self.min_confidence
  94. if valid:
  95. self._obs.append((ts, int(obs.state), float(obs.confidence)))
  96. self._last_valid_ts = ts
  97. self._prune(ts)
  98. candidate, cand_conf = self._vote()
  99. changed = False
  100. reason = obs.reason
  101. if candidate is None:
  102. # 没有可信候选:先保持,再超时置 UNKNOWN
  103. gap = ts - self._last_valid_ts if self._last_valid_ts > 0 else ts
  104. if self._state != int(SceneState.UNKNOWN) and gap > self.lost_timeout_s:
  105. changed = self._commit(int(SceneState.UNKNOWN), 0.0, ts, "lost_timeout")
  106. elif self._state != int(SceneState.UNKNOWN) and gap > self.hold_s:
  107. self._reason = "hold(lost=%.2fs)" % gap
  108. else:
  109. self._reason = obs.reason or "no_candidate"
  110. elif candidate == self._state:
  111. self._pending = None
  112. self._conf = cand_conf
  113. if obs.reason:
  114. self._reason = obs.reason
  115. else:
  116. # 候选与当前状态不同:需要连续驻留 min_dwell_s。
  117. # 注意:这里**不再**给 UNKNOWN 开绿灯。冷启动/复位后的第一帧可能
  118. # 只有一个观测,单帧误检(如箱侧壁被当成车斗门板)必须在驻留门
  119. # 之前就被挡住,不能直接 commit 给 PLC。
  120. if self._pending != candidate:
  121. self._pending = candidate
  122. self._pending_since = self._candidate_since(candidate, ts)
  123. if (
  124. ts - self._pending_since >= self.min_dwell_s
  125. and ts > self._pending_since
  126. and len(self._obs) >= 2
  127. ):
  128. changed = self._commit(candidate, cand_conf, ts, obs.reason or "vote")
  129. stable = (
  130. self._state != int(SceneState.UNKNOWN)
  131. and (ts - self._since) >= self.min_dwell_s
  132. and (ts - self._last_valid_ts) <= self.hold_s
  133. )
  134. return Decision(
  135. state=int(self._state),
  136. confidence=float(self._conf),
  137. stable=bool(stable),
  138. seq=int(self._seq),
  139. since_ts=float(self._since),
  140. reason=self._reason,
  141. changed=bool(changed),
  142. )
  143. # ------------------------------------------------------------- 内部
  144. def _prune(self, now: float) -> None:
  145. if self.window_s <= 0:
  146. return
  147. while self._obs and (now - self._obs[0][0]) > self.window_s:
  148. self._obs.popleft()
  149. def _vote(self) -> Tuple[Optional[int], float]:
  150. """滑窗投票。返回 ``(状态, 平均置信度)``;票数不足返回 ``(None, 0)``。"""
  151. if not self._obs:
  152. return None, 0.0
  153. stats: Dict[int, List[float]] = {}
  154. for _ts, state, conf in self._obs:
  155. stats.setdefault(int(state), []).append(float(conf))
  156. best_state = max(stats.keys(), key=lambda s: (len(stats[s]), sum(stats[s])))
  157. confs = stats[best_state]
  158. required = min(self.min_votes, len(self._obs))
  159. if len(confs) < required:
  160. return None, 0.0
  161. return int(best_state), float(sum(confs) / len(confs))
  162. def _candidate_since(self, candidate: int, now: float) -> float:
  163. """候选状态在窗口内连续出现的最早时间戳(没有则用 now)。"""
  164. since = now
  165. for ts, state, _conf in reversed(self._obs):
  166. if int(state) != int(candidate):
  167. break
  168. since = ts
  169. return since
  170. def _commit(self, state: int, conf: float, ts: float, reason: str) -> bool:
  171. changed = int(state) != int(self._state)
  172. if changed:
  173. self._state = int(state)
  174. self._since = ts
  175. self._seq += 1
  176. self._commits[int(state)] = self._commits.get(int(state), 0) + 1
  177. self._conf = float(conf)
  178. self._reason = reason or self._reason
  179. self._pending = None
  180. return changed
  181. def current(self) -> Decision:
  182. """不喂新观测,取当前判决(用于心跳发布)。"""
  183. now = self._last_ts or time.time()
  184. stable = (
  185. self._state != int(SceneState.UNKNOWN)
  186. and (now - self._since) >= self.min_dwell_s
  187. and (now - self._last_valid_ts) <= self.hold_s
  188. )
  189. return Decision(
  190. state=int(self._state),
  191. confidence=float(self._conf),
  192. stable=bool(stable),
  193. seq=int(self._seq),
  194. since_ts=float(self._since),
  195. reason=self._reason,
  196. changed=False,
  197. )