Coverage for tests/test_binImage.py: 97%
153 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-18 02:23 -0800
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-18 02:23 -0800
1# This file is part of afw.
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# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <https://www.gnu.org/licenses/>.
22import unittest
24import numpy as np
26import lsst.utils.tests
27import lsst.afw.image as afwImage
28import lsst.afw.math as afwMath
29import lsst.afw.display as afwDisplay
31try:
32 type(display)
33except NameError:
34 display = False
36# An integer slightly less than np.iinfo(np.int32).max/4, so it can be binned
37# only 2x2 before overflowing.
38maxint_d4 = 536870847
41def divide_nearest(array: np.ndarray, divisor: int):
42 """Divide an array by an integer while rounding to the nearest even int."""
43 exact = (array % divisor) == 0
44 array[exact] = array[exact] // divisor
45 array[~exact] = np.round(array[~exact]/np.double(divisor)).astype(array.dtype)
46 return array
49def rebin_array(array: np.ndarray, bin_x: int, bin_y: int) -> np.ndarray:
50 """Rebin an array by summing pixel values."""
51 n_y, n_x = array.shape
52 result = array.reshape(
53 n_y//bin_y, bin_y, n_x//bin_x, bin_x
54 ).sum(3).sum(1)
55 return result
58def rebin_mask(array: np.ndarray, bin_x: int, bin_y: int) -> np.ndarray:
59 """Rebin a mask array by summing pixel values."""
60 n_y, n_x = array.shape
61 result = array.reshape(
62 n_y//bin_y, bin_y, n_x//bin_x, bin_x
63 )
64 result = np.bitwise_or.reduce(result, axis=3)
65 result = np.bitwise_or.reduce(result, axis=1)
66 return result
69class BinImageTestCase(unittest.TestCase):
70 """A test case for binning images.
71 """
73 def setUp(self):
74 np.random.seed(1)
76 image_d = afwImage.ImageD(35, 63)
77 image_d.array[:, :] = np.random.uniform(low=-1, high=1, size=image_d.array.shape)
79 self.image_d = image_d
81 def tearDown(self):
82 del self.image_d
84 def testBin(self):
85 """Test that we can bin images.
86 """
87 inImage = afwImage.ImageF(203, 131)
88 inImage.set(1)
89 bin = 4
91 outImage = afwMath.binImage(inImage, bin)
93 self.assertEqual(outImage.getWidth(), inImage.getWidth()//bin)
94 self.assertEqual(outImage.getHeight(), inImage.getHeight()//bin)
96 stats = afwMath.makeStatistics(outImage, afwMath.MAX | afwMath.MIN)
97 self.assertEqual(stats.getValue(afwMath.MIN), 1)
98 self.assertEqual(stats.getValue(afwMath.MAX), 1)
100 def testBin2(self):
101 """Test that we can bin images anisotropically.
102 """
103 inImage = afwImage.ImageF(203, 131)
104 val = 1
105 inImage.set(val)
106 binX, binY = 2, 4
108 outImage = afwMath.binImage(inImage, binX, binY)
110 self.assertEqual(outImage.getWidth(), inImage.getWidth()//binX)
111 self.assertEqual(outImage.getHeight(), inImage.getHeight()//binY)
113 stats = afwMath.makeStatistics(outImage, afwMath.MAX | afwMath.MIN)
114 self.assertEqual(stats.getValue(afwMath.MIN), val)
115 self.assertEqual(stats.getValue(afwMath.MAX), val)
117 inImage.set(0)
118 subImg = inImage.Factory(inImage, lsst.geom.BoxI(lsst.geom.PointI(4, 4), lsst.geom.ExtentI(4, 8)),
119 afwImage.LOCAL)
120 subImg.set(100)
121 del subImg
122 outImage = afwMath.binImage(inImage, binX, binY)
124 if display: 124 ↛ 125line 124 didn't jump to line 125 because the condition on line 124 was never true
125 afwDisplay.Display(frame=2).mtv(inImage, title="unbinned")
126 afwDisplay.Display(frame=3).mtv(outImage, title=f"binned {binX}x{binY}")
128 def testBinValuesMasked(self):
129 """Test that binning works correctly for small masked images.
130 """
131 image_i = afwImage.ImageI(8, 8)
132 image_i.array.flat = np.arange(64)
134 # Trivial binning
135 binned = afwMath.binImage(image_i, 1)
136 np.testing.assert_array_equal(image_i.array, binned.array)
138 # Make sum odd in some bins and test rounding to even
139 image_i.array += (image_i.array % 4) == 0
140 binned = afwMath.binImage(image_i, 2)
141 truth = divide_nearest(rebin_array(image_i.array, 2, 2), 4)
142 np.testing.assert_array_equal(binned.array, truth)
144 value = 100
145 image_i.set(value)
147 # Basic test of maskImage binning
148 mimage_i = afwImage.makeMaskedImage(image_i)
149 mimage_i.variance.set(value)
151 binned = afwMath.binImage(mimage_i, 3)
153 np.testing.assert_array_equal(
154 binned.image.array,
155 np.full((2, 2), value),
156 )
157 np.testing.assert_allclose(
158 binned.variance.array,
159 np.full((2, 2), value/9).astype(np.float32),
160 rtol=1e-8,
161 atol=1e-8,
162 )
164 def testBinValuesInteger(self):
165 """Test that binning works correctly for small (half-)integer values.
166 """
167 shape = (6, 6)
168 image_d = afwImage.ImageD(*shape)
169 image_f = afwImage.ImageF(*shape)
171 image_i = afwImage.ImageI(*shape)
172 image_u = afwImage.ImageU(*shape)
173 # ImageL is not yet supported by binImage.
175 for offset in (0, 1, maxint_d4):
176 image_d.array = np.arange(shape[0]*shape[1]).reshape(shape) + offset
177 image_f.array = image_d.array
178 image_i.array = image_d.array
179 image_u.array = image_i.array
180 binned = (
181 (
182 2, 2,
183 np.array([
184 [3.5, 5.5, 7.5],
185 [15.5, 17.5, 19.5],
186 [27.5, 29.5, 31.5],
187 ]),
188 ),
189 (
190 2, 3,
191 np.array([
192 [6.5, 8.5, 10.5],
193 [24.5, 26.5, 28.5],
194 ]),
195 ),
196 (
197 3, 2,
198 np.array([
199 [4., 7.],
200 [16., 19.],
201 [28., 31.],
202 ])
203 ),
204 (
205 3, 3,
206 np.array([
207 [7., 10.],
208 [25., 28.],
209 ])
210 ),
211 )
212 for bin_x, bin_y, truth in binned:
213 truth += offset
214 # Small offsets actually tests exactly equal with ImageD (not ImageF)
215 # but this could be compiler/optimization-dependent
216 for image, rtol, atol in ((image_d, 1e-14, 1e-14), (image_f, 1e-9, 1e-10)):
217 # These adjustments are somewhat arbitrary and may need
218 # to be more principled
219 if (offset > 1e8) and ((atol >= 1e-12) or (rtol >= 1e-12)):
220 atol *= 1000*offset
221 rtol *= 100
222 np.testing.assert_allclose(
223 afwMath.binImage(image, bin_x, bin_y).array,
224 truth,
225 rtol=rtol,
226 atol=atol,
227 )
228 for image in (image_u, image_i):
229 # image_u will overflow for large offsets, but it should
230 # still overflow predictably
231 truth_t = np.round(truth).astype(image.array.dtype)
232 np.testing.assert_array_equal(
233 afwMath.binImage(image, bin_x, bin_y).array,
234 truth_t,
235 )
237 def testBinValuesFloat(self):
238 """Test that binning works correctly for a wide range of floats.
239 """
240 image_d_original = self.image_d
241 n_y, n_x = image_d_original.array.shape
243 mask = afwImage.makeMaskFromArray(np.zeros((0, 0), dtype=np.int32))
244 mask = afwImage.makeMaskFromArray(
245 np.random.uniform(
246 high=2**(1 + max(mask.getMaskPlaneDict().values())) - 1,
247 size=(n_y, n_x),
248 ).astype(np.int32)
249 )
251 bin_info = tuple(
252 (bin_x, bin_y, rebin_mask(mask.array, bin_x, bin_y))
253 for bin_x, bin_y in (
254 (5, 21),
255 (7, 7),
256 )
257 )
259 # Test that rebinning works on a larger array with a wider range
260 # of floating point values
262 for multiple, rtol_d, rtol_f, rtol_v in (
263 (1e-32, 1e-12, None, None),
264 (1./maxint_d4, 1e-13, 1e-8, 5e-5),
265 (1./32564, 5e-14, 1e-7, 5e-7,),
266 (1, 1e-14, 1e-6, 5e-7),
267 (32564, 5e-14, 1e-6, 5e-6),
268 (maxint_d4, 1e-12, 1e-6, 5e-5),
269 (1e32, 1e-12, None, None),
270 ):
271 image_d = image_d_original.clone()
272 image_d.array *= multiple
274 if rtol_f is not None:
275 image_f = afwImage.ImageF(image_d, deep=True)
276 else:
277 image_f = None
278 if maxint_d4 >= multiple >= 1:
279 image_i = afwImage.ImageI(image_d, deep=True)
280 else:
281 image_i = None
283 for bin_x, bin_y, mask_truth in bin_info:
284 bin_xy = bin_x*bin_y
285 truth = rebin_array(image_d.array/bin_xy, bin_x, bin_y)
286 binned_image = afwMath.binImage(image_d, bin_x, bin_y).array
287 np.testing.assert_allclose(
288 binned_image,
289 truth,
290 rtol=rtol_d,
291 atol=rtol_d,
292 )
293 variance_large = multiple > 32564
294 self._compareBinnedMaskedImage(
295 image_d, mask, bin_x, bin_y, binned_image, mask_truth, rtol_v, rtol_v,
296 variance_large=variance_large,
297 )
299 if image_f is not None:
300 binned_image = afwMath.binImage(image_f, bin_x, bin_y).array
301 np.testing.assert_allclose(
302 binned_image,
303 truth.astype(np.float32),
304 rtol=rtol_f,
305 atol=multiple*max(rtol_f, 1e-6),
306 )
307 self._compareBinnedMaskedImage(
308 image_f, mask, bin_x, bin_y, binned_image, mask_truth, rtol_v, rtol_v,
309 variance_large=variance_large,
310 )
311 if image_i is not None:
312 truth = rebin_array(image_i.array.astype(np.int64), bin_x, bin_y)
313 divide_nearest(truth, bin_xy)
314 binned_image = afwMath.binImage(image_i, bin_x, bin_y).array
316 np.testing.assert_array_equal(binned_image, truth)
317 # The utility of an integer image with floating variance
318 # is dubious, but it should still work.
319 self._compareBinnedMaskedImage(
320 image_i, mask, bin_x, bin_y, binned_image, mask_truth, rtol_v, rtol_v,
321 variance_large=variance_large,
322 )
324 @staticmethod
325 def _compareBinnedMaskedImage(
326 image, mask, bin_x, bin_y, binned_image, mask_truth, rtol, atol,
327 variance=None, variance_large=False,
328 ):
329 """Assert that the results of binning a masked image are correct.
331 This is a convenience function that
332 """
333 bin_xy = bin_x*bin_y
334 variance = (image.array[::-1] if variance is None else variance).astype(np.float32)
335 masked = afwImage.makeMaskedImageFromArrays(image.array, mask.array, variance)
337 binned = afwMath.binImage(masked, bin_x, bin_y)
338 # Assert that the binning gives the same result without a mask
339 np.testing.assert_array_equal(binned_image, binned.image.array)
340 np.testing.assert_array_equal(binned.mask.array, mask_truth)
341 if rtol is not None and atol is not None:
342 truth = rebin_array(
343 masked.variance.array/(bin_xy if variance_large else 1), bin_x, bin_y
344 )
345 truth /= bin_xy*(1 if variance_large else bin_xy)
346 truth = truth.astype(np.float32)
347 np.testing.assert_allclose(
348 binned.variance.array,
349 truth,
350 rtol=rtol,
351 atol=atol,
352 )
355class TestMemory(lsst.utils.tests.MemoryTestCase):
356 pass
359def setup_module(module):
360 lsst.utils.tests.init()
363if __name__ == "__main__": 363 ↛ 364line 363 didn't jump to line 364 because the condition on line 363 was never true
364 lsst.utils.tests.init()
365 unittest.main()