Coverage for core / src / sensorkit / std / instrument.py: 98%

92 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-11-24 01:04 +0000

1# SPDX-License-Identifier: Apache-2.0 

2from collections.abc import Mapping 

3from datetime import UTC, datetime 

4from enum import StrEnum 

5from typing import Literal, Self 

6 

7from pydantic import AwareDatetime, BaseModel 

8 

9import sensorkit.api as sk 

10from sensorkit.std.traits import TemperatureUnit 

11 

12 

13class FrameType(StrEnum): 

14 """Astronomical frame type for a camera capture.""" 

15 

16 LIGHT = "light" 

17 BIAS = "bias" 

18 DARK = "dark" 

19 FLAT = "flat" 

20 

21 

22class AcquireData(sk.DeviceCommand): 

23 """Control instrument data acquisition. 

24 

25 While nothing stops a device from implementing this command directly, typically commands 

26 derived from it, such as `CameraCapture`, which add fields and specialize the command 

27 semantics for a particular device archetype, are implemented instead. 

28 

29 Four distinct actions are defined here, indicated by the `action` field: 

30 

31 - *acquire* - Executes a single, self-contained acquisition cycle. This is used for 

32 one-shot data collection operations where the device performs a complete measurement 

33 and returns the result. The acquisition begins and ends within a single command execution. 

34 The command returns when the acquisition is complete. 

35 

36 - *start* - Initiates a passive acquisition process. This begins an ongoing operation where 

37 the device continuously collects data until explicitly stopped by another `AcquireData` 

38 command (graceful), by an `Abort` command (forcible), or an error occurs. The context 

39 parameter allows implementation-specific configuration passthrough and provides metadata for 

40 data products in the case where the implementation outputs data products continuously. The 

41 command returns once the acquisition has successfully begun. 

42 

43 - *continue* - Maintains a passive acquisition that was previously started. This action is 

44 used to update the acquisition context or to act as a keepalive signal, should those things 

45 be supported or required by the device implementation. If a passive collection is not 

46 underway, an error is raised. In all cases, this command should return immediately. 

47 

48 - *stop* - Ends a passive acquisition that was previously started. If the device writes its 

49 output data product once at the end of acquisition, it may support the context parameter in 

50 this mode. 

51 

52 Note that the storage or transfer of the acquired data is outside the scope of this command. 

53 Typically, the device implementing the command will also be the receiver of the acquired data 

54 and will write it to a configured `DataGraph`, but it is also possible for data to be handled 

55 differently, e.g., received by a different entity or even handled entirely out-of-band of 

56 SensorKit. 

57 

58 Attributes: 

59 action: either "acquire", "start", "continue", or "stop" 

60 context: dictionary containing context Keywords 

61 """ 

62 

63 action: Literal["acquire", "start", "continue", "stop"] 

64 context: sk.Context | None 

65 

66 

67@sk.declare_keyword 

68class Binning(BaseModel): 

69 """Camera pixel binning configuration. 

70 

71 Attributes: 

72 x: horizontal binning factor 

73 y: vertical binning factor 

74 """ 

75 

76 x: float 

77 y: float 

78 

79 

80@sk.declare_keyword 

81class CameraSensorSize(BaseModel): 

82 """Camera sensor physical dimensions in pixels. 

83 

84 Attributes: 

85 x: sensor width in pixels 

86 y: sensor height in pixels 

87 """ 

88 

89 x: int 

90 y: int 

91 

92 @property 

93 def width(self): 

94 return self.x 

95 

96 @property 

97 def height(self): 

98 return self.y 

99 

100 

101@sk.declare_keyword 

102class CameraSensorTemperature(BaseModel): 

103 """Camera sensor temperature measurement or setpoint. 

104 

105 Attributes: 

106 temperature: sensor temperature value 

107 units: temperature unit (Fahrenheit, Celsius, or Kelvin) 

108 """ 

109 

110 temperature: float 

111 units: TemperatureUnit 

112 

113 

114class ConfigureCameraCooler(sk.DeviceCommand): 

115 """Set the target temperature of a camera cooler. 

116 

117 Attributes: 

118 enable: whether the cooler should be enabled 

119 setpoint: the target `CameraSensorTemperature` 

120 """ 

121 

122 enable: bool 

123 setpoint: CameraSensorTemperature 

124 

125 

126class ConfigureCameraSensor(sk.DeviceCommand): 

127 """Configure the camera sensor and other settings.""" 

128 

129 binning: Binning | None = None 

130 bias: float | None = None 

131 gain: float | None = None 

132 readout_mode: int | None = None 

133 

134 

135class CameraCapture(AcquireData): 

136 """Execute a single camera exposure. 

137 

138 Attributes: 

139 action: action type for the command (always "acquire") 

140 integration_time: exposure time in seconds 

141 frame_type: frame type to capture (light, dark, bias, flat) 

142 """ 

143 

144 action: Literal["acquire"] = "acquire" 

145 integration_time: float 

146 frame_type: FrameType = FrameType.LIGHT 

147 

148 

149@sk.declare_keyword(key="Exposure") 

