Coverage for core / src / sensorkit / sensor / autofocus.py: 88%

95 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"""Plan a fixed autofocus sweep and read back its analysis. 

3 

4Each position requests a focuser move followed by one light frame. 

5Frames carry `FocusSweepContext` identifying the sweep and sample. 

6The configured provider publishes `FocusSweepAnalysis` for the controller 

7to select the final focuser position. 

8""" 

9 

10from __future__ import annotations 

11 

12import asyncio 

13import contextlib 

14import math 

15from collections.abc import AsyncIterator, Callable, Mapping 

16from dataclasses import dataclass 

17from uuid import UUID 

18 

19import sensorkit.api as sk 

20from sensorkit.backend.base import KeyNotFound 

21from sensorkit.common.aio import cleanup_future, defer_cancellation 

22from sensorkit.sensor.binding import BoundSensor 

23from sensorkit.sensor.collect import ( 

24 AcquisitionRequest, 

25 CollectIntent, 

26 CommandRequest, 

27 InstrumentRequest, 

28 RequestEpoch, 

29) 

30from sensorkit.sensor.lifecycle import Entry, LifecycleWorkflow, OpSpec, Phase 

31from sensorkit.sensor.selection import IsRef, Supports 

32from sensorkit.sensor.standard_task import capture_settings, instrument_selection 

33from sensorkit.sensor.topology import Placement 

34from sensorkit.std.focus import ( 

35 AutoFocus, 

36 ChangeFocusPosition, 

37 FocusAnalysisSource, 

38 FocusPosition, 

39 FocusProvider, 

40 FocusSweepAnalysis, 

41 FocusSweepContext, 

42) 

43 

44 

45def translate_autofocus( 

46 task: AutoFocus, 

47 positions: list[float], 

48 *, 

49 sweep_id: UUID, 

50 focuser: str, 

51 instruments: Mapping[str, Placement], 

52 readout_margin_s: float = 60.0, 

53) -> CollectIntent: 

54 """Translate a fixed focus sweep into one epoch per position. 

55 

56 Preserve the supplied position order, pointing, and tracking. 

57 Each frame carries `FocusSweepContext`. 

58 Capture timeouts allow the exposure duration plus the readout margin. 

59 

60 Raises: 

61 ValueError: The instrument name is unknown. 

62 """ 

63 selection = instrument_selection(task.instrument, instruments) 

64 camera = capture_settings( 

65 task.filter_name, binning=task.binning, gain=task.gain, readout_mode=task.readout_mode 

66 ) 

67 count = len(positions) 

68 

69 def sample(index: int, position: float) -> RequestEpoch: 

70 move = CommandRequest(command=ChangeFocusPosition(position=position), device=focuser) 

71 request = InstrumentRequest( 

72 id=f"sample-{index}", 

73 assignment="sweep", 

74 acquisition=AcquisitionRequest( 

75 integration_time_s=task.integration_time_seconds, 

76 timeout_s=task.integration_time_seconds + readout_margin_s, 

77 ), 

78 keywords=( 

79 FocusSweepContext( 

80 sweep_id=sweep_id, 

81 sample_index=index, 

82 sample_count=count, 

83 commanded_position=position, 

84 ), 

85 ), 

86 select=selection, 

87 settings=(move, *camera), 

88 ) 

89 

90 return RequestEpoch(units=(request,)) 

91 

92 return CollectIntent( 

93 name=task.task_type, 

94 epochs=tuple(sample(index, position) for index, position in enumerate(positions)), 

95 ) 

96 

97 

98@dataclass(frozen=True) 

99class Focuser: 

100 """The one focuser on an instrument's chain and its starting position.""" 

101 

102 device: str 

103 start: float 

104 

105 @classmethod 

106 def on( 

107 cls, 

108 sensor: BoundSensor, 

109 instrument: str, 

110 instruments: Mapping[str, Placement], 

111 contexts: Mapping[str, sk.Context], 

112 ) -> Focuser: 

113 """Find the instrument's focuser and its reported position. 

114 

115 Raises: 

116 ValueError: The instrument is unknown, its chain has no single 

117 focuser, or the focuser reports no finite position. 

118 """ 

119 # Reject an unknown name with the error collect uses. 

120 instrument_selection(instrument, instruments) 

121 chain = sensor.topology.chain(instruments[instrument]) 

122 

123 match Supports(supports=ChangeFocusPosition).refs(chain, sensor): 

124 case (device,): 

125 pass 

126 case (): 

127 raise ValueError(f"Instrument '{instrument}' has no focuser") 

128 case found: 

