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

371 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"""Expand acquisition requests, assign instruments and compile collect 

3workflows. 

4 

5`pack` chooses participants, routes settings and splits incompatible requests 

6into child epochs. `compile_collect` derives dependencies and emits planned 

7steps. Shared graph compilation builds the executable graphs. Each acquisition expands 

8into a camera capture with planned keywords. 

9 

10Settings must describe absolute state. Each placement holds one setting per 

11command type. A later command replaces that setting without merging partial 

12fields. Equal commands with equal authored timeouts reuse the earlier step. 

13Relative commands such as offsets are unsuitable because each occurrence may 

14need to execute. Preparation establishes settings under the same rules. 

15 

16Settings wait for preceding operations on their device and acquisitions that 

17use it. Acquisitions require successful settings and preparation on their 

18chain. Captures run serially on each instrument. Independent chains may overlap 

19across epoch boundaries. 

20 

21Midpoint alignment centers acquisition blocks using integration-time estimates. 

22Cleanup runs in a separate graph, armed by attempted preparation. Without 

23preparation, any attempted command arms cleanup. Cleanup should stop ongoing 

24work. Recovery belongs to the agent. 

25""" 

26 

27from __future__ import annotations 

28 

29import itertools 

30from collections.abc import Mapping 

31from dataclasses import dataclass, replace 

32from typing import Literal 

33 

34from pydantic import BaseModel 

35 

36from sensorkit.common.keyword import KeywordDict 

37from sensorkit.core.device import DeviceCommand 

38from sensorkit.sensor.binding import BoundSensor 

39from sensorkit.sensor.routing import ( 

40 CommandRouter, 

41 RoutedCommand, 

42 Scope, 

43 Subject, 

44 partition, 

45) 

46from sensorkit.sensor.selection import Selection 

47from sensorkit.sensor.topology import Placement, format_paths 

48from sensorkit.sensor.workflow import ( 

49 Acquisition, 

50 CleanupPlan, 

51 DeadlineRule, 

52 Dependency, 

53 ExecutableWorkflow, 

54 OperatorRule, 

55 Origin, 

56 PlannedStep, 

57 format_command, 

58 lower, 

59) 

60from sensorkit.std.collect import CollectInfo 

61from sensorkit.std.instrument import CameraCapture, FrameType 

62from sensorkit.std.optics import SelectPort 

63 

64 

65class PackingConflict(ValueError): 

66 """Requests or participants cannot share one epoch. 

67 

68 The packer may open another epoch for this error. Other planning failures 

69 propagate because splitting an epoch would not fix them. 

70 """ 

71 

72 

73class SettingUnsatisfiable(ValueError): 

74 """A requested setting lacks command support or fails a target requirement. 

75 

76 Checks use reported capabilities and planning facts. They do not verify 

77 that hardware can achieve the requested value. 

78 """ 

79 

80 

81@dataclass(frozen=True) 

82class AcquisitionRequest: 

83 """Integration time, frame type, and optional command timeout for one 

84 capture. 

85 

86 Zero integration is allowed for bias frames. `timeout_s` limits each 

87 capture. `None` inherits configured deadline rules. 

88 """ 

89 

90 integration_time_s: float 

91 frame_type: FrameType = FrameType.LIGHT 

92 timeout_s: float | None = None 

93 

94 

95@dataclass(frozen=True) 

96class CommandRequest: 

97 """A command request with routing filters and an optional explicit 

98 timeout. 

99 

100 `subject` chooses sensor-wide or per-instrument routing. `scope`, `select` 

101 and `device` narrow the targets. Requests can configure an epoch, 

102 individual instruments, preparation or cleanup. 

103 

104 Every predicate in `requires` must match every routed target. Instrument 

105 settings with unmet requirements make the instrument ineligible during 

106 assignment. Routing chooses targets before checking requirements. 

107 

108 Each matching `prefers` predicate adds one point per routed target to the 

109 instrument's ranking. Only instrument settings may specify preferences. 

110 

111 Collect settings must be absolute, with one state per command type. Restate 

112 all required fields in partial-update commands; compilation does not merge 

113 them. Requests merged on one target must agree on both command and timeout. 

114 """ 

115 

116 command: DeviceCommand 

117 subject: Subject = "instrument" 

118 select: Selection | None = None 

119 scope: Scope = "any" 

120 device: str | None = None 

121 timeout_s: float | None = None 

122 requires: tuple[Selection, ...] = () 

123 prefers: tuple[Selection, ...] = () 

124 

125 def resolve( 

126 self, participants: tuple[Placement, ...], sensor: BoundSensor 

127 ) -> tuple[RoutedCommand, ...]: 

128 """Route this command, check target requirements and attach its 

129 authored timeout. 

130 

131 Packing checks that requests sharing a target agree. An explicit 

132 device must belong to a participating chain and support the command. 

133 

134 Raises: 

135 SettingUnsatisfiable: A participant group has no supporting device, 

136 or a routed target fails a requirement. 

137 ValueError: Routing is ambiguous, filters remove all candidates, or 

138 a named device is unreachable or unsupported. 

139 """ 

140 router = CommandRouter(sensor) 

141 named = type(self.command).model_tag() 

142 unsupported = next( 

143 ( 

144 group 

145 for group in partition(self.subject, participants) 

146 if not router.supported_on(named, group) 

147 ), 

148 None, 

149 ) 

150 

151 if self.device is None and unsupported is not None: 

