Coverage for core / src / sensorkit / std / focus.py: 100%

127 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"""Focuser commands and focus analysis schemas.""" 

3 

4from __future__ import annotations 

5 

6from collections.abc import Mapping 

7from typing import Literal, Self 

8from uuid import UUID 

9 

10from pydantic import BaseModel, Field, FiniteFloat, model_validator 

11 

12import sensorkit.api as sk 

13from sensorkit.std.instrument import Binning, ExposureInfo 

14 

15 

16@sk.declare_keyword 

17class FocusPosition(BaseModel): 

18 """Current position of the focuser.""" 

19 

20 position: float 

21 

22 def get_fits_cards(self): 

23 """Yield the reported focuser position as FOCPOS.""" 

24 yield "FOCPOS", (self.position, "Reported focus position") 

25 

26 @classmethod 

27 def from_fits_header(cls, header: Mapping[str, object]) -> Self | None: 

28 """Read the reported focuser position, or None if the header has no FOCPOS card. 

29 

30 Raises: 

31 ValidationError: If the card value is invalid. 

32 """ 

33 if "FOCPOS" not in header: 

34 return None 

35 

36 return cls.model_validate({"position": header["FOCPOS"]}) 

37 

38 

39class ChangeFocusPosition(sk.DeviceCommand): 

40 """Move the focuser to an absolute position. 

41 

42 Drivers may quantize the requested position to their supported resolution. 

43 Positions outside the device's travel limits fail. 

44 

45 A successful response confirms that motion has ended and the final 

46 position matches the target within the device's supported resolution. 

47 Publish that position as 

48 `FocusPosition` before responding successfully. 

49 

50 The command fails if the final position cannot be verified or differs 

51 from the target. 

52 """ 

53 

54 position: float 

55 

56 

57StandardFocuser = sk.declare_archetype( 

58 "focuser", 

59 required_commands=(ChangeFocusPosition,), 

60 required_keywords=("FocusPosition",), 

61) 

62"""A device that reports and adjusts a focus position.""" 

63 

64 

65class AutoFocus(sk.Task): 

66 """Run a fixed focus sweep for one instrument. 

67 

68 The sweep takes one light frame at each of `count` positions spaced `step` apart, 

69 lowest first, centered on `center` or else on the focuser's position at the start 

70 of the task. Current pointing and tracking are preserved. 

71 The task schema is beta. 

72 

73 Attributes: 

74 instrument: Name of the controller instrument that takes the sweep. 

75 step: Focuser travel between adjacent positions. 

76 count: Number of positions, with one exposure at each. Defaults to seven. 

77 center: Sweep center, or None for the focuser's starting position. 

78 integration_time_seconds: Exposure time of each frame. 

79 binning: Camera binning, or None to keep the current setting. 

80 gain: Camera gain, or None to keep the current setting. 

81 readout_mode: Camera readout mode, or None to keep the current setting. 

82 filter_name: Filter to select, or None to keep the current filter. 

83 """ 

84 

85 task_type: Literal["autofocus"] = "autofocus" 

86 instrument: str = Field(min_length=1) 

87 step: FiniteFloat = Field(gt=0) 

88 count: int = Field(default=7, ge=3) 

89 center: FiniteFloat | None = None 

90 integration_time_seconds: FiniteFloat = Field(gt=0) 

91 binning: Binning | None = None 

92 gain: FiniteFloat | None = None 

93 readout_mode: int | None = None 

94 filter_name: str | None = None 

95 

96 def positions(self, start: float) -> list[float]: 

97 """Return the sweep's positions, lowest first, around `center` or else `start`.""" 

98 middle = start if self.center is None else self.center 

99 offset = (self.count - 1) / 2 

100 

101 return [middle + (index - offset) * self.step for index in range(self.count)] 

102 

103 

104@sk.declare_keyword(kind="config") 

105class FocusAnalysisSource(BaseModel): 

106 """Focus analysis provider selected by a controller. 

107 

108 Attributes: 

109 entity: The entity that publishes focus analysis results. 

110 """ 

