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
« 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.
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)`.
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.
16Authored selections use a distinguishing key; a bare string names a trait.
17Routing chooses a command target from matching placements in `routing`.
18"""
20from __future__ import annotations
22from abc import ABC, abstractmethod
23from collections.abc import Mapping
24from enum import StrEnum
25from typing import Annotated, ClassVar, Literal
27from pydantic import (
28 BaseModel,
29 BeforeValidator,
30 Discriminator,
31 Field,
32 Tag,
33 model_validator,
34)
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
44class SelectionError(ValueError):
45 """A predicate requires a bound sensor or device keywords that were not
46 supplied.
47 """
50def _known(facts: BoundSensor | None, question: str) -> BoundSensor:
51 """Require a bound sensor for a predicate, naming it in the error.
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")
59 return facts
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()
67 return v
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
75 info = get_keyword_info(v)
76 if info is None:
77 raise ValueError(f"'{v.__name__}' is not a declared keyword")
79 return info.key
82class SelectionType(StrEnum):
83 """Authored key that identifies each selection type.
85 A mapping naming several keys takes the first in definition order.
86 """
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"
101class Selection(BaseModel, ABC, frozen=True, extra="forbid"):
102 """A predicate over one placement or an instrument chain.
104 Compositions apply their members to the same placement in `matches`, and
105 independently to the whole chain in `reaches`.
106 """
108 type: ClassVar[SelectionType]
110 @abstractmethod
111 def matches(self, placement: Placement, facts: BoundSensor | None = None) -> bool:
112 """Test whether one placement satisfies this predicate.
114 Raises:
115 SelectionError: The predicate requires a bound sensor and none
116 was supplied.
117 """
118 ...
120 def matching(
121 self, placements: tuple[Placement, ...], facts: BoundSensor | None = None
122 ) -> tuple[Placement, ...]:
123 """Return matching placements in the supplied order.
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))
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))
136 def reaches(self, chain: tuple[Placement, ...], facts: BoundSensor | None = None) -> bool:
137 """Test whether the chain satisfies this predicate.
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)
146class HasTrait(Selection):
147 """Match a trait established at binding, regardless of authored
148 assertions.
149 """
151 type = SelectionType.trait
152 trait: str
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
159 def matches(self, placement, facts=None):
160 known = _known(facts, f"trait: {self.trait}")
162 return self.trait in known.traits(placement)
165class HasTag(Selection):
166 """Match a grouping tag declared on the device or selector record."""
168 type = SelectionType.tag
169 tag: str
171 def matches(self, placement, facts=None):
172 known = _known(facts, f"tag: {self.tag}")
174 return self.tag in known.topology.tags(placement)
177class IsRef(Selection):
178 """Match a device key; no bound sensor is required."""
180 type = SelectionType.device
181 device: str
183 def matches(self, placement, facts=None):
184 return self.device == placement.device
187class IsKind(Selection):
188 """Match the record kind, or every placement when `kind` is `any`."""
190 type = SelectionType.kind
191 kind: Literal["device", "instrument", "selector", "any"]
193 def matches(self, placement, facts=None):
194 known = _known(facts, f"kind: {self.kind}")
196 return self.kind in ("any", known.topology.kind(placement))
199class IsInstrument(Selection):
200 """Match configured instrument status.
202 `instrument: false` selects placements that are not collection targets.
203 """
205 type = SelectionType.instrument
206 instrument: bool = True
208 def matches(self, placement, facts=None):
209 known = _known(facts, f"instrument: {self.instrument}")
211 return known.topology.instrument(placement) == self.instrument
214class Supports(Selection):
215 """Match a reported command identifier.
217 A command class may be supplied in place of its identifier.
218 """
220 type = SelectionType.supports
221 supports: Annotated[str, BeforeValidator(_command_tag)]
223 def matches(self, placement, facts=None):
224 known = _known(facts, f"supports: {self.supports}")
226 return self.supports in known.supported_commands(placement.device)
229class Publishes(Selection):
230 """Match a reported keyword identifier, regardless of its current value.
232 A declared keyword class may be supplied in place of its identifier.
233 """
235 type = SelectionType.publishes
236 publishes: Annotated[str, BeforeValidator(_keyword_key)]
238 def matches(self, placement, facts=None):
239 known = _known(facts, f"publishes: {self.publishes}")
241 return self.publishes in known.published_keywords(placement.device)
244class KeywordMatch(Selection):
245 """Match a device keyword with a predicate at an optional field path.
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.
251 A missing device or keyword is passed to the predicate as absent.
252 A sensor without a device keyword mapping raises `SelectionError`.
253 """
255 type = SelectionType.keyword
256 keyword: Annotated[str, BeforeValidator(_keyword_key)]
257 field: str | None = None
258 predicate: AnyPredicate
260 @model_validator(mode="after")
261 def _checks_keyword(self) -> KeywordMatch:
262 keyword_type = get_keyword_type(self.keyword)
264 if keyword_type is None:
265 raise ValueError(f"'{self.keyword}' is not a declared keyword")
267 self.field_match.validate_against(keyword_type)
269 return self
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)
276 def matches(self, placement, facts=None):
277 question = f"keyword: {self.keyword}"
278 copied = _known(facts, question).device_keywords(placement.device)
280 if copied is None:
281 raise SelectionError(
282 f"'{question}' is answered from device keywords, and none were given"
283 )
285 return self.field_match.test(copied.get(self.keyword))
288class AllOf(Selection):
289 """Require every member to match.
291 On a chain, different placements may satisfy different members.
292 """
294 type = SelectionType.all_of
295 all_of: tuple[AnySelection, ...] = Field(min_length=1)
297 @classmethod
298 def supporting(cls, trait: Trait) -> AllOf:
299 """Build predicates for every command and keyword required by a
300 trait.
302 Use `matches` to check that a single device satisfies the trait.
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 ]
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 )
320 return cls(all_of=tuple(members))
322 def matches(self, placement, facts=None):
323 return all(s.matches(placement, facts) for s in self.all_of)
325 def reaches(self, chain, facts=None):
326 return all(s.reaches(chain, facts) for s in self.all_of)
329class AnyOf(Selection):
330 """Require at least one member to match the placement or chain."""
332 type = SelectionType.any_of
333 any_of: tuple[AnySelection, ...] = Field(min_length=1)
335 def matches(self, placement, facts=None):
336 return any(s.matches(placement, facts) for s in self.any_of)
338 def reaches(self, chain, facts=None):
339 return any(s.reaches(chain, facts) for s in self.any_of)
342class Not(Selection, populate_by_name=True):
343 """Negate a member at the placement or whole-chain level."""
345 type = SelectionType.negated
346 negated: AnySelection = Field(alias="not")
348 def matches(self, placement, facts=None):
349 return not self.negated.matches(placement, facts)
351 def reaches(self, chain, facts=None):
352 return not self.negated.reaches(chain, facts)
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)
365 return None
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]
383# Resolve recursive annotations now that `AnySelection` is defined.
384AllOf.model_rebuild()
385AnyOf.model_rebuild()
386Not.model_rebuild()