commit.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. """P1c:落位(commit)相位判定。
  2. 为什么需要单独的 commit 门
  3. ---------------------------
  4. ``evidence_v2`` 回答的是“这一帧看起来像 1 还是 2”;PLC 真正需要的是
  5. “**箱已经落到位,可以按这个车型执行落箱工艺**”。两者不能混为一谈:
  6. * A 片段(C70 敞车 + 罐箱)在 clip 结束时仍差 ≈0.2 m,但单帧间隙只有
  7. 9–12 px,按 0.10 m 的单一阈值可能误命中;
  8. * B 片段(X70 平车)落位帧间隙只有 3 px,必须允许提交。
  9. 因此本模块用**组合条件**而不是单一阈值:
  10. 1. ``gap_m <= gap_m_max``(默认 0.10 m);
  11. 2. **安全硬门** ``gap_px <= gap_px_hard_max``(默认 8 px)——前视模式箱底
  12. 像素本身有 ±5 px 不确定度,0.10 m 在 115 px/m 下约 11.5 px;加这条
  13. 可以确保 A 的 9–12 px 不会提交,同时 B 的 3 px 仍能通过;
  14. 3. 最近 ``stable_frames`` 帧状态一致、结构证据持续成立;
  15. 4. 运动门控通过,间隙没有明显回升;
  16. 5. 可选 PLC “到位 / 吊具松开”信号可**替代**间隙门(但仍需结构与稳定帧)。
  17. ``allow_state2`` 默认 **True**(现场验收后已打开):平车 `2` 与 `1` 一样进入
  18. commit;置 false 可回退为“只识别、不提交”。顶层 ``evidence_v2.allow_state2``
  19. 与 ``evidence_v2.commit.allow_state2`` 串联,任一 false 都会关闭提交。
  20. 本模块不依赖 OpenCV / numpy,只做状态机;图像特征由
  21. :mod:`portcv.logic.evidence_v2` 提供。
  22. """
  23. from __future__ import annotations
  24. from collections import deque
  25. from dataclasses import dataclass
  26. from typing import Deque, Optional, Tuple
  27. from ..config import Config
  28. __all__ = [
  29. "CommitParams",
  30. "CommitState",
  31. "CommitTracker",
  32. "DEFAULT_GAP_M_MAX",
  33. "DEFAULT_GAP_PX_HARD_MAX",
  34. ]
  35. #: 路线文档锁定的间隙门(米)。
  36. DEFAULT_GAP_M_MAX = 0.10
  37. #: 前视箱底像素不确定度对应的安全硬门(≈0.07 m @ 115 px/m)。
  38. DEFAULT_GAP_PX_HARD_MAX = 8.0
  39. #: 箱底与车面直接贴合(flat_contact 归零)的容差;该分支不要求 px_per_m。
  40. CONTACT_GAP_PX = 1.0
  41. @dataclass(frozen=True)
  42. class CommitParams:
  43. """commit 门参数(对应配置段 ``evidence_v2.commit.*``)。"""
  44. gap_m_max: float = DEFAULT_GAP_M_MAX
  45. gap_px_hard_max: float = DEFAULT_GAP_PX_HARD_MAX
  46. stable_frames: int = 5
  47. structure_frames: int = 5
  48. min_structure_hits: float = 0.60
  49. max_gap_rise_m: float = 0.01
  50. allow_state1: bool = True
  51. allow_state2: bool = True
  52. # P0-Q9:空车 state=3 是否允许提交。false = 只识别、不提交(与 allow_state2 同构)。
  53. allow_state3: bool = True
  54. require_motion_ok: bool = True
  55. require_view_known: bool = True
  56. use_plc_arrival: bool = True
  57. def __post_init__(self) -> None:
  58. if self.gap_m_max < 0.0:
  59. raise ValueError("gap_m_max 不能为负")
  60. if self.gap_px_hard_max < 0.0:
  61. raise ValueError("gap_px_hard_max 不能为负")
  62. if self.stable_frames < 1:
  63. raise ValueError("stable_frames 至少为 1")
  64. if self.structure_frames < 1:
  65. raise ValueError("structure_frames 至少为 1")
  66. if not 0.0 <= self.min_structure_hits <= 1.0:
  67. raise ValueError("min_structure_hits 必须在 0..1")
  68. @classmethod
  69. def from_config(cls, cfg: Config) -> "CommitParams":
  70. section = cfg.section("evidence_v2")
  71. raw = section.get("commit") or {}
  72. # 与 C++ `apply_evidence_v2` 同口径:顶层与 commit 两个开关串联,任一 false 即关闭。
  73. allow_state2 = bool(raw.get("allow_state2", True)) and bool(
  74. section.get("allow_state2", True)
  75. )
  76. allow_state3 = bool(raw.get("allow_state3", True)) and bool(
  77. section.get("allow_state3", True)
  78. )
  79. return cls(
  80. gap_m_max=float(raw.get("gap_m_max", DEFAULT_GAP_M_MAX)),
  81. gap_px_hard_max=float(raw.get("gap_px_hard_max", DEFAULT_GAP_PX_HARD_MAX)),
  82. stable_frames=int(raw.get("stable_frames", 5)),
  83. structure_frames=int(raw.get("structure_frames", 5)),
  84. min_structure_hits=float(raw.get("min_structure_hits", 0.60)),
  85. max_gap_rise_m=float(raw.get("max_gap_rise_m", 0.01)),
  86. allow_state1=bool(raw.get("allow_state1", True)),
  87. allow_state2=allow_state2,
  88. allow_state3=allow_state3,
  89. require_motion_ok=bool(raw.get("require_motion_ok", True)),
  90. require_view_known=bool(raw.get("require_view_known", True)),
  91. use_plc_arrival=bool(raw.get("use_plc_arrival", True)),
  92. )
  93. @dataclass(frozen=True)
  94. class CommitState:
  95. """``CommitTracker.update()`` 的输出(可直接写进 evidence 诊断)。"""
  96. committed: bool
  97. phase: str # T1 / T2 / T3
  98. reason: str
  99. gap_m: Optional[float] = None
  100. gap_px: Optional[float] = None
  101. stable_frames: int = 0
  102. structure_frames: int = 0
  103. gap_slope_m_per_s: Optional[float] = None
  104. plc_arrival: bool = False
  105. hoist_high: bool = False
  106. def to_dict(self) -> dict:
  107. return {
  108. "committed": bool(self.committed),
  109. "phase": self.phase,
  110. "reason": self.reason,
  111. "gap_m": None if self.gap_m is None else round(float(self.gap_m), 4),
  112. "gap_px": None if self.gap_px is None else round(float(self.gap_px), 2),
  113. "stable_frames": int(self.stable_frames),
  114. "structure_frames": int(self.structure_frames),
  115. "gap_slope_m_per_s": (
  116. None if self.gap_slope_m_per_s is None
  117. else round(float(self.gap_slope_m_per_s), 4)
  118. ),
  119. "plc_arrival": bool(self.plc_arrival),
  120. "hoist_high": bool(self.hoist_high),
  121. }
  122. @dataclass
  123. class _Sample:
  124. ts: float
  125. state: int
  126. gap_m: Optional[float]
  127. gap_px: Optional[float]
  128. structure_ok: bool
  129. motion_ok: bool
  130. class CommitTracker:
  131. """有状态的 commit 判定器(线程内使用、非线程安全)。"""
  132. def __init__(self, params: Optional[CommitParams] = None) -> None:
  133. self.p = params or CommitParams()
  134. self._samples: Deque[_Sample] = deque(maxlen=256)
  135. self._last_ts = 0.0
  136. self._last = CommitState(False, "T1", "init")
  137. @classmethod
  138. def from_config(cls, cfg: Config) -> "CommitTracker":
  139. return cls(CommitParams.from_config(cfg))
  140. @property
  141. def params(self) -> CommitParams:
  142. return self.p
  143. @property
  144. def last(self) -> CommitState:
  145. return self._last
  146. def reset(self) -> None:
  147. self._samples.clear()
  148. self._last_ts = 0.0
  149. self._last = CommitState(False, "T1", "reset")
  150. # ---------------------------------------------------------------- 主入口
  151. def update(
  152. self,
  153. ts: float,
  154. *,
  155. state: int,
  156. gap_m: Optional[float],
  157. gap_px: Optional[float],
  158. structure_hits: float = 1.0,
  159. motion_ok: bool = True,
  160. view_known: bool = True,
  161. plc_arrived: bool = False,
  162. plc_spreader_released: bool = False,
  163. hoist_high: bool = False,
  164. ) -> CommitState:
  165. """喂入一帧证据,返回是否允许提交。
  166. ``state`` 是 ``evidence_v2`` 的**单帧分类结果**(0/1/2/255);
  167. ``structure_hits`` 是该帧结构证据强度(0..1),不是像素计数。
  168. ``hoist_high`` 表示画面出现吊具/钢缆/臂架高悬特征:箱体尚未落位,
  169. 无论间隙看起来多小都不得提交(安全门优先于所有几何门)。
  170. """
  171. now = float(ts)
  172. if now < self._last_ts:
  173. now = self._last_ts
  174. self._last_ts = now
  175. state = int(state)
  176. structure_ok = float(structure_hits) >= self.p.min_structure_hits
  177. arrival = bool(
  178. self.p.use_plc_arrival and (plc_arrived or plc_spreader_released)
  179. )
  180. # 安全门:吊具/钢缆/臂架仍在画面上方,说明箱体未落位。即使视觉
  181. # 把箱侧壁误当成车斗门板、算出“零间隙”,也不得累计 commit 帧。
  182. # 这一分支不写 _samples,避免高悬消失后立刻复用之前的窗口。
  183. if hoist_high:
  184. self._last = CommitState(
  185. False, "T3", "hoist_high", gap_m, gap_px, 0, 0, None, arrival, True
  186. )
  187. return self._last
  188. if state not in (0, 1, 2, 3):
  189. self._last = CommitState(
  190. False, "T3" if not motion_ok else "T1", "state_unknown",
  191. gap_m, gap_px, 0, 0, None, arrival,
  192. )
  193. return self._last
  194. if state == 1 and not self.p.allow_state1:
  195. self._last = CommitState(False, "T1", "state1_disabled",
  196. gap_m, gap_px, 0, 0, None, arrival)
  197. return self._last
  198. if state == 2 and not self.p.allow_state2:
  199. # 平车在 PLC 签字前只识别、不提交;仍记录窗口,便于诊断。
  200. self._append(now, state, gap_m, gap_px, structure_ok, motion_ok)
  201. self._last = CommitState(False, "T1", "state2_disabled",
  202. gap_m, gap_px, 0, 0, None, arrival)
  203. return self._last
  204. if state == 3 and not self.p.allow_state3:
  205. # 空车 3 同理:只识别、不提交(现场可先观察再打开)。
  206. self._append(now, state, gap_m, gap_px, structure_ok, motion_ok)
  207. self._last = CommitState(False, "T1", "state3_disabled",
  208. gap_m, gap_px, 0, 0, None, arrival)
  209. return self._last
  210. self._append(now, state, gap_m, gap_px, structure_ok, motion_ok)
  211. if not motion_ok and self.p.require_motion_ok:
  212. self._last = CommitState(False, "T3", "motion", gap_m, gap_px,
  213. 0, 0, None, arrival)
  214. return self._last
  215. if not view_known and self.p.require_view_known:
  216. self._last = CommitState(False, "T1", "view_unknown", gap_m, gap_px,
  217. 0, 0, None, arrival)
  218. return self._last
  219. # 0 是“其他/不在车上”,不需要间隙门;仍需稳定帧与正面证据。
  220. gap_ok = True
  221. if state in (1, 2):
  222. if arrival:
  223. gap_ok = True
  224. else:
  225. contact = gap_px is not None and float(gap_px) <= CONTACT_GAP_PX
  226. gap_ok = (
  227. gap_px is not None
  228. and float(gap_px) <= self.p.gap_px_hard_max
  229. and (
  230. contact
  231. or (
  232. gap_m is not None
  233. and float(gap_m) <= self.p.gap_m_max
  234. )
  235. )
  236. )
  237. window = self._window(max(self.p.stable_frames, self.p.structure_frames))
  238. stable_n = self._same_state_run(state)
  239. structure_n = sum(1 for s in window if s.structure_ok)
  240. gap_n = sum(1 for s in window if self._gap_ok(s, arrival))
  241. slope = self._gap_slope(window)
  242. stable_enough = stable_n >= self.p.stable_frames
  243. structure_enough = structure_n >= self.p.structure_frames
  244. gap_enough = gap_n >= self.p.stable_frames
  245. not_rising = slope is None or slope <= self.p.max_gap_rise_m
  246. phase = "T2" if gap_ok else "T1"
  247. committed = bool(
  248. gap_ok and stable_enough and structure_enough and gap_enough and not_rising
  249. )
  250. reason_parts = []
  251. if not gap_ok:
  252. reason_parts.append("gap")
  253. if not stable_enough:
  254. reason_parts.append("stable=%d/%d" % (stable_n, self.p.stable_frames))
  255. if not structure_enough:
  256. reason_parts.append("structure=%d/%d" % (structure_n, self.p.structure_frames))
  257. if not gap_enough:
  258. reason_parts.append("gap_window=%d/%d" % (gap_n, self.p.stable_frames))
  259. if not not_rising:
  260. reason_parts.append("gap_rising")
  261. reason = "commit" if committed else (
  262. "wait:" + ",".join(reason_parts) if reason_parts else "wait"
  263. )
  264. if arrival and committed:
  265. reason = "commit:plc_arrival"
  266. self._last = CommitState(
  267. committed=committed,
  268. phase=phase,
  269. reason=reason,
  270. gap_m=gap_m,
  271. gap_px=gap_px,
  272. stable_frames=int(stable_n),
  273. structure_frames=int(structure_n),
  274. gap_slope_m_per_s=slope,
  275. plc_arrival=arrival,
  276. )
  277. return self._last
  278. # ---------------------------------------------------------------- 内部
  279. def _append(
  280. self,
  281. ts: float,
  282. state: int,
  283. gap_m: Optional[float],
  284. gap_px: Optional[float],
  285. structure_ok: bool,
  286. motion_ok: bool,
  287. ) -> None:
  288. self._samples.append(
  289. _Sample(ts, int(state), gap_m, gap_px, bool(structure_ok), bool(motion_ok))
  290. )
  291. def _window(self, n: int) -> Tuple[_Sample, ...]:
  292. if n <= 0:
  293. return tuple()
  294. return tuple(list(self._samples)[-n:])
  295. def _same_state_run(self, state: int) -> int:
  296. count = 0
  297. for sample in reversed(self._samples):
  298. if sample.state != int(state):
  299. break
  300. count += 1
  301. return count
  302. def _gap_ok(self, sample: _Sample, arrival: bool) -> bool:
  303. if sample.state == 0 or arrival:
  304. return True
  305. if sample.gap_px is None or float(sample.gap_px) > self.p.gap_px_hard_max:
  306. return False
  307. # 零间隙 = 已直接接触:没有 px_per_m 时 gap_m 为空,不能因此拒绝。
  308. if float(sample.gap_px) <= CONTACT_GAP_PX:
  309. return True
  310. return bool(
  311. sample.gap_m is not None
  312. and float(sample.gap_m) <= self.p.gap_m_max
  313. )
  314. def _gap_slope(self, window: Tuple[_Sample, ...]) -> Optional[float]:
  315. points = [(s.ts, s.gap_m) for s in window if s.gap_m is not None]
  316. if len(points) < 2:
  317. return None
  318. t0, g0 = points[0]
  319. t1, g1 = points[-1]
  320. dt = float(t1) - float(t0)
  321. if dt <= 1e-6:
  322. return None
  323. return (float(g1) - float(g0)) / dt