111 

112 entity: sk.EntityRef 

113 

114 

115@sk.declare_keyword(key="FocusSweep") 

116class FocusSweepContext(BaseModel): 

117 """Sweep identity and commanded position for one sample, available in context as `FocusSweep`. 

118 

119 Attributes: 

120 sweep_id: Unique sweep identifier, written as FOCSWEEP. 

121 sample_index: Zero-based sample index, written as FOCSAMP. 

122 sample_count: Requested sample count, written as FOCCOUNT. 

123 commanded_position: Requested focuser position, written as FOCCMD. 

124 """ 

125 

126 sweep_id: UUID 

127 sample_index: int = Field(ge=0) 

128 sample_count: int = Field(gt=0) 

129 commanded_position: FiniteFloat 

130 

131 @model_validator(mode="after") 

132 def _check_index(self) -> Self: 

133 if self.sample_index >= self.sample_count: 

134 raise ValueError("sample_index: must be less than sample_count") 

135 

136 return self 

137 

138 def get_fits_cards(self): 

139 """Yield FITS cards identifying this sweep sample.""" 

140 yield "FOCSWEEP", (str(self.sweep_id), "Focus sweep ID") 

141 yield "FOCSAMP", (self.sample_index, "Zero-based focus sample index") 

142 yield "FOCCOUNT", (self.sample_count, "Requested focus sample count") 

143 yield "FOCCMD", (self.commanded_position, "Commanded focus position") 

144 

145 @classmethod 

146 def from_fits_header(cls, header: Mapping[str, object]) -> Self | None: 

147 """Read sweep context from FITS header values. 

148 

149 Args: 

150 header: Header card values, such as an Astropy Header. 

151 

152 Returns: 

153 The sweep context, or None if the header has no sweep marker. 

154 

155 Raises: 

156 KeyError: If the header has a sweep marker but lacks another sweep card. 

157 ValidationError: If a sweep card value is invalid. 

158 """ 

159 if "FOCSWEEP" not in header: 

160 return None 

161 

162 return cls.model_validate( 

163 { 

164 "sweep_id": header["FOCSWEEP"], 

165 "sample_index": header["FOCSAMP"], 

166 "sample_count": header["FOCCOUNT"], 

167 "commanded_position": header["FOCCMD"], 

168 } 

169 ) 

170 

171 

172@sk.declare_keyword 

173class FocusAnalysis(BaseModel): 

174 """Focus measurement and capture metadata for one image. 

175 

176 Invalid measurements include a reason and may retain a measured FWHM and measurement count. 

177 

178 Attributes: 

179 controller_id: The controller that owns the instrument. 

180 instrument: Name of the controller instrument that took the image. 

181 image_id: Provider identifier of the analyzed image. 

182 exposure: Exposure metadata recorded at capture. 

183 reported_position: Focuser position reported at capture, if known. 

184 sweep: Sweep membership, or None for an image outside a sweep. 

185 median_fwhm_pixels: Median point-source FWHM in image pixels. 

186 measurement_count: Number of FWHM measurements represented by the result. 

187 valid: Whether the measurement is usable. 

188 reason: Why the measurement is unusable. 

189 """ 

190 

191 controller_id: sk.ControllerRef 

192 instrument: str = Field(min_length=1) 

193 image_id: str = Field(min_length=1) 

194 exposure: ExposureInfo 

195 reported_position: FiniteFloat | None = None 

196 sweep: FocusSweepContext | None = None 

197 median_fwhm_pixels: FiniteFloat | None = Field(default=None, gt=0) 

198 measurement_count: int = Field(ge=0) 

199 valid: bool 

200 reason: str | None = Field(default=None, min_length=1) 

201 

202 @model_validator(mode="after") 

203 def _check_measurement(self) -> Self: 

204 match self: 

205 case FocusAnalysis(valid=True, reason=str()): 

206 raise ValueError("reason: a valid measurement has no failure reason") 

207 case FocusAnalysis(valid=True, median_fwhm_pixels=None): 

