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