publish_gate.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. """V2 PublishGate:把内部 ``Decision`` 映射成 PLC 可以安全消费的结果。
  2. 背景
  3. ----
  4. V1 在不确定时直接把 ``state=255`` 写进 PLC 寄存器;V2 的目标契约是
  5. **PLC 侧只看到 0/1/2**,255 只存在于视觉内部。做法:
  6. * 内部有效(0/1/2、稳定、置信度达标)→ 发布该状态,置
  7. ``RESULT_VALID`` 与 ``STABLE``;
  8. * 内部 255 / 低置信度 / 未稳定 → **保持上一稳定值**,清两个标志;
  9. * 帧超时 → 同样保持上一稳定值(超时优先于有效结果);
  10. * PLC ``cmd=2`` 复位 → 回到 ``0 + flags 0/0``,并清掉 last stable;
  11. * 从未有过稳定值(冷启动)→ ``0 + flags 0/0``。
  12. ``0 + flags 0/0`` 只表示“不知道/保持”,**不是**“已确认不在车上”;
  13. PLC 必须按 ``RESULT_VALID && STABLE`` 门控。
  14. 本模块只做输出映射,不依赖检测/证据模块;P1a 先用合成 ``Decision``
  15. 验证契约,P1b 再把它接进运行时。
  16. """
  17. from __future__ import annotations
  18. import math
  19. from dataclasses import dataclass
  20. from typing import Optional, Tuple
  21. from ..schema import Decision
  22. __all__ = [
  23. "DEFAULT_MIN_CONFIDENCE",
  24. "PublishGate",
  25. "PublishResult",
  26. "evaluate_publish_gate",
  27. ]
  28. #: 与 ``decision.min_confidence`` 的默认值一致(45%)。
  29. DEFAULT_MIN_CONFIDENCE = 0.45
  30. _VALID_STATES = (0, 1, 2, 3)
  31. def _is_valid_state(state: int) -> bool:
  32. return int(state) in _VALID_STATES
  33. def _confidence_milli(conf: float) -> int:
  34. """把 0..1 的置信度换成 0..1000 的整数(half-up)。
  35. 不用 Python 内置 ``round`` / C++ ``std::lround`` 的原因:两者对
  36. ``.5`` 的舍入规则不同(banker's vs away-from-zero),会造成
  37. Python/C++ 同一输入得到不同千分比。这里固定为
  38. ``floor(conf * 1000 + 0.5)``,两侧逐位一致。
  39. """
  40. if not math.isfinite(conf) or conf <= 0.0:
  41. return 0
  42. if conf >= 1.0:
  43. return 1000
  44. return int(math.floor(conf * 1000.0 + 0.5))
  45. @dataclass(frozen=True)
  46. class PublishResult:
  47. """PublishGate 的输出;字段与 PLC 结果区的前三个字对应。"""
  48. state: int
  49. result_valid: bool
  50. stable: bool
  51. confidence: int
  52. last_stable: Optional[int]
  53. perception_uncertain: bool = False
  54. def __post_init__(self) -> None:
  55. if self.state not in _VALID_STATES:
  56. raise ValueError("PublishGate.state 必须是 0/1/2/3,实际 %r" % (self.state,))
  57. if self.result_valid and not self.stable:
  58. raise ValueError("RESULT_VALID=1 时必须 STABLE=1")
  59. if self.result_valid and self.perception_uncertain:
  60. raise ValueError("PERCEPTION_UNCERTAIN=1 时不得置 RESULT_VALID")
  61. if not 0 <= int(self.confidence) <= 1000:
  62. raise ValueError("confidence 必须在 0..1000,实际 %r" % (self.confidence,))
  63. if not self.result_valid and int(self.confidence) != 0:
  64. raise ValueError("结果无效时 confidence 必须为 0")
  65. if self.last_stable is not None and self.last_stable not in _VALID_STATES:
  66. raise ValueError("last_stable 必须是 0/1/2/3 或 None")
  67. def as_tuple(self) -> Tuple[int, int, int, int, Optional[int]]:
  68. """返回契约测试用的五元组(1/0 而非 bool)。"""
  69. return (
  70. int(self.state),
  71. int(bool(self.result_valid)),
  72. int(bool(self.stable)),
  73. int(self.confidence),
  74. self.last_stable,
  75. )
  76. def _hold(last_stable: Optional[int], perception_uncertain: bool = True) -> PublishResult:
  77. """不确定时的安全输出:保持 last stable;没有历史则 0/None。
  78. P0-2:只要走“保持”分支,就置 ``perception_uncertain``;调用方据此
  79. 置 ``PERCEPTION_UNCERTAIN``/``MRC_REQUEST``,且绝不会同时置
  80. ``RESULT_VALID``。
  81. """
  82. if last_stable is not None and _is_valid_state(int(last_stable)):
  83. last = int(last_stable)
  84. return PublishResult(state=last, result_valid=False, stable=False,
  85. confidence=0, last_stable=last,
  86. perception_uncertain=bool(perception_uncertain))
  87. return PublishResult(state=0, result_valid=False, stable=False,
  88. confidence=0, last_stable=None,
  89. perception_uncertain=bool(perception_uncertain))
  90. def evaluate_publish_gate(
  91. decision: Decision,
  92. *,
  93. frame_timeout: bool = False,
  94. reset: bool = False,
  95. last_stable: Optional[int] = None,
  96. min_conf: float = DEFAULT_MIN_CONFIDENCE,
  97. perception_uncertain: bool = False,
  98. ) -> PublishResult:
  99. """纯函数版 PublishGate(便于单测/回放)。
  100. 优先级:``reset`` > ``frame_timeout`` > ``perception_uncertain`` >
  101. 有效结果 > 保持。``last_stable`` 是**上一稳定值**,不是本帧内部状态;
  102. 有效时才更新。
  103. """
  104. if reset:
  105. return PublishResult(state=0, result_valid=False, stable=False,
  106. confidence=0, last_stable=None)
  107. if frame_timeout:
  108. return _hold(last_stable, True)
  109. if perception_uncertain:
  110. return _hold(last_stable, True)
  111. threshold = float(min_conf)
  112. if not math.isfinite(threshold):
  113. threshold = DEFAULT_MIN_CONFIDENCE
  114. conf = float(decision.confidence)
  115. valid = (
  116. _is_valid_state(int(decision.state))
  117. and bool(decision.stable)
  118. and math.isfinite(conf)
  119. and conf >= threshold
  120. )
  121. if not valid:
  122. return _hold(last_stable, True)
  123. state = int(decision.state)
  124. return PublishResult(state=state, result_valid=True, stable=True,
  125. confidence=_confidence_milli(conf), last_stable=state,
  126. perception_uncertain=False)
  127. class PublishGate:
  128. """有状态的 PublishGate:在自己内部保存 last stable。
  129. 线程内使用、非线程安全;每个发布循环一个实例即可。
  130. """
  131. def __init__(self, min_conf: float = DEFAULT_MIN_CONFIDENCE) -> None:
  132. threshold = float(min_conf)
  133. self._min_conf = threshold if math.isfinite(threshold) else DEFAULT_MIN_CONFIDENCE
  134. self._last_stable: Optional[int] = None
  135. @property
  136. def min_conf(self) -> float:
  137. return self._min_conf
  138. @property
  139. def last_stable(self) -> Optional[int]:
  140. return self._last_stable
  141. def reset(self) -> None:
  142. """PLC ``cmd=2``:清掉 last stable(下一次有效结果重新建立)。"""
  143. self._last_stable = None
  144. def apply(
  145. self,
  146. decision: Decision,
  147. *,
  148. frame_timeout: bool = False,
  149. reset: bool = False,
  150. min_conf: Optional[float] = None,
  151. perception_uncertain: bool = False,
  152. ) -> PublishResult:
  153. """处理一个内部 Decision,更新并返回发布结果。"""
  154. threshold = self._min_conf if min_conf is None else float(min_conf)
  155. result = evaluate_publish_gate(
  156. decision,
  157. frame_timeout=frame_timeout,
  158. reset=reset,
  159. last_stable=self._last_stable,
  160. min_conf=threshold,
  161. perception_uncertain=perception_uncertain,
  162. )
  163. self._last_stable = result.last_stable
  164. return result