208 raise ValueError("median_fwhm_pixels: a valid measurement requires a FWHM") 

209 case FocusAnalysis(valid=True, measurement_count=0): 

210 raise ValueError("measurement_count: a valid measurement requires a measurement") 

211 case FocusAnalysis(valid=False, reason=None): 

212 raise ValueError("reason: an invalid measurement requires a reason") 

213 

214 return self 

215 

216 

217@sk.declare_keyword 

218class FocusSweepAnalysis(BaseModel): 

219 """Focus fit outcome and sample measurements for one sweep. 

220 

221 A successful fit estimates best focus or its direction beyond the sampled range. 

222 A failed fit includes a reason and may retain sample measurements and a fit residual. 

223 

224 Attributes: 

225 controller_id: The controller that owns the instrument. 

226 instrument: Name of the controller instrument that took the sweep. 

227 sweep_id: Unique sweep identifier. 

228 outcome: Whether the fit estimated a focus position or direction. 

229 position: Estimated focus position or sampled boundary, depending on disposition. 

230 disposition: Relationship of best focus to position. `equals` gives an 

231 estimated minimum. `greater_than` and `less_than` indicate best focus 

232 beyond the corresponding boundary of the sampled range. 

233 rms_residual_pixels: Root mean square residual of the fitted FWHM values, in pixels. 

234 reason: Why the fit failed. 

235 samples: Per-image measurements used to assess the sweep. 

236 """ 

237 

238 controller_id: sk.ControllerRef 

239 instrument: str = Field(min_length=1) 

240 sweep_id: UUID 

241 outcome: Literal["success", "failure"] 

242 position: FiniteFloat | None = None 

243 disposition: Literal["equals", "greater_than", "less_than"] | None = None 

244 rms_residual_pixels: FiniteFloat | None = Field(default=None, ge=0) 

245 reason: str | None = Field(default=None, min_length=1) 

246 samples: list[FocusAnalysis] = Field(default_factory=list) 

247 

248 @model_validator(mode="after") 

249 def _check_outcome(self) -> Self: 

250 match self: 

251 case FocusSweepAnalysis(outcome="success", reason=str()): 

252 raise ValueError("reason: a successful sweep has no failure reason") 

253 case FocusSweepAnalysis(outcome="success", position=None): 

254 raise ValueError("position: a successful sweep requires a position") 

255 case FocusSweepAnalysis(outcome="success", disposition=None): 

256 raise ValueError("disposition: a successful sweep requires a disposition") 

257 case FocusSweepAnalysis(outcome="success", rms_residual_pixels=None): 

258 raise ValueError("rms_residual_pixels: a successful sweep requires a residual") 

259 case FocusSweepAnalysis(outcome="success") if not any(s.valid for s in self.samples): 

260 raise ValueError("samples: a successful sweep requires a valid sample") 

261 case FocusSweepAnalysis(outcome="failure", reason=None): 

262 raise ValueError("reason: a failed sweep requires a reason") 

263 case FocusSweepAnalysis(outcome="failure", position=float()): 

264 raise ValueError("position: a failed sweep has no position") 

265 case FocusSweepAnalysis(outcome="failure", disposition=str()): 

266 raise ValueError("disposition: a failed sweep has no disposition") 

267 

268 return self 

269 

270 @model_validator(mode="after") 

271 def _check_samples(self) -> Self: 

272 for sample in self.samples: 

273 if sample.sweep is None or sample.sweep.sweep_id != self.sweep_id: 

274 raise ValueError("samples: each sample requires context from this sweep") 

275 

276 if sample.controller_id != self.controller_id: 

277 raise ValueError("samples: controller must match the sweep controller") 

278 

279 if sample.instrument != self.instrument: 

280 raise ValueError("samples: instrument must match the sweep instrument") 

281 

282 return self 

283 

284 

285FocusProvider = sk.declare_trait( 

286 "focus_provider", 

287 required_keywords=("FocusAnalysis", "FocusSweepAnalysis"), 

288) 

289"""An entity that publishes per-image and per-sweep focus analysis."""