lsst.afw  13.0-57-g42cae95
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
testUtils.py
Go to the documentation of this file.
1 #
2 # LSST Data Management System
3 # Copyright 2016 LSST Corporation.
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 __all__ = ["BoxGrid"]
25 
26 from builtins import range
27 from builtins import object
28 
29 import itertools
30 import math
31 import os
32 
33 import astshim
34 import numpy as np
35 from numpy.testing import assert_allclose, assert_array_equal
36 from astshim.test import makeForwardPolyMap, makeTwoWayPolyMap
37 
38 from .box import Box2I, Box2D
39 import lsst.afw.geom as afwGeom
40 from lsst.pex.exceptions import InvalidParameterError
41 import lsst.utils
42 import lsst.utils.tests
43 
44 
45 class BoxGrid(object):
46  """!Divide a box into nx by ny sub-boxes that tile the region
47  """
48 
49  def __init__(self, box, numColRow):
50  """!Construct a BoxGrid
51 
52  The sub-boxes will be of the same type as `box` and will exactly tile `box`;
53  they will also all be the same size, to the extent possible (some variation
54  is inevitable for integer boxes that cannot be evenly divided.
55 
56  @param[in] box box (an lsst.afw.geom.Box2I or Box2D);
57  the boxes in the grid will be of the same type
58  @param[in] numColRow number of columns and rows (a pair of ints)
59  """
60  if len(numColRow) != 2:
61  raise RuntimeError(
62  "numColRow=%r; must be a sequence of two integers" % (numColRow,))
63  self._numColRow = tuple(int(val) for val in numColRow)
64 
65  if isinstance(box, Box2I):
66  stopDelta = 1
67  elif isinstance(box, Box2D):
68  stopDelta = 0
69  else:
70  raise RuntimeError("Unknown class %s of box %s" % (type(box), box))
71  self.boxClass = type(box)
72  self.stopDelta = stopDelta
73 
74  minPoint = box.getMin()
75  self.pointClass = type(minPoint)
76  dtype = np.array(minPoint).dtype
77 
78  self._divList = [np.linspace(start=box.getMin()[i],
79  stop=box.getMax()[i] + self.stopDelta,
80  num=self._numColRow[i] + 1,
81  endpoint=True,
82  dtype=dtype) for i in range(2)]
83 
84  @property
85  def numColRow(self):
86  return self._numColRow
87 
88  def __getitem__(self, indXY):
89  """!Return the box at the specified x,y index (a pair of ints)
90  """
91  beg = self.pointClass(*[self._divList[i][indXY[i]] for i in range(2)])
92  end = self.pointClass(
93  *[self._divList[i][indXY[i] + 1] - self.stopDelta for i in range(2)])
94  return self.boxClass(beg, end)
95 
96  def __len__(self):
97  return self.shape[0]*self.shape[1]
98 
99  def __iter__(self):
100  """!Return an iterator over all boxes, where column varies most quickly
101  """
102  for row in range(self.numColRow[1]):
103  for col in range(self.numColRow[0]):
104  yield self[col, row]
105 
106 
107 class FrameSetInfo(object):
108  """Information about a FrameSet
109 
110  Attributes
111  ----------
112  baseInd : `int`
113  Index of base frame
114  currInd : `int`
115  Index of current frame
116  isBaseSkyFrame : `bool`
117  Is the base frame an `astshim.SkyFrame`?
118  isCurrSkyFrame : `bool`
119  Is the current frame an `astshim.SkyFrame`?
120  """
121  def __init__(self, frameSet):
122  """Construct a FrameSetInfo
123 
124  Parameters
125  ----------
126  frameSet : `astshim.FrameSet`
127  The FrameSet about which you want information
128  """
129  self.baseInd = frameSet.base
130  self.currInd = frameSet.current
131  self.isBaseSkyFrame = frameSet.getFrame(self.baseInd).className == "SkyFrame"
132  self.isCurrSkyFrame = frameSet.getFrame(self.currInd).className == "SkyFrame"
133 
134 
135 class PermutedFrameSet(object):
136  """A FrameSet with base or current frame possibly permuted, with associated
137  information
138 
139  Only two-axis frames will be permuted.
140 
141  Attributes
142  ----------
143  frameSet : `astshim.FrameSet`
144  The FrameSet that may be permuted. A local copy is made.
145  isBaseSkyFrame : `bool`
146  Is the base frame an `astshim.SkyFrame`?
147  isCurrSkyFrame : `bool`
148  Is the current frame an `astshim.SkyFrame`?
149  isBasePermuted : `bool`
150  Are the base frame axes permuted?
151  isCurrPermuted : `bool`
152  Are the current frame axes permuted?
153  """
154  def __init__(self, frameSet, permuteBase, permuteCurr):
155  """Construct a PermutedFrameSet
156 
157  Make a copy of a FrameSet and permute the base and/or current frames if
158  requested
159 
160  Parameters
161  ----------
162  frameSet : `astshim.FrameSet`
163  The FrameSet you wish to permute. A deep copy is made.
164  permuteBase : `bool`
165  Permute the base frame's axes?
166  permuteCurr : `bool`
167  Permute the current frame's axes?
168 
169  Raises
170  ------
171  `RuntimeError`
172  If you try to permute a frame that does not have 2 axes
173  """
174  self.frameSet = frameSet.copy()
175  fsInfo = FrameSetInfo(self.frameSet)
176  self.isBaseSkyFrame = fsInfo.isBaseSkyFrame
177  self.isCurrSkyFrame = fsInfo.isCurrSkyFrame
178  if permuteBase:
179  baseNAxes = self.frameSet.getFrame(fsInfo.baseInd).nAxes
180  if baseNAxes != 2:
181  raise RuntimeError("Base frame has {} axes; 2 required to permute".format(baseNAxes))
182  self.frameSet.current = fsInfo.baseInd
183  self.frameSet.permAxes([2, 1])
184  self.frameSet.current = fsInfo.currInd
185  if permuteCurr:
186  currNAxes = self.frameSet.getFrame(fsInfo.currInd).nAxes
187  if currNAxes != 2:
188  raise RuntimeError("Current frame has {} axes; 2 required to permute".format(currNAxes))
189  assert self.frameSet.getFrame(fsInfo.currInd).nAxes == 2
190  self.frameSet.permAxes([2, 1])
191  self.isBasePermuted = permuteBase
192  self.isCurrPermuted = permuteCurr
193 
194 
195 class TransformTestBaseClass(lsst.utils.tests.TestCase):
196  """Base class for unit tests of Transform<X>To<Y> and subclasses
197 
198  Subclasses must call `TransformTestBaseClass.setUp(self)`
199  if they provide their own version.
200 
201  If a package other than afw uses this class then it must
202  override the `getTestDir` method to avoid writing into
203  afw's test directory.
204  """
205 
206  def getTestDir(self):
207  """Return a directory where temporary test files can be written
208 
209  The default implementation returns the test directory of the `afw`
210  package.
211 
212  If this class is used by a test in a package other than `afw`
213  then the subclass must override this method.
214  """
215  return os.path.join(lsst.utils.getPackageDir("afw"), "tests")
216 
217  def setUp(self):
218  """Set up a test
219 
220  Subclasses should call this method if they override setUp.
221  """
222  # tell unittest to use the msg argument of asserts as a supplement
223  # to the error message, rather than as the whole error message
224  self.longMessage = True
225 
226  # list of endpoint class name prefixes; the full name is prefix + "Endpoint"
227  self.endpointPrefixes = ("Generic", "Point2", "SpherePoint")
228 
229  # GoodNAxes is dict of endpoint class name prefix:
230  # tuple containing 0 or more valid numbers of axes
231  self.goodNAxes = {
232  "Generic": (1, 2, 3, 4), # all numbers of axes are valid for GenericEndpoint
233  "Point2": (2,),
234  "SpherePoint": (2,),
235  }
236 
237  # BadAxes is dict of endpoint class name prefix:
238  # tuple containing 0 or more invalid numbers of axes
239  self.badNAxes = {
240  "Generic": (), # all numbers of axes are valid for GenericEndpoint
241  "Point2": (1, 3, 4),
242  "SpherePoint": (1, 3, 4),
243  }
244 
245  # Dict of frame index: identity name for frames created by makeFrameSet
246  self.frameIdentDict = {
247  1: "baseFrame",
248  2: "frame2",
249  3: "frame3",
250  4: "currFrame",
251  }
252 
253  @staticmethod
254  def makeRawArrayData(nPoints, nAxes, delta=0.123):
255  """Make an array of generic point data
256 
257  The data will be suitable for spherical points
258 
259  Parameters
260  ----------
261  nPoints : `int`
262  Number of points in the array
263  nAxes : `int`
264  Number of axes in the point
265 
266  Returns
267  -------
268  np.array of floats with shape (nAxes, nPoints)
269  The values are as follows; if nAxes != 2:
270  The first point has values `[0, delta, 2*delta, ..., (nAxes-1)*delta]`
271  The Nth point has those values + N
272  if nAxes == 2 then the data is scaled so that the max value of axis 1
273  is a bit less than pi/2
274  """
275  delta = 0.123
276  # oneAxis = [0, 1, 2, ...nPoints-1]
277  oneAxis = np.arange(nPoints, dtype=float) # [0, 1, 2...]
278  # rawData = [oneAxis, oneAxis + delta, oneAxis + 2 delta, ...]
279  rawData = np.array([j * delta + oneAxis for j in range(nAxes)], dtype=float)
280  if nAxes == 2:
281  # scale rawData so that max value of 2nd axis is a bit less than pi/2,
282  # thus making the data safe for SpherePoint
283  maxLatitude = np.max(rawData[1])
284  rawData *= math.pi * 0.4999 / maxLatitude
285  return rawData
286 
287  @staticmethod
288  def makeRawPointData(nAxes, delta=0.123):
289  """Make one generic point
290 
291  Parameters
292  ----------
293  nAxes : `int`
294  Number of axes in the point
295  delta : `float`
296  Increment between axis values
297 
298  Returns
299  -------
300  A list of `nAxes` floats with values `[0, delta, ..., (nAxes-1)*delta]
301  """
302  return [i*delta for i in range(nAxes)]
303 
304  @staticmethod
305  def makeEndpoint(name, nAxes=None):
306  """Make an endpoint
307 
308  Parameters
309  ----------
310  name : `str`
311  Endpoint class name prefix; the full class name is name + "Endpoint"
312  nAxes : `int` or `None`, optional
313  number of axes; an int is required if `name` == "Generic";
314  otherwise ignored
315 
316  Returns
317  -------
318  subclass of `lsst.afw.geom.BaseEndpoint`
319  The constructed endpoint
320 
321  Raises
322  ------
323  `TypeError`
324  If `name` == "Generic" and `nAxes` is None or <= 0
325  """
326  EndpointClassName = name + "Endpoint"
327  EndpointClass = getattr(afwGeom, EndpointClassName)
328  if name == "Generic":
329  if nAxes is None:
330  raise TypeError("nAxes must be an integer for GenericEndpoint")
331  return EndpointClass(nAxes)
332  return EndpointClass()
333 
334  @classmethod
335  def makeGoodFrame(cls, name, nAxes=None):
336  """Return the appropriate frame for the given name and nAxes
337 
338  Parameters
339  ----------
340  name : `str`
341  Endpoint class name prefix; the full class name is name + "Endpoint"
342  nAxes : `int` or `None`, optional
343  number of axes; an int is required if `name` == "Generic";
344  otherwise ignored
345 
346  Returns
347  -------
348  `astshim.Frame`
349  The constructed frame
350 
351  Raises
352  ------
353  `TypeError`
354  If `name` == "Generic" and `nAxes` is `None` or <= 0
355  """
356  return cls.makeEndpoint(name, nAxes).makeFrame()
357 
358  @staticmethod
359  def makeBadFrames(name):
360  """Return a list of 0 or more frames that are not a valid match for the
361  named endpoint
362 
363  Parameters
364  ----------
365  name : `str`
366  Endpoint class name prefix; the full class name is name + "Endpoint"
367 
368  Returns
369  -------
370  Collection of `astshim.Frame`
371  A collection of 0 or more frames
372  """
373  return {
374  "Generic": [],
375  "Point2": [
376  astshim.SkyFrame(),
377  astshim.Frame(1),
378  astshim.Frame(3),
379  ],
380  "SpherePoint": [
381  astshim.Frame(1),
382  astshim.Frame(2),
383  astshim.Frame(3),
384  ],
385  }[name]
386 
387  def makeFrameSet(self, baseFrame, currFrame):
388  """Make a FrameSet
389 
390  The FrameSet will contain 4 frames and three transforms connecting them.
391  The idenity of each frame is provided by self.frameIdentDict
392 
393  Frame Index Mapping from this frame to the next
394  `baseFrame` 1 `astshim.UnitMap(nIn)`
395  Frame(nIn) 2 `polyMap`
396  Frame(nOut) 3 `astshim.UnitMap(nOut)`
397  `currFrame` 4
398 
399  where:
400  - `nIn` = `baseFrame.nAxes`
401  - `nOut` = `currFrame.nAxes`
402  - `polyMap` = `makeTwoWayPolyMap(nIn, nOut)`
403 
404  Return
405  ------
406  `astshim.FrameSet`
407  The FrameSet as described above
408 
409  Parameters
410  ----------
411  baseFrame : `astshim.Frame`
412  base frame
413  currFrame : `astshim.Frame`
414  current frame
415  """
416  nIn = baseFrame.nAxes
417  nOut = currFrame.nAxes
418  polyMap = makeTwoWayPolyMap(nIn, nOut)
419 
420  # The only way to set the Ident of a frame in a FrameSet is to set it in advance,
421  # and I don't want to modify the inputs, so replace the input frames with copies
422  baseFrame = baseFrame.copy()
423  baseFrame.ident = self.frameIdentDict[1]
424  currFrame = currFrame.copy()
425  currFrame.ident = self.frameIdentDict[4]
426 
427  frameSet = astshim.FrameSet(baseFrame)
428  frame2 = astshim.Frame(nIn)
429  frame2.ident = self.frameIdentDict[2]
430  frameSet.addFrame(astshim.FrameSet.CURRENT, astshim.UnitMap(nIn), frame2)
431  frame3 = astshim.Frame(nOut)
432  frame3.ident = self.frameIdentDict[3]
433  frameSet.addFrame(astshim.FrameSet.CURRENT, polyMap, frame3)
434  frameSet.addFrame(astshim.FrameSet.CURRENT, astshim.UnitMap(nOut), currFrame)
435  return frameSet
436 
437  @staticmethod
438  def permuteFrameSetIter(frameSet):
439  """Iterator over 0 or more frameSets with SkyFrames axes permuted
440 
441  Only base and current SkyFrames are permuted. If neither the base nor
442  the current frame is a SkyFrame then no frames are returned.
443 
444  Returns
445  -------
446  iterator over `PermutedFrameSet`
447  """
448 
449  fsInfo = FrameSetInfo(frameSet)
450  if not (fsInfo.isBaseSkyFrame or fsInfo.isCurrSkyFrame):
451  return
452 
453  permuteBaseList = [False, True] if fsInfo.isBaseSkyFrame else [False]
454  permuteCurrList = [False, True] if fsInfo.isCurrSkyFrame else [False]
455  for permuteBase in permuteBaseList:
456  for permuteCurr in permuteCurrList:
457  yield PermutedFrameSet(frameSet, permuteBase, permuteCurr)
458 
459  @staticmethod
460  def makeJacobian(nIn, nOut, inPoint):
461  """Make a Jacobian matrix for the equation described by
462  `makeTwoWayPolyMap`.
463 
464  Parameters
465  ----------
466  nIn, nOut : `int`
467  the dimensions of the input and output data; see makeTwoWayPolyMap
468  inPoint : `numpy.ndarray`
469  an array of size `nIn` representing the point at which the Jacobian
470  is measured
471 
472  Returns
473  -------
474  J : `numpy.ndarray`
475  an `nOut` x `nIn` array of first derivatives
476  """
477  basePolyMapCoeff = 0.001 # see makeTwoWayPolyMap
478  baseCoeff = 2.0 * basePolyMapCoeff
479  coeffs = np.empty((nOut, nIn))
480  for iOut in range(nOut):
481  coeffOffset = baseCoeff * iOut
482  for iIn in range(nIn):
483  coeffs[iOut, iIn] = baseCoeff * (iIn + 1) + coeffOffset
484  coeffs[iOut, iIn] *= inPoint[iIn]
485  assert coeffs.ndim == 2
486  # Avoid spurious errors when comparing to a simplified array
487  assert coeffs.shape == (nOut, nIn)
488  return coeffs
489 
490  def checkTransformation(self, transform, mapping, msg=""):
491  """Check tranForward and tranInverse for a transform
492 
493  Parameters
494  ----------
495  transform : `lsst.afw.geom.Transform`
496  The transform to check
497  mapping : `astshim.Mapping`
498  The mapping the transform should use. This mapping
499  must contain valid forward or inverse transformations,
500  but they need not match if both present. Hence the
501  mappings returned by make*PolyMap are acceptable.
502  msg : `str`
503  Error message suffix describing test parameters
504  """
505  fromEndpoint = transform.fromEndpoint
506  toEndpoint = transform.toEndpoint
507  frameSet = transform.getFrameSet()
508 
509  nIn = mapping.nIn
510  nOut = mapping.nOut
511  self.assertEqual(nIn, fromEndpoint.nAxes, msg=msg)
512  self.assertEqual(nOut, toEndpoint.nAxes, msg=msg)
513 
514  # forward transformation of one point
515  rawInPoint = self.makeRawPointData(nIn)
516  inPoint = fromEndpoint.pointFromData(rawInPoint)
517 
518  # forward transformation of an array of points
519  nPoints = 7 # arbitrary
520  rawInArray = self.makeRawArrayData(nPoints, nIn)
521  inArray = fromEndpoint.arrayFromData(rawInArray)
522 
523  if mapping.hasForward:
524  self.assertTrue(transform.hasForward)
525  outPoint = transform.tranForward(inPoint)
526  rawOutPoint = toEndpoint.dataFromPoint(outPoint)
527  assert_allclose(rawOutPoint, mapping.tranForward(rawInPoint), err_msg=msg)
528  assert_allclose(rawOutPoint, frameSet.tranForward(rawInPoint), err_msg=msg)
529 
530  outArray = transform.tranForward(inArray)
531  rawOutArray = toEndpoint.dataFromArray(outArray)
532  self.assertFloatsAlmostEqual(rawOutArray, mapping.tranForward(rawInArray), msg=msg)
533  self.assertFloatsAlmostEqual(rawOutArray, frameSet.tranForward(rawInArray), msg=msg)
534  else:
535  # Need outPoint, but don't need it to be consistent with inPoint
536  rawOutPoint = self.makeRawPointData(nOut)
537  outPoint = toEndpoint.pointFromData(rawOutPoint)
538  rawOutArray = self.makeRawArrayData(nPoints, nOut)
539  outArray = toEndpoint.arrayFromData(rawOutArray)
540 
541  self.assertFalse(transform.hasForward)
542 
543  if mapping.hasInverse:
544  self.assertTrue(transform.hasInverse)
545  # inverse transformation of one point;
546  # remember that the inverse need not give the original values
547  # (see the description of the `mapping` parameter)
548  inversePoint = transform.tranInverse(outPoint)
549  rawInversePoint = fromEndpoint.dataFromPoint(inversePoint)
550  assert_allclose(rawInversePoint, mapping.tranInverse(rawOutPoint), err_msg=msg)
551  assert_allclose(rawInversePoint, frameSet.tranInverse(rawOutPoint), err_msg=msg)
552 
553  # inverse transformation of an array of points;
554  # remember that the inverse will not give the original values
555  # (see the description of the `mapping` parameter)
556  inverseArray = transform.tranInverse(outArray)
557  rawInverseArray = fromEndpoint.dataFromArray(inverseArray)
558  self.assertFloatsAlmostEqual(rawInverseArray, mapping.tranInverse(rawOutArray), msg=msg)
559  self.assertFloatsAlmostEqual(rawInverseArray, frameSet.tranInverse(rawOutArray), msg=msg)
560  else:
561  self.assertFalse(transform.hasInverse)
562 
563  def checkInverseTransformation(self, forward, inverse, msg=""):
564  """Check that two Transforms are each others' inverses.
565 
566  Parameters
567  ----------
568  forward : `lsst.afw.geom.Transform`
569  the reference Transform to test
570  inverse : `lsst.afw.geom.Transform`
571  the transform that should be the inverse of `forward`
572  msg : `str`
573  error message suffix describing test parameters
574  """
575  fromEndpoint = forward.fromEndpoint
576  toEndpoint = forward.toEndpoint
577  frameSet = forward.getFrameSet()
578  invFrameSet = inverse.getFrameSet()
579 
580  # properties
581  self.assertEqual(forward.fromEndpoint,
582  inverse.toEndpoint, msg=msg)
583  self.assertEqual(forward.toEndpoint,
584  inverse.fromEndpoint, msg=msg)
585  self.assertEqual(forward.hasForward, inverse.hasInverse, msg=msg)
586  self.assertEqual(forward.hasInverse, inverse.hasForward, msg=msg)
587 
588  # transformations of one point
589  # we don't care about whether the transformation itself is correct
590  # (see checkTransformation), so inPoint/outPoint need not be related
591  rawInPoint = self.makeRawPointData(fromEndpoint.nAxes)
592  inPoint = fromEndpoint.pointFromData(rawInPoint)
593  rawOutPoint = self.makeRawPointData(toEndpoint.nAxes)
594  outPoint = toEndpoint.pointFromData(rawOutPoint)
595 
596  # transformations of arrays of points
597  nPoints = 7 # arbitrary
598  rawInArray = self.makeRawArrayData(nPoints, fromEndpoint.nAxes)
599  inArray = fromEndpoint.arrayFromData(rawInArray)
600  rawOutArray = self.makeRawArrayData(nPoints, toEndpoint.nAxes)
601  outArray = toEndpoint.arrayFromData(rawOutArray)
602 
603  if forward.hasForward:
604  self.assertEqual(forward.tranForward(inPoint),
605  inverse.tranInverse(inPoint), msg=msg)
606  self.assertEqual(frameSet.tranForward(rawInPoint),
607  invFrameSet.tranInverse(rawInPoint), msg=msg)
608  # Assertions must work with both lists and numpy arrays
609  assert_array_equal(forward.tranForward(inArray),
610  inverse.tranInverse(inArray),
611  err_msg=msg)
612  assert_array_equal(frameSet.tranForward(rawInArray),
613  invFrameSet.tranInverse(rawInArray),
614  err_msg=msg)
615 
616  if forward.hasInverse:
617  self.assertEqual(forward.tranInverse(outPoint),
618  inverse.tranForward(outPoint), msg=msg)
619  self.assertEqual(frameSet.tranInverse(rawOutPoint),
620  invFrameSet.tranForward(rawOutPoint), msg=msg)
621  assert_array_equal(forward.tranInverse(outArray),
622  inverse.tranForward(outArray),
623  err_msg=msg)
624  assert_array_equal(frameSet.tranInverse(rawOutArray),
625  invFrameSet.tranForward(rawOutArray),
626  err_msg=msg)
627 
628  def checkTransformFromMapping(self, fromName, toName):
629  """Check Transform_<fromName>_<toName> using the Mapping constructor
630 
631  Parameters
632  ----------
633  fromName, toName : `str`
634  Endpoint name prefix for "from" and "to" endpoints, respectively,
635  e.g. "Point2" for `lsst.afw.geom.Point2Endpoint`
636  fromAxes, toAxes : `int`
637  number of axes in fromFrame and toFrame, respectively
638  """
639  transformClassName = "Transform{}To{}".format(fromName, toName)
640  TransformClass = getattr(afwGeom, transformClassName)
641  baseMsg = "TransformClass={}".format(TransformClass.__name__)
642 
643  # check valid numbers of inputs and outputs
644  for nIn, nOut in itertools.product(self.goodNAxes[fromName],
645  self.goodNAxes[toName]):
646  msg = "{}, nIn={}, nOut={}".format(baseMsg, nIn, nOut)
647  polyMap = makeTwoWayPolyMap(nIn, nOut)
648  transform = TransformClass(polyMap)
649 
650  # desired output from `str(transform)`
651  desStr = "{}[{}->{}]".format(transformClassName, nIn, nOut)
652  self.assertEqual("{}".format(transform), desStr)
653  self.assertEqual(repr(transform), "lsst.afw.geom." + desStr)
654 
655  self.checkTransformation(transform, polyMap, msg=msg)
656 
657  # Forward transform but no inverse
658  polyMap = makeForwardPolyMap(nIn, nOut)
659  transform = TransformClass(polyMap)
660  self.checkTransformation(transform, polyMap, msg=msg)
661 
662  # Inverse transform but no forward
663  polyMap = makeForwardPolyMap(nOut, nIn).getInverse()
664  transform = TransformClass(polyMap)
665  self.checkTransformation(transform, polyMap, msg=msg)
666 
667  # check invalid # of output against valid # of inputs
668  for nIn, badNOut in itertools.product(self.goodNAxes[fromName],
669  self.badNAxes[toName]):
670  badPolyMap = makeTwoWayPolyMap(nIn, badNOut)
671  msg = "{}, nIn={}, badNOut={}".format(baseMsg, nIn, badNOut)
672  with self.assertRaises(InvalidParameterError, msg=msg):
673  TransformClass(badPolyMap)
674 
675  # check invalid # of inputs against valid and invalid # of outputs
676  for badNIn, nOut in itertools.product(self.badNAxes[fromName],
677  self.goodNAxes[toName] + self.badNAxes[toName]):
678  badPolyMap = makeTwoWayPolyMap(badNIn, nOut)
679  msg = "{}, badNIn={}, nOut={}".format(baseMsg, nIn, nOut)
680  with self.assertRaises(InvalidParameterError, msg=msg):
681  TransformClass(badPolyMap)
682 
683  def checkTransformFromFrameSet(self, fromName, toName):
684  """Check Transform_<fromName>_<toName> using the FrameSet constructor
685 
686  Parameters
687  ----------
688  fromName, toName : `str`
689  Endpoint name prefix for "from" and "to" endpoints, respectively,
690  e.g. "Point2" for `lsst.afw.geom.Point2Endpoint`
691  """
692  transformClassName = "Transform{}To{}".format(fromName, toName)
693  TransformClass = getattr(afwGeom, transformClassName)
694  baseMsg = "TransformClass={}".format(TransformClass.__name__)
695  for nIn, nOut in itertools.product(self.goodNAxes[fromName],
696  self.goodNAxes[toName]):
697  msg = "{}, nIn={}, nOut={}".format(baseMsg, nIn, nOut)
698 
699  baseFrame = self.makeGoodFrame(fromName, nIn)
700  currFrame = self.makeGoodFrame(toName, nOut)
701  frameSet = self.makeFrameSet(baseFrame, currFrame)
702  self.assertEqual(frameSet.nFrame, 4)
703 
704  # construct 0 or more frame sets that are invalid for this transform class
705  for badBaseFrame in self.makeBadFrames(fromName):
706  badFrameSet = self.makeFrameSet(badBaseFrame, currFrame)
707  with self.assertRaises(InvalidParameterError):
708  TransformClass(badFrameSet)
709  for badCurrFrame in self.makeBadFrames(toName):
710  reallyBadFrameSet = self.makeFrameSet(badBaseFrame, badCurrFrame)
711  with self.assertRaises(InvalidParameterError):
712  TransformClass(reallyBadFrameSet)
713  for badCurrFrame in self.makeBadFrames(toName):
714  badFrameSet = self.makeFrameSet(baseFrame, badCurrFrame)
715  with self.assertRaises(InvalidParameterError):
716  TransformClass(badFrameSet)
717 
718  transform = TransformClass(frameSet)
719 
720  desStr = "{}[{}->{}]".format(transformClassName, nIn, nOut)
721  self.assertEqual("{}".format(transform), desStr)
722  self.assertEqual(repr(transform), "lsst.afw.geom." + desStr)
723 
724  self.checkPersistence(transform)
725 
726  frameSetCopy = transform.getFrameSet()
727 
728  desNFrame = 4 # desired number of frames
729  self.assertEqual(frameSet.nFrame, desNFrame)
730  self.assertEqual(frameSetCopy.nFrame, desNFrame)
731  for frameInd in range(1, 1 + desNFrame):
732  self.assertEqual(frameSet.getFrame(frameInd).ident,
733  self.frameIdentDict[frameInd])
734 
735  polyMap = makeTwoWayPolyMap(nIn, nOut)
736 
737  self.checkTransformation(transform, mapping=polyMap, msg=msg)
738 
739  # If the base and/or current frame of frameSet is a SkyFrame,
740  # try permuting that frame (in place, so the connected mappings are
741  # correctly updated). The Transform constructor should undo the permutation,
742  # (via SpherePointEndpoint.normalizeFrame) in its internal copy of frameSet,
743  # forcing the axes of the SkyFrame into standard (longitude, latitude) order
744  for permutedFS in self.permuteFrameSetIter(frameSet):
745  if permutedFS.isBaseSkyFrame:
746  baseFrame = permutedFS.frameSet.getFrame(astshim.FrameSet.BASE)
747  # desired base longitude axis
748  desBaseLonAxis = 2 if permutedFS.isBasePermuted else 1
749  self.assertEqual(baseFrame.lonAxis, desBaseLonAxis)
750  if permutedFS.isCurrSkyFrame:
751  currFrame = permutedFS.frameSet.getFrame(astshim.FrameSet.CURRENT)
752  # desired current base longitude axis
753  desCurrLonAxis = 2 if permutedFS.isCurrPermuted else 1
754  self.assertEqual(currFrame.lonAxis, desCurrLonAxis)
755 
756  permTransform = TransformClass(permutedFS.frameSet)
757  # If the base and/or current frame is a SkyFrame then make sure the frame
758  # in the *Transform* has axes in standard (longitude, latitude) order
759  unpermFrameSet = permTransform.getFrameSet()
760  if permutedFS.isBaseSkyFrame:
761  self.assertEqual(unpermFrameSet.getFrame(astshim.FrameSet.BASE).lonAxis, 1)
762  if permutedFS.isCurrSkyFrame:
763  self.assertEqual(unpermFrameSet.getFrame(astshim.FrameSet.CURRENT).lonAxis, 1)
764 
765  self.checkTransformation(permTransform, mapping=polyMap, msg=msg)
766 
767  def checkGetInverse(self, fromName, toName):
768  """Test Transform<fromName>To<toName>.getInverse
769 
770  Parameters
771  ----------
772  fromName, toName : `str`
773  Endpoint name prefix for "from" and "to" endpoints, respectively,
774  e.g. "Point2" for `lsst.afw.geom.Point2Endpoint`
775  """
776  transformClassName = "Transform{}To{}".format(fromName, toName)
777  TransformClass = getattr(afwGeom, transformClassName)
778  baseMsg = "TransformClass={}".format(TransformClass.__name__)
779  for nIn, nOut in itertools.product(self.goodNAxes[fromName],
780  self.goodNAxes[toName]):
781  msg = "{}, nIn={}, nOut={}".format(baseMsg, nIn, nOut)
782  self.checkInverseMapping(
783  TransformClass,
784  makeTwoWayPolyMap(nIn, nOut),
785  "{}, Map={}".format(msg, "TwoWay"))
786  self.checkInverseMapping(
787  TransformClass,
788  makeForwardPolyMap(nIn, nOut),
789  "{}, Map={}".format(msg, "Forward"))
790  self.checkInverseMapping(
791  TransformClass,
792  makeForwardPolyMap(nOut, nIn).getInverse(),
793  "{}, Map={}".format(msg, "Inverse"))
794 
795  self.checkInverseFrameSet(TransformClass,
796  self.makeGoodFrame(fromName, nIn),
797  self.makeGoodFrame(toName, nOut))
798 
799  def checkInverseMapping(self, TransformClass, mapping, msg):
800  """Test Transform<fromName>To<toName>.getInverse for a specific mapping.
801 
802  Parameters
803  ----------
804  TransformClass : `type`
805  The class of transform to test, such as TransformPoint2ToSpherePoint
806  mapping : `astshim.Mapping`
807  The mapping to use for the transform
808  msg : `str`
809  Error message suffix
810  """
811  transform = TransformClass(mapping)
812  inverse = transform.getInverse()
813  inverseInverse = inverse.getInverse()
814 
815  self.checkInverseTransformation(transform, inverse, msg=msg)
816  self.checkInverseTransformation(inverse, inverseInverse, msg=msg)
817  self.checkTransformation(inverseInverse, mapping, msg=msg)
818 
819  def checkInverseFrameSet(self, TransformClass, frameIn, frameOut):
820  """Test whether inverting a Transform preserves all information
821  in its FrameSet.
822 
823  Parameters
824  ----------
825  TransformClass : `type`
826  the transform to test
827  frameIn, frameOut : `astshim.Frame`
828  the frames to between which `TransformClass` shall convert. Must be
829  compatible with `TransformClass`.
830  """
831  desNFrame = 4 # desired number of frames
832  frameSet = self.makeFrameSet(frameIn, frameOut)
833  self.assertEqual(frameSet.nFrame, desNFrame)
834 
835  baseMsg = "TransformClass={}, nIn={}, nOut={}".format(
836  TransformClass.__name__, frameIn.nAxes, frameOut.nAxes)
837  transform = TransformClass(frameSet)
838  forwardFrames = transform.getFrameSet()
839  self.assertFalse(forwardFrames.isInverted)
840  self.assertEqual(forwardFrames.base, 1)
841  self.assertEqual(forwardFrames.current, desNFrame)
842 
843  self.assertEqual(forwardFrames.nFrame, desNFrame, msg=baseMsg)
844  for frameInd in range(1, 1 + desNFrame):
845  self.assertEqual(forwardFrames.getFrame(frameInd).ident,
846  self.frameIdentDict[frameInd], msg=baseMsg)
847 
848  reverseFrames = transform.getInverse().getFrameSet()
849  self.assertTrue(reverseFrames.isInverted)
850  self.assertEqual(reverseFrames.base, desNFrame)
851  self.assertEqual(reverseFrames.current, 1)
852  self.assertEqual(reverseFrames.nFrame, desNFrame, msg=baseMsg)
853  for frameInd in range(1, 1 + desNFrame):
854  self.assertEqual(reverseFrames.getFrame(frameInd).ident,
855  self.frameIdentDict[frameInd], msg=baseMsg)
856 
857  def checkGetJacobian(self, fromName, toName):
858  """Test Transform<fromName>To<toName>.getJacobian
859 
860  Parameters
861  ----------
862  fromName, toName : `str`
863  Endpoint name prefix for "from" and "to" endpoints, respectively,
864  e.g. "Point2" for `lsst.afw.geom.Point2Endpoint`
865  """
866  transformClassName = "Transform{}To{}".format(fromName, toName)
867  TransformClass = getattr(afwGeom, transformClassName)
868  baseMsg = "TransformClass={}".format(TransformClass.__name__)
869  for nIn, nOut in itertools.product(self.goodNAxes[fromName],
870  self.goodNAxes[toName]):
871  msg = "{}, nIn={}, nOut={}".format(baseMsg, nIn, nOut)
872  polyMap = makeForwardPolyMap(nIn, nOut)
873  transform = TransformClass(polyMap)
874  fromEndpoint = transform.fromEndpoint
875 
876  # Test multiple points to ensure correct functional form
877  rawInPoint = self.makeRawPointData(nIn)
878  inPoint = fromEndpoint.pointFromData(rawInPoint)
879  jacobian = transform.getJacobian(inPoint)
880  assert_allclose(jacobian, self.makeJacobian(nIn, nOut, rawInPoint),
881  err_msg=msg)
882 
883  rawInPoint = self.makeRawPointData(nIn, 0.111)
884  inPoint = fromEndpoint.pointFromData(rawInPoint)
885  jacobian = transform.getJacobian(inPoint)
886  assert_allclose(jacobian, self.makeJacobian(nIn, nOut, rawInPoint),
887  err_msg=msg)
888 
889  def checkThen(self, fromName, midName, toName):
890  """Test Transform<fromName>To<midName>.then(Transform<midName>To<toName>)
891 
892  Parameters
893  ----------
894  fromName : `str`
895  the prefix of the starting endpoint (e.g., "Point2" for a
896  Point2Endpoint) for the final, concatenated Transform
897  midName : `str`
898  the prefix for the shared endpoint where two Transforms will be
899  concatenated
900  toName : `str`
901  the prefix of the ending endpoint for the final, concatenated
902  Transform
903  """
904  TransformClass1 = getattr(afwGeom,
905  "Transform{}To{}".format(fromName, midName))
906  TransformClass2 = getattr(afwGeom,
907  "Transform{}To{}".format(midName, toName))
908  baseMsg = "{}.then({})".format(TransformClass1.__name__,
909  TransformClass2.__name__)
910  for nIn, nMid, nOut in itertools.product(self.goodNAxes[fromName],
911  self.goodNAxes[midName],
912  self.goodNAxes[toName]):
913  msg = "{}, nIn={}, nMid={}, nOut={}".format(
914  baseMsg, nIn, nMid, nOut)
915  polyMap1 = makeTwoWayPolyMap(nIn, nMid)
916  transform1 = TransformClass1(polyMap1)
917  polyMap2 = makeTwoWayPolyMap(nMid, nOut)
918  transform2 = TransformClass2(polyMap2)
919  transform = transform1.then(transform2)
920 
921  fromEndpoint = transform1.fromEndpoint
922  toEndpoint = transform2.toEndpoint
923 
924  inPoint = fromEndpoint.pointFromData(self.makeRawPointData(nIn))
925  outPointMerged = transform.tranForward(inPoint)
926  outPointSeparate = transform2.tranForward(
927  transform1.tranForward(inPoint))
928  assert_allclose(toEndpoint.dataFromPoint(outPointMerged),
929  toEndpoint.dataFromPoint(outPointSeparate),
930  err_msg=msg)
931 
932  outPoint = toEndpoint.pointFromData(self.makeRawPointData(nOut))
933  inPointMerged = transform.tranInverse(outPoint)
934  inPointSeparate = transform1.tranInverse(
935  transform2.tranInverse(outPoint))
936  assert_allclose(
937  fromEndpoint.dataFromPoint(inPointMerged),
938  fromEndpoint.dataFromPoint(inPointSeparate),
939  err_msg=msg)
940 
941  # Mismatched number of axes should fail
942  if midName == "Generic":
943  nIn = self.goodNAxes[fromName][0]
944  nOut = self.goodNAxes[toName][0]
945  polyMap = makeTwoWayPolyMap(nIn, 3)
946  transform1 = TransformClass1(polyMap)
947  polyMap = makeTwoWayPolyMap(2, nOut)
948  transform2 = TransformClass2(polyMap)
949  with self.assertRaises(InvalidParameterError):
950  transform = transform1.then(transform2)
951 
952  # Mismatched types of endpoints should fail
953  if fromName != midName:
954  # Use TransformClass1 for both args to keep test logic simple
955  outName = midName
956  joinNAxes = set(self.goodNAxes[fromName]).intersection(
957  self.goodNAxes[outName])
958 
959  for nIn, nMid, nOut in itertools.product(self.goodNAxes[fromName],
960  joinNAxes,
961  self.goodNAxes[outName]):
962  polyMap = makeTwoWayPolyMap(nIn, nMid)
963  transform1 = TransformClass1(polyMap)
964  polyMap = makeTwoWayPolyMap(nMid, nOut)
965  transform2 = TransformClass1(polyMap)
966  with self.assertRaises(InvalidParameterError):
967  transform = transform1.then(transform2)
968 
969  def checkPersistence(self, transform):
970  """Check persistence of a transform
971  """
972  className = type(transform).__name__
973  fileName = "persisted_{}.dat".format(className)
974  filePath = os.path.join(self.getTestDir(), fileName)
975  transform.saveToFile(filePath)
976  transformRoundTrip = afwGeom.readTransform(filePath)
977  self.assertEqual(type(transform), type(transformRoundTrip))
978  self.assertEqual(transform.getFrameSet().show(),
979  transformRoundTrip.getFrameSet().show())
980 
981  fromEndpoint = transform.fromEndpoint
982  toEndpoint = transform.toEndpoint
983  frameSet = transform.getFrameSet()
984  nIn = frameSet.nIn
985  nOut = frameSet.nOut
986 
987  if frameSet.hasForward:
988  nPoints = 7 # arbitrary
989  rawInArray = self.makeRawArrayData(nPoints, nIn)
990  inArray = fromEndpoint.arrayFromData(rawInArray)
991  outArray = transform.tranForward(inArray)
992  outData = toEndpoint.dataFromArray(outArray)
993  outArrayRoundTrip = transformRoundTrip.tranForward(inArray)
994  outDataRoundTrip = toEndpoint.dataFromArray(outArrayRoundTrip)
995  assert_allclose(outData, outDataRoundTrip)
996 
997  if frameSet.hasInverse:
998  nPoints = 7 # arbitrary
999  rawOutArray = self.makeRawArrayData(nPoints, nOut)
1000  outArray = toEndpoint.arrayFromData(rawOutArray)
1001  inArray = transform.tranInverse(outArray)
1002  inData = fromEndpoint.dataFromArray(inArray)
1003  inArrayRoundTrip = transformRoundTrip.tranInverse(outArray)
1004  inDataRoundTrip = fromEndpoint.dataFromArray(inArrayRoundTrip)
1005  assert_allclose(inData, inDataRoundTrip)
1006  # remove the file (if the test passes)
1007  os.remove(filePath)
def __init__
Construct a BoxGrid.
Definition: testUtils.py:49
def __iter__
Return an iterator over all boxes, where column varies most quickly.
Definition: testUtils.py:99
Divide a box into nx by ny sub-boxes that tile the region.
Definition: testUtils.py:45
def __getitem__
Return the box at the specified x,y index (a pair of ints)
Definition: testUtils.py:88