Coverage for tests / test_image.py: 21%

122 statements  

« prev     ^ index     » next       coverage.py v7.14.0, created at 2026-05-16 07:54 +0000

1# This file is part of lsst-images. 

2# 

3# Developed for the LSST Data Management System. 

4# This product includes software developed by the LSST Project 

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

6# See the COPYRIGHT 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 

14import os 

15import unittest 

16 

17import astropy.io.fits 

18import astropy.units as u 

19import numpy as np 

20from astro_metadata_translator import ObservationInfo 

21 

22import lsst.utils.tests 

23from lsst.images import Box, DetectorFrame, Image 

24from lsst.images.tests import ( 

25 RoundtripFits, 

26 RoundtripJson, 

27 RoundtripNdf, 

28 assert_close, 

29 assert_images_equal, 

30 assert_projections_equal, 

31 compare_image_to_legacy, 

32 make_random_projection, 

33) 

34 

35try: 

36 import h5py # noqa: F401 

37 

38 HAVE_H5PY = True 

39except ImportError: 

40 HAVE_H5PY = False 

41 

42DATA_DIR = os.environ.get("TESTDATA_IMAGES_DIR", None) 

43 

44 

45class ImageTestCase(unittest.TestCase): 

46 """Tests for the Image class.""" 

47 

48 def test_basics(self): 

49 """Test basic constructor patterns.""" 

50 image = Image(42, shape=(5, 5), metadata={"three": 3}) 

51 assert_close(self, image.array, np.zeros([5, 5], dtype=np.int64) + 42) 

52 self.assertEqual(image.metadata["three"], 3) 

53 

54 data = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) 

55 image = Image(data) 

56 subset = image[Box.factory[:3, 1:3]] 

57 subset2 = image.absolute[:3, 1:3] 

58 assert_images_equal(self, subset2, subset, expect_view=True) 

59 

60 assert_images_equal(self, image.copy(), image, expect_view=False) 

61 

62 # Add an explicit bounding box and then slice it. 

63 image = Image(data, bbox=Box.factory[-2:1, 10:14]) 

64 with self.assertRaises(IndexError): 

65 # Same slice no longer works in absolute slicing because we have 

66 # moved origin. 

67 image.absolute[:3, 1:3] 

68 # That slice does still work in local coordinates. 

69 assert_close(self, image.local[:3, 1:3].array, subset2.array) 

70 # And we can write an equivalent slice in absolute coordinates. 

71 assert_close(self, image.absolute[:0, 11:13].array, np.array([[2, 3], [6, 7]])) 

72 

73 # Test __eq__ behavior. 

74 self.assertEqual(image[...], image) 

75 self.assertEqual(image.__eq__(data), NotImplemented) 

76 self.assertNotEqual(image, list(data)) 

77 

78 with self.assertRaises(ValueError): 

79 # bbox does not match array shape. 

80 Image(np.array([[1, 2, 3], [4, 5, 6]]), bbox=Box.factory[0:2, 0:4]) 

81 

82 with self.assertRaises(ValueError): 

83 # shape does not match array shape. 

84 Image(np.array([[2, 3, 4], [6, 7, 8]]), shape=[5, 2]) 

85 

86 with self.assertRaises(TypeError): 

87 # shape and bbox both None. 

88 Image() 

89 

90 with self.assertRaises(ValueError): 

91 # Shape mismatch. 

92 Image(shape=[3, 6], bbox=Box.factory[-5:10, 0:10]) 

93 

94 def test_json_roundtrip(self) -> None: 

95 """Test saving a tiny image to pure JSON.""" 

96 image = Image( 

97 np.arange(15).reshape(5, 3), 

98 start=(2, -1), 

99 ) 

100 with RoundtripJson(self, image) as roundtrip: 

101 pass 

102 assert_images_equal(self, image, roundtrip.result) 

103 

104 def test_fits_roundtrip(self) -> None: 

105 """Test saving a tiny image to FITS generically.""" 

106 image = Image( 

107 np.arange(15).reshape(5, 3), 

108 start=(2, -1), 

109 ) 

110 with RoundtripFits(self, image) as roundtrip: 

111 subbox = Box.factory[3:5, 0:1] 

112 assert_images_equal(self, image[subbox], roundtrip.get(bbox=subbox)) 

113 assert_images_equal(self, image, roundtrip.result) 

114 

115 @unittest.skipUnless(HAVE_H5PY, "h5py is not installed") 

116 def test_ndf_roundtrip(self) -> None: 

117 """Test saving a tiny image to NDF.""" 

118 image = Image( 

119 np.arange(15).reshape(5, 3), 

120 start=(2, -1), 

121 ) 

122 with RoundtripNdf(self, image) as roundtrip: 

123 pass 

124 assert_images_equal(self, image, roundtrip.result) 

125 

126 @unittest.skipUnless(HAVE_H5PY, "h5py is not installed") 

127 def test_fits_ndf_consistency(self): 

128 """Writing via FITS and via NDF, then reading back, produces equal 

129 Images. 

130 """ 

131 rng = np.random.default_rng(321) 

132 image = Image( 

133 rng.normal(100.0, 8.0, size=(60, 80)), 

134 dtype=np.float64, 

135 unit=u.nJy, 

136 start=(0, 0), 

137 ) 

138 with RoundtripFits(self, image) as fits_rt, RoundtripNdf(self, image) as ndf_rt: 

