lsst.afw  15.0-17-g0b88e3da8
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 from __future__ import absolute_import, division, print_function
23 
24 # the asserts are automatically imported so unit tests can find them without special imports;
25 # the other functions are hidden unless explicitly asked for
26 __all__ = ["assertImagesAlmostEqual", "assertImagesEqual", "assertMasksEqual",
27  "assertMaskedImagesAlmostEqual", "assertMaskedImagesEqual",
28  "assertImagesNearlyEqual", "assertMaskedImagesNearlyEqual"]
29 
30 import warnings
31 
32 import numpy as np
33 
34 import lsst.utils.tests
35 from .image import ImageF
36 from .basicUtils import makeMaskedImageFromArrays
37 
38 
39 def makeGaussianNoiseMaskedImage(dimensions, sigma, variance=1.0):
40  """Make a gaussian noise MaskedImageF
41 
42  Inputs:
43  - dimensions: dimensions of output array (cols, rows)
44  - sigma; sigma of image plane's noise distribution
45  - variance: constant value for variance plane
46  """
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.int32)
51  variance = np.zeros(npSize, dtype=np.float32) + variance
52 
53  return makeMaskedImageFromArrays(image, mask, variance)
54 
55 
56 def makeRampImage(bbox, start=0, stop=None, imageClass=ImageF):
57  """!Make an image whose values are a linear ramp
58 
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)
63  """
64  im = imageClass(bbox)
65  imDim = im.getDimensions()
66  numPix = imDim[0]*imDim[1]
67  imArr = im.getArray()
68  if stop is None:
69  # increase by integer values
70  stop = start + numPix - 1
71  rampArr = np.linspace(start=start, stop=stop,
72  endpoint=True, num=numPix, dtype=imArr.dtype)
73  # numpy arrays are transposed w.r.t. afwImage
74  imArr[:] = np.reshape(rampArr, (imDim[1], imDim[0]))
75  return im
76 
77 
78 @lsst.utils.tests.inTestCase
79 def assertImagesAlmostEqual(testCase, image0, image1, skipMask=None,
80  rtol=1.0e-05, atol=1e-08, msg="Images differ"):
81  """!Assert that two images are almost equal, including non-finite values
82 
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 ": "
95 
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.
99 
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.
102 
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).
106 
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
111 
112  @throw TypeError if the dimensions of image0, image1 and skipMask do not match,
113  or any are not of a numeric data type.
114  """
115  errStr = imagesDiffer(
116  image0, image1, skipMask=skipMask, rtol=rtol, atol=atol)
117  if errStr:
118  testCase.fail("%s: %s" % (msg, errStr))
119 
120 
121 @lsst.utils.tests.inTestCase
122 def assertImagesEqual(*args, **kwds):
123  """!Assert that two images are exactly equal, including non-finite values.
124 
125  All arguments are forwarded to assertAnglesAlmostEqual aside from atol and rtol,
126  which are set to zero.
127  """
128  return assertImagesAlmostEqual(*args, atol=0, rtol=0, **kwds)
129 
130 
131 @lsst.utils.tests.inTestCase
132 def assertMasksEqual(testCase, mask0, mask1, skipMask=None, msg="Masks differ"):
133  """!Assert that two masks are equal
134 
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 ": "
145 
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.Mask with dimensions (2, 3)
148  and skipMask is a numpy array, then skipMask must have shape (3, 2).
149 
150  @throw self.failureException (usually AssertionError) if any any un-skipped pixels differ
151 
152  @throw TypeError if the dimensions of mask0, mask1 and skipMask do not match,
153  or any are not of a numeric data type.
154  """
155  errStr = imagesDiffer(mask0, mask1, skipMask=skipMask, rtol=0, atol=0)
156  if errStr:
157  testCase.fail("%s: %s" % (msg, errStr))
158 
159 
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",
165 ):
166  """!Assert that two masked images are nearly equal, including non-finite values
167 
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 ": "
183 
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.
187 
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.
190 
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).
194 
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
200 
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.
205  """
206  maskedImageArrList0 = maskedImage0.getArrays() if hasattr(
207  maskedImage0, "getArrays") else maskedImage0
208  maskedImageArrList1 = maskedImage1.getArrays() if hasattr(
209  maskedImage1, "getArrays") else maskedImage1
210 
211  for arrList, arg, name in (
212  (maskedImageArrList0, maskedImage0, "maskedImage0"),
213  (maskedImageArrList1, maskedImage1, "maskedImage1"),
214  ):
215  try:
216  assert len(arrList) == 3
217  # check that array shapes are all identical
218  # check that image and variance are float or int of some kind
219  # and mask is int of some kind
220  for i in (0, 2):
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")
224  except Exception:
225  raise TypeError("%s=%r is not a supported type" % (name, arg))
226 
227  errStrList = []
228  for ind, (doPlane, planeName) in enumerate(((doImage, "image"),
229  (doMask, "mask"),
230  (doVariance, "variance"))):
231  if not doPlane:
232  continue
233 
234  if planeName == "mask":
235  errStr = imagesDiffer(maskedImageArrList0[ind], maskedImageArrList1[ind], skipMask=skipMask,
236  rtol=0, atol=0)
237  if errStr:
238  errStrList.append(errStr)
239  else:
240  errStr = imagesDiffer(maskedImageArrList0[ind], maskedImageArrList1[ind],
241  skipMask=skipMask, rtol=rtol, atol=atol)
242  if errStr:
243  errStrList.append("%s planes differ: %s" % (planeName, errStr))
244 
245  if errStrList:
246  testCase.fail("%s: %s" % (msg, "; ".join(errStrList)))
247 
248 
249 @lsst.utils.tests.inTestCase
250 def assertMaskedImagesEqual(*args, **kwds):
251  """!Assert that two masked images are exactly equal, including non-finite values.
252 
253  All arguments are forwarded to assertMaskedImagesAlmostEqual aside from atol and rtol,
254  which are set to zero.
255  """
256  return assertMaskedImagesAlmostEqual(*args, atol=0, rtol=0, **kwds)
257 
258 
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
261 
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
271 
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.
275 
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.
278 
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).
282 
283  @return a string which is non-empty if the images differ
284 
285  @throw TypeError if the dimensions of image0, image1 and skipMask do not match,
286  or any are not of a numeric data type.
287  """
288  errStrList = []
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
292 
293  # check the inputs
294  arrArgNameList = [
295  (imageArr0, image0, "image0"),
296  (imageArr1, image1, "image1"),
297  ]
298  if skipMask is not None:
299  arrArgNameList.append((skipMaskArr, skipMask, "skipMask"))
300  for i, (arr, arg, name) in enumerate(arrArgNameList):
301  try:
302  assert arr.dtype.kind in ("b", "i", "u", "f", "c")
303  except Exception:
304  raise TypeError("%r=%r is not a supported type" % (name, arg))
305  if i != 0:
306  if arr.shape != imageArr0.shape:
307  raise TypeError("%s shape = %s != %s = image0 shape" %
308  (name, arr.shape, imageArr0.shape))
309 
310  # np.allclose mis-handled unsigned ints in numpy 1.8
311  # and subtraction doesn't give the desired answer in any case
312  # so cast unsigned arrays into int64 (there may be a simple
313  # way to safely use a smaller data type but I've not found it)
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))
320 
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)
327  else:
328  skipMaskArr = None
329  filledArr0 = imageArr0
330  filledArr1 = imageArr1
331 
332  try:
333  np.array([np.nan], dtype=imageArr0.dtype)
334  np.array([np.nan], dtype=imageArr1.dtype)
335  except Exception:
336  # one or both images does not support non-finite values (nan, etc.)
337  # so just use value comparison
338  valSkipMaskArr = skipMaskArr
339  else:
340  # both images support non-finite values, of which numpy has exactly three: nan, +inf and -inf;
341  # compare those individually in order to give useful diagnostic output
342  nan0 = np.isnan(filledArr0)
343  nan1 = np.isnan(filledArr1)
344  if np.any(nan0 != nan1):
345  errStrList.append("NaNs differ")
346 
347  posinf0 = np.isposinf(filledArr0)
348  posinf1 = np.isposinf(filledArr1)
349  if np.any(posinf0 != posinf1):
350  errStrList.append("+infs differ")
351 
352  neginf0 = np.isneginf(filledArr0)
353  neginf1 = np.isneginf(filledArr1)
354  if np.any(neginf0 != neginf1):
355  errStrList.append("-infs differ")
356 
357  valSkipMaskArr = nan0 | nan1 | posinf0 | posinf1 | neginf0 | neginf1
358  if skipMaskArr is not None:
359  valSkipMaskArr |= skipMaskArr
360 
361  # compare values that should be comparable (are finite and not masked)
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)
366 
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)
376 
377  return "; ".join(errStrList)
378 
379 
380 @lsst.utils.tests.inTestCase
381 def assertImagesNearlyEqual(*args, **kwargs):
382  warnings.warn("Deprecated. Use assertImagesAlmostEqual",
383  DeprecationWarning, 2)
384  assertImagesAlmostEqual(*args, **kwargs)
385 
386 
387 @lsst.utils.tests.inTestCase
388 def assertMaskedImagesNearlyEqual(*args, **kwargs):
389  warnings.warn("Deprecated. Use assertMaskedImagesAlmostEqual",
390  DeprecationWarning, 2)
391  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:80
def assertMaskedImagesNearlyEqual(args, kwargs)
Definition: testUtils.py:388
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:165
def assertMaskedImagesEqual(args, kwds)
Assert that two masked images are exactly equal, including non-finite values.
Definition: testUtils.py:250
def makeGaussianNoiseMaskedImage(dimensions, sigma, variance=1.0)
Definition: testUtils.py:39
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:259
def assertImagesEqual(args, kwds)
Assert that two images are exactly equal, including non-finite values.
Definition: testUtils.py:122
def makeMaskedImageFromArrays(image, mask=None, variance=None)
Definition: basicUtils.py:49
def assertMasksEqual(testCase, mask0, mask1, skipMask=None, msg="Masks differ")
Assert that two masks are equal.
Definition: testUtils.py:132
def assertImagesNearlyEqual(args, kwargs)
Definition: testUtils.py:381
def makeRampImage(bbox, start=0, stop=None, imageClass=ImageF)
Make an image whose values are a linear ramp.
Definition: testUtils.py:56