Coverage for core / src / sensorkit / core / trait.py: 100%
74 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"""Entity traits and device archetypes.
4Traits match device commands or declared keyword publications. An entity can
5satisfy multiple traits. Archetypes identify a device's declared principal role
6and specify required commands, required sub-traits, and optional commands.
7"""
9from __future__ import annotations
11import itertools
12from collections.abc import Iterable
13from dataclasses import dataclass
14from typing import TYPE_CHECKING
16if TYPE_CHECKING:
17 from sensorkit.core.device import DeviceCommand
18 from sensorkit.core.entity import DeviceDetails, EntityDetails
20_trait_registry: dict[str, Trait] = {}
23@dataclass(frozen=True, eq=False)
24class Trait:
25 """A named set of required device commands or keyword publications."""
27 name: str
28 required_commands: tuple[type[DeviceCommand], ...] = ()
29 required_keywords: tuple[str, ...] = ()
31 def effective_command_ids(self) -> frozenset[str]:
32 """Return all command IDs required by this trait."""
33 return frozenset(cmd.model_tag() for cmd in self.required_commands)
35 def effective_keyword_ids(self) -> frozenset[str]:
36 """Return all keyword IDs required by this trait."""
37 return frozenset(self.required_keywords)
39 def match(self, details: EntityDetails | None) -> bool:
40 """Return whether the advertised capabilities satisfy this trait."""
41 # Entity metadata imports the trait helpers.
42 from sensorkit.core.entity import DeviceDetails
44 if details is None:
45 return False
47 commands = self.effective_command_ids()
49 if commands:
50 # Command-based traits trust devices to publish required keywords.
51 match details:
52 case DeviceDetails(supported_commands=supported):
53 return commands <= supported
54 case _:
55 return False
57 return self.effective_keyword_ids() <= details.published_keywords
59 def __hash__(self):
60 return hash(self.name)
62 def __eq__(self, other):
63 return isinstance(other, Trait) and self.name == other.name
65 def __repr__(self):
66 return f"Trait({self.name!r})"
69@dataclass(frozen=True, eq=False)
70class Archetype(Trait):
71 """A device's principal role, assigned by declaration.
73 A device can structurally satisfy multiple archetypes as traits.
74 Required sub-traits contribute to matching. Optional commands describe
75 extended capabilities and do not affect matching.
76 """
78 required_traits: tuple[Trait, ...] = ()
79 optional_commands: tuple[type[DeviceCommand], ...] = ()
81 def effective_command_ids(self) -> frozenset[str]:
82 """Return all command IDs required by this archetype and its required sub-traits."""
83 return frozenset(
84 itertools.chain(
85 (cmd.model_tag() for cmd in self.required_commands),
86 *(sub_trait.effective_command_ids() for sub_trait in self.required_traits),
87 )
88 )
90 def effective_keyword_ids(self) -> frozenset[str]:
91 """Return all keyword IDs required by this archetype and its required sub-traits."""
92 return frozenset(
93 itertools.chain(
94 self.required_keywords,
95 *(sub_trait.effective_keyword_ids() for sub_trait in self.required_traits),
96 )
97 )
99 def __repr__(self):
100 return f"Archetype({self.name!r})"
103def declare_trait(
104 name: str,
105 *,
106 required_commands: tuple[type[DeviceCommand], ...] = (),
107 required_keywords: tuple[str, ...] = (),
108) -> Trait:
109 """Declare an entity trait and add it to the registry.
111 Raises:
112 ValueError: The name is already registered as a trait or archetype.
113 """
114 if name in _trait_registry:
115 raise ValueError(f"Trait name '{name}' is already registered")
117 trait = Trait(
118 name=name,
119 required_commands=required_commands,
120 required_keywords=required_keywords,
121 )
122 _trait_registry[name] = trait
123 return trait
126def declare_archetype(
127 name: str,
128 *,
129 required_commands: tuple[type[DeviceCommand], ...] = (),
130 required_keywords: tuple[str, ...] = (),
131 required_traits: tuple[Trait, ...] = (),
132 optional_commands: tuple[type[DeviceCommand], ...] = (),
133) -> Archetype:
134 """Declare an archetype and add it to the trait registry.
136 Archetypes extend traits with required sub-traits and optional commands.
137 Sub-traits must themselves be plain Traits, not Archetypes.
139 Raises:
140 ValueError: The name is already registered, or a sub-trait is an archetype.
141 """
142 if name in _trait_registry:
143 raise ValueError(f"Trait name '{name}' is already registered")
145 for t in required_traits:
146 if isinstance(t, Archetype):
147 raise ValueError(
148 f"Sub-trait '{t.name}' is an archetype and cannot be used as a sub-trait"
149 )
151 archetype = Archetype(
152 name=name,
153 required_commands=required_commands,
154 required_keywords=required_keywords,
155 required_traits=required_traits,
156 optional_commands=optional_commands,
157 )
159 _trait_registry[name] = archetype
161 return archetype
164def get_registered_traits() -> frozenset[Trait]:
165 """Return all registered traits (including archetypes)."""
166 return frozenset(_trait_registry.values())
169def get_trait(name: str) -> Trait | None:
170 """Return the registered trait or archetype with this name, or None."""
171 return _trait_registry.get(name)
174def get_registered_archetypes() -> frozenset[Archetype]:
175 """Return all registered archetypes."""
176 return frozenset(trait for trait in _trait_registry.values() if isinstance(trait, Archetype))
179def match_traits(
180 details: EntityDetails | None,
181 traits: Iterable[Trait] | None = None,
182) -> list[Trait]:
183 """Return traits satisfied by the entity's advertised capabilities."""
184 if traits is None:
185 traits = _trait_registry.values()
187 output = []
189 for trait in traits:
190 if trait.match(details):
191 output.append(trait)
193 return output
196def trait_keyword_ids(
197 details: DeviceDetails,
198 traits: Iterable[Trait] | None = None,
199) -> frozenset[str]:
200 """Return the keyword IDs required by every trait the device satisfies."""
201 return frozenset().union(*(trait.effective_keyword_ids() for trait in match_traits(details, traits)))