Coverage for core / src / sensorkit / sensor / selection.py: 99%

157 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"""Select devices by placement properties, reported capabilities and device 

3keywords. 

4 

5`matches` tests one placement. `matching` filters supplied placements. `reaches` 

6tests an instrument chain. On a chain, `AllOf` may match different members at 

7different placements. A wheel can satisfy `Supports(supports=SetFilter)` while 

8its camera satisfies `Supports(supports=CameraCapture)`. 

9 

10Except for device-key comparisons, predicates read a `BoundSensor`. Tags, kind 

11and instrument status come from its topology. Evaluating a predicate without a 

12sensor raises, including under negation. `KeywordMatch` requires a device 

13keyword mapping. Capability predicates use reported command and keyword 

14identifiers. 

15 

16Authored selections use a distinguishing key; a bare string names a trait. 

17Routing chooses a command target from matching placements in `routing`. 

18""" 

19 

20from __future__ import annotations 

21 

22from abc import ABC, abstractmethod 

23from collections.abc import Mapping 

24from enum import StrEnum 

25from typing import Annotated, ClassVar, Literal 

26 

27from pydantic import ( 

28 BaseModel, 

29 BeforeValidator, 

30 Discriminator, 

31 Field, 

32 Tag, 

33 model_validator, 

34) 

35 

36from sensorkit.common.keyword import get_keyword_info, get_keyword_type 

37from sensorkit.common.predicate import AnyPredicate, FieldMatch 

38from sensorkit.core.device import DeviceCommand 

39from sensorkit.core.trait import Trait 

40from sensorkit.sensor.binding import BoundSensor 

41from sensorkit.sensor.topology import Placement 

42 

43 

44class SelectionError(ValueError): 

45 """A predicate requires a bound sensor or device keywords that were not 

46 supplied. 

47 """ 

48 

49 

50def _known(facts: BoundSensor | None, question: str) -> BoundSensor: 

51 """Require a bound sensor for a predicate, naming it in the error. 

52 

53 Raises: 

54 SelectionError: No sensor was supplied. 

55 """ 

56 if facts is None: 

57 raise SelectionError(f"'{question}' is answered from a bound sensor, and none was given") 

58 

59 return facts 

60 

61 

62def _command_tag(v: object) -> object: 

63 """Convert a command class to its registered identifier.""" 

64 if isinstance(v, type) and issubclass(v, DeviceCommand): 

65 return v.model_tag() 

66 

67 return v 

68 

69 

70def _keyword_key(v: object) -> object: 

71 """Convert a declared keyword class to its registered key.""" 

72 if not isinstance(v, type): 

73 return v 

74 

75 info = get_keyword_info(v) 

76 if info is None: 

77 raise ValueError(f"'{v.__name__}' is not a declared keyword") 

78 

79 return info.key 

80 

81 

82class SelectionType(StrEnum): 

83 """Authored key that identifies each selection type. 

84 

85 A mapping naming several keys takes the first in definition order. 

86 """ 

87 

88 trait = "trait" 

89 tag = "tag" 

90 device = "device" 

91 kind = "kind" 

92 instrument = "instrument" 

93 supports = "supports" 

94 publishes = "publishes" 

95 keyword = "keyword" 

96 all_of = "all_of" 

97 any_of = "any_of" 

98 negated = "not" 

99 

100 

101class Selection(BaseModel, ABC, frozen=True, extra="forbid"): 

102 """A predicate over one placement or an instrument chain. 

103 

104 Compositions apply their members to the same placement in `matches`, and 

105 independently to the whole chain in `reaches`. 

106 """ 

107 

108 type: ClassVar[SelectionType] 

109 

110 @abstractmethod 

111 def matches(self, placement: Placement, facts: BoundSensor | None = None) -> bool: 

112 """Test whether one placement satisfies this predicate. 

113 

114 Raises: 

115 SelectionError: The predicate requires a bound sensor and none 

116 was supplied. 

117 """ 

118 ... 

119 

120 def matching( 

121 self, placements: tuple[Placement, ...], facts: BoundSensor | None = None 

122 ) -> tuple[Placement, ...]: 

123 """Return matching placements in the supplied order. 

124 

125 Callers supply the search set, such as a whole sensor or a 

126 participant's chain. The sensor does not enumerate placements. 

127 """ 

128 return tuple(p for p in placements if self.matches(p, facts)) 

129 

