lsst.afw  15.0-29-ga12a2b06e
testUtils.py
Go to the documentation of this file.
1 #
2 # LSST Data Management System
3 # Copyright 2008-2017 LSST/AURA.
4 #
5 # This product includes software developed by the
6 # LSST Project (http://www.lsst.org/).
7 #
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the LSST License Statement and
19 # the GNU General Public License along with this program. If not,
20 # see <http://www.lsstcorp.org/LegalNotices/>.
21 #
22 
23 # the asserts are automatically imported so unit tests can find them without special imports;
24 # the other functions are hidden unless explicitly asked for
25 __all__ = ["assertImagesAlmostEqual", "assertImagesEqual", "assertMasksEqual",
26  "assertMaskedImagesAlmostEqual", "assertMaskedImagesEqual",
27  "assertImagesNearlyEqual", "assertMaskedImagesNearlyEqual"]
28 
29 import warnings
30 
31 import numpy as np
32 
33 import lsst.utils.tests
34 from .image import ImageF
35 from .basicUtils import makeMaskedImageFromArrays
36 
37 
38 def makeGaussianNoiseMaskedImage(dimensions, sigma, variance=1.0):
39  """Make a gaussian noise MaskedImageF
40 
41  Inputs:
42  - dimensions: dimensions of output array (cols, rows)
43  - sigma; sigma of image plane's noise distribution
44  - variance: constant value for variance plane
45  """
46  npSize = (dimensions[1], dimensions[0])
47  image = np.random.normal(loc=0.0, scale=sigma,
48  size=npSize).astype(np.float32)
49  mask = np.zeros(npSize, dtype=np.int32)
50  variance = np.zeros(npSize, dtype=np.float32) + variance
51 
52  return makeMaskedImageFromArrays(image, mask, variance)
53 
54 
55 def makeRampImage(bbox, start=0, stop=None, imageClass=ImageF):
56  """!Make an image whose values are a linear ramp
57 
58  @param[in] bbox bounding box of image (an lsst.afw.geom.Box2I)
59  @param[in] start starting ramp value, inclusive
60  @param[in] stop ending ramp value, inclusive; if None, increase by integer values
61  @param[in] imageClass type of image (e.g. lsst.afw.image.ImageF)
62  """
63  im = imageClass(bbox)
64  imDim = im.getDimensions()
65  numPix = imDim[0]*imDim[1]
66  imArr = im.getArray()
67  if stop is None:
68  # increase by integer values
69  stop = start + numPix - 1
70  rampArr = np.linspace(start=start, stop=stop,
71  endpoint=True, num=numPix, dtype=imArr.dtype)
72  # numpy arrays are transposed w.r.t. afwImage
73  imArr[:] = np.reshape(rampArr, (imDim[1], imDim[0]))
74  return im
75 
76 
77 @lsst.utils.tests.inTestCase
78 def assertImagesAlmostEqual(testCase, image0, image1, skipMask=None,
79  rtol=1.0e-05, atol=1e-08, msg="Images differ"):
80  """!Assert that two images are almost equal, including non-finite values
81 
82  @param[in] testCase unittest.TestCase instance the test is part of;
83  an object supporting one method: fail(self, msgStr)
84  @param[in] image0 image 0, an lsst.afw.image.Image, lsst.afw.image.Mask,
85  or transposed numpy array (see warning)
86  @param[in] image1 image 1, an lsst.afw.image.Image, lsst.afw.image.Mask,
87  or transposed numpy array (see warning)
88  @param[in] skipMask mask of pixels to skip, or None to compare all pixels;
89  an lsst.afw.image.Mask, lsst.afw.image.Image, or transposed numpy array (see warning);
90  all non-zero pixels are skipped
91  @param[in] rtol maximum allowed relative tolerance; more info below
92  @param[in] atol maximum allowed absolute tolerance; more info below
93  @param[in] msg exception message prefix; details of the error are appended after ": "
94 
95  The images are nearly equal if all pixels obey:
96  |val1 - val0| <= rtol*|val1| + atol
97  or, for float types, if nan/inf/-inf pixels match.
98 
99  @warning the comparison equation is not symmetric, so in rare cases the assertion
100  may give different results depending on which image comes first.
101 
102  @warning the axes of numpy arrays are transposed with respect to Image and Mask data.
103  Thus for example if image0 and image1 are both lsst.afw.image.ImageD with dimensions (2, 3)
104  and skipMask is a numpy array, then skipMask must have shape (3, 2).
105 
106  @throw self.failureException (usually AssertionError) if any of the following are true
107  for un-skipped pixels:
108  - non-finite values differ in any way (e.g. one is "nan" and another is not)
109  - finite values differ by too much, as defined by atol and rtol
110 
111  @throw TypeError if the dimensions of image0, image1 and skipMask do not match,
112  or any are not of a numeric data type.
113  """
114  errStr = imagesDiffer(
115  image0, image1, skipMask=skipMask, rtol=rtol, atol=atol)
116  if errStr:
117  testCase.fail("%s: %s" % (msg, errStr))
118 
119 
120 @lsst.utils.tests.inTestCase
121 def assertImagesEqual(*args, **kwds):
122  """!Assert that two images are exactly equal, including non-finite values.
123 
124  All arguments are forwarded to assertAnglesAlmostEqual aside from atol and rtol,
125  which are set to zero.
126  """
127  return assertImagesAlmostEqual(*args, atol=0, rtol=0, **kwds)
128 
129 
130 @lsst.utils.tests.inTestCase
131 def assertMasksEqual(testCase, mask0, mask1, skipMask=None, msg="Masks differ"):
132  """!Assert that two masks are equal
133 
134  @param[in] testCase unittest.TestCase instance the test is part of;
135  an object supporting one method: fail(self, msgStr)
136  @param[in] mask0 mask 0, an lsst.afw.image.Mask, lsst.afw.image.Image,
137  or transposed numpy array (see warning)
138  @param[in] mask1 mask 1, an lsst.afw.image.Mask, lsst.afw.image.Image,
139  or transposed numpy array (see warning)
140  @param[in] skipMask mask of pixels to skip, or None to compare all pixels;
141  an lsst.afw.image.Mask, lsst.afw.image.Image, or transposed numpy array (see warning);
142  all non-zero pixels are skipped
143  @param[in] msg exception message prefix; details of the error are appended after ": "
144 
145  @warning the axes of numpy arrays are transposed with respect to Mask and Image.
146  Thus for example if mask0 and mask1 are both lsst.afw.image.Mask with dimensions (2, 3)
147  and skipMask is a numpy array, then skipMask must have shape (3, 2).
148 
149  @throw self.failureException (usually AssertionError) if any any un-skipped pixels differ
150 
151  @throw TypeError if the dimensions of mask0, mask1 and skipMask do not match,
152  or any are not of a numeric data type.
153  """
154  errStr = imagesDiffer(mask0, mask1, skipMask=skipMask, rtol=0, atol=0)
155  if errStr:
156  testCase.fail("%s: %s" % (msg, errStr))
157 
158 
159 @lsst.utils.tests.inTestCase
161  testCase, maskedImage0, maskedImage1,
162  doImage=True, doMask=True, doVariance=True, skipMask=None,
163  rtol=1.0e-05, atol=1e-08, msg="Masked images differ",
164 ):
165  """!Assert that two masked images are nearly equal, including non-finite values
166 
167  @param[in] testCase unittest.TestCase instance the test is part of;
168  an object supporting one method: fail(self, msgStr)
169  @param[in] maskedImage0 masked image 0 (an lsst.afw.image.MaskedImage or
170  collection of three transposed numpy arrays: image, mask, variance)
171  @param[in] maskedImage1 masked image 1 (an lsst.afw.image.MaskedImage or
172  collection of three transposed numpy arrays: image, mask, variance)
173  @param[in] doImage compare image planes if True
174  @param[in] doMask compare mask planes if True
175  @param[in] doVariance compare variance planes if True
176  @param[in] skipMask mask of pixels to skip, or None to compare all pixels;
177  an lsst.afw.image.Mask, lsst.afw.image.Image, or transposed numpy array;
178  all non-zero pixels are skipped
179  @param[in] rtol maximum allowed relative tolerance; more info below
180  @param[in] atol maximum allowed absolute tolerance; more info below
181  @param[in] msg exception message prefix; details of the error are appended after ": "
182 
183  The mask planes must match exactly. The image and variance planes are nearly equal if all pixels obey:
184  |val1 - val0| <= rtol*|val1| + atol
185  or, for float types, if nan/inf/-inf pixels match.
186 
187  @warning the comparison equation is not symmetric, so in rare cases the assertion
188  may give different results depending on which masked image comes first.
189 
190  @warning the axes of numpy arrays are transposed with respect to MaskedImage data.
191  Thus for example if maskedImage0 and maskedImage1 are both lsst.afw.image.MaskedImageD
192  with dimensions (2, 3) and skipMask is a numpy array, then skipMask must have shape (3, 2).
193 
194  @throw self.failureException (usually AssertionError) if any of the following are true
195  for un-skipped pixels:
196  - non-finite image or variance values differ in any way (e.g. one is "nan" and another is not)
197  - finite values differ by too much, as defined by atol and rtol
198  - mask pixels differ at all
199 
200  @throw TypeError if the dimensions of maskedImage0, maskedImage1 and skipMask do not match,
201  either image or variance plane is not of a numeric data type,
202  either mask plane is not of an integer type (unsigned or signed),
203  or skipMask is not of a numeric data type.
204  """
205  maskedImageArrList0 = maskedImage0.getArrays() if hasattr(
206  maskedImage0, "getArrays") else maskedImage0
207  maskedImageArrList1 = maskedImage1.getArrays() if hasattr(
208  maskedImage1, "getArrays") else maskedImage1
209 
210  for arrList, arg, name in (
211  (maskedImageArrList0, maskedImage0, "maskedImage0"),
212  (maskedImageArrList1, maskedImage1, "maskedImage1"),
213  ):
214  try:
215  assert len(arrList) == 3
216  # check that array shapes are all identical
217  # check that image and variance are float or int of some kind
218  # and mask is int of some kind
219  for i in (0, 2):
220  assert arrList[i].shape == arrList[1].shape
221  assert arrList[i].dtype.kind in ("b", "i", "u", "f", "c")
222  assert arrList[1].dtype.kind in ("b", "i", "u")
223  except Exception:
224  raise TypeError("%s=%r is not a supported type" % (name, arg))
225 
226  errStrList = []
227  for ind, (doPlane, planeName) in enumerate(((doImage, "image"),
228  (doMask, "mask"),
229  (doVariance, "variance"))):
230  if not doPlane:
231  continue
232 
233  if planeName == "mask":
234  errStr = imagesDiffer(maskedImageArrList0[ind], maskedImageArrList1[ind], skipMask=skipMask,
235  rtol=0, atol=0)
236  if errStr:
237  errStrList.append(errStr)
238  else:
239  errStr = imagesDiffer(maskedImageArrList0[ind], maskedImageArrList1[ind],
240  skipMask=skipMask, rtol=rtol, atol=atol)
241  if errStr:
242  errStrList.append("%s planes differ: %s" % (planeName, errStr))
243 
244  if errStrList:
245  testCase.fail("%s: %s" % (msg, "; ".join(errStrList)))
246 
247 
248 @lsst.utils.tests.inTestCase
249 def assertMaskedImagesEqual(*args, **kwds):
250  """!Assert that two masked images are exactly equal, including non-finite values.
251 
252  All arguments are forwarded to assertMaskedImagesAlmostEqual aside from atol and rtol,
253  which are set to zero.
254  """
255  return assertMaskedImagesAlmostEqual(*args, atol=0, rtol=0, **kwds)
256 
257 
258 def imagesDiffer(image0, image1, skipMask=None, rtol=1.0e-05, atol=1e-08):
259  """!Compare the pixels of two image or mask arrays; return True if close, False otherwise
260 
261  @param[in] image0 image 0, an lsst.afw.image.Image, lsst.afw.image.Mask,
262  or transposed numpy array (see warning)
263  @param[in] image1 image 1, an lsst.afw.image.Image, lsst.afw.image.Mask,
264  or transposed numpy array (see warning)
265  @param[in] skipMask mask of pixels to skip, or None to compare all pixels;
266  an lsst.afw.image.Mask, lsst.afw.image.Image, or transposed numpy array (see warning);
267  all non-zero pixels are skipped
268  @param[in] rtol maximum allowed relative tolerance; more info below
269  @param[in] atol maximum allowed absolute tolerance; more info below
270 
271  The images are nearly equal if all pixels obey:
272  |val1 - val0| <= rtol*|val1| + atol
273  or, for float types, if nan/inf/-inf pixels match.
274 
275  @warning the comparison equation is not symmetric, so in rare cases the assertion
276  may give different results depending on which image comes first.
277 
278  @warning the axes of numpy arrays are transposed with respect to Image and Mask data.
279  Thus for example if image0 and image1 are both lsst.afw.image.ImageD with dimensions (2, 3)
280  and skipMask is a numpy array, then skipMask must have shape (3, 2).
281 
282  @return a string which is non-empty if the images differ
283 
284  @throw TypeError if the dimensions of image0, image1 and skipMask do not match,
285  or any are not of a numeric data type.
286  """
287  errStrList = []
288  imageArr0 = image0.getArray() if hasattr(image0, "getArray") else image0
289  imageArr1 = image1.getArray() if hasattr(image1, "getArray") else image1
290  skipMaskArr = skipMask.getArray() if hasattr(skipMask, "getArray") else skipMask
291 
292  # check the inputs
293  arrArgNameList = [
294  (imageArr0, image0, "image0"),
295  (imageArr1, image1, "image1"),
296  ]
297  if skipMask is not None:
298  arrArgNameList.append((skipMaskArr, skipMask, "skipMask"))
299  for i, (arr, arg, name) in enumerate(arrArgNameList):
300  try:
301  assert arr.dtype.kind in ("b", "i", "u", "f", "c")
302  except Exception:
303  raise TypeError("%r=%r is not a supported type" % (name, arg))
304  if i != 0:
305  if arr.shape != imageArr0.shape:
306  raise TypeError("%s shape = %s != %s = image0 shape" %
307  (name, arr.shape, imageArr0.shape))
308 
309  # np.allclose mis-handled unsigned ints in numpy 1.8
310  # and subtraction doesn't give the desired answer in any case
311  # so cast unsigned arrays into int64 (there may be a simple
312  # way to safely use a smaller data type but I've not found it)
313  if imageArr0.dtype.kind == "u":
314  imageArr0 = imageArr0.astype(
315  np.promote_types(imageArr0.dtype, np.int8))
316  if imageArr1.dtype.kind == "u":
317  imageArr1 = imageArr1.astype(
318  np.promote_types(imageArr1.dtype, np.int8))
319 
320  if skipMaskArr is not None:
321  skipMaskArr = np.array(skipMaskArr, dtype=bool)
322  maskedArr0 = np.ma.array(imageArr0, copy=False, mask=skipMaskArr)
323  maskedArr1 = np.ma.array(imageArr1, copy=False, mask=skipMaskArr)
324  filledArr0 = maskedArr0.filled(0.0)
325  filledArr1 = maskedArr1.filled(0.0)
326  else:
327  skipMaskArr = None
328  filledArr0 = imageArr0
329  filledArr1 = imageArr1
330 
331  try:
332  np.array([np.nan], dtype=imageArr0.dtype)
333  np.array([np.nan], dtype=imageArr1.dtype)
334  except Exception:
335  # one or both images does not support non-finite values (nan, etc.)
336  # so just use value comparison
337  valSkipMaskArr = skipMaskArr
338  else:
339  # both images support non-finite values, of which numpy has exactly three: nan, +inf and -inf;
340  # compare those individually in order to give useful diagnostic output
341  nan0 = np.isnan(filledArr0)
342  nan1 = np.isnan(filledArr1)
343  if np.any(nan0 != nan1):
344  errStrList.append("NaNs differ")
345 
346  posinf0 = np.isposinf(filledArr0)
347  posinf1 = np.isposinf(filledArr1)
348  if np.any(posinf0 != posinf1):
349  errStrList.append("+infs differ")
350 
351  neginf0 = np.isneginf(filledArr0)
352  neginf1 = np.isneginf(filledArr1)
353  if np.any(neginf0 != neginf1):
354  errStrList.append("-infs differ")
355 
356  valSkipMaskArr = nan0 | nan1 | posinf0 | posinf1 | neginf0 | neginf1
357  if skipMaskArr is not None:
358  valSkipMaskArr |= skipMaskArr
359 
360  # compare values that should be comparable (are finite and not masked)
361  valMaskedArr1 = np.ma.array(imageArr0, copy=False, mask=valSkipMaskArr)
362  valMaskedArr2 = np.ma.array(imageArr1, copy=False, mask=valSkipMaskArr)
363  valFilledArr1 = valMaskedArr1.filled(0.0)
364  valFilledArr2 = valMaskedArr2.filled(0.0)
365 
366  if not np.allclose(valFilledArr1, valFilledArr2, rtol=rtol, atol=atol):
367  errArr = np.abs(valFilledArr1 - valFilledArr2)
368  maxErr = errArr.max()
369  maxPosInd = np.where(errArr == maxErr)
370  maxPosTuple = (maxPosInd[1][0], maxPosInd[0][0])
371  errStr = "maxDiff=%s at position %s; value=%s vs. %s" % \
372  (maxErr, maxPosTuple,
373  valFilledArr1[maxPosInd][0], valFilledArr2[maxPosInd][0])
374  errStrList.insert(0, errStr)
375 
376  return "; ".join(errStrList)
377 
378 
379 @lsst.utils.tests.inTestCase
380 def assertImagesNearlyEqual(*args, **kwargs):
381  warnings.warn("Deprecated. Use assertImagesAlmostEqual",
382  DeprecationWarning, 2)
383  assertImagesAlmostEqual(*args, **kwargs)
384 
385 
386 @lsst.utils.tests.inTestCase
387 def assertMaskedImagesNearlyEqual(*args, **kwargs):
388  warnings.warn("Deprecated. Use assertMaskedImagesAlmostEqual",
389  DeprecationWarning, 2)
390  assertMaskedImagesAlmostEqual(*args, **kwargs)
def assertImagesAlmostEqual(testCase, image0, image1, skipMask=None, rtol=1.0e-05, atol=1e-08, msg="Images differ")
Assert that two images are almost equal, including non-finite values.
Definition: testUtils.py:79
def assertMaskedImagesNearlyEqual(args, kwargs)
Definition: testUtils.py:387
def assertMaskedImagesAlmostEqual(testCase, maskedImage0, maskedImage1, doImage=True, doMask=True, doVariance=True, skipMask=None, rtol=1.0e-05, atol=1e-08, msg="Masked images differ")
Assert that two masked images are nearly equal, including non-finite values.
Definition: testUtils.py:164
def assertMaskedImagesEqual(args, kwds)
Assert that two masked images are exactly equal, including non-finite values.
Definition: testUtils.py:249
def makeGaussianNoiseMaskedImage(dimensions, sigma, variance=1.0)
Definition: testUtils.py:38
def imagesDiffer(image0, image1, skipMask=None, rtol=1.0e-05, atol=1e-08)
Compare the pixels of two image or mask arrays; return True if close, False otherwise.
Definition: testUtils.py:258
def assertImagesEqual(args, kwds)
Assert that two images are exactly equal, including non-finite values.
Definition: testUtils.py:121
def makeMaskedImageFromArrays(image, mask=None, variance=None)
Definition: basicUtils.py:48
def assertMasksEqual(testCase, mask0, mask1, skipMask=None, msg="Masks differ")
Assert that two masks are equal.
Definition: testUtils.py:131
def assertImagesNearlyEqual(args, kwargs)
Definition: testUtils.py:380
def makeRampImage(bbox, start=0, stop=None, imageClass=ImageF)
Make an image whose values are a linear ramp.
Definition: testUtils.py:55