commit.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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. require_motion_ok: bool = True
  53. require_view_known: bool = True
  54. use_plc_arrival: bool = True
  55. def __post_init__(self) -> None:
  56. if self.gap_m_max < 0.0:
  57. raise ValueError("gap_m_max 不能为负")
  58. if self.gap_px_hard_max < 0.0:
  59. raise ValueError("gap_px_hard_max 不能为负")
  60. if self.stable_frames < 1:
  61. raise ValueError("stable_frames 至少为 1")
  62. if self.structure_frames < 1:
  63. raise ValueError("structure_frames 至少为 1")
  64. if not 0.0 <= self.min_structure_hits <= 1.0:
  65. raise ValueError("min_structure_hits 必须在 0..1")
  66. @classmethod
  67. def from_config(cls, cfg: Config) -> "CommitParams":
  68. section = cfg.section("evidence_v2")
  69. raw = section.get("commit") or {}
  70. # 与 C++ `apply_evidence_v2` 同口径:顶层与 commit 两个开关串联,任一 false 即关闭。
  71. allow_state2 = bool(raw.get("allow_state2", True)) and bool(
  72. section.get("allow_state2", True)
  73. )
  74. return cls(
  75. gap_m_max=float(raw.get("gap_m_max", DEFAULT_GAP_M_MAX)),
  76. gap_px_hard_max=float(raw.get("gap_px_hard_max", DEFAULT_GAP_PX_HARD_MAX)),
  77. stable_frames=int(raw.get("stable_frames", 5)),
  78. structure_frames=int(raw.get("structure_frames", 5)),
  79. min_structure_hits=float(raw.get("min_structure_hits", 0.60)),
  80. max_gap_rise_m=float(raw.get("max_gap_rise_m", 0.01)),
  81. allow_state1=bool(raw.get("allow_state1", True)),
  82. allow_state2=allow_state2,
  83. require_motion_ok=bool(raw.get("require_motion_ok", True)),
  84. require_view_known=bool(raw.get("require_view_known", True)),
  85. use_plc_arrival=bool(raw.get("use_plc_arrival", True)),
  86. )
  87. @dataclass(frozen=True)
  88. class CommitState:
  89. """``CommitTracker.update()`` 的输出(可直接写进 evidence 诊断)。"""
  90. committed: bool
  91. phase: str # T1 / T2 / T3
  92. reason: str
  93. gap_m: Optional[float] = None
  94. gap_px: Optional[float] = None
  95. stable_frames: int = 0
  96. structure_frames: int = 0
  97. gap_slope_m_per_s: Optional[float] = None
  98. plc_arrival: bool = False
  99. hoist_high: bool = False
  100. def to_dict(self) -> dict:
  101. return {
  102. "committed": bool(self.committed),
  103. "phase": self.phase,
  104. "reason": self.reason,
  105. "gap_m": None if self.gap_m is None else round(float(self.gap_m), 4),
  106. "gap_px": None if self.gap_px is None else round(float(self.gap_px), 2),
  107. "stable_frames": int(self.stable_frames),
  108. "structure_frames": int(self.structure_frames),
  109. "gap_slope_m_per_s": (
  110. None if self.gap_slope_m_per_s is None
  111. else round(float(self.gap_slope_m_per_s), 4)
  112. ),
  113. "plc_arrival": bool(self.plc_arrival),
  114. "hoist_high": bool(self.hoist_high),
  115. }
  116. @dataclass
  117. class _Sample:
  118. ts: float
  119. state: int
  120. gap_m: Optional[float]
  121. gap_px: Optional[float]
  122. structure_ok: bool
  123. motion_ok: bool
  124. class CommitTracker:
  125. """有状态的 commit 判定器(线程内使用、非线程安全)。"""
  126. def __init__(self, params: Optional[CommitParams] = None) -> None:
  127. self.p = params or CommitParams()
  128. self._samples: Deque[_Sample] = deque(maxlen=256)
  129. self._last_ts = 0.0
  130. self._last = CommitState(False, "T1", "init")
  131. @classmethod
  132. def from_config(cls, cfg: Config) -> "CommitTracker":
  133. return cls(CommitParams.from_config(cfg))
  134. @property
  135. def params(self) -> CommitParams:
  136. return self.p
  137. @property
  138. def last(self) -> CommitState:
  139. return self._last
  140. def reset(self) -> None:
  141. self._samples.clear()
  142. self._last_ts = 0.0
  143. self._last = CommitState(False, "T1", "reset")
  144. # ---------------------------------------------------------------- 主入口
  145. def update(
  146. self,
  147. ts: float,
  148. *,
  149. state: int,
  150. gap_m: Optional[float],
  151. gap_px: Optional[float],
  152. structure_hits: float = 1.0,
  153. motion_ok: bool = True,
  154. view_known: bool = True,
  155. plc_arrived: bool = False,
  156. plc_spreader_released: bool = False,
  157. hoist_high: bool = False,
  158. ) -> CommitState:
  159. """喂入一帧证据,返回是否允许提交。
  160. ``state`` 是 ``evidence_v2`` 的**单帧分类结果**(0/1/2/255);
  161. ``structure_hits`` 是该帧结构证据强度(0..1),不是像素计数。
  162. ``hoist_high`` 表示画面出现吊具/钢缆/臂架高悬特征:箱体尚未落位,
  163. 无论间隙看起来多小都不得提交(安全门优先于所有几何门)。
  164. """
  165. now = float(ts)
  166. if now < self._last_ts:
  167. now = self._last_ts
  168. self._last_ts = now
  169. state = int(state)
  170. structure_ok = float(structure_hits) >= self.p.min_structure_hits
  171. arrival = bool(
  172. self.p.use_plc_arrival and (plc_arrived or plc_spreader_released)
  173. )
  174. # 安全门:吊具/钢缆/臂架仍在画面上方,说明箱体未落位。即使视觉
  175. # 把箱侧壁误当成车斗门板、算出“零间隙”,也不得累计 commit 帧。
  176. # 这一分支不写 _samples,避免高悬消失后立刻复用之前的窗口。
  177. if hoist_high:
  178. self._last = CommitState(
  179. False, "T3", "hoist_high", gap_m, gap_px, 0, 0, None, arrival, True
  180. )
  181. return self._last
  182. if state not in (0, 1, 2):
  183. self._last = CommitState(
  184. False, "T3" if not motion_ok else "T1", "state_unknown",
  185. gap_m, gap_px, 0, 0, None, arrival,
  186. )
  187. return self._last
  188. if state == 1 and not self.p.allow_state1:
  189. self._last = CommitState(False, "T1", "state1_disabled",
  190. gap_m, gap_px, 0, 0, None, arrival)
  191. return self._last
  192. if state == 2 and not self.p.allow_state2:
  193. # 平车在 PLC 签字前只识别、不提交;仍记录窗口,便于诊断。
  194. self._append(now, state, gap_m, gap_px, structure_ok, motion_ok)
  195. self._last = CommitState(False, "T1", "state2_disabled",
  196. gap_m, gap_px, 0, 0, None, arrival)
  197. return self._last
  198. self._append(now, state, gap_m, gap_px, structure_ok, motion_ok)
  199. if not motion_ok and self.p.require_motion_ok:
  200. self._last = CommitState(False, "T3", "motion", gap_m, gap_px,
  201. 0, 0, None, arrival)
  202. return self._last
  203. if not view_known and self.p.require_view_known:
  204. self._last = CommitState(False, "T1", "view_unknown", gap_m, gap_px,
  205. 0, 0, None, arrival)
  206. return self._last
  207. # 0 是“其他/不在车上”,不需要间隙门;仍需稳定帧与正面证据。
  208. gap_ok = True
  209. if state in (1, 2):
  210. if arrival:
  211. gap_ok = True
  212. else:
  213. contact = gap_px is not None and float(gap_px) <= CONTACT_GAP_PX
  214. gap_ok = (
  215. gap_px is not None
  216. and float(gap_px) <= self.p.gap_px_hard_max
  217. and (
  218. contact
  219. or (
  220. gap_m is not None
  221. and float(gap_m) <= self.p.gap_m_max
  222. )
  223. )
  224. )
  225. window = self._window(max(self.p.stable_frames, self.p.structure_frames))
  226. stable_n = self._same_state_run(state)
  227. structure_n = sum(1 for s in window if s.structure_ok)
  228. gap_n = sum(1 for s in window if self._gap_ok(s, arrival))
  229. slope = self._gap_slope(window)
  230. stable_enough = stable_n >= self.p.stable_frames
  231. structure_enough = structure_n >= self.p.structure_frames
  232. gap_enough = gap_n >= self.p.stable_frames
  233. not_rising = slope is None or slope <= self.p.max_gap_rise_m
  234. phase = "T2" if gap_ok else "T1"
  235. committed = bool(
  236. gap_ok and stable_enough and structure_enough and gap_enough and not_rising
  237. )
  238. reason_parts = []
  239. if not gap_ok:
  240. reason_parts.append("gap")
  241. if not stable_enough:
  242. reason_parts.append("stable=%d/%d" % (stable_n, self.p.stable_frames))
  243. if not structure_enough:
  244. reason_parts.append("structure=%d/%d" % (structure_n, self.p.structure_frames))
  245. if not gap_enough:
  246. reason_parts.append("gap_window=%d/%d" % (gap_n, self.p.stable_frames))
  247. if not not_rising:
  248. reason_parts.append("gap_rising")
  249. reason = "commit" if committed else (
  250. "wait:" + ",".join(reason_parts) if reason_parts else "wait"
  251. )
  252. if arrival and committed:
  253. reason = "commit:plc_arrival"
  254. self._last = CommitState(
  255. committed=committed,
  256. phase=phase,
  257. reason=reason,
  258. gap_m=gap_m,
  259. gap_px=gap_px,
  260. stable_frames=int(stable_n),
  261. structure_frames=int(structure_n),
  262. gap_slope_m_per_s=slope,
  263. plc_arrival=arrival,
  264. )
  265. return self._last
  266. # ---------------------------------------------------------------- 内部
  267. def _append(
  268. self,
  269. ts: float,
  270. state: int,
  271. gap_m: Optional[float],
  272. gap_px: Optional[float],
  273. structure_ok: bool,
  274. motion_ok: bool,
  275. ) -> None:
  276. self._samples.append(
  277. _Sample(ts, int(state), gap_m, gap_px, bool(structure_ok), bool(motion_ok))
  278. )
  279. def _window(self, n: int) -> Tuple[_Sample, ...]:
  280. if n <= 0:
  281. return tuple()
  282. return tuple(list(self._samples)[-n:])
  283. def _same_state_run(self, state: int) -> int:
  284. count = 0
  285. for sample in reversed(self._samples):
  286. if sample.state != int(state):
  287. break
  288. count += 1
  289. return count
  290. def _gap_ok(self, sample: _Sample, arrival: bool) -> bool:
  291. if sample.state == 0 or arrival:
  292. return True
  293. if sample.gap_px is None or float(sample.gap_px) > self.p.gap_px_hard_max:
  294. return False
  295. # 零间隙 = 已直接接触:没有 px_per_m 时 gap_m 为空,不能因此拒绝。
  296. if float(sample.gap_px) <= CONTACT_GAP_PX:
  297. return True
  298. return bool(
  299. sample.gap_m is not None
  300. and float(sample.gap_m) <= self.p.gap_m_max
  301. )
  302. def _gap_slope(self, window: Tuple[_Sample, ...]) -> Optional[float]:
  303. points = [(s.ts, s.gap_m) for s in window if s.gap_m is not None]
  304. if len(points) < 2:
  305. return None
  306. t0, g0 = points[0]
  307. t1, g1 = points[-1]
  308. dt = float(t1) - float(t0)
  309. if dt <= 1e-6:
  310. return None
  311. return (float(g1) - float(g0)) / dt