Coverage for core / src / sensorkit / common / condition.py: 96%

117 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-11-24 01:04 +0000

1# SPDX-License-Identifier: Apache-2.0 

2"""Condition types for threshold and change-detection logic over value streams.""" 

3 

4from __future__ import annotations 

5 

6from abc import ABC, abstractmethod 

7from typing import Literal, override 

8 

9from pydantic import BaseModel 

10 

11 

12def resolve_field(obj: object, field_path: str) -> object: 

13 """Resolve a dot-separated field path on an object or dict.""" 

14 value = obj 

15 for part in field_path.split("."): 

16 if isinstance(value, dict): 

17 value = value.get(part) 

18 else: 

19 value = getattr(value, part, None) 

20 if value is None: 

21 return None 

22 return value 

23 

24 

25def _coerce_to_threshold_type(value: object, threshold: float | str | bool | None) -> object: 

26 """Coerce a value to the threshold's type for comparison.""" 

27 if threshold is None: 

28 return value 

29 if isinstance(threshold, bool): 

30 if isinstance(value, bool): 

31 return value 

32 if value is None: 

33 return None 

34 return bool(value) 

35 if isinstance(threshold, (int, float)): 

36 try: 

37 return float(value) 

38 except (TypeError, ValueError): 

39 return None 

40 return value 

41 

42 

43class Condition(BaseModel, ABC): 

44 """Abstract condition evaluated against a value stream. Discriminated on `kind`.""" 

45 

46 kind: str 

47 

48 @abstractmethod 

49 def evaluate( 

50 self, 

51 current: object, 

52 previous: object, 

53 was_active: bool, 

54 ) -> tuple[bool, bool]: 

55 """Evaluate notification and active state for one value update. 

56 

57 Returns: 

58 A pair of booleans. The first requests a notification for this update. 

59 The second records active state for subsequent hysteresis or edge checks. 

60 """ 

61 ... 

62 

63 

64class ChangesCondition(Condition): 

65 """Fires on any value change.""" 

66 

67 kind: Literal["changes"] = "changes" 

68 

69 @override 

70 def evaluate(self, current, previous, was_active): 

71 """Return `(True, True)` when `current != previous`, otherwise `(False, False)`.""" 

72 fired = current != previous 

73 return (fired, fired) 

74 

75 

76class AboveCondition(Condition): 

77 """Fires every update while value > threshold. 

78 

79 With *deadband*: remains active until value < threshold - deadband. 

80 """ 

81 

82 kind: Literal["above"] = "above" 

83 threshold: float 

84 deadband: float = 0.0 

85 

86 @override 

87 def evaluate(self, current, previous, was_active): 

88 """Fire while the numeric value exceeds the threshold, applying deadband hysteresis.""" 

89 try: 

90 v = float(current) 

91 except (TypeError, ValueError): 

92 return (False, False) 

93 if was_active: 

94 still = v >= self.threshold - self.deadband 

95 return (still, still) 

96 newly = v > self.threshold 

97 return (newly, newly) 

98 

99 

100class BelowCondition(Condition): 

101 """Fires every update while value < threshold. 

102 

103 With *deadband*: remains active until value > threshold + deadband. 

104 """ 

105 

106 kind: Literal["below"] = "below" 

107 threshold: float 

108 deadband: float = 0.0 

109 

110 @override 

111 def evaluate(self, current, previous, was_active): 

112 """Fire while the numeric value is below the threshold, applying deadband hysteresis.""" 

113 try: 

114 v = float(current) 

115 except (TypeError, ValueError): 

116 return (False, False) 

117 if was_active: 

118 still = v <= self.threshold + self.deadband 

119 return (still, still) 

120 newly = v < self.threshold 

121 return (newly, newly) 

122 

123 

124class EqualsCondition(Condition): 

125 """Fires every update while value equals threshold.""" 

126 

127 kind: Literal["equals"] = "equals" 

128 threshold: float | str | bool 

129 

130 @override 

131 def evaluate(self, current, previous, was_active): 

132 """Fire on every update where current (coerced to the threshold type) equals the threshold.""" 

133 matches = _coerce_to_threshold_type(current, self.threshold) == self.threshold 

134 return (matches, matches) 

135 

136 

137class BecomesCondition(Condition): 

138 """Fires once when value transitions to equal threshold.""" 

139 

140 kind: Literal["becomes"] = "becomes" 

141 threshold: float | str | bool | None 

142 

143 @override 

144 def evaluate(self, current, previous, was_active): 

145 """Fire exactly once when the value transitions from not-equal to equal to the threshold.""" 

146 coerced_cur = _coerce_to_threshold_type(current, self.threshold) 

147 coerced_prev = _coerce_to_threshold_type(previous, self.threshold) 

148 fired = coerced_cur == self.threshold and coerced_prev != self.threshold 

149 return (fired, fired) 

150 

151 

152class CrossesAboveCondition(Condition): 

153 """Fires once on upward crossing. 

154 

155 With *deadband*: won't re-fire until value drops below 

156 threshold - deadband and crosses back above. 

157 """ 

158 

159 kind: Literal["crosses_above"] = "crosses_above" 

160 threshold: float 

161 deadband: float = 0.0 

162 

163 @override 

164 def evaluate(self, current, previous, was_active): 

165 """Fire once when value crosses upward through the threshold; deadband prevents re-firing.""" 

166 try: 

167 v = float(current) 

168 p = float(previous) 

169 except (TypeError, ValueError): 

170 return (False, False) 

171 if was_active: 

172 still = v >= self.threshold - self.deadband 

173 return (False, still) 

174 crossed = v > self.threshold and p <= self.threshold 

175 return (crossed, crossed) 

176 

177 

178class CrossesBelowCondition(Condition): 

179 """Fires once on downward crossing. 

180 

181 With *deadband*: won't re-fire until value rises above 

182 threshold + deadband and crosses back below. 

183 """ 

184 

185 kind: Literal["crosses_below"] = "crosses_below" 

186 threshold: float 

187 deadband: float = 0.0 

188 

189 @override 

190 def evaluate(self, current, previous, was_active): 

191 """Fire once when value crosses downward through the threshold; deadband prevents re-firing.""" 

192 try: 

193 v = float(current) 

194 p = float(previous) 

195 except (TypeError, ValueError): 

196 return (False, False) 

197 if was_active: 

198 still = v <= self.threshold + self.deadband 

199 return (False, still) 

200 crossed = v < self.threshold and p >= self.threshold 

201 return (crossed, crossed) 

202 

203 

204type AnyCondition = ( 

205 ChangesCondition 

206 | AboveCondition 

207 | BelowCondition 

208 | EqualsCondition 

209 | BecomesCondition 

210 | CrossesAboveCondition 

211 | CrossesBelowCondition 

212)