Coverage for python / astro_metadata_translator / tests.py: 18%

115 statements  

« prev     ^ index     » next       coverage.py v7.13.2, created at 2026-02-19 01:05 -0800

1# This file is part of astro_metadata_translator. 

2# 

3# Developed for the LSST Data Management System. 

4# This product includes software developed by the LSST Project 

5# (http://www.lsst.org). 

6# See the LICENSE file at the top-level directory of this distribution 

7# for details of code ownership. 

8# 

9# Use of this source code is governed by a 3-clause BSD-style 

10# license that can be found in the LICENSE file. 

11 

12from __future__ import annotations 

13 

14__all__ = ("MetadataAssertHelper", "read_test_file") 

15 

16import json 

17import pickle 

18import warnings 

19from collections.abc import MutableMapping 

20from typing import TYPE_CHECKING, Any, NoReturn 

21 

22import astropy.units as u 

23import astropy.utils.exceptions 

24import yaml 

25from astropy.io.fits import Header 

26from astropy.io.fits.verify import VerifyWarning 

27from astropy.time import Time 

28from lsst.resources import ResourcePath 

29 

30from astro_metadata_translator import ObservationInfo 

31 

32# PropertyList is optional 

33try: 

34 import lsst.daf.base as daf_base 

35except ImportError: 

36 daf_base = None 

37 

38 

39# For YAML >= 5.1 need a different Loader for the constructor 

40Loader: type[yaml.Loader] | type[yaml.FullLoader] 

41try: 

42 Loader = yaml.FullLoader 

43except AttributeError: 

44 Loader = yaml.Loader 

45 

46if TYPE_CHECKING: 

47 from lsst.resources import ResourcePathExpression 

48 

49 

50# Define a YAML loader for lsst.daf.base.PropertySet serializations that 

51# we can use if daf_base is not available. 

52def pl_constructor(loader: yaml.Loader, node: yaml.SequenceNode) -> Any: 

53 """Construct an OrderedDict from a YAML file containing a PropertyList. 

54 

55 Parameters 

56 ---------- 

57 loader : `yaml.Loader` 

58 Instance used to load YAML file. 

59 node : `yaml.SequenceNode` 

60 Node to examine. 

61 

62 Yields 

63 ------ 

64 pl : `dict` 

65 Contents of PropertyList as a dict. 

66 """ 

67 pl: dict[str, Any] = {} 

68 yield pl 

69 state = loader.construct_sequence(node, deep=True) 

70 for key, dtype, value, _ in state: 

71 if dtype == "Double": 

72 pl[key] = float(value) 

73 elif dtype == "Int": 

74 pl[key] = int(value) 

75 elif dtype == "Bool": 

76 pl[key] = value 

77 else: 

78 pl[key] = value 

79 

80 

81if daf_base is None: 81 ↛ 82line 81 didn't jump to line 82 because the condition on line 81 was never true

82 yaml.add_constructor("lsst.daf.base.PropertyList", pl_constructor, Loader=Loader) # type: ignore 

83 

84 

85def read_test_file( 

86 filename: ResourcePathExpression, dir: ResourcePathExpression | None = None 

87) -> MutableMapping[str, Any]: 

88 """Read the named test file relative to the location of this helper. 

89 

90 Parameters 

91 ---------- 

92 filename : `str` or `lsst.resources.ResourcePathExpression` 

93 Name of file in the data directory. 

94 dir : `str`, optional 

95 Directory from which to read file. Current directory used if none 

96 specified. 

97 

98 Returns 

99 ------- 

100 header : `dict`-like 

101 Header read from file. 

102 """ 

103 uri = ResourcePath(filename, forceAbsolute=False, forceDirectory=False) 

104 if dir is not None and not uri.isabs(): 

105 test_dir = ResourcePath(dir, forceDirectory=True) 

106 uri = test_dir.join(uri, forceDirectory=False) 

107 content = uri.read() 

108 ext = uri.getExtension() 

109 if ext == ".yaml": 

110 header = yaml.load(content, Loader=Loader) 

111 elif ext == ".json": 

112 header = json.loads(content) 

113 else: 

114 raise RuntimeError(f"Unrecognized file format: {uri}") 

115 

116 # Cannot directly check for Mapping because PropertyList is not one 

117 if not hasattr(header, "items"): 

118 raise ValueError(f"Contents of YAML file {filename} are not a mapping, they are {type(header)}") 

119 return header 

120 

121 

122class MetadataAssertHelper: 

123 """Class with helpful asserts that can be used for testing metadata 

124 translations. 

125 """ 

126 

127 # This class is assumed to be combined with unittest.TestCase but mypy 

128 # does not know this. We need to teach mypy about the APIs we are using. 

129 if TYPE_CHECKING: 

130 

131 def assertAlmostEqual( # noqa: N802 

132 self, 

133 a: float, 

134 b: float, 

135 places: int | None = None, 

136 msg: str | None = None, 

137 delta: float | None = None, 

138 ) -> None: 

139 pass 

140 

141 def assertIsNotNone(self, a: Any, msg: str | None = None) -> None: # noqa: N802 

142 pass 

143 

144 def assertEqual(self, a: Any, b: Any, msg: str | None = None) -> None: # noqa: N802 

145 pass 

146 

147 def assertLess(self, a: Any, b: Any, msg: str | None = None) -> None: # noqa: N802 

148 pass 

149 

150 def assertLessEqual(self, a: Any, b: Any, msg: str | None = None) -> None: # noqa: N802 

151 pass 

152 

153 def assertGreaterEqual(self, a: Any, b: Any, msg: str | None = None) -> None: # noqa: N802 

154 pass 

155 

156 def fail(self, msg: str) -> NoReturn: 

157 pass 

158 

159 def assertCoordinatesConsistent( # noqa: N802 

160 self, obsinfo: ObservationInfo, max_sep: float = 1.0, min_sep: float = 0.0, amdelta: float = 0.01 

161 ) -> None: 

162 """Check that SkyCoord, AltAz, and airmass are self consistent. 

163 

164 Parameters 

165 ---------- 

166 obsinfo : `ObservationInfo` 

167 Object to check. 

168 max_sep : `float`, optional 

169 Maximum separation between AltAz derived from RA/Dec headers 

170 and that found in the AltAz headers. 

171 min_sep : `float`, optional 

172 Minimum separation between AltAz derived from RA/Dec headers 

173 and that found in the AltAz headers. This is to accommodate 

174 cases where the telecsope boresight headers required adjustment. 

175 amdelta : `float`, optional 

176 Max difference between header airmass and derived airmass. 

177 

178 Raises 

179 ------ 

180 AssertionError 

181 Inconsistencies found. 

182 """ 

183 self.assertIsNotNone(obsinfo.tracking_radec, msg="Checking tracking_radec is defined") 

184 self.assertIsNotNone(obsinfo.altaz_begin, msg="Checking AltAz is defined") 

185 

186 assert obsinfo.altaz_begin is not None 

187 assert obsinfo.boresight_airmass is not None 

188 # Is airmass from header close to airmass from AltAz headers? 

189 # In most cases there is uncertainty over whether the elevation 

190 # and airmass in the header are for the start, end, or middle 

191 # of the observation. Sometimes the AltAz is from the start 

192 # but the airmass is from the middle so accuracy is not certain. 

193 self.assertAlmostEqual( 

194 obsinfo.altaz_begin.secz.to_value(), 

195 obsinfo.boresight_airmass, 

196 delta=amdelta, 

197 msg="Checking airmass is consistent", 

198 ) 

199 

200 # Is AltAz from headers close to AltAz from RA/Dec headers? 

201 # Can trigger warnings from Astropy if date is in future 

202 assert obsinfo.altaz_begin is not None 

203 assert obsinfo.tracking_radec is not None 

204 with warnings.catch_warnings(): 

205 warnings.simplefilter("ignore", category=astropy.utils.exceptions.AstropyWarning) 

206 sep = obsinfo.altaz_begin.separation(obsinfo.tracking_radec.altaz) 

207 self.assertLess(sep.to_value(unit="arcmin"), max_sep, msg="AltAz inconsistent with RA/Dec") 

208 self.assertGreaterEqual( 

209 sep.to_value(unit="arcmin"), 

210 min_sep, 

211 msg="Difference between AltAz and RA/Dec is less than expected from fixed boresight headers.", 

212 ) 

213 

214 def assertObservationInfoFromYaml( # noqa: N802 

215 self, 

216 file: str, 

217 dir: str | None = None, 

218 check_wcs: bool = True, 

219 wcs_params: dict[str, Any] | None = None, 

220 check_altaz: bool = False, 

221 **kwargs: Any, 

222 ) -> None: 

223 """Check contents of an ObservationInfo. 

224 

225 Parameters 

226 ---------- 

227 file : `str` 

228 Path to YAML file representing the header. 

229 dir : `str`, optional 

230 Optional directory from which to read ``file``. 

231 check_wcs : `bool`, optional 

232 Check the consistency of the RA/Dec and AltAz values. 

233 wcs_params : `dict`, optional 

234 Parameters to pass to `assertCoordinatesConsistent`. 

235 check_altaz : `bool`, optional 

236 Check that an alt/az value has been calculated. 

237 **kwargs : `dict` 

238 Keys matching `ObservationInfo` properties with values 

239 to be tested. 

240 

241 Raises 

242 ------ 

243 AssertionError 

244 A value in the ObservationInfo derived from the file is 

245 inconsistent. 

246 """ 

247 header = read_test_file(file, dir=dir) 

248 

249 # DM-30093: Astropy Header does not always behave dict-like 

250 astropy_header = Header() 

251 for key, val in header.items(): 

252 values = val if isinstance(val, list) else [val] 

253 for v in values: 

254 # Appending ensures *all* duplicated keys are also preserved. 

255 # astropy.io.fits complains about long keywords rather than 

256 # letting us say "thank you for using the standard to let 

257 # us write this header" so we need to catch the warnings. 

258 with warnings.catch_warnings(): 

259 warnings.simplefilter("ignore", category=VerifyWarning) 

260 astropy_header.append((key, v)) 

261 

262 for hdr in (header, astropy_header): 

263 try: 

264 self.assertObservationInfo( 

265 header, 

266 filename=file, 

267 check_wcs=check_wcs, 

268 wcs_params=wcs_params, 

269 check_altaz=check_altaz, 

270 **kwargs, 

271 ) 

272 except AssertionError as e: 

273 raise AssertionError( 

274 f"ObservationInfo derived from {type(hdr)} type is inconsistent: {e}" 

275 ) from e 

276 

277 def assertObservationInfo( # noqa: N802 

278 self, 

279 header: MutableMapping[str, Any], 

280 filename: str | None = None, 

281 check_wcs: bool = True, 

282 wcs_params: dict[str, Any] | None = None, 

283 check_altaz: bool = False, 

284 **kwargs: Any, 

285 ) -> None: 

286 """Check contents of an ObservationInfo. 

287 

288 Parameters 

289 ---------- 

290 header : `dict`-like 

291 Header to be checked. 

292 filename : `str`, optional 

293 Name of the filename associated with this header if known. 

294 check_wcs : `bool`, optional 

295 Check the consistency of the RA/Dec and AltAz values. Checks 

296 are automatically disabled if the translated header does 

297 not appear to be "science". 

298 wcs_params : `dict`, optional 

299 Parameters to pass to `assertCoordinatesConsistent`. 

300 check_altaz : `bool`, optional 

301 Check that an alt/az value has been calculated. 

302 **kwargs : `dict` 

303 Keys matching `ObservationInfo` properties with values 

304 to be tested. 

305 

306 Raises 

307 ------ 

308 AssertionError 

309 A value in the ObservationInfo derived from the file is 

310 inconsistent. 

311 """ 

312 # For testing we force pedantic mode since we are in charge 

313 # of all the translations 

314 obsinfo = ObservationInfo(header, pedantic=True, filename=filename) 

315 translator = obsinfo.translator_class_name 

316 

317 # Check that we can pickle and get back the same properties 

318 newinfo = pickle.loads(pickle.dumps(obsinfo)) 

319 self.assertEqual(obsinfo, newinfo) 

320 

321 # Check the properties 

322 for property, expected in kwargs.items(): 

323 calculated = getattr(obsinfo, property) 

324 msg = f"Comparing property {property} using translator {translator}" 

325 if isinstance(expected, u.Quantity) and calculated is not None: 

326 calculated = calculated.to_value(unit=expected.unit) 

327 expected = expected.to_value() 

328 self.assertAlmostEqual(calculated, expected, msg=msg) 

329 elif isinstance(calculated, u.Quantity): 

330 # Only happens if the test is not a quantity when it should be 

331 self.fail(f"Expected {expected!r} but got Quantity '{calculated}': {msg}") 

332 elif isinstance(expected, float) and calculated is not None: 

333 self.assertAlmostEqual(calculated, expected, msg=msg) 

334 else: 

335 self.assertEqual(calculated, expected, msg=msg) 

336 

337 # Date comparison error reports will benefit by specifying ISO 

338 # format. Generate a new Time object at fixed precision 

339 # to work around the fact that (as of astropy 3.1) adding 0.0 seconds 

340 # to a Time results in a new Time object that is a few picoseconds in 

341 # the past. 

342 def _format_date_for_testing(date: Time | None) -> Time | None: 

343 if date is not None: 

344 date.format = "isot" 

345 date.precision = 9 

346 date = Time(str(date), scale=date.scale, format="isot") 

347 return date 

348 

349 datetime_begin = _format_date_for_testing(obsinfo.datetime_begin) 

350 datetime_end = _format_date_for_testing(obsinfo.datetime_end) 

351 

352 # Check that dates are defined and end is the same or after beginning 

353 self.assertLessEqual(datetime_begin, datetime_end) 

354 

355 # Check that exposure time is not outside datetime_end 

356 assert obsinfo.exposure_time is not None 

357 assert obsinfo.datetime_begin is not None 

358 self.assertLessEqual(obsinfo.datetime_begin + obsinfo.exposure_time, obsinfo.datetime_end) 

359 

360 # Do we expect an AltAz value or not. 

361 if check_altaz: 

362 self.assertIsNotNone(obsinfo.altaz_begin, "altaz_begin is None but should have a value") 

363 

364 # Check the WCS consistency 

365 if check_wcs and obsinfo.observation_type == "science": 

366 if wcs_params is None: 

367 wcs_params = {} 

368 self.assertCoordinatesConsistent(obsinfo, **wcs_params)