Coverage for tests / test_image.py: 18%
103 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-05-01 08:36 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-05-01 08:36 +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.
12from __future__ import annotations
14import os
15import unittest
17import astropy.io.fits
18import astropy.units as u
19import numpy as np
20from astro_metadata_translator import ObservationInfo
22import lsst.utils.tests
23from lsst.images import Box, DetectorFrame, Image
24from lsst.images.tests import (
25 RoundtripFits,
26 RoundtripJson,
27 assert_close,
28 assert_images_equal,
29 assert_projections_equal,
30 compare_image_to_legacy,
31 make_random_projection,
32)
34DATA_DIR = os.environ.get("TESTDATA_IMAGES_DIR", None)
37class ImageTestCase(unittest.TestCase):
38 """Tests for the Image class."""
40 def test_basics(self):
41 """Test basic constructor patterns."""
42 image = Image(42, shape=(5, 5), metadata={"three": 3})
43 assert_close(self, image.array, np.zeros([5, 5], dtype=np.int64) + 42)
44 self.assertEqual(image.metadata["three"], 3)
46 data = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
47 image = Image(data)
48 subset = image[Box.factory[:3, 1:3]]
49 subset2 = image.absolute[:3, 1:3]
50 assert_images_equal(self, subset2, subset, expect_view=True)
52 assert_images_equal(self, image.copy(), image, expect_view=False)
54 # Add an explicit bounding box and then slice it.
55 image = Image(data, bbox=Box.factory[-2:1, 10:14])
56 with self.assertRaises(IndexError):
57 # Same slice no longer works in absolute slicing because we have
58 # moved origin.
59 image.absolute[:3, 1:3]
60 # That slice does still work in local coordinates.
61 assert_close(self, image.local[:3, 1:3].array, subset2.array)
62 # And we can write an equivalent slice in absolute coordinates.
63 assert_close(self, image.absolute[:0, 11:13].array, np.array([[2, 3], [6, 7]]))
65 # Test __eq__ behavior.
66 self.assertEqual(image[...], image)
67 self.assertEqual(image.__eq__(data), NotImplemented)
68 self.assertNotEqual(image, list(data))
70 with self.assertRaises(ValueError):
71 # bbox does not match array shape.
72 Image(np.array([[1, 2, 3], [4, 5, 6]]), bbox=Box.factory[0:2, 0:4])
74 with self.assertRaises(ValueError):
75 # shape does not match array shape.
76 Image(np.array([[2, 3, 4], [6, 7, 8]]), shape=[5, 2])
78 with self.assertRaises(TypeError):
79 # shape and bbox both None.
80 Image()
82 with self.assertRaises(ValueError):
83 # Shape mismatch.
84 Image(shape=[3, 6], bbox=Box.factory[-5:10, 0:10])
86 def test_json_roundtrip(self) -> None:
87 """Test saving a tiny image to pure JSON."""
88 image = Image(
89 np.arange(15).reshape(5, 3),
90 start=(2, -1),
91 )
92 with RoundtripJson(self, image) as roundtrip:
93 pass
94 assert_images_equal(self, image, roundtrip.result)
96 def test_fits_roundtrip(self) -> None:
97 """Test saving a tiny image to FITS generically."""
98 image = Image(
99 np.arange(15).reshape(5, 3),
100 start=(2, -1),
101 )
102 with RoundtripFits(self, image) as roundtrip:
103 subbox = Box.factory[3:5, 0:1]
104 assert_images_equal(self, image[subbox], roundtrip.get(bbox=subbox))
105 assert_images_equal(self, image, roundtrip.result)
107 def test_quantity(self):
108 """Test quantities."""
109 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]])
110 data2 = data.copy() * 2.0
111 image = Image(data, unit=u.mJy, bbox=Box.factory[-2:1, 3:7])
113 q = image.quantity
114 self.assertEqual(q[1, 0], 5.0 * u.mJy)
115 image.quantity = image.array * 10.0 * u.uJy
116 q = image.quantity
117 self.assertEqual(q[1, 0], 0.05 * u.mJy)
119 image2 = Image(data2, unit=u.Jy)
120 image[Box.factory[-1:0, 5:7]] = image2.local[1:2, 2:4]
121 assert_close(
122 self,
123 image.array,
124 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]]),
125 )
127 def test_read_write(self):
128 """Round trip through file.
130 This uses the read_fits and write_fits methods (which RoundtripFits
131 does not use).
132 """
133 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]])
134 md = {"int": 1, "float": 42.0, "bool": False, "long string header": "This is a string"}
135 obsinfo = ObservationInfo(telescope="Simonyi", instrument="LSSTCam", relative_humidity=23.5)
136 det_frame = DetectorFrame(instrument="Inst", visit=1234, detector=1, bbox=Box.factory[1:4096, 1:4096])
137 rng = np.random.default_rng(500)
138 projection = make_random_projection(rng, det_frame, Box.factory[1:4096, 1:4096])
140 image = Image(
141 data,
142 unit=u.nJy,
143 metadata=md,
144 obs_info=obsinfo,
145 bbox=Box.factory[-2:1, 3:7],
146 projection=projection,
147 )
149 with lsst.utils.tests.getTempFilePath(".fits") as tmpFile:
150 image.write_fits(tmpFile)
152 new = Image.read_fits(tmpFile)
153 self.assertEqual(new, image)
155 # __eq__ does not test all components.
156 self.assertEqual(new.obs_info, image.obs_info)
157 self.assertEqual(new.metadata, image.metadata)
158 self.maxDiff = None
159 assert_projections_equal(self, new.projection, image.projection, expect_identity=False)
161 # Read subset.
162 subset = Image.read_fits(tmpFile, bbox=Box.factory[-2:0, 5:7])
163 self.assertEqual(subset, image.absolute[-2:0, 5:7])
164 self.assertEqual(subset, image.local[0:2, 2:4])
165 self.assertEqual(str(subset), "Image([y=-2:0, x=5:7], float64)")
166 self.assertEqual(
167 repr(subset),
168 "Image(..., bbox=Box(y=Interval(start=-2, stop=0), x=Interval(start=5, stop=7)), "
169 "dtype=dtype('float64'))",
170 )
172 # Check that WCS headers were written out.
173 with astropy.io.fits.open(tmpFile) as hdul:
174 hdu1 = hdul[1]
175 hdr1 = hdu1.header
176 self.assertEqual(hdr1["CTYPE1"], "RA---TAN")
178 @unittest.skipUnless(DATA_DIR is not None, "TESTDATA_IMAGES_DIR is not in the environment.")
179 def test_legacy(self) -> None:
180 """Test Image.read_legacy, Image.to_legacy, and Image.from_legacy."""
181 assert DATA_DIR is not None, "Guaranteed by decorator."
182 filename = os.path.join(DATA_DIR, "dp2", "legacy", "visit_image.fits")
183 det_frame = DetectorFrame(instrument="Inst", visit=1234, detector=1, bbox=Box.factory[1:4096, 1:4096])
184 image = Image.read_legacy(filename, preserve_quantization=True, fits_wcs_frame=det_frame)
185 try:
186 from lsst.afw.image import MaskedImageFitsReader
187 except ImportError:
188 raise unittest.SkipTest("'lsst.afw.image' could not be imported.") from None
189 reader = MaskedImageFitsReader(filename)
190 legacy_image = reader.readImage()
191 compare_image_to_legacy(self, image, legacy_image, expect_view=False)
192 # Converting back to afw will not share memory, because
193 # preserve_quantization=True makes the array read-only and to_legacy
194 # has to copy in that case.
195 compare_image_to_legacy(self, image, image.to_legacy(), expect_view=False)
196 # Converting from afw will always share memory.
197 image_view = Image.from_legacy(legacy_image)
198 compare_image_to_legacy(self, image_view, legacy_image, expect_view=True)
199 # Converting back to afw from the in-memory view will be another view.
200 compare_image_to_legacy(self, image_view, image_view.to_legacy(), expect_view=True)
203if __name__ == "__main__":
204 unittest.main()