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

119 statements  

« prev     ^ index     » next       coverage.py v7.4.4, created at 2024-03-20 11:09 +0000

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__ = ("read_test_file", "MetadataAssertHelper") 

15 

16import json 

17import os 

18import pickle 

19import warnings 

20from collections.abc import MutableMapping 

21from typing import TYPE_CHECKING, Any, NoReturn 

22 

23import astropy.units as u 

24import astropy.utils.exceptions 

25import yaml 

26from astropy.io.fits import Header 

27from astropy.io.fits.verify import VerifyWarning 

28from astropy.time import Time 

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 

46 

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

48# we can use if daf_base is not available. 

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

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

51 

52 Parameters 

53 ---------- 

54 loader : `yaml.Loader` 

55 Instance used to load YAML file. 

56 node : `yaml.SequenceNode` 

57 Node to examine. 

58 

59 Yields 

60 ------ 

61 pl : `dict` 

62 Contents of PropertyList as a dict. 

63 """ 

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

65 yield pl 

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

67 for key, dtype, value, comment in state: 

68 if dtype == "Double": 

69 pl[key] = float(value) 

70 elif dtype == "Int": 

71 pl[key] = int(value) 

72 elif dtype == "Bool": 

73 pl[key] = value 

74 else: 

75 pl[key] = value 

76 

77 

78if daf_base is None: 78 ↛ 79line 78 didn't jump to line 79, because the condition on line 78 was never true

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

80 

81 

82def read_test_file(filename: str, dir: str | None = None) -> MutableMapping[str, Any]: 

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

84 

85 Parameters 

86 ---------- 

87 filename : `str` 

88 Name of file in the data directory. 

89 dir : `str`, optional 

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

91 specified. 

92 

93 Returns 

94 ------- 

95 header : `dict`-like 

96 Header read from file. 

97 """ 

98 if dir is not None and not os.path.isabs(filename): 

99 filename = os.path.join(dir, filename) 

100 with open(filename) as fd: 

101 if filename.endswith(".yaml"): 

102 header = yaml.load(fd, Loader=Loader) 

103 elif filename.endswith(".json"): 

104 header = json.load(fd) 

105 else: 

106 raise RuntimeError(f"Unrecognized file format: {filename}") 

107 

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

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

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

111 return header 

112 

113 

114class MetadataAssertHelper: 

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

116 translations. 

117 """ 

118 

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

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

121 if TYPE_CHECKING: 121 ↛ 123line 121 didn't jump to line 123, because the condition on line 121 was never true

122 

123 def assertAlmostEqual( # noqa: N802 

124 self, 

125 a: float, 

126 b: float, 

127 places: int | None = None, 

128 msg: str | None = None, 

129 delta: float | None = None, 

130 ) -> None: 

131 pass 

132 

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

134 pass 

135 

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

137 pass 

138 

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

140 pass 

141 

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

143 pass 

144 

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

146 pass 

147 

148 def assertCoordinatesConsistent( # noqa: N802 

149 self, obsinfo: ObservationInfo, max_sep: float = 1.0, amdelta: float = 0.01 

150 ) -> None: 

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

152 

153 Parameters 

154 ---------- 

155 obsinfo : `ObservationInfo` 

156 Object to check. 

157 max_sep : `float`, optional 

158 Maximum separation between AltAz derived from RA/Dec headers 

159 and that found in the AltAz headers. 

160 amdelta : `float`, optional 

161 Max difference between header airmass and derived airmass. 

162 

163 Raises 

164 ------ 

165 AssertionError 

166 Inconsistencies found. 

167 """ 

168 self.assertIsNotNone(obsinfo.tracking_radec) 

169 self.assertIsNotNone(obsinfo.altaz_begin) 

170 

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

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

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

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

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

176 self.assertAlmostEqual(obsinfo.altaz_begin.secz.to_value(), obsinfo.boresight_airmass, delta=amdelta) 