139 assert_images_equal(self, image, fits_rt.result) 

140 assert_images_equal(self, image, ndf_rt.result) 

141 assert_images_equal(self, fits_rt.result, ndf_rt.result) 

142 

143 def test_quantity(self): 

144 """Test quantities.""" 

145 data = np.array([[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0]]) 

146 data2 = data.copy() * 2.0 

147 image = Image(data, unit=u.mJy, bbox=Box.factory[-2:1, 3:7]) 

148 

149 q = image.quantity 

150 self.assertEqual(q[1, 0], 5.0 * u.mJy) 

151 image.quantity = image.array * 10.0 * u.uJy 

152 q = image.quantity 

153 self.assertEqual(q[1, 0], 0.05 * u.mJy) 

154 

155 image2 = Image(data2, unit=u.Jy) 

156 image[Box.factory[-1:0, 5:7]] = image2.local[1:2, 2:4] 

157 assert_close( 

158 self, 

159 image.array, 

160 np.array([[0.01, 0.02, 0.03, 0.04], [0.05, 0.06, 14000.0, 16000.0], [0.09, 0.1, 0.11, 0.12]]), 

161 ) 

162 

163 def test_read_write(self): 

164 """Round trip through file. 

165 

166 This uses the read_fits and write_fits methods (which RoundtripFits 

167 does not use). 

168 """ 

169 data = np.array([[1.0, 2.0, np.nan, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0]]) 

170 md = {"int": 1, "float": 42.0, "bool": False, "long string header": "This is a string"} 

171 obsinfo = ObservationInfo(telescope="Simonyi", instrument="LSSTCam", relative_humidity=23.5) 

172 det_frame = DetectorFrame(instrument="Inst", visit=1234, detector=1, bbox=Box.factory[1:4096, 1:4096]) 

173 rng = np.random.default_rng(500) 

174 projection = make_random_projection(rng, det_frame, Box.factory[1:4096, 1:4096]) 

175 

176 image = Image( 

177 data, 

178 unit=u.dn, 

179 metadata=md, 

180 obs_info=obsinfo, 

181 bbox=Box.factory[-2:1, 3:7], 

182 projection=projection, 

183 ) 

184 

185 with lsst.utils.tests.getTempFilePath(".fits") as tmpFile: 

186 image.write_fits(tmpFile) 

187 

188 new = Image.read_fits(tmpFile) 

189 self.assertEqual(new, image) 

190 

191 # __eq__ does not test all components. 

192 self.assertEqual(new.obs_info, image.obs_info) 

193 self.assertEqual(new.metadata, image.metadata) 

194 self.maxDiff = None 

195 assert_projections_equal(self, new.projection, image.projection, expect_identity=False) 

196 

197 # Read subset. 

198 subset = Image.read_fits(tmpFile, bbox=Box.factory[-2:0, 5:7]) 

199 self.assertEqual(subset, image.absolute[-2:0, 5:7]) 

200 self.assertEqual(subset, image.local[0:2, 2:4]) 

201 self.assertEqual(str(subset), "Image([y=-2:0, x=5:7], float64)") 

202 self.assertEqual( 

203 repr(subset), 

204 "Image(..., bbox=Box(y=Interval(start=-2, stop=0), x=Interval(start=5, stop=7)), " 

205 "dtype=dtype('float64'))", 

206 ) 

207 

208 # Check that WCS headers were written out. 

209 with astropy.io.fits.open(tmpFile) as hdul: 

210 hdu1 = hdul[1] 

211 hdr1 = hdu1.header 

212 self.assertEqual(hdr1["CTYPE1"], "RA---TAN") 

213 

214 @unittest.skipUnless(DATA_DIR is not None, "TESTDATA_IMAGES_DIR is not in the environment.") 

215 def test_legacy(self) -> None: 

216 """Test Image.read_legacy, Image.to_legacy, and Image.from_legacy.""" 

217 assert DATA_DIR is not None, "Guaranteed by decorator." 

218 filename = os.path.join(DATA_DIR, "dp2", "legacy", "visit_image.fits") 

219 det_frame = DetectorFrame(instrument="Inst", visit=1234, detector=1, bbox=Box.factory[1:4096, 1:4096]) 

220 image = Image.read_legacy(filename, preserve_quantization=True, fits_wcs_frame=det_frame) 

221 try: 

222 from lsst.afw.image import MaskedImageFitsReader 

223 except ImportError: 

224 raise unittest.SkipTest("'lsst.afw.image' could not be imported.") from None 

225 reader = MaskedImageFitsReader(filename) 

226 legacy_image = reader.readImage() 

227 compare_image_to_legacy(self, image, legacy_image, expect_view=False) 

228 # Converting back to afw will not share memory, because 

229 # preserve_quantization=True makes the array read-only and to_legacy 

230 # has to copy in that case. 

231 compare_image_to_legacy(self, image, image.to_legacy(), expect_view=False) 

232 # Converting from afw will always share memory. 

233 image_view = Image.from_legacy(legacy_image) 

234 compare_image_to_legacy(self, image_view, legacy_image, expect_view=True) 

235 # Converting back to afw from the in-memory view will be another view. 

236 compare_image_to_legacy(self, image_view, image_view.to_legacy(), expect_view=True) 

237 

238 

239if __name__ == "__main__": 

240 unittest.main()