150class ExposureInfo(BaseModel): 

151 """Parameters of the exposure that produced an image. 

152 

153 Records the capture time, duration, detector, and camera settings. 

154 Fields supply the corresponding FITS header cards. 

155 

156 Attributes: 

157 start: Start of the exposure, as a timezone-aware datetime. -> DATE-OBS 

158 duration: Actual exposure duration in seconds. -> EXPTIME 

159 detector: Detector name reported by the device, such as a camera model or sensor 

160 chip. -> DETECTOR 

161 frame_type: Frame type (light, dark, bias, flat). -> IMAGETYP 

162 readout_mode: Camera readout mode, as an index or a name. -> READOUTM 

163 gain: Camera gain. -> GAIN 

164 offset: Camera offset / bias level. -> OFFSET 

165 temperature: Sensor temperature during the exposure, in degrees Celsius. -> CCD-TEMP 

166 set_temperature: Cooler setpoint, in degrees Celsius. -> SET-TEMP 

167 max_adu: Saturation level in ADU under the active readout configuration. -> SATURATE 

168 """ 

169 

170 start: AwareDatetime 

171 duration: float 

172 detector: str | None = None 

173 frame_type: FrameType | None = None 

174 readout_mode: int | str | None = None 

175 gain: float | None = None 

176 offset: float | None = None 

177 temperature: float | None = None 

178 set_temperature: float | None = None 

179 max_adu: int | None = None 

180 

181 def get_fits_cards(self): 

182 utc = self.start.astimezone(UTC).replace(tzinfo=None) 

183 

184 yield "DATE-OBS", (utc.isoformat(), "UTC start of exposure") 

185 yield "EXPTIME", (self.duration, "Exposure time [s]") 

186 

187 if self.detector is not None: 

188 yield "DETECTOR", (self.detector, "Detector name") 

189 if self.frame_type is not None: 

190 yield "IMAGETYP", (str(self.frame_type), "Frame type") 

191 if self.readout_mode is not None: 

192 yield "READOUTM", (self.readout_mode, "Readout mode") 

193 if self.gain is not None: 

194 yield "GAIN", (self.gain, "Camera gain") 

195 if self.offset is not None: 

196 yield "OFFSET", (self.offset, "Camera offset") 

197 if self.temperature is not None: 

198 yield "CCD-TEMP", (self.temperature, "CCD temperature [C]") 

199 if self.set_temperature is not None: 

200 yield "SET-TEMP", (self.set_temperature, "Cooler setpoint [C]") 

201 if self.max_adu is not None: 

202 yield "SATURATE", (self.max_adu, "Saturation level [ADU]") 

203 

204 @classmethod 

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

206 """Read exposure metadata from FITS header cards. 

207 

208 DATE-OBS values without a time zone are interpreted as UTC. 

209 

210 Returns: 

211 Exposure metadata, or None if DATE-OBS or EXPTIME is absent. 

212 

213 Raises: 

214 ValueError: If DATE-OBS is not an ISO 8601 time. 

215 ValidationError: If another card value is invalid. 

216 """ 

217 if not all(card in header for card in ("DATE-OBS", "EXPTIME")): 

218 return None 

219 

220 start = datetime.fromisoformat(str(header["DATE-OBS"])) 

221 

222 return cls.model_validate( 

223 { 

224 "start": start if start.tzinfo else start.replace(tzinfo=UTC), 

225 "duration": header["EXPTIME"], 

226 "detector": header.get("DETECTOR"), 

227 "frame_type": header.get("IMAGETYP"), 

228 "readout_mode": header.get("READOUTM"), 

229 "gain": header.get("GAIN"), 

230 "offset": header.get("OFFSET"), 

231 "temperature": header.get("CCD-TEMP"), 

232 "set_temperature": header.get("SET-TEMP"), 

233 "max_adu": header.get("SATURATE"), 

234 } 

235 ) 

236 

237 

238StandardCamera = sk.declare_archetype( 

239 "camera", 

240 required_commands=(CameraCapture,), 

241 optional_commands=(ConfigureCameraCooler,), 

242) 

243"""A standard camera device that can capture images with configurable integration time. 

244 

245This archetype defines the interface for camera devices capable of image acquisition 

246with specified exposure durations. It supports optional temperature control for 

247cooled camera sensors. 

248""" 

249 

250 

251@sk.declare_keyword 

252class RotatorPosition(BaseModel): 

253 """Current angular position of the rotator.""" 

254 position: float 

255 

256 

257class ChangeRotatorPosition(sk.DeviceCommand): 

258 """Move the rotator to a specified orientation. 

259 

260 Attributes: 

261 position: target position value for the rotator 

262 """ 

263 

264 position: float 

265 

266 

267StandardRotator = sk.declare_archetype( 

268 "rotator", 

269 required_commands=(ChangeRotatorPosition,), 

270) 

271"""A device that can rotate an optical element to a specified position. 

272 

273This archetype defines the interface for rotator devices that control the orientation of optical 

274components such as cameras instrument adapters within an optical system. 

275"""