"""V2 PublishGate:把内部 ``Decision`` 映射成 PLC 可以安全消费的结果。 背景 ---- V1 在不确定时直接把 ``state=255`` 写进 PLC 寄存器;V2 的目标契约是 **PLC 侧只看到 0/1/2**,255 只存在于视觉内部。做法: * 内部有效(0/1/2、稳定、置信度达标)→ 发布该状态,置 ``RESULT_VALID`` 与 ``STABLE``; * 内部 255 / 低置信度 / 未稳定 → **保持上一稳定值**,清两个标志; * 帧超时 → 同样保持上一稳定值(超时优先于有效结果); * PLC ``cmd=2`` 复位 → 回到 ``0 + flags 0/0``,并清掉 last stable; * 从未有过稳定值(冷启动)→ ``0 + flags 0/0``。 ``0 + flags 0/0`` 只表示“不知道/保持”,**不是**“已确认不在车上”; PLC 必须按 ``RESULT_VALID && STABLE`` 门控。 本模块只做输出映射,不依赖检测/证据模块;P1a 先用合成 ``Decision`` 验证契约,P1b 再把它接进运行时。 """ from __future__ import annotations import math from dataclasses import dataclass from typing import Optional, Tuple from ..schema import Decision __all__ = [ "DEFAULT_MIN_CONFIDENCE", "PublishGate", "PublishResult", "evaluate_publish_gate", ] #: 与 ``decision.min_confidence`` 的默认值一致(45%)。 DEFAULT_MIN_CONFIDENCE = 0.45 _VALID_STATES = (0, 1, 2, 3) def _is_valid_state(state: int) -> bool: return int(state) in _VALID_STATES def _confidence_milli(conf: float) -> int: """把 0..1 的置信度换成 0..1000 的整数(half-up)。 不用 Python 内置 ``round`` / C++ ``std::lround`` 的原因:两者对 ``.5`` 的舍入规则不同(banker's vs away-from-zero),会造成 Python/C++ 同一输入得到不同千分比。这里固定为 ``floor(conf * 1000 + 0.5)``,两侧逐位一致。 """ if not math.isfinite(conf) or conf <= 0.0: return 0 if conf >= 1.0: return 1000 return int(math.floor(conf * 1000.0 + 0.5)) @dataclass(frozen=True) class PublishResult: """PublishGate 的输出;字段与 PLC 结果区的前三个字对应。""" state: int result_valid: bool stable: bool confidence: int last_stable: Optional[int] perception_uncertain: bool = False def __post_init__(self) -> None: if self.state not in _VALID_STATES: raise ValueError("PublishGate.state 必须是 0/1/2/3,实际 %r" % (self.state,)) if self.result_valid and not self.stable: raise ValueError("RESULT_VALID=1 时必须 STABLE=1") if self.result_valid and self.perception_uncertain: raise ValueError("PERCEPTION_UNCERTAIN=1 时不得置 RESULT_VALID") if not 0 <= int(self.confidence) <= 1000: raise ValueError("confidence 必须在 0..1000,实际 %r" % (self.confidence,)) if not self.result_valid and int(self.confidence) != 0: raise ValueError("结果无效时 confidence 必须为 0") if self.last_stable is not None and self.last_stable not in _VALID_STATES: raise ValueError("last_stable 必须是 0/1/2/3 或 None") def as_tuple(self) -> Tuple[int, int, int, int, Optional[int]]: """返回契约测试用的五元组(1/0 而非 bool)。""" return ( int(self.state), int(bool(self.result_valid)), int(bool(self.stable)), int(self.confidence), self.last_stable, ) def _hold(last_stable: Optional[int], perception_uncertain: bool = True) -> PublishResult: """不确定时的安全输出:保持 last stable;没有历史则 0/None。 P0-2:只要走“保持”分支,就置 ``perception_uncertain``;调用方据此 置 ``PERCEPTION_UNCERTAIN``/``MRC_REQUEST``,且绝不会同时置 ``RESULT_VALID``。 """ if last_stable is not None and _is_valid_state(int(last_stable)): last = int(last_stable) return PublishResult(state=last, result_valid=False, stable=False, confidence=0, last_stable=last, perception_uncertain=bool(perception_uncertain)) return PublishResult(state=0, result_valid=False, stable=False, confidence=0, last_stable=None, perception_uncertain=bool(perception_uncertain)) def evaluate_publish_gate( decision: Decision, *, frame_timeout: bool = False, reset: bool = False, last_stable: Optional[int] = None, min_conf: float = DEFAULT_MIN_CONFIDENCE, perception_uncertain: bool = False, ) -> PublishResult: """纯函数版 PublishGate(便于单测/回放)。 优先级:``reset`` > ``frame_timeout`` > ``perception_uncertain`` > 有效结果 > 保持。``last_stable`` 是**上一稳定值**,不是本帧内部状态; 有效时才更新。 """ if reset: return PublishResult(state=0, result_valid=False, stable=False, confidence=0, last_stable=None) if frame_timeout: return _hold(last_stable, True) if perception_uncertain: return _hold(last_stable, True) threshold = float(min_conf) if not math.isfinite(threshold): threshold = DEFAULT_MIN_CONFIDENCE conf = float(decision.confidence) valid = ( _is_valid_state(int(decision.state)) and bool(decision.stable) and math.isfinite(conf) and conf >= threshold ) if not valid: return _hold(last_stable, True) state = int(decision.state) return PublishResult(state=state, result_valid=True, stable=True, confidence=_confidence_milli(conf), last_stable=state, perception_uncertain=False) class PublishGate: """有状态的 PublishGate:在自己内部保存 last stable。 线程内使用、非线程安全;每个发布循环一个实例即可。 """ def __init__(self, min_conf: float = DEFAULT_MIN_CONFIDENCE) -> None: threshold = float(min_conf) self._min_conf = threshold if math.isfinite(threshold) else DEFAULT_MIN_CONFIDENCE self._last_stable: Optional[int] = None @property def min_conf(self) -> float: return self._min_conf @property def last_stable(self) -> Optional[int]: return self._last_stable def reset(self) -> None: """PLC ``cmd=2``:清掉 last stable(下一次有效结果重新建立)。""" self._last_stable = None def apply( self, decision: Decision, *, frame_timeout: bool = False, reset: bool = False, min_conf: Optional[float] = None, perception_uncertain: bool = False, ) -> PublishResult: """处理一个内部 Decision,更新并返回发布结果。""" threshold = self._min_conf if min_conf is None else float(min_conf) result = evaluate_publish_gate( decision, frame_timeout=frame_timeout, reset=reset, last_stable=self._last_stable, min_conf=threshold, perception_uncertain=perception_uncertain, ) self._last_stable = result.last_stable return result