22 from __future__
import absolute_import, division, print_function
26 __all__ = [
"assertImagesAlmostEqual",
"assertImagesEqual",
"assertMasksEqual",
27 "assertMaskedImagesAlmostEqual",
"assertMaskedImagesEqual",
28 "assertImagesNearlyEqual",
"assertMaskedImagesNearlyEqual"]
34 import lsst.utils.tests
35 from .image
import ImageF
36 from .basicUtils
import makeMaskedImageFromArrays
40 """Make a gaussian noise MaskedImageF
43 - dimensions: dimensions of output array (cols, rows)
44 - sigma; sigma of image plane's noise distribution
45 - variance: constant value for variance plane
47 npSize = (dimensions[1], dimensions[0])
48 image = np.random.normal(loc=0.0, scale=sigma,
49 size=npSize).astype(np.float32)
50 mask = np.zeros(npSize, dtype=np.uint16)
51 variance = np.zeros(npSize, dtype=np.float32) + variance
57 """!Make an image whose values are a linear ramp
59 @param[in] bbox bounding box of image (an lsst.afw.geom.Box2I)
60 @param[in] start starting ramp value, inclusive
61 @param[in] stop ending ramp value, inclusive; if None, increase by integer values
62 @param[in] imageClass type of image (e.g. lsst.afw.image.ImageF)
65 imDim = im.getDimensions()
66 numPix = imDim[0]*imDim[1]
70 stop = start + numPix - 1
71 rampArr = np.linspace(start=start, stop=stop,
72 endpoint=
True, num=numPix, dtype=imArr.dtype)
74 imArr[:] = np.reshape(rampArr, (imDim[1], imDim[0]))
78 @lsst.utils.tests.inTestCase
80 rtol=1.0e-05, atol=1e-08, msg=
"Images differ"):
81 """!Assert that two images are almost equal, including non-finite values
83 @param[in] testCase unittest.TestCase instance the test is part of;
84 an object supporting one method: fail(self, msgStr)
85 @param[in] image0 image 0, an lsst.afw.image.Image, lsst.afw.image.Mask,
86 or transposed numpy array (see warning)
87 @param[in] image1 image 1, an lsst.afw.image.Image, lsst.afw.image.Mask,
88 or transposed numpy array (see warning)
89 @param[in] skipMask mask of pixels to skip, or None to compare all pixels;
90 an lsst.afw.image.Mask, lsst.afw.image.Image, or transposed numpy array (see warning);
91 all non-zero pixels are skipped
92 @param[in] rtol maximum allowed relative tolerance; more info below
93 @param[in] atol maximum allowed absolute tolerance; more info below
94 @param[in] msg exception message prefix; details of the error are appended after ": "
96 The images are nearly equal if all pixels obey:
97 |val1 - val0| <= rtol*|val1| + atol
98 or, for float types, if nan/inf/-inf pixels match.
100 @warning the comparison equation is not symmetric, so in rare cases the assertion
101 may give different results depending on which image comes first.
103 @warning the axes of numpy arrays are transposed with respect to Image and Mask data.
104 Thus for example if image0 and image1 are both lsst.afw.image.ImageD with dimensions (2, 3)
105 and skipMask is a numpy array, then skipMask must have shape (3, 2).
107 @throw self.failureException (usually AssertionError) if any of the following are true
108 for un-skipped pixels:
109 - non-finite values differ in any way (e.g. one is "nan" and another is not)
110 - finite values differ by too much, as defined by atol and rtol
112 @throw TypeError if the dimensions of image0, image1 and skipMask do not match,
113 or any are not of a numeric data type.
116 image0, image1, skipMask=skipMask, rtol=rtol, atol=atol)
118 testCase.fail(
"%s: %s" % (msg, errStr))
121 @lsst.utils.tests.inTestCase
123 """!Assert that two images are exactly equal, including non-finite values.
125 All arguments are forwarded to assertAnglesAlmostEqual aside from atol and rtol,
126 which are set to zero.
131 @lsst.utils.tests.inTestCase
133 """!Assert that two masks are equal
135 @param[in] testCase unittest.TestCase instance the test is part of;
136 an object supporting one method: fail(self, msgStr)
137 @param[in] mask0 mask 0, an lsst.afw.image.Mask, lsst.afw.image.Image,
138 or transposed numpy array (see warning)
139 @param[in] mask1 mask 1, an lsst.afw.image.Mask, lsst.afw.image.Image,
140 or transposed numpy array (see warning)
141 @param[in] skipMask mask of pixels to skip, or None to compare all pixels;
142 an lsst.afw.image.Mask, lsst.afw.image.Image, or transposed numpy array (see warning);
143 all non-zero pixels are skipped
144 @param[in] msg exception message prefix; details of the error are appended after ": "
146 @warning the axes of numpy arrays are transposed with respect to Mask and Image.
147 Thus for example if mask0 and mask1 are both lsst.afw.image.MaskU with dimensions (2, 3)
148 and skipMask is a numpy array, then skipMask must have shape (3, 2).
150 @throw self.failureException (usually AssertionError) if any any un-skipped pixels differ
152 @throw TypeError if the dimensions of mask0, mask1 and skipMask do not match,
153 or any are not of a numeric data type.
155 errStr =
imagesDiffer(mask0, mask1, skipMask=skipMask, rtol=0, atol=0)
157 testCase.fail(
"%s: %s" % (msg, errStr))
160 @lsst.utils.tests.inTestCase
162 testCase, maskedImage0, maskedImage1,
163 doImage=
True, doMask=
True, doVariance=
True, skipMask=
None,
164 rtol=1.0e-05, atol=1e-08, msg=
"Masked images differ",
166 """!Assert that two masked images are nearly equal, including non-finite values
168 @param[in] testCase unittest.TestCase instance the test is part of;
169 an object supporting one method: fail(self, msgStr)
170 @param[in] maskedImage0 masked image 0 (an lsst.afw.image.MaskedImage or
171 collection of three transposed numpy arrays: image, mask, variance)
172 @param[in] maskedImage1 masked image 1 (an lsst.afw.image.MaskedImage or
173 collection of three transposed numpy arrays: image, mask, variance)
174 @param[in] doImage compare image planes if True
175 @param[in] doMask compare mask planes if True
176 @param[in] doVariance compare variance planes if True
177 @param[in] skipMask mask of pixels to skip, or None to compare all pixels;
178 an lsst.afw.image.Mask, lsst.afw.image.Image, or transposed numpy array;
179 all non-zero pixels are skipped
180 @param[in] rtol maximum allowed relative tolerance; more info below
181 @param[in] atol maximum allowed absolute tolerance; more info below
182 @param[in] msg exception message prefix; details of the error are appended after ": "
184 The mask planes must match exactly. The image and variance planes are nearly equal if all pixels obey:
185 |val1 - val0| <= rtol*|val1| + atol
186 or, for float types, if nan/inf/-inf pixels match.
188 @warning the comparison equation is not symmetric, so in rare cases the assertion
189 may give different results depending on which masked image comes first.
191 @warning the axes of numpy arrays are transposed with respect to MaskedImage data.
192 Thus for example if maskedImage0 and maskedImage1 are both lsst.afw.image.MaskedImageD
193 with dimensions (2, 3) and skipMask is a numpy array, then skipMask must have shape (3, 2).
195 @throw self.failureException (usually AssertionError) if any of the following are true
196 for un-skipped pixels:
197 - non-finite image or variance values differ in any way (e.g. one is "nan" and another is not)
198 - finite values differ by too much, as defined by atol and rtol
199 - mask pixels differ at all
201 @throw TypeError if the dimensions of maskedImage0, maskedImage1 and skipMask do not match,
202 either image or variance plane is not of a numeric data type,
203 either mask plane is not of an integer type (unsigned or signed),
204 or skipMask is not of a numeric data type.
206 maskedImageArrList0 = maskedImage0.getArrays()
if hasattr(
207 maskedImage0,
"getArrays")
else maskedImage0
208 maskedImageArrList1 = maskedImage1.getArrays()
if hasattr(
209 maskedImage1,
"getArrays")
else maskedImage1
211 for arrList, arg, name
in (
212 (maskedImageArrList0, maskedImage0,
"maskedImage0"),
213 (maskedImageArrList1, maskedImage1,
"maskedImage1"),
216 assert len(arrList) == 3
221 assert arrList[i].shape == arrList[1].shape
222 assert arrList[i].dtype.kind
in (
"b",
"i",
"u", "f", "c")
223 assert arrList[1].dtype.kind
in (
"b",
"i",
"u")
225 raise TypeError(
"%s=%r is not a supported type" % (name, arg))
228 for ind, (doPlane, planeName)
in enumerate(((doImage,
"image"),
230 (doVariance,
"variance"))):
234 if planeName ==
"mask":
235 errStr =
imagesDiffer(maskedImageArrList0[ind], maskedImageArrList1[ind], skipMask=skipMask,
238 errStrList.append(errStr)
240 errStr =
imagesDiffer(maskedImageArrList0[ind], maskedImageArrList1[ind],
241 skipMask=skipMask, rtol=rtol, atol=atol)
243 errStrList.append(
"%s planes differ: %s" % (planeName, errStr))
246 testCase.fail(
"%s: %s" % (msg,
"; ".join(errStrList)))
249 @lsst.utils.tests.inTestCase
251 """!Assert that two masked images are exactly equal, including non-finite values.
253 All arguments are forwarded to assertMaskedImagesAlmostEqual aside from atol and rtol,
254 which are set to zero.
259 def imagesDiffer(image0, image1, skipMask=None, rtol=1.0e-05, atol=1e-08):
260 """!Compare the pixels of two image or mask arrays; return True if close, False otherwise
262 @param[in] image0 image 0, an lsst.afw.image.Image, lsst.afw.image.Mask,
263 or transposed numpy array (see warning)
264 @param[in] image1 image 1, an lsst.afw.image.Image, lsst.afw.image.Mask,
265 or transposed numpy array (see warning)
266 @param[in] skipMask mask of pixels to skip, or None to compare all pixels;
267 an lsst.afw.image.Mask, lsst.afw.image.Image, or transposed numpy array (see warning);
268 all non-zero pixels are skipped
269 @param[in] rtol maximum allowed relative tolerance; more info below
270 @param[in] atol maximum allowed absolute tolerance; more info below
272 The images are nearly equal if all pixels obey:
273 |val1 - val0| <= rtol*|val1| + atol
274 or, for float types, if nan/inf/-inf pixels match.
276 @warning the comparison equation is not symmetric, so in rare cases the assertion
277 may give different results depending on which image comes first.
279 @warning the axes of numpy arrays are transposed with respect to Image and Mask data.
280 Thus for example if image0 and image1 are both lsst.afw.image.ImageD with dimensions (2, 3)
281 and skipMask is a numpy array, then skipMask must have shape (3, 2).
283 @return a string which is non-empty if the images differ
285 @throw TypeError if the dimensions of image0, image1 and skipMask do not match,
286 or any are not of a numeric data type.
289 imageArr0 = image0.getArray()
if hasattr(image0,
"getArray")
else image0
290 imageArr1 = image1.getArray()
if hasattr(image1,
"getArray")
else image1
291 skipMaskArr = skipMask.getArray()
if hasattr(skipMask,
"getArray")
else skipMask
295 (imageArr0, image0,
"image0"),
296 (imageArr1, image1,
"image1"),
298 if skipMask
is not None:
299 arrArgNameList.append((skipMaskArr, skipMask,
"skipMask"))
300 for i, (arr, arg, name)
in enumerate(arrArgNameList):
302 assert arr.dtype.kind
in (
"b",
"i",
"u", "f", "c")
304 raise TypeError(
"%r=%r is not a supported type" % (name, arg))
306 if arr.shape != imageArr0.shape:
307 raise TypeError(
"%s shape = %s != %s = image0 shape" %
308 (name, arr.shape, imageArr0.shape))
314 if imageArr0.dtype.kind ==
"u":
315 imageArr0 = imageArr0.astype(
316 np.promote_types(imageArr0.dtype, np.int8))
317 if imageArr1.dtype.kind ==
"u":
318 imageArr1 = imageArr1.astype(
319 np.promote_types(imageArr1.dtype, np.int8))
321 if skipMaskArr
is not None:
322 skipMaskArr = np.array(skipMaskArr, dtype=bool)
323 maskedArr0 = np.ma.array(imageArr0, copy=
False, mask=skipMaskArr)
324 maskedArr1 = np.ma.array(imageArr1, copy=
False, mask=skipMaskArr)
325 filledArr0 = maskedArr0.filled(0.0)
326 filledArr1 = maskedArr1.filled(0.0)
329 filledArr0 = imageArr0
330 filledArr1 = imageArr1
333 np.array([np.nan], dtype=imageArr0.dtype)
334 np.array([np.nan], dtype=imageArr1.dtype)
338 valSkipMaskArr = skipMaskArr
342 nan0 = np.isnan(filledArr0)
343 nan1 = np.isnan(filledArr1)
344 if np.any(nan0 != nan1):
345 errStrList.append(
"NaNs differ")
347 posinf0 = np.isposinf(filledArr0)
348 posinf1 = np.isposinf(filledArr1)
349 if np.any(posinf0 != posinf1):
350 errStrList.append(
"+infs differ")
352 neginf0 = np.isneginf(filledArr0)
353 neginf1 = np.isneginf(filledArr1)
354 if np.any(neginf0 != neginf1):
355 errStrList.append(
"-infs differ")
357 valSkipMaskArr = nan0 | nan1 | posinf0 | posinf1 | neginf0 | neginf1
358 if skipMaskArr
is not None:
359 valSkipMaskArr |= skipMaskArr
362 valMaskedArr1 = np.ma.array(imageArr0, copy=
False, mask=valSkipMaskArr)
363 valMaskedArr2 = np.ma.array(imageArr1, copy=
False, mask=valSkipMaskArr)
364 valFilledArr1 = valMaskedArr1.filled(0.0)
365 valFilledArr2 = valMaskedArr2.filled(0.0)
367 if not np.allclose(valFilledArr1, valFilledArr2, rtol=rtol, atol=atol):
368 errArr = np.abs(valFilledArr1 - valFilledArr2)
369 maxErr = errArr.max()
370 maxPosInd = np.where(errArr == maxErr)
371 maxPosTuple = (maxPosInd[1][0], maxPosInd[0][0])
372 errStr =
"maxDiff=%s at position %s; value=%s vs. %s" % \
373 (maxErr, maxPosTuple,
374 valFilledArr1[maxPosInd][0], valFilledArr2[maxPosInd][0])
375 errStrList.insert(0, errStr)
377 return "; ".join(errStrList)
380 @lsst.utils.tests.inTestCase
382 warnings.warn(
"Deprecated. Use assertImagesAlmostEqual",
387 @lsst.utils.tests.inTestCase
389 warnings.warn(
"Deprecated. Use assertMaskedImagesAlmostEqual",
def assertMaskedImagesAlmostEqual
Assert that two masked images are nearly equal, including non-finite values.
def assertMasksEqual
Assert that two masks are equal.
def assertMaskedImagesNearlyEqual
def makeRampImage
Make an image whose values are a linear ramp.
def assertImagesAlmostEqual
Assert that two images are almost equal, including non-finite values.
def assertMaskedImagesEqual
Assert that two masked images are exactly equal, including non-finite values.
def assertImagesEqual
Assert that two images are exactly equal, including non-finite values.
def assertImagesNearlyEqual
def imagesDiffer
Compare the pixels of two image or mask arrays; return True if close, False otherwise.
def makeGaussianNoiseMaskedImage
def makeMaskedImageFromArrays