129 raise ValueError( 

130 f"Instrument '{instrument}' has focusers {', '.join(found)}; " 

131 f"an autofocus moves exactly one" 

132 ) 

133 

134 reported = contexts[device].get(FocusPosition) 

135 

136 if reported is None or not math.isfinite(reported.position): 

137 raise ValueError(f"Focuser '{device}' reports no position to return to") 

138 

139 return cls(device=device, start=reported.position) 

140 

141 def move(self, position: float) -> LifecycleWorkflow: 

142 """Request one move, failing on its first error.""" 

143 return LifecycleWorkflow( 

144 name="autofocus", 

145 fail_fast=True, 

146 phases=( 

147 Phase( 

148 name="focus", 

149 entries=( 

150 Entry( 

151 select=IsRef(device=self.device), 

152 ops=(OpSpec(command=ChangeFocusPosition(position=position)),), 

153 ), 

154 ), 

155 ), 

156 ), 

157 ) 

158 

159 

160async def focus_source(controller: sk.ControllerImpl) -> sk.EntityClient: 

161 """Resolve the controller's configured focus analysis entity. 

162 

163 Raises: 

164 ValueError: No source is configured, or it is offline or does not 

165 publish focus analysis. 

166 """ 

167 try: 

168 configured = await controller.kv_get_model(FocusAnalysisSource) 

169 except KeyNotFound: 

170 raise ValueError("No FocusAnalysisSource names a focus analysis entity") from None 

171 

172 name = configured.entity.name 

173 source = controller.sensorkit().entity(name) 

174 

175 if not await source.is_online(): 

176 raise ValueError(f"Focus analysis source '{name}' is offline") 

177 

178 try: 

179 details = await source.get_details() 

180 except (KeyNotFound, ValueError): 

181 raise ValueError(f"'{name}' does not publish focus analysis") from None 

182 

183 if not FocusProvider.match(details): 

184 raise ValueError(f"'{name}' does not publish focus analysis") 

185 

186 return source 

187 

188 

189@contextlib.asynccontextmanager 

190async def first_sweep_analysis( 

191 source: sk.EntityClient, *, controller: str, instrument: str, sweep_id: UUID 

192) -> AsyncIterator[asyncio.Task[FocusSweepAnalysis]]: 

193 """Yield a task resolving to the first analysis of one sweep from `source`. 

194 

195 The subscription is live before this yields and is released on exit. 

196 """ 

197 identity = (controller, instrument, sweep_id) 

198 

199 def wanted(result: FocusSweepAnalysis) -> bool: 

200 return (result.controller_id.name, result.instrument, result.sweep_id) == identity 

201 

202 subscribed = asyncio.get_running_loop().create_future() 

203 waiter = asyncio.create_task(_receive(source, wanted, subscribed)) 

204 

205 try: 

206 await asyncio.wait({subscribed, waiter}, return_when=asyncio.FIRST_COMPLETED) 

207 

208 if not subscribed.done(): 

209 waiter.result() 

210 

211 yield waiter 

212 finally: 

213 waiter.cancel() 

214 await defer_cancellation(asyncio.wait({waiter})) 

215 cleanup_future(waiter) 

216 

217 

218async def _receive( 

219 source: sk.EntityClient, 

220 wanted: Callable[[FocusSweepAnalysis], bool], 

221 subscribed: asyncio.Future[None], 

222) -> FocusSweepAnalysis: 

223 """Return the first wanted analysis, resolving `subscribed` once results can arrive.""" 

224 results = await source.monitor(FocusSweepAnalysis) 

225 

226 async with contextlib.aclosing(results): 

227 subscribed.set_result(None) 

228 

229 async for _, analysis in results: 

230 if wanted(analysis): 

231 return analysis 

232 

233 raise RuntimeError(f"'{source.entity}' stopped publishing focus analysis") 

234 

235 

236def final_focus_position(analysis: FocusSweepAnalysis, positions: list[float]) -> float: 

237 """Return the final focuser position from the sweep analysis. 

238 

239 Return the estimated best focus within the sweep, or the sampled boundary 

240 in the direction of best focus. 

241 

242 Raises: 

243 RuntimeError: The analysis failed or puts its position outside the sweep. 

244 """ 

245 low, high = min(positions), max(positions) 

246 

247 match analysis: 

248 case FocusSweepAnalysis(outcome="failure", reason=reason): 

249 raise RuntimeError(f"Focus sweep analysis failed: {reason}") 

250 case FocusSweepAnalysis(position=float(position)) if low <= position <= high: 

251 return position 

252 case FocusSweepAnalysis(position=position): 

253 raise RuntimeError( 

254 f"Focus position {position} lies outside the swept range {low} to {high}" 

255 )