130 def refs( 

131 self, placements: tuple[Placement, ...], facts: BoundSensor | None = None 

132 ) -> tuple[str, ...]: 

133 """Return matching device keys in the supplied placement order.""" 

134 return tuple(p.device for p in self.matching(placements, facts)) 

135 

136 def reaches(self, chain: tuple[Placement, ...], facts: BoundSensor | None = None) -> bool: 

137 """Test whether the chain satisfies this predicate. 

138 

139 Simple predicates match if any placement does. `AllOf` may match its 

140 members on different devices. `Not` matches only if its member fails 

141 to match the chain as a whole. 

142 """ 

143 return any(self.matches(p, facts) for p in chain) 

144 

145 

146class HasTrait(Selection): 

147 """Match a trait established at binding, regardless of authored 

148 assertions. 

149 """ 

150 

151 type = SelectionType.trait 

152 trait: str 

153 

154 @model_validator(mode="before") 

155 @classmethod 

156 def _str_shorthand(cls, v: object) -> object: 

157 return {"trait": v} if isinstance(v, str) else v 

158 

159 def matches(self, placement, facts=None): 

160 known = _known(facts, f"trait: {self.trait}") 

161 

162 return self.trait in known.traits(placement) 

163 

164 

165class HasTag(Selection): 

166 """Match a grouping tag declared on the device or selector record.""" 

167 

168 type = SelectionType.tag 

169 tag: str 

170 

171 def matches(self, placement, facts=None): 

172 known = _known(facts, f"tag: {self.tag}") 

173 

174 return self.tag in known.topology.tags(placement) 

175 

176 

177class IsRef(Selection): 

178 """Match a device key; no bound sensor is required.""" 

179 

180 type = SelectionType.device 

181 device: str 

182 

183 def matches(self, placement, facts=None): 

184 return self.device == placement.device 

185 

186 

187class IsKind(Selection): 

188 """Match the record kind, or every placement when `kind` is `any`.""" 

189 

190 type = SelectionType.kind 

191 kind: Literal["device", "instrument", "selector", "any"] 

192 

193 def matches(self, placement, facts=None): 

194 known = _known(facts, f"kind: {self.kind}") 

195 

196 return self.kind in ("any", known.topology.kind(placement)) 

197 

198 

199class IsInstrument(Selection): 

200 """Match configured instrument status. 

201 

202 `instrument: false` selects placements that are not collection targets. 

203 """ 

204 

205 type = SelectionType.instrument 

206 instrument: bool = True 

207 

208 def matches(self, placement, facts=None): 

209 known = _known(facts, f"instrument: {self.instrument}") 

210 

211 return known.topology.instrument(placement) == self.instrument 

212 

213 

214class Supports(Selection): 

215 """Match a reported command identifier. 

216 

217 A command class may be supplied in place of its identifier. 

218 """ 

219 

220 type = SelectionType.supports 

221 supports: Annotated[str, BeforeValidator(_command_tag)] 

222 

223 def matches(self, placement, facts=None): 

224 known = _known(facts, f"supports: {self.supports}") 

225 

226 return self.supports in known.supported_commands(placement.device) 

227 

228 

229class Publishes(Selection): 

230 """Match a reported keyword identifier, regardless of its current value. 

231 

232 A declared keyword class may be supplied in place of its identifier. 

233 """ 

234 

235 type = SelectionType.publishes 

236 publishes: Annotated[str, BeforeValidator(_keyword_key)] 

237 

238 def matches(self, placement, facts=None): 

239 known = _known(facts, f"publishes: {self.publishes}") 

240 

241 return self.publishes in known.published_keywords(placement.device) 

242 

243 

244class KeywordMatch(Selection): 

245 """Match a device keyword with a predicate at an optional field path. 

246 

247 A declared keyword class may be supplied in place of its key. The field and 

248 predicate are checked against the keyword type when authored. An omitted 

249 field tests the keyword object itself. 

250 

251 A missing device or keyword is passed to the predicate as absent. 

252 A sensor without a device keyword mapping raises `SelectionError`. 

253 """ 

254 

255 type = SelectionType.keyword 

256 keyword: Annotated[str, BeforeValidator(_keyword_key)] 

257 field: str | None = None 

258 predicate: AnyPredicate 

259 

260 @model_validator(mode="after") 

261 def _checks_keyword(self) -> KeywordMatch: 

262 keyword_type = get_keyword_type(self.keyword) 

263 

264 if keyword_type is None: 