177 

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

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

180 with warnings.catch_warnings(): 

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

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

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

184 

185 def assertObservationInfoFromYaml( # noqa: N802 

186 self, 

187 file: str, 

188 dir: str | None = None, 

189 check_wcs: bool = True, 

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

191 check_altaz: bool = False, 

192 **kwargs: Any, 

193 ) -> None: 

194 """Check contents of an ObservationInfo. 

195 

196 Parameters 

197 ---------- 

198 file : `str` 

199 Path to YAML file representing the header. 

200 dir : `str`, optional 

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

202 check_wcs : `bool`, optional 

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

204 wcs_params : `dict`, optional 

205 Parameters to pass to `assertCoordinatesConsistent`. 

206 check_altaz : `bool`, optional 

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

208 **kwargs : `dict` 

209 Keys matching `ObservationInfo` properties with values 

210 to be tested. 

211 

212 Raises 

213 ------ 

214 AssertionError 

215 A value in the ObservationInfo derived from the file is 

216 inconsistent. 

217 """ 

218 header = read_test_file(file, dir=dir) 

219 

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

221 astropy_header = Header() 

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

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

224 for v in values: 

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

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

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

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

229 with warnings.catch_warnings(): 

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

231 astropy_header.append((key, v)) 

232 

233 for hdr in (header, astropy_header): 

234 try: 

235 self.assertObservationInfo( 

236 header, 

237 filename=file, 

238 check_wcs=check_wcs, 

239 wcs_params=wcs_params, 

240 check_altaz=check_altaz, 

241 **kwargs, 

242 ) 

243 except AssertionError as e: 

244 raise AssertionError( 

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

246 ) from e 

247 

248 def assertObservationInfo( # noqa: N802 

249 self, 

250 header: MutableMapping[str, Any], 

251 filename: str | None = None, 

252 check_wcs: bool = True, 

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

254 check_altaz: bool = False, 

255 **kwargs: Any, 

256 ) -> None: 

257 """Check contents of an ObservationInfo. 

258 

259 Parameters 

260 ---------- 

261 header : `dict`-like 

262 Header to be checked. 

263 filename : `str`, optional 

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

265 check_wcs : `bool`, optional 

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

267 are automatically disabled if the translated header does 

268 not appear to be "science". 

269 wcs_params : `dict`, optional 

270 Parameters to pass to `assertCoordinatesConsistent`. 

271 check_altaz : `bool`, optional 

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

273 **kwargs : `dict` 

274 Keys matching `ObservationInfo` properties with values 

275 to be tested. 

276 

277 Raises 

278 ------ 

279 AssertionError 

280 A value in the ObservationInfo derived from the file is 

281 inconsistent. 

282 """ 

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

284 # of all the translations 

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

286 translator = obsinfo.translator_class_name 

287 

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

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

290 self.assertEqual(obsinfo, newinfo) 

291 

292 # Check the properties 

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

294 calculated = getattr(obsinfo, property) 

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

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

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

298 expected = expected.to_value() 

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

300 elif isinstance(calculated, u.Quantity): 

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

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

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

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

305 else: 

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

307 

308 # Date comparison error reports will benefit by specifying ISO 

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

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

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

312 # the past. 

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

314 if date is not None: 

315 date.format = "isot" 

316 date.precision = 9 

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

318 return date 

319 

320 datetime_begin = _format_date_for_testing(obsinfo.datetime_begin) 

321 datetime_end = _format_date_for_testing(obsinfo.datetime_end) 

322 

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

324 self.assertLessEqual(datetime_begin, datetime_end) 

325 

326 # Check that exposure time is not outside datetime_end 

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

328 

329 # Do we expect an AltAz value or not. 

330 if check_altaz: 

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

332 

333 # Check the WCS consistency 

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

335 if wcs_params is None: 

336 wcs_params = {} 

337 self.assertCoordinatesConsistent(obsinfo, **wcs_params)