152 raise SettingUnsatisfiable( 

153 f"no device on {format_paths(unsupported)} supports '{named}', so " 

154 f"nothing can establish what it was asked for" 

155 ) 

156 

157 routed = router.route( 

158 self.command, 

159 self.subject, 

160 participants, 

161 select=self.select, 

162 scope=self.scope, 

163 device=self.device, 

164 ) 

165 unmet = next( 

166 ( 

167 (r.target, requirement) 

168 for r in routed 

169 for requirement in self.requires 

170 if not requirement.matches(r.target, sensor) 

171 ), 

172 None, 

173 ) 

174 

175 if unmet is not None: 

176 target, requirement = unmet 

177 raise SettingUnsatisfiable( 

178 f"'{target.device}' takes '{named}' for {format_paths(participants)} but " 

179 f"does not satisfy {requirement.model_dump_json(by_alias=True)}" 

180 ) 

181 

182 return tuple(replace(r, timeout_s=self.timeout_s) for r in routed) 

183 

184 def resolve_shared( 

185 self, participants: tuple[Placement, ...], sensor: BoundSensor 

186 ) -> tuple[RoutedCommand, ...]: 

187 """Route an epoch setting, distinguishing combined-participant 

188 conflicts. 

189 

190 Raises: 

191 PackingConflict: Combined routing fails although each participant 

192 routes successfully alone. 

193 SettingUnsatisfiable: A participant group has no supporting device, 

194 or a routed target fails a requirement. 

195 ValueError: Routing fails for an individual participant. 

196 """ 

197 try: 

198 return self.resolve(participants, sensor) 

199 except SettingUnsatisfiable: 

200 raise 

201 except ValueError as conflict: 

202 if len(participants) > 1 and all(self._alone(p, sensor) for p in participants): 

203 raise PackingConflict(str(conflict)) from conflict 

204 

205 raise 

206 

207 def _alone(self, participant: Placement, sensor: BoundSensor) -> bool: 

208 """Test whether the request routes successfully for one participant.""" 

209 try: 

210 self.resolve((participant,), sensor) 

211 except ValueError: 

212 return False 

213 

214 return True 

215 

216 

217@dataclass(frozen=True) 

218class InstrumentRequest: 

219 """Acquisitions to repeat on selected instruments under requested settings. 

220 

221 `count` is the number of captures per assigned instrument. 

222 `distribute="one"` chooses one instrument for the entire count. 

223 `distribute="each"` gives the entire count to every eligible instrument. 

224 

225 `select` tests instrument placements. Each predicate in `requires` must 

226 match the instrument's chain. Each setting must route successfully and 

227 satisfy its target requirements. Chain preferences and setting target 

228 preferences contribute to the same ranking. 

229 

230 `collect` carries the requested target and camera parameters. Expansion 

231 fills its per-instrument frame number. `keywords` adds typed keywords to 

232 every capture of the request. Dispatch samples device keywords for each 

233 capture's header. 

234 

235 Requests with the same `assignment` form a group across the collect. 

236 The chosen instruments must be eligible for every segment. Segments must 

237 agree on distribution but may have different counts. Request ordinals 

238 continue per instrument across segments. An unnamed request forms its own 

239 group. 

240 """ 

241 

242 id: str 

243 acquisition: AcquisitionRequest 

244 count: int = 1 

245 distribute: Literal["one", "each"] = "one" 

246 collect: CollectInfo | None = None 

247 keywords: tuple[BaseModel, ...] = () 

248 select: Selection | None = None 

249 settings: tuple[CommandRequest, ...] = () 

250 requires: tuple[Selection, ...] = () 

251 prefers: tuple[Selection, ...] = () 

252 assignment: str | None = None 

253 

254 def expand( 

255 self, target: Placement, first_frame: int, first_index: int 

256 ) -> tuple[PlannedAcquisition, ...]: 

257 """Expand the full request into camera captures for one chosen 

258 instrument. 

259 

260 `first_frame` starts per-instrument frame numbering. `first_index` 

261 starts this segment's request ordinals. Each capture carries planned 

262 keywords and the acquisition timeout. Dispatch builds its header. 

263 Duration estimates include integration time only. 

264 """ 

265 asked = self.acquisition 

266 frames = range(first_frame, first_frame + self.count) 

267 

268 return tuple( 

269 PlannedAcquisition( 

270 acquisition=Acquisition( 

271 request=self.id, 

272 index=first_index + offset, 

273 frame_number=frame, 

274 keywords=self._capture_keywords(frame), 

275 ), 

276 target=target, 

277 command=CameraCapture( 

278 integration_time=asked.integration_time_s, 

279 frame_type=asked.frame_type, 

280 context=None, 

281 ), 

282 estimated_duration_s=asked.integration_time_s, 

283 timeout_s=asked.timeout_s, 

284 ) 

285 for offset, frame in enumerate(frames) 

286 ) 

287 

288 def _capture_keywords(self, frame: int) -> KeywordDict: 

289 """Copy per-capture keywords and assign the collect frame number.""" 

290 planned = KeywordDict(None, *(keyword.model_copy(deep=True) for keyword in self.keywords)) 

291 

292 if self.collect is not None: 

293 planned.set(self.collect.model_copy(deep=True, update={"frame_number": frame})) 

294 

295 return planned 

296 

297 def assignment_key(self, epoch: int, position: int) -> tuple[bool, str]: 

298 """Return the named assignment group or a unique key for an unnamed 

299 request. 

300 

301 Named groups span the collect; unnamed requests are keyed by epoch and 

302 position. 

303 """ 

304 if self.assignment is None: 

305 return False, f"{epoch}/{position}" 

306 

307 return True, self.assignment 

308 

309 def admits(self, placement: Placement, sensor: BoundSensor) -> bool: 

310 """Test instrument selection at the placement and requirements over its 

311 chain. 

312 """ 

313 if self.select is not None and not self.select.matches(placement, sensor): 

314 return False 

315 

316 chain = sensor.topology.chain(placement) 

317 

318 return all(requirement.reaches(chain, sensor) for requirement in self.requires) 

319 

320 def check(self, where: str) -> None: 

321 """Check that the request has a positive count and nonnegative 

322 integration. 

323 

324 Raises: 

325 ValueError: Count is below one or integration time is negative. 

326 """ 

327 if self.count < 1: 

328 raise ValueError( 

329 f"{where}: request '{self.id}' takes {self.count} " 

330 f"acquisition(s); drop the request instead" 

331 ) 

332 

333 asked = self.acquisition 

334 

335 # Bias frames permit zero integration time. 

336 if asked.integration_time_s < 0: 

337 raise ValueError( 

338 f"{where}: request '{self.id}' integrates for {asked.integration_time_s} seconds" 

339 ) 

340 

341 

342@dataclass(frozen=True) 

343class PlannedAcquisition: 

344 """A capture command for a chosen instrument, with frame metadata and 

345 estimate. 

346 

347 The dispatcher fills the header on a copy of the command. Acquisition 

348 metadata passes unchanged to the operation. `timeout_s` retains the 

349 request's override. 

350 """ 

351 

352 acquisition: Acquisition 

353 target: Placement 

354 command: DeviceCommand 

355 estimated_duration_s: float 

356 timeout_s: float | None = None 

357 

358 

359@dataclass(frozen=True) 

360class Epoch[Setting, Unit]: 

361 """A group of acquisitions under one configuration, before or after 

362 binding. 

363 

364 Packing may split incompatible requests into child epochs while preserving 

365 authored boundaries. Each child retains the epoch's settings and alignment. 

366 Request settings also apply to the child. Alignment is calculated per 

367 child. Bound settings contain commands routed to placements. 

368 """ 

369 

370 units: tuple[Unit, ...] 

371 settings: tuple[Setting, ...] = () 

372 align: Literal["start", "midpoint"] = "start" 

373 

374 

375@dataclass(frozen=True) 

376class Collect[Setting, Unit]: 

377 """An ordered set of configuration epochs with preparation and cleanup. 

378 

379 Preparation runs in the main graph and gates acquisitions. Cleanup runs 

380 separately after it drains, unless hard cancellation skips it. Any 

381 attempted preparation arms cleanup; without preparation, any attempted 

382 command does. A workflow with no attempted command never arms its cleanup. 

383 

384 `fail_fast` sets the default for main-workflow operations. Cleanup continues 

385 after command failures and is bounded by `cleanup_timeout_s`. Command 

386 deadlines apply independently. 

387 """ 

388 

389 name: str 

390 epochs: tuple[Epoch[Setting, Unit], ...] 

391 prepare: tuple[Setting, ...] = () 

392 cleanup: tuple[Setting, ...] = () 

393 cleanup_timeout_s: float = 60.0 

394 fail_fast: bool = True 

395 

396 

397RequestEpoch = Epoch[CommandRequest, InstrumentRequest] 

398"""An authored configuration epoch before participant assignment.""" 

399 

400CollectIntent = Collect[CommandRequest, InstrumentRequest] 

401"""An authored collect before participant assignment and routing.""" 

402 

403BoundEpoch = Epoch[RoutedCommand, PlannedAcquisition] 

404"""A configuration epoch with chosen instruments and routed settings.""" 

405 

406BoundCollect = Collect[RoutedCommand, PlannedAcquisition] 

407"""A collect with chosen instruments, numbered acquisitions and routed 

408commands. 

409""" 

410 

411 

412type Members = tuple[tuple[InstrumentRequest, RequestEpoch], ...] 

413 

414 

415def pack( 

416 intent: CollectIntent, 

417 sensor: BoundSensor, 

418 *, 

419 device_keywords: Mapping[str, KeywordDict] | None = None, 

420) -> BoundCollect: 

421 """Choose instruments, route commands and split incompatible 

422 configuration epochs. 

423 

424 Rank assignment options by the number of satisfied chain and target 

425 preferences, then by lowest accumulated integration time. Choose the first 

426 option that fits the current child epoch, or open a new child. Charge each 

427 assignment group's full duration when first placed. Preserve authored 

428 epoch boundaries, order, settings and per-child alignment. 

429 

430 `device_keywords` supplies the keywords for planning selections and 

431 replaces any keywords in `sensor`. A missing mapping, device or keyword 

432 is treated as absent. 

433 

434 Raises: 

435 SettingUnsatisfiable: A required setting has no supporting device, 

436 or a routed target fails a requirement. 

437 ValueError: Requests or assignments are invalid, target preferences 

438 appear outside instrument settings, routing fails, or a request 

439 cannot fit even by itself. `PackingConflict` is a subclass. 

440 """ 

441 return CollectPacker(intent, sensor, device_keywords=device_keywords).run() 

442 

443 

444class CollectPacker: 

445 """Single-use state for assigning instruments and splitting epochs. 

446 

447 Track each assignment group's chosen instruments, accumulated integration 

448 time per instrument, and frame and ordinal counters across the collect. 

449 """ 

450 

451 def __init__( 

452 self, 

453 intent: CollectIntent, 

454 sensor: BoundSensor, 

455 *, 

456 device_keywords: Mapping[str, KeywordDict] | None = None, 

457 ): 

458 self.intent = intent 

459 self.sensor = BoundSensor( 

460 sensor.topology, 

461 sensor.details, 

462 device_keywords={} if device_keywords is None else device_keywords, 

463 ) 

464 self.groups: dict[tuple[bool, str], Members] = {} 

465 self.chosen: dict[tuple[bool, str], tuple[Placement, ...]] = {} 

466 self.load: dict[Placement, float] = {} 

467 self.frames: dict[Placement, int] = {} 

468 self.ordinals: dict[tuple[str, Placement], int] = {} 

469 

470 def run(self) -> BoundCollect: 

471 """Validate and group requests, pack each authored epoch, then route 

472 preparation and cleanup over all participants. 

473 """ 

474 intent = self.intent 

475 _unranked(intent) 

476 self.groups = _grouped(intent) 

477 packed: list[BoundEpoch] = [] 

478 

479 for index, epoch in enumerate(intent.epochs): 

480 packed += self._pack_epoch(epoch, index) 

481 

482 participants = tuple( 

483 dict.fromkeys(unit.target for epoch in packed for unit in epoch.units) 

484 ) 

485 

486 return BoundCollect( 

487 name=intent.name, 

488 epochs=tuple(packed), 

489 prepare=tuple( 

490 routed for r in intent.prepare for routed in r.resolve(participants, self.sensor) 

491 ), 

492 cleanup=tuple( 

493 routed for r in intent.cleanup for routed in r.resolve(participants, self.sensor) 

494 ), 

495 cleanup_timeout_s=intent.cleanup_timeout_s, 

496 fail_fast=intent.fail_fast, 

497 ) 

498 

499 def _pack_epoch(self, epoch: RequestEpoch, index: int) -> list[BoundEpoch]: 

500 """Pack one authored epoch into compatible child epochs without 

501 crossing its boundary. 

502 """ 

503 where = f"epoch {index}" 

504 children: list[list[tuple[InstrumentRequest, tuple[Placement, ...]]]] = [[]] 

505 

506 for position, request in enumerate(epoch.units): 

507 key = request.assignment_key(index, position) 

508 options = (self.chosen[key],) if key in self.chosen else self._options(key, where) 

509 targets = next( 

510 ( 

511 option 

512 for option in options 

513 if self._fits([*children[-1], (request, option)], epoch, where) 

514 ), 

515 None, 

516 ) 

517 

518 if targets is None: 

519 children.append([]) 

520 targets = options[0] 

521 # A request that fails alone cannot be repaired by splitting epochs. 

522 self._resolved([(request, targets)], epoch, where) 

523 

524 self._bind(key, targets) 

525 children[-1].append((request, targets)) 

526 

527 return [self._child(child, epoch, where) for child in children if child] 

528 

529 def _options(self, key: tuple[bool, str], where: str) -> tuple[tuple[Placement, ...], ...]: 

530 """Rank an assignment group's eligible instrument sets. 

531 

532 Fan-out has one option containing every eligible instrument. 

533 Single-target options rank by most satisfied preferences, then lowest 

534 accumulated integration time. 

535 """ 

536 members = self.groups[key] 

537 eligible = _eligible(members, self.sensor, where) 

538 first, _ = members[0] 

539 

540 if first.distribute == "each": 

541 return (eligible,) 

542 

543 ranked = sorted( 

544 eligible, 

545 key=lambda p: (-_preferred(members, p, self.sensor), self.load.get(p, 0.0)), 

546 ) 

547 

548 return tuple((placement,) for placement in ranked) 

549 

550 def _bind(self, key: tuple[bool, str], targets: tuple[Placement, ...]) -> None: 

551 """Record a group's first assignment and charge its full duration to 

552 each target. 

553 """ 

554 if key in self.chosen: 

555 return 

556 

557 self.chosen[key] = targets 

558 

559 for target in targets: 

560 self.load[target] = self.load.get(target, 0.0) + _duration(self.groups[key]) 

561 

562 def _child( 

563 self, 

564 assigned: list[tuple[InstrumentRequest, tuple[Placement, ...]]], 

565 epoch: RequestEpoch, 

566 where: str, 

567 ) -> BoundEpoch: 

568 """Expand assigned requests and route the child epoch's settings. 

569 

570 Frame numbers continue per instrument across the collect. Ordinals 

571 continue per named assignment group and instrument; unnamed requests 

572 start at zero. 

573 """ 

574 units: list[PlannedAcquisition] = [] 

575 

576 for request, targets in assigned: 

577 count = request.count 

578 

579 for target in targets: 

580 frame = self.frames.get(target, 0) 

581 self.frames[target] = frame + count 

582 

583 match request.assignment: 

584 # An unnamed request starts a new ordinal sequence. 

585 case None: 

586 ordinal = 0 

587 case name: 

588 ordinal = self.ordinals.get((name, target), 0) 

589 self.ordinals[(name, target)] = ordinal + count 

590 

591 units += request.expand(target, frame, ordinal) 

592 

593 return BoundEpoch( 

594 units=tuple(units), align=epoch.align, settings=self._resolved(assigned, epoch, where) 

595 ) 

596 

597 def _fits( 

598 self, 

599 assigned: list[tuple[InstrumentRequest, tuple[Placement, ...]]], 

600 epoch: RequestEpoch, 

601 where: str, 

602 ) -> bool: 

603 """Test whether assigned requests can share an epoch. 

604 

605 Return false only for `PackingConflict`; other planning errors 

606 propagate. 

607 """ 

608 try: 

609 self._resolved(assigned, epoch, where) 

610 except PackingConflict: 

611 return False 

612 

613 return True 

614 

615 def _resolved( 

616 self, 

617 assigned: list[tuple[InstrumentRequest, tuple[Placement, ...]]], 

618 epoch: RequestEpoch, 

619 where: str, 

620 ) -> tuple[RoutedCommand, ...]: 

621 """Route and merge epoch settings and each request's instrument 

622 settings. 

623 

624 Raises: 

625 PackingConflict: Participants are exclusive or commands disagree on 

626 a shared state key. 

627 ValueError: Timeouts disagree, a setting overrides a derived 

628 selector position, or routing fails. 

629 """ 

630 sensor = self.sensor 

631 participants = tuple(dict.fromkeys(p for _, targets in assigned for p in targets)) 

632 _exclusive(participants, sensor, where) 

633 held: dict[tuple[Placement, type], tuple[RoutedCommand, str]] = {} 

634 

635 for setting in epoch.settings: 

636 for routed in setting.resolve_shared(participants, sensor): 

637 _put(held, routed, "the epoch", where) 

638 

639 for request, targets in assigned: 

640 for setting in request.settings: 

641 for routed in setting.resolve(targets, sensor): 

642 _put(held, routed, f"request '{request.id}'", where) 

643 

644 _positioned(held, participants, sensor, where) 

645 

646 return tuple(routed for routed, _ in held.values()) 

647 

648 

649def _put( 

650 held: dict[tuple[Placement, type], tuple[RoutedCommand, str]], 

651 routed: RoutedCommand, 

652 origin: str, 

653 where: str, 

654) -> None: 

655 """Merge a setting by placement and command type, requiring equal 

656 requests. 

657 

658 Raises: 

659 PackingConflict: Commands disagree for the same key. 

660 ValueError: Equal commands have different authored timeouts. 

661 """ 

662 key = (routed.target, type(routed.command)) 

663 seen = held.get(key) 

664 

665 if seen is None: 

666 held[key] = (routed, origin) 

667 

668 return 

669 

670 if seen[0].command != routed.command: 

671 raise PackingConflict( 

672 f"{where}: '{routed.target.device}' is asked for " 

673 f"{format_command(routed.command)} by {origin} and for " 

674 f"{format_command(seen[0].command)} by {seen[1]}; a device holds " 

675 f"one value per epoch" 

676 ) 

677 

678 if seen[0].timeout_s != routed.timeout_s: 

679 raise ValueError( 

680 f"{where}: {origin} and {seen[1]} ask '{routed.target.device}' for " 

681 f"{format_command(routed.command)} under deadlines of " 

682 f"{routed.timeout_s} and {seen[0].timeout_s} seconds; nothing here " 

683 f"chooses between them" 

684 ) 

685 

686 

687def _positioned( 

688 held: Mapping[tuple[Placement, type], tuple[RoutedCommand, str]], 

689 participants: tuple[Placement, ...], 

690 sensor: BoundSensor, 

691 where: str, 

692) -> None: 

693 """Reject authored settings on selectors whose positions follow from 

694 the participants. 

695 

696 Raises: 

697 ValueError: A setting targets a selector on a participating port path. 

698 """ 

699 positioned = { 

700 selector 

701 for participant in participants 

702 for selector, _ in sensor.topology.selector_states(participant) 

703 } 

704 commanded = sorted({target.device for target, _ in held if target in positioned}) 

705 

706 if commanded: 

707 raise ValueError( 

708 f"{where}: selector positions follow from the participants; do not " 

709 f"command {', '.join(repr(device) for device in commanded)}" 

710 ) 

711 

712 

713def _eligible(members: Members, sensor: BoundSensor, where: str) -> tuple[Placement, ...]: 

714 """Find instruments satisfying every segment and routing all group 

715 settings. 

716 

717 Check all segments before choosing so later segments keep the same 

718 assignment. 

719 

720 Raises: 

721 SettingUnsatisfiable: No admitted instrument can establish all 

722 settings. 

723 ValueError: No instrument meets selection and requirements, or routing 

724 fails structurally on an admitted instrument. 

725 """ 

726 admitted = tuple( 

727 placement 

728 for placement in sensor.topology.instruments() 

729 if all(member.admits(placement, sensor) for member, _ in members) 

730 ) 

731 

732 if not admitted: 

733 raise ValueError(f"{where}: no instrument satisfies {_asked(members)}") 

734 

735 refused: SettingUnsatisfiable | None = None 

736 settled: list[Placement] = [] 

737 

738 for placement in admitted: 

739 try: 

740 _establishes(members, placement, sensor) 

741 except SettingUnsatisfiable as unmet: 

742 refused = refused or unmet 

743 else: 

744 settled.append(placement) 

745 

746 if not settled: 

747 raise SettingUnsatisfiable(f"{where}: {refused}") 

748 

749 return tuple(settled) 

750 

751 

752def _establishes( 

753 members: Members, 

754 placement: Placement, 

755 sensor: BoundSensor, 

756) -> None: 

757 """Check all segment and epoch settings against one instrument's chain. 

758 

759 Packing checks compatibility with other participants separately. 

760 

761 Raises: 

762 SettingUnsatisfiable: A setting has no supporting device on this chain, 

763 or its target fails a requirement. 

764 ValueError: Routing fails structurally. 

765 """ 

766 for member, epoch in members: 

767 for setting in (*epoch.settings, *member.settings): 

768 setting.resolve((placement,), sensor) 

769 

770 

771def _preferred( 

772 members: Members, 

773 placement: Placement, 

774 sensor: BoundSensor, 

775) -> int: 

776 """Count satisfied chain and target preferences across every segment of an 

777 assignment group. 

778 

779 Each matching target preference contributes one point per routed target 

780 of its setting. Eligibility checks have already validated these routes. 

781 """ 

782 chain = sensor.topology.chain(placement) 

783 chained = sum( 

784 preference.reaches(chain, sensor) for member, _ in members for preference in member.prefers 

785 ) 

786 targeted = sum( 

787 preference.matches(routed.target, sensor) 

788 for member, _ in members 

789 for setting in member.settings 

790 if setting.prefers 

791 for routed in setting.resolve((placement,), sensor) 

792 for preference in setting.prefers 

793 ) 

794 

795 return chained + targeted 

796 

797 

798def _unranked(intent: CollectIntent) -> None: 

799 """Reject target preferences on epoch, preparation and cleanup settings. 

800 

801 Raises: 

802 ValueError: An epoch, preparation or cleanup setting has target 

803 preferences. 

804 """ 

805 placed = ( 

806 *((f"epoch {index}", epoch.settings) for index, epoch in enumerate(intent.epochs)), 

807 ("preparation", intent.prepare), 

808 ("cleanup", intent.cleanup), 

809 ) 

810 misplaced = [where for where, settings in placed if any(s.prefers for s in settings)] 

811 

812 if misplaced: 

813 raise ValueError( 

814 f"{', '.join(misplaced)}: target preferences rank instruments, so only " 

815 f"instrument settings may carry them" 

816 ) 

817 

818 

819def _grouped( 

820 intent: CollectIntent, 

821) -> dict[tuple[bool, str], Members]: 

822 """Validate requests and group them with their containing authored 

823 epochs. 

824 

825 Raises: 

826 ValueError: A request has invalid count or integration, or a named 

827 group mixes distribution modes. 

828 """ 

829 groups: dict[tuple[bool, str], list[tuple[InstrumentRequest, RequestEpoch]]] = {} 

830 

831 for index, epoch in enumerate(intent.epochs): 

832 for position, request in enumerate(epoch.units): 

833 request.check(f"epoch {index}") 

834 groups.setdefault(request.assignment_key(index, position), []).append((request, epoch)) 

835 

836 for (named, name), members in groups.items(): 

837 if named and len({m.distribute for m, _ in members}) > 1: 

838 raise ValueError( 

839 f"assignment '{name}' mixes distribute values; every " 

840 f"segment of one request takes the same instruments" 

841 ) 

842 

843 return {key: tuple(members) for key, members in groups.items()} 

844 

845 

846def _duration(members: Members) -> float: 

847 """Sum group integration time for load ranking, excluding readout and 

848 overhead. 

849 """ 

850 return sum(member.acquisition.integration_time_s * member.count for member, _ in members) 

851 

852 

853def _exclusive(participants: tuple[Placement, ...], sensor: BoundSensor, where: str) -> None: 

854 """Reject participants requiring different ports of one selector. 

855 

856 Raises: 

857 PackingConflict: The instruments cannot share a selector position. 

858 """ 

859 for a, b in itertools.combinations(participants, 2): 

860 selector = sensor.topology.mutually_exclusive(a, b) 

861 

862 if selector is not None: 

863 raise PackingConflict( 

864 f"{where}: '{a.device}' and '{b.device}' are on different " 

865 f"ports of selector '{selector.device}'" 

866 ) 

867 

868 

869def _asked(members: Members) -> str: 

870 """Format unique request ids in a group for diagnostics.""" 

871 return ", ".join(sorted({f"'{member.id}'" for member, _ in members})) 

872 

873 

874def compile_collect( 

875 collect: BoundCollect, 

876 sensor: BoundSensor, 

877 *, 

878 deadlines: tuple[DeadlineRule, ...] = (), 

879 rules: tuple[OperatorRule, ...] = (), 

880) -> ExecutableWorkflow: 

881 """Compile a bound collect into executable graphs without contacting 

882 devices. 

883 

884 Dependencies follow previously emitted steps. The result can be inspected 

885 before execution. 

886 

887 Raises: 

888 ValueError: Bound settings or participants conflict, commands are 

889 unsupported, or shared graph compilation rejects the workflow. 

890 """ 

891 return CollectCompiler(collect, sensor, deadlines=deadlines, rules=rules).run() 

892 

893 

894class CollectCompiler: 

895 """Single-use state for deriving collect dependencies and planned steps. 

896 

897 Track governing settings by placement and command type, latest operations 

898 per device, and latest acquisitions per instrument. Shared graph compilation handles 

899 omissions, deadlines, operator rules and graph construction. 

900 """ 

901 

902 def __init__( 

903 self, 

904 collect: BoundCollect, 

905 sensor: BoundSensor, 

906 *, 

907 deadlines: tuple[DeadlineRule, ...] = (), 

908 rules: tuple[OperatorRule, ...] = (), 

909 ): 

910 self.collect = collect 

911 self.sensor = sensor 

912 self.topology = sensor.topology 

913 self.deadlines = deadlines 

914 self.rules = rules 

915 self.steps: list[PlannedStep] = [] 

916 # Governing command and its step, keyed by placement and command type. 

917 self.governing: dict[tuple[Placement, type[DeviceCommand]], tuple[str, RoutedCommand]] = {} 

918 self.latest: dict[Placement, str] = {} 

919 self.last_unit: dict[Placement, str] = {} 

920 self.prepared: list[tuple[Placement, str]] = [] 

921 self.emitted = 0 

922 

923 def run(self) -> ExecutableWorkflow: 

924 """Emit preparation, epochs and cleanup, then compile their planned 

925 steps. 

926 """ 

927 for position, routed in enumerate(self.collect.prepare): 

928 name = self._setting(routed, "prepare", ("prepare", position)) 

929 self.prepared.append((routed.target, name)) 

930 

931 for index, epoch in enumerate(self.collect.epochs): 

932 self._compile_epoch(epoch, index) 

933 

934 cleanup = (self._cleanup(),) if self.collect.cleanup else () 

935 

936 return lower( 

937 self.collect.name, 

938 tuple(self.steps), 

939 self.sensor, 

940 cleanup=cleanup, 

941 deadlines=self.deadlines, 

942 rules=self.rules, 

943 ) 

944 

945 def _compile_epoch(self, epoch: BoundEpoch, index: int) -> None: 

946 """Emit changed settings and each instrument's acquisition block.""" 

947 where = f"epoch {index}" 

948 participants = tuple(dict.fromkeys(unit.target for unit in epoch.units)) 

949 _consistent(epoch, participants, self.sensor, where) 

950 

951 for routed in (*self._ports(participants), *epoch.settings): 

952 if not self._in_force(routed): 

953 self._setting(routed, where, (index, routed.command.model_tag())) 

954 

955 blocks: dict[Placement, list[PlannedAcquisition]] = {} 

956 

957 for unit in epoch.units: 

958 blocks.setdefault(unit.target, []).append(unit) 

959 

960 needs = {instrument: self._needs(instrument) for instrument in blocks} 

961 aligned, offsets = self._align(epoch, blocks, needs, index) 

962 

963 for instrument, units in blocks.items(): 

964 hard, soft = needs[instrument] 

965 self._emit_units( 

966 units, 

967 index, 

968 hard, 

969 soft if aligned is None else (*soft, aligned), 

970 offsets[instrument], 

971 ) 

972 

973 def _ports(self, participants: tuple[Placement, ...]) -> tuple[RoutedCommand, ...]: 

974 """Derive distinct selector-position commands from participant port 

975 paths. 

976 """ 

977 states = dict.fromkeys( 

978 state 

979 for participant in participants 

980 for state in self.topology.selector_states(participant) 

981 ) 

982 

983 return tuple( 

984 RoutedCommand(target=selector, command=SelectPort(port=port)) 

985 for selector, port in states 

986 ) 

987 

988 def _in_force(self, routed: RoutedCommand) -> bool: 

989 """Test whether the current setting has an equal command and timeout. 

990 

991 An equal setting reuses the earlier step and its success requirement, 

992 even if that step fails. 

993 """ 

994 held = self.governing.get(routed.governs) 

995 

996 return held is not None and held[1] == routed 

997 

998 def _setting(self, routed: RoutedCommand, group: str, path: tuple[str | int, ...]) -> str: 

999 """Emit a governing setting after preceding readers and device work 

1000 complete. 

1001 

1002 Completion dependencies serialize the device without requiring prior 

1003 success. 

1004 """ 

1005 target = routed.target 

1006 waits = [ 

1007 self.last_unit[reader] 

1008 for reader in self.topology.readers_of(target) 

1009 if reader in self.last_unit 

1010 ] 

1011 

1012 if target in self.latest: 

1013 waits.append(self.latest[target]) 

1014 

1015 step = self._planned( 

1016 group, 

1017 path, 

1018 target=target, 

1019 command=routed.command, 

1020 timeout_s=routed.timeout_s, 

1021 deps=Dependency.completion(waits), 

1022 ) 

1023 self.steps.append(step) 

1024 self.governing[routed.governs] = (step.name, routed) 

1025 self.latest[target] = step.name 

1026 

1027 return step.name 

1028 

1029 def _needs(self, instrument: Placement) -> tuple[tuple[str, ...], tuple[str, ...]]: 

1030 """Return required successes and completion waits for an 

1031 instrument's next block. 

1032 

1033 Require governing settings and all preparation on its chain. Follow its 

1034 last acquisition on completion. Preparation remains required after 

1035 later settings replace its governing state. 

1036 """ 

1037 chain = frozenset(self.topology.chain(instrument)) 

1038 hard = [name for (placement, _), (name, _) in self.governing.items() if placement in chain] 

1039 hard += [name for placement, name in self.prepared if placement in chain] 

1040 soft = (self.last_unit[instrument],) if instrument in self.last_unit else () 

1041 

1042 return tuple(dict.fromkeys(hard)), soft 

1043 

1044 def _align( 

1045 self, 

1046 epoch: BoundEpoch, 

1047 blocks: Mapping[Placement, list[PlannedAcquisition]], 

1048 needs: Mapping[Placement, tuple[tuple[str, ...], tuple[str, ...]]], 

1049 index: int, 

1050 ) -> tuple[str | None, dict[Placement, float]]: 

1051 """Build a common readiness point and offsets for estimated block 

1052 midpoints. 

1053 

1054 Spans sum acquisition estimates, currently integration time only. 

1055 Readout and transfer overhead are excluded, so actual block midpoints 

1056 may differ. Start alignment and single-instrument blocks add no common 

1057 ordering node. 

1058 """ 

1059 if epoch.align != "midpoint" or len(blocks) <= 1: 

1060 return None, dict.fromkeys(blocks, 0.0) 

1061 

1062 waits = [name for hard, soft in needs.values() for name in (*hard, *soft)] 

1063 step = self._planned( 

1064 f"epoch {index}", 

1065 (index, "align"), 

1066 deps=Dependency.completion(dict.fromkeys(waits)), 

1067 reason=f"align midpoints of epoch {index}", 

1068 ) 

1069 self.steps.append(step) 

1070 spans = { 

1071 instrument: sum(unit.estimated_duration_s for unit in units) 

1072 for instrument, units in blocks.items() 

1073 } 

1074 longest = max(spans.values()) 

1075 

1076 return step.name, {instrument: (longest - span) / 2 for instrument, span in spans.items()} 

1077 

1078 def _emit_units( 

1079 self, 

1080 units: list[PlannedAcquisition], 

1081 index: int, 

1082 hard: tuple[str, ...], 

1083 soft: tuple[str, ...], 

1084 delay_s: float, 

1085 ) -> None: 

1086 """Emit one instrument's acquisition block with serial completion 

1087 dependencies. 

1088 

1089 Every unit requires successful block settings. A failed capture alone 

1090 does not skip the next, though fail-fast policy can stop the whole run. 

1091 """ 

1092 previous: str | None = None 

1093 

1094 for unit in units: 

1095 acquisition = unit.acquisition 

1096 follows = soft if previous is None else (previous,) 

1097 step = self._planned( 

1098 f"epoch {index}", 

1099 (index, acquisition.request, acquisition.frame_number), 

1100 target=unit.target, 

1101 command=unit.command, 

1102 timeout_s=unit.timeout_s, 

1103 acquisition=acquisition, 

1104 delay_s=delay_s if previous is None else 0.0, 

1105 deps=(*(Dependency(on=name) for name in hard), *Dependency.completion(follows)), 

1106 ) 

1107 self.steps.append(step) 

1108 previous = step.name 

1109 

1110 if previous is not None: 

1111 self.last_unit[units[0].target] = previous 

1112 

1113 def _cleanup(self) -> CleanupPlan: 

1114 """Plan teardown armed by preparation, or by any command if 

1115 preparation is absent. 

1116 

1117 Ordering steps do not arm it. Commands serialize per device on 

1118 completion and otherwise run independently. Non-fail-fast policy lets 

1119 teardown continue after a failed command. 

1120 """ 

1121 steps: list[PlannedStep] = [] 

1122 latest: dict[Placement, str] = {} 

1123 

1124 for position, routed in enumerate(self.collect.cleanup): 

1125 target = routed.target 

1126 step = self._planned( 

1127 "cleanup", 

1128 ("cleanup", position), 

1129 target=target, 

1130 command=routed.command, 

1131 timeout_s=routed.timeout_s, 

1132 deps=Dependency.completion((latest[target],) if target in latest else ()), 

1133 fail_fast=False, 

1134 ) 

1135 steps.append(step) 

1136 latest[target] = step.name 

1137 

1138 armed_by = ( 

1139 tuple(name for _, name in self.prepared) 

1140 if self.collect.prepare 

1141 else tuple(step.name for step in self.steps if step.command is not None) 

1142 ) 

1143 

1144 return CleanupPlan( 

1145 steps=tuple(steps), 

1146 origin=Origin(source=self.collect.name, path=("cleanup",)), 

1147 when="always", 

1148 timeout_s=self.collect.cleanup_timeout_s, 

1149 armed_by=armed_by, 

1150 ) 

1151 

1152 def _planned( 

1153 self, 

1154 group: str, 

1155 path: tuple[str | int, ...], 

1156 *, 

1157 target: Placement | None = None, 

1158 command: DeviceCommand | None = None, 

1159 deps: tuple[Dependency, ...] = (), 

1160 timeout_s: float | None = None, 

1161 acquisition: Acquisition | None = None, 

1162 delay_s: float = 0.0, 

1163 reason: str = "", 

1164 fail_fast: bool | None = None, 

1165 ) -> PlannedStep: 

1166 """Build a uniquely named step, inheriting collect failure policy 

1167 unless overridden. 

1168 """ 

1169 self.emitted += 1 

1170 where = "ordering" if target is None else target.device 

1171 

1172 return PlannedStep( 

1173 name=f"{group}/{where}/{self.emitted}", 

1174 origin=Origin(source=self.collect.name, path=path, reason=reason), 

1175 group=group, 

1176 target=target, 

1177 command=command, 

1178 deps=deps, 

1179 fail_fast=self.collect.fail_fast if fail_fast is None else fail_fast, 

1180 timeout_s=timeout_s, 

1181 acquisition=acquisition, 

1182 delay_s=delay_s, 

1183 ) 

1184 

1185 

1186def _consistent( 

1187 epoch: BoundEpoch, participants: tuple[Placement, ...], sensor: BoundSensor, where: str 

1188) -> None: 

1189 """Check bound-epoch compatibility, including for manually built 

1190 collects. 

1191 

1192 Raises: 

1193 ValueError: Participants are exclusive, commands or timeouts conflict, 

1194 or settings override derived selector positions. 

1195 """ 

1196 _exclusive(participants, sensor, where) 

1197 held: dict[tuple[Placement, type], tuple[RoutedCommand, str]] = {} 

1198 

1199 for routed in epoch.settings: 

1200 _put(held, routed, "the epoch", where) 

1201 

1202 _positioned(held, participants, sensor, where)