265 raise ValueError(f"'{self.keyword}' is not a declared keyword") 

266 

267 self.field_match.validate_against(keyword_type) 

268 

269 return self 

270 

271 @property 

272 def field_match(self) -> FieldMatch: 

273 """Return the field and predicate as a match on the keyword.""" 

274 return FieldMatch(field=self.field, predicate=self.predicate) 

275 

276 def matches(self, placement, facts=None): 

277 question = f"keyword: {self.keyword}" 

278 copied = _known(facts, question).device_keywords(placement.device) 

279 

280 if copied is None: 

281 raise SelectionError( 

282 f"'{question}' is answered from device keywords, and none were given" 

283 ) 

284 

285 return self.field_match.test(copied.get(self.keyword)) 

286 

287 

288class AllOf(Selection): 

289 """Require every member to match. 

290 

291 On a chain, different placements may satisfy different members. 

292 """ 

293 

294 type = SelectionType.all_of 

295 all_of: tuple[AnySelection, ...] = Field(min_length=1) 

296 

297 @classmethod 

298 def supporting(cls, trait: Trait) -> AllOf: 

299 """Build predicates for every command and keyword required by a 

300 trait. 

301 

302 Use `matches` to check that a single device satisfies the trait. 

303 

304 Raises: 

305 ValueError: The trait requires no commands or keywords. 

306 """ 

307 members: list[AnySelection] = [ 

308 Supports(supports=command) for command in sorted(trait.effective_command_ids()) 

309 ] 

310 members += [ 

311 Publishes(publishes=keyword) for keyword in sorted(trait.effective_keyword_ids()) 

312 ] 

313 

314 if not members: 

315 raise ValueError( 

316 f"trait '{trait.name}' requires no command or keyword, so " 

317 f"there is nothing to ask a device for" 

318 ) 

319 

320 return cls(all_of=tuple(members)) 

321 

322 def matches(self, placement, facts=None): 

323 return all(s.matches(placement, facts) for s in self.all_of) 

324 

325 def reaches(self, chain, facts=None): 

326 return all(s.reaches(chain, facts) for s in self.all_of) 

327 

328 

329class AnyOf(Selection): 

330 """Require at least one member to match the placement or chain.""" 

331 

332 type = SelectionType.any_of 

333 any_of: tuple[AnySelection, ...] = Field(min_length=1) 

334 

335 def matches(self, placement, facts=None): 

336 return any(s.matches(placement, facts) for s in self.any_of) 

337 

338 def reaches(self, chain, facts=None): 

339 return any(s.reaches(chain, facts) for s in self.any_of) 

340 

341 

342class Not(Selection, populate_by_name=True): 

343 """Negate a member at the placement or whole-chain level.""" 

344 

345 type = SelectionType.negated 

346 negated: AnySelection = Field(alias="not") 

347 

348 def matches(self, placement, facts=None): 

349 return not self.negated.matches(placement, facts) 

350 

351 def reaches(self, chain, facts=None): 

352 return not self.negated.reaches(chain, facts) 

353 

354 

355def _selection_type(v: object) -> SelectionType | None: 

356 """Identify a selection from its model, mapping key or trait shorthand.""" 

357 match v: 

358 case str(): 

359 return SelectionType.trait 

360 case Selection(): 

361 return v.type 

362 case Mapping(): 

363 return next((k for k in SelectionType if k in v), None) 

364 

365 return None 

366 

367 

368type AnySelection = Annotated[ 

369 Annotated[HasTrait, Tag(HasTrait.type)] 

370 | Annotated[HasTag, Tag(HasTag.type)] 

371 | Annotated[IsRef, Tag(IsRef.type)] 

372 | Annotated[IsKind, Tag(IsKind.type)] 

373 | Annotated[IsInstrument, Tag(IsInstrument.type)] 

374 | Annotated[Supports, Tag(Supports.type)] 

375 | Annotated[Publishes, Tag(Publishes.type)] 

376 | Annotated[KeywordMatch, Tag(KeywordMatch.type)] 

377 | Annotated[AllOf, Tag(AllOf.type)] 

378 | Annotated[AnyOf, Tag(AnyOf.type)] 

379 | Annotated[Not, Tag(Not.type)], 

380 Discriminator(_selection_type), 

381] 

382 

383# Resolve recursive annotations now that `AnySelection` is defined. 

384AllOf.model_rebuild() 

385AnyOf.model_rebuild() 

386Not.model_rebuild()