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

109 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-01-13 01:21 -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 # Is airmass from header close to airmass from AltAz headers? 

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

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

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

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

191 self.assertAlmostEqual( 

192 obsinfo.altaz_begin.secz.to_value(), 

193 obsinfo.boresight_airmass, 

194 delta=amdelta, 

195 msg="Checking airmass is consistent", 

196 ) 

197 

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

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

200 with warnings.catch_warnings(): 

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

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

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

204 self.assertGreaterEqual( 

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

206 min_sep, 

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

208 ) 

209 

210 def assertObservationInfoFromYaml( # noqa: N802 

211 self, 

212 file: str, 

213 dir: str | None = None, 

214 check_wcs: bool = True, 

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

216 check_altaz: bool = False, 

217 **kwargs: Any, 

218 ) -> None: 

219 """Check contents of an ObservationInfo. 

220 

221 Parameters 

222 ---------- 

223 file : `str` 

224 Path to YAML file representing the header. 

225 dir : `str`, optional 

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

227 check_wcs : `bool`, optional 

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

229 wcs_params : `dict`, optional 

230 Parameters to pass to `assertCoordinatesConsistent`. 

231 check_altaz : `bool`, optional 

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

233 **kwargs : `dict` 

234 Keys matching `ObservationInfo` properties with values 

235 to be tested. 

236 

237 Raises 

238 ------ 

239 AssertionError 

240 A value in the ObservationInfo derived from the file is 

241 inconsistent. 

242 """ 

243 header = read_test_file(file, dir=dir) 

244 

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

246 astropy_header = Header() 

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

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

249 for v in values: 

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

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

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

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

254 with warnings.catch_warnings(): 

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

256 astropy_header.append((key, v)) 

257 

258 for hdr in (header, astropy_header): 

259 try: 

260 self.assertObservationInfo( 

261 header, 

262 filename=file, 

263 check_wcs=check_wcs, 

264 wcs_params=wcs_params, 

265 check_altaz=check_altaz, 

266 **kwargs, 

267 ) 

268 except AssertionError as e: 

269 raise AssertionError( 

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

271 ) from e 

272 

273 def assertObservationInfo( # noqa: N802 

274 self, 

275 header: MutableMapping[str, Any], 

276 filename: str | None = None, 

277 check_wcs: bool = True, 

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

279 check_altaz: bool = False, 

280 **kwargs: Any, 

281 ) -> None: 

282 """Check contents of an ObservationInfo. 

283 

284 Parameters 

285 ---------- 

286 header : `dict`-like 

287 Header to be checked. 

288 filename : `str`, optional 

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

290 check_wcs : `bool`, optional 

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

292 are automatically disabled if the translated header does 

293 not appear to be "science". 

294 wcs_params : `dict`, optional 

295 Parameters to pass to `assertCoordinatesConsistent`. 

296 check_altaz : `bool`, optional 

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

298 **kwargs : `dict` 

299 Keys matching `ObservationInfo` properties with values 

300 to be tested. 

301 

302 Raises 

303 ------ 

304 AssertionError 

305 A value in the ObservationInfo derived from the file is 

306 inconsistent. 

307 """ 

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

309 # of all the translations 

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

311 translator = obsinfo.translator_class_name 

312 

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

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

315 self.assertEqual(obsinfo, newinfo) 

316 

317 # Check the properties 

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

319 calculated = getattr(obsinfo, property) 

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

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

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

323 expected = expected.to_value() 

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

325 elif isinstance(calculated, u.Quantity): 

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

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

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

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

330 else: 

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

332 

333 # Date comparison error reports will benefit by specifying ISO 

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

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

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

337 # the past. 

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

339 if date is not None: 

340 date.format = "isot" 

341 date.precision = 9 

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

343 return date 

344 

345 datetime_begin = _format_date_for_testing(obsinfo.datetime_begin) 

346 datetime_end = _format_date_for_testing(obsinfo.datetime_end) 

347 

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

349 self.assertLessEqual(datetime_begin, datetime_end) 

350 

351 # Check that exposure time is not outside datetime_end 

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

353 

354 # Do we expect an AltAz value or not. 

355 if check_altaz: 

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

357 

358 # Check the WCS consistency 

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

360 if wcs_params is None: 

361 wcs_params = {} 

362 self.assertCoordinatesConsistent(obsinfo, **wcs_params)