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

153 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"""Describe a sensor's structure and index its device relationships. 

3 

4Devices occupy positions within units and selector ports. Each device has one 

5placement, identified by its device key and path. Instruments are collection 

6targets; their chains contain the devices they depend on, from root to leaf. 

7Instruments behind different ports of the same selector are mutually exclusive. 

8 

9`Topology` validates device uniqueness and sibling path names, then indexes 

10chains, readers, private devices and required selector states without contacting 

11hardware. Binding checks declared traits against reported capabilities. 

12Tags group devices without asserting capabilities. 

13""" 

14 

15from __future__ import annotations 

16 

17from collections.abc import Iterable, Mapping 

18from dataclasses import dataclass 

19from typing import Annotated, Literal 

20 

21from pydantic import BaseModel, BeforeValidator, Discriminator, Field, Tag 

22 

23type StructurePath = tuple[str, ...] 

24"""Path of unit names, port names and an instrument key, from root to leaf. 

25 

26The sensor name is excluded; root devices have an empty path. 

27""" 

28 

29 

30@dataclass(frozen=True) 

31class Placement: 

32 """A device key and its structural path, used to identify workflow targets.""" 

33 

34 device: str 

35 path: StructurePath 

36 

37 @property 

38 def depth(self) -> int: 

39 """Number of path segments below the sensor root.""" 

40 return len(self.path) 

41 

42 @property 

43 def path_str(self) -> str: 

44 """Path segments joined with slashes, or `<root>` at the sensor root.""" 

45 return "/".join(self.path) or "<root>" 

46 

47 

48def _listed(v: object) -> object: 

49 """Accept a single name wherever a list of names is expected.""" 

50 return [v] if isinstance(v, str) else v 

51 

52 

53class Device(BaseModel, frozen=True, extra="forbid"): 

54 """A device reference with optional trait assertions and grouping tags. 

55 

56 Binding requires the device to satisfy every declared trait. These 

57 assertions do not limit which reported capabilities the planner can use. 

58 

59 Set `instrument` to make the device a collection target. Its key becomes a 

60 final path segment, distinguishing instruments in the same component list. 

61 """ 

62 

63 device: str 

64 traits: Annotated[tuple[str, ...], BeforeValidator(_listed)] = () 

65 tags: Annotated[tuple[str, ...], BeforeValidator(_listed)] = () 

66 instrument: bool = False 

67 

68 def placement(self, path: StructurePath) -> Placement: 

69 """Return the placement at `path`, appending the key for an instrument.""" 

70 return Placement(self.device, path + (self.device,) if self.instrument else path) 

71 

72 

73class Unit(BaseModel, frozen=True, extra="forbid"): 

74 """An organizational container, such as an aperture or an instrument bench. 

75 

76 Units may nest. Non-instrument devices in a unit appear on every instrument 

77 chain within it, including chains in nested units and selector ports. 

78 """ 

79 

80 unit: str 

81 components: tuple[Component, ...] = () 

82 

83 

84class Port(BaseModel, frozen=True, extra="forbid"): 

85 """A selector port containing devices reachable in one selector position. 

86 

87 `name` is both a path segment and the value commanded on the selector. 

88 Collect compilation derives this value from the participating instruments; 

89 callers must not also set that selector in the same epoch. 

90 """ 

91 

92 name: str 

93 components: tuple[Component, ...] = () 

94 

95 

96class Selector(BaseModel, frozen=True, extra="forbid"): 

97 """A device that routes the beam to one of its ports. 

98 

99 The selector occupies its parent's path; each port adds a segment below it. 

100 At least one port is required. Traits and tags work as they do on `Device`. 

101 """ 

102 

103 selector: str 

104 ports: tuple[Port, ...] = Field(min_length=1) 

105 traits: Annotated[tuple[str, ...], BeforeValidator(_listed)] = () 

106 tags: Annotated[tuple[str, ...], BeforeValidator(_listed)] = () 

107 

108 

109def _record_kind(v: object) -> str | None: 

110 """Identify a component by its model type or identifying mapping key.""" 

111 match v: 

112 case Device(): 

113 return "device" 

114 case Unit(): 

115 return "unit" 

116 case Selector(): 

117 return "selector" 

118 case Mapping(): 

119 return next((k for k in ("device", "unit", "selector") if k in v), None) 

120 

121 return None 

122 

123 

124# Use the identifying key to report validation errors for the selected model. 

125type Component = Annotated[ 

126 Annotated[Device, Tag("device")] 

127 | Annotated[Unit, Tag("unit")] 

128 | Annotated[Selector, Tag("selector")], 

129 Discriminator(_record_kind), 

130] 

131 

132 

133class Structure(BaseModel, frozen=True, extra="forbid"): 

134 """The root components of one sensor. 

135 

136 Non-instrument devices at the root, such as a mount or dome, appear on every 

137 instrument's chain. 

138 Build a `Topology` to check device uniqueness and sibling path names. 

139 """ 

140 

141 components: tuple[Component, ...] = () 

142 

143 

144# Resolve recursive component annotations now that `Component` is defined. 

145Unit.model_rebuild() 

146Port.model_rebuild() 

147Selector.model_rebuild() 

148 

149 

150def format_paths(placements: Iterable[Placement]) -> str: 

151 """Render participant paths for routing diagnostics.""" 

152 return ", ".join(p.path_str for p in placements) or "<no instrument>" 

153 

154 

155class Topology: 

156 """Validated indexes of placements, instrument chains and shared devices. 

157 

158 All relationships come from the structure; construction requires no device 

159 clients or capability facts. 

160 

161 Raises: 

162 ValueError: A device key occurs more than once, or sibling units, ports 

163 or instruments contribute duplicate path segments. 

164 """ 

165 

166 def __init__(self, structure: Structure): 

167 self.structure = structure 

168 self._records: dict[Placement, Device | Selector] = {} 

169 self._chains: dict[Placement, tuple[Placement, ...]] = {} 

170 self._ports: dict[Placement, tuple[tuple[Placement, str], ...]] = {} 

171 self._placed: dict[str, Placement] = {} 

172 

173 self._visit(structure.components, (), (), ()) 

174 

175 # Preserve traversal order for discovery and other per-device operations. 

176 self._placements = tuple(self._records) 

177 self._instruments = tuple(self._chains) 

178 

179 readers: dict[Placement, list[Placement]] = {} 

180 

181 for instrument, chain in self._chains.items(): 

182 for placement in chain: 

183 readers.setdefault(placement, []).append(instrument) 

184 

185 self._readers = {p: tuple(insts) for p, insts in readers.items()} 

186 self._private = { 

187 instrument: frozenset(p for p in chain if self._owned(p, instrument)) 

188 for instrument, chain in self._chains.items() 

189 } 

190 

191 def placements(self) -> tuple[Placement, ...]: 

192 """Return one placement per device, in structure traversal order.""" 

193 return self._placements 

194 

195 def record(self, placement: Placement) -> Device | Selector: 

196 """Return the authored device or selector record for a placement. 

197 

198 Raises: 

199 KeyError: The placement is not in this topology. 

200 """ 

201 return self._records[placement] 

202 

203 def tags(self, placement: Placement) -> frozenset[str]: 

204 """Return grouping tags from the authored placement record. 

205 

206 Raises: 

207 KeyError: The placement is not in this topology. 

208 """ 

209 return frozenset(self.record(placement).tags) 

210 

211 def kind(self, placement: Placement) -> Literal["device", "instrument", "selector"]: 

212 """Return the placement's device, instrument or selector kind. 

213 

214 Raises: 

215 KeyError: The placement is not in this topology. 

216 """ 

217 match self.record(placement): 

218 case Selector(): 

219 return "selector" 

220 case Device(instrument=True): 

221 return "instrument" 

222 

223 return "device" 

224 

225 def instrument(self, placement: Placement) -> bool: 

226 """Test whether the record marks this placement as a collection 

227 target. 

228 

229 Instrument status is configured, not inferred from camera capabilities. 

230 

231 Raises: 

232 KeyError: The placement is not in this topology. 

233 """ 

234 record = self.record(placement) 

235 

236 return isinstance(record, Device) and record.instrument 

237 

238 def instruments(self) -> tuple[Placement, ...]: 

239 """Return collection targets in structure traversal order.""" 

240 return self._instruments 

241 

242 def chain(self, instrument: Placement) -> tuple[Placement, ...]: 

243 """Return the instrument's device chain, from root to instrument. 

244 

245 The chain includes non-instrument devices at each containing level, 

246 selectors and the instrument itself. 

247 

248 Raises: 

249 KeyError: The placement is not an instrument. 

250 """ 

251 return self._chains[instrument] 

252 

253 def readers_of(self, placement: Placement) -> tuple[Placement, ...]: 

254 """Return instruments whose chains include this placement. 

255 

256 Collect barriers use these readers to wait for acquisitions before 

257 changing a device's settings. Return an empty tuple if there are none. 

258 """ 

259 return self._readers.get(placement, ()) 

260 

261 def private(self, instrument: Placement) -> frozenset[Placement]: 

262 """Return chain placements local to this instrument and used only by it. 

263 

264 A placement is local if it shares the instrument's path or sits directly 

265 beside it in the parent component list. Ancestor devices remain shared 

266 infrastructure even when this instrument is their only reader. 

267 

268 Raises: 

269 KeyError: The placement is not an instrument. 

270 """ 

271 return self._private[instrument] 

272 

273 def selector_states(self, instrument: Placement) -> tuple[tuple[Placement, str], ...]: 

274 """Return selector placements and required port names, from root to leaf. 

275 

276 Raises: 

277 KeyError: The placement is not an instrument. 

278 """ 

279 return self._ports[instrument] 

280 

281 def mutually_exclusive(self, a: Placement, b: Placement) -> Placement | None: 

282 """Return the first selector requiring different ports for the instruments. 

283 

284 Return `None` if both instruments can be reached at once. 

285 

286 Raises: 

287 KeyError: Either placement is not an instrument in this topology. 

288 """ 

289 ports = dict(self._ports[b]) 

290 

291 for selector, port in self._ports[a]: 

292 if selector in ports and ports[selector] != port: 

293 return selector 

294 

295 return None 

296 

297 def _visit( 

298 self, 

299 components: tuple[Component, ...], 

300 path: StructurePath, 

301 above: tuple[Placement, ...], 

302 selected: tuple[tuple[Placement, str], ...], 

303 ) -> None: 

304 """Index a component list, then descend into its units and selector ports. 

305 

306 Add the level's non-instrument devices and selectors to every chain 

307 before recording instruments. Record devices first, then visit units 

308 and selectors in their authored order. 

309 """ 

310 here = above + self._scan(components, path) 

311 

312 for node in components: 

313 if isinstance(node, Device): 

314 placement = node.placement(path) 

315 self._records[placement] = node 

316 

317 if node.instrument: 

318 self._chains[placement] = here + (placement,) 

319 self._ports[placement] = selected 

320 

321 for node in components: 

322 match node: 

323 case Unit(): 

324 self._visit(node.components, path + (node.unit,), here, selected) 

325 case Selector(): 

326 placement = Placement(node.selector, path) 

327 self._records[placement] = node 

328 

329 for port in node.ports: 

330 self._visit( 

331 port.components, 

332 path + (port.name,), 

333 here, 

334 selected + ((placement, port.name),), 

335 ) 

336 

337 def _scan( 

338 self, components: tuple[Component, ...], path: StructurePath 

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

340 """Validate this level and return its shared placements in authored order. 

341 

342 Non-instrument devices and selectors are shared by the level's 

343 instruments and descendants. Each instrument ends its own chain. 

344 

345 Raises: 

346 ValueError: A device is placed twice, or two children contribute 

347 the same path segment. 

348 """ 

349 shared: list[Placement] = [] 

350 segments: list[str] = [] 

351 

352 for node in components: 

353 match node: 

354 case Device(): 

355 placement = node.placement(path) 

356 self._claim(node.device, placement) 

357 

358 if node.instrument: 

359 segments.append(node.device) 

360 else: 

361 shared.append(placement) 

362 case Unit(): 

363 segments.append(node.unit) 

364 case Selector(): 

365 placement = Placement(node.selector, path) 

366 self._claim(node.selector, placement) 

367 shared.append(placement) 

368 segments.extend(port.name for port in node.ports) 

369 

370 # Selectors add no path segment, so their ports share a namespace with 

371 # sibling units, instruments and other selectors' ports. 

372 dupes = sorted({s for s in segments if segments.count(s) > 1}) 

373 

374 if dupes: 

375 where = "/".join(path) or "<root>" 

376 raise ValueError(f"positions named twice under '{where}': {', '.join(dupes)}") 

377 

378 return tuple(shared) 

379 

380 def _claim(self, device: str, placement: Placement) -> None: 

381 """Reserve a device key for one placement. 

382 

383 Raises: 

384 ValueError: The device key has already been claimed. 

385 """ 

386 held = self._placed.get(device) 

387 

388 if held is not None: 

389 raise ValueError( 

390 f"device '{device}' is placed twice, at " 

391 f"'{held.path_str}' and '{placement.path_str}'" 

392 ) 

393 

394 self._placed[device] = placement 

395 

396 def _owned(self, placement: Placement, instrument: Placement) -> bool: 

397 """Test whether a chain placement is local and has only this reader.""" 

398 local = placement.path in (instrument.path[:-1], instrument.path) 

399 

400 return local and self._readers[placement] == (instrument,)