lsst.afw  13.0-100-ge0459d59f+5
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  transformCopy = TransformClass(frameSetCopy)
729  self.assertEqual(type(transform), type(transformCopy))
730  self.assertEqual(transform.getFrameSet(), transformCopy.getFrameSet())
731 
732  desNFrame = 4 # desired number of frames
733  self.assertEqual(frameSet.nFrame, desNFrame)
734  self.assertEqual(frameSetCopy.nFrame, desNFrame)
735  for frameInd in range(1, 1 + desNFrame):
736  self.assertEqual(frameSet.getFrame(frameInd).ident,
737  self.frameIdentDict[frameInd])
738 
739  polyMap = makeTwoWayPolyMap(nIn, nOut)
740 
741  self.checkTransformation(transform, mapping=polyMap, msg=msg)
742 
743  # If the base and/or current frame of frameSet is a SkyFrame,
744  # try permuting that frame (in place, so the connected mappings are
745  # correctly updated). The Transform constructor should undo the permutation,
746  # (via IcrsCoordEndpoint.normalizeFrame) in its internal copy of frameSet,
747  # forcing the axes of the SkyFrame into standard (longitude, latitude) order
748  for permutedFS in self.permuteFrameSetIter(frameSet):
749  if permutedFS.isBaseSkyFrame:
750  baseFrame = permutedFS.frameSet.getFrame(astshim.FrameSet.BASE)
751  # desired base longitude axis
752  desBaseLonAxis = 2 if permutedFS.isBasePermuted else 1
753  self.assertEqual(baseFrame.lonAxis, desBaseLonAxis)
754  if permutedFS.isCurrSkyFrame:
755  currFrame = permutedFS.frameSet.getFrame(astshim.FrameSet.CURRENT)
756  # desired current base longitude axis
757  desCurrLonAxis = 2 if permutedFS.isCurrPermuted else 1
758  self.assertEqual(currFrame.lonAxis, desCurrLonAxis)
759 
760  permTransform = TransformClass(permutedFS.frameSet)
761  # If the base and/or current frame is a SkyFrame then make sure the frame
762  # in the *Transform* has axes in standard (longitude, latitude) order
763  unpermFrameSet = permTransform.getFrameSet()
764  if permutedFS.isBaseSkyFrame:
765  self.assertEqual(unpermFrameSet.getFrame(astshim.FrameSet.BASE).lonAxis, 1)
766  if permutedFS.isCurrSkyFrame:
767  self.assertEqual(unpermFrameSet.getFrame(astshim.FrameSet.CURRENT).lonAxis, 1)
768 
769  self.checkTransformation(permTransform, mapping=polyMap, msg=msg)
770 
771  def checkGetInverse(self, fromName, toName):
772  """Test Transform<fromName>To<toName>.getInverse
773 
774  Parameters
775  ----------
776  fromName, toName : `str`
777  Endpoint name prefix for "from" and "to" endpoints, respectively,
778  e.g. "Point2" for `lsst.afw.geom.Point2Endpoint`
779  """
780  transformClassName = "Transform{}To{}".format(fromName, toName)
781  TransformClass = getattr(afwGeom, transformClassName)
782  baseMsg = "TransformClass={}".format(TransformClass.__name__)
783  for nIn, nOut in itertools.product(self.goodNAxes[fromName],
784  self.goodNAxes[toName]):
785  msg = "{}, nIn={}, nOut={}".format(baseMsg, nIn, nOut)
786  self.checkInverseMapping(
787  TransformClass,
788  makeTwoWayPolyMap(nIn, nOut),
789  "{}, Map={}".format(msg, "TwoWay"))
790  self.checkInverseMapping(
791  TransformClass,
792  makeForwardPolyMap(nIn, nOut),
793  "{}, Map={}".format(msg, "Forward"))
794  self.checkInverseMapping(
795  TransformClass,
796  makeForwardPolyMap(nOut, nIn).getInverse(),
797  "{}, Map={}".format(msg, "Inverse"))
798 
799  self.checkInverseFrameSet(TransformClass,
800  self.makeGoodFrame(fromName, nIn),
801  self.makeGoodFrame(toName, nOut))
802 
803  def checkInverseMapping(self, TransformClass, mapping, msg):
804  """Test Transform<fromName>To<toName>.getInverse for a specific mapping.
805 
806  Parameters
807  ----------
808  TransformClass : `type`
809  The class of transform to test, such as TransformPoint2ToIcrsCoord
810  mapping : `astshim.Mapping`
811  The mapping to use for the transform
812  msg : `str`
813  Error message suffix
814  """
815  transform = TransformClass(mapping)
816  inverse = transform.getInverse()
817  inverseInverse = inverse.getInverse()
818 
819  self.checkInverseTransformation(transform, inverse, msg=msg)
820  self.checkInverseTransformation(inverse, inverseInverse, msg=msg)
821  self.checkTransformation(inverseInverse, mapping, msg=msg)
822 
823  def checkInverseFrameSet(self, TransformClass, frameIn, frameOut):
824  """Test whether inverting a Transform preserves all information
825  in its FrameSet.
826 
827  Parameters
828  ----------
829  TransformClass : `type`
830  the transform to test
831  frameIn, frameOut : `astshim.Frame`
832  the frames to between which `TransformClass` shall convert. Must be
833  compatible with `TransformClass`.
834  """
835  desNFrame = 4 # desired number of frames
836  frameSet = self.makeFrameSet(frameIn, frameOut)
837  self.assertEqual(frameSet.nFrame, desNFrame)
838 
839  baseMsg = "TransformClass={}, nIn={}, nOut={}".format(
840  TransformClass.__name__, frameIn.nAxes, frameOut.nAxes)
841  transform = TransformClass(frameSet)
842  forwardFrames = transform.getFrameSet()
843  self.assertFalse(forwardFrames.isInverted)
844  self.assertEqual(forwardFrames.base, 1)
845  self.assertEqual(forwardFrames.current, desNFrame)
846 
847  self.assertEqual(forwardFrames.nFrame, desNFrame, msg=baseMsg)
848  for frameInd in range(1, 1 + desNFrame):
849  self.assertEqual(forwardFrames.getFrame(frameInd).ident,
850  self.frameIdentDict[frameInd], msg=baseMsg)
851 
852  reverseFrames = transform.getInverse().getFrameSet()
853  self.assertTrue(reverseFrames.isInverted)
854  self.assertEqual(reverseFrames.base, desNFrame)
855  self.assertEqual(reverseFrames.current, 1)
856  self.assertEqual(reverseFrames.nFrame, desNFrame, msg=baseMsg)
857  for frameInd in range(1, 1 + desNFrame):
858  self.assertEqual(reverseFrames.getFrame(frameInd).ident,
859  self.frameIdentDict[frameInd], msg=baseMsg)
860 
861  def checkGetJacobian(self, fromName, toName):
862  """Test Transform<fromName>To<toName>.getJacobian
863 
864  Parameters
865  ----------
866  fromName, toName : `str`
867  Endpoint name prefix for "from" and "to" endpoints, respectively,
868  e.g. "Point2" for `lsst.afw.geom.Point2Endpoint`
869  """
870  transformClassName = "Transform{}To{}".format(fromName, toName)
871  TransformClass = getattr(afwGeom, transformClassName)
872  baseMsg = "TransformClass={}".format(TransformClass.__name__)
873  for nIn, nOut in itertools.product(self.goodNAxes[fromName],
874  self.goodNAxes[toName]):
875  msg = "{}, nIn={}, nOut={}".format(baseMsg, nIn, nOut)
876  polyMap = makeForwardPolyMap(nIn, nOut)
877  transform = TransformClass(polyMap)
878  fromEndpoint = transform.fromEndpoint
879 
880  # Test multiple points to ensure correct functional form
881  rawInPoint = self.makeRawPointData(nIn)
882  inPoint = fromEndpoint.pointFromData(rawInPoint)
883  jacobian = transform.getJacobian(inPoint)
884  assert_allclose(jacobian, self.makeJacobian(nIn, nOut, rawInPoint),
885  err_msg=msg)
886 
887  rawInPoint = self.makeRawPointData(nIn, 0.111)
888  inPoint = fromEndpoint.pointFromData(rawInPoint)
889  jacobian = transform.getJacobian(inPoint)
890  assert_allclose(jacobian, self.makeJacobian(nIn, nOut, rawInPoint),
891  err_msg=msg)
892 
893  def checkThen(self, fromName, midName, toName):
894  """Test Transform<fromName>To<midName>.then(Transform<midName>To<toName>)
895 
896  Parameters
897  ----------
898  fromName : `str`
899  the prefix of the starting endpoint (e.g., "Point2" for a
900  Point2Endpoint) for the final, concatenated Transform
901  midName : `str`
902  the prefix for the shared endpoint where two Transforms will be
903  concatenated
904  toName : `str`
905  the prefix of the ending endpoint for the final, concatenated
906  Transform
907  """
908  TransformClass1 = getattr(afwGeom,
909  "Transform{}To{}".format(fromName, midName))
910  TransformClass2 = getattr(afwGeom,
911  "Transform{}To{}".format(midName, toName))
912  baseMsg = "{}.then({})".format(TransformClass1.__name__,
913  TransformClass2.__name__)
914  for nIn, nMid, nOut in itertools.product(self.goodNAxes[fromName],
915  self.goodNAxes[midName],
916  self.goodNAxes[toName]):
917  msg = "{}, nIn={}, nMid={}, nOut={}".format(
918  baseMsg, nIn, nMid, nOut)
919  polyMap1 = makeTwoWayPolyMap(nIn, nMid)
920  transform1 = TransformClass1(polyMap1)
921  polyMap2 = makeTwoWayPolyMap(nMid, nOut)
922  transform2 = TransformClass2(polyMap2)
923  transform = transform1.then(transform2)
924 
925  fromEndpoint = transform1.fromEndpoint
926  toEndpoint = transform2.toEndpoint
927 
928  inPoint = fromEndpoint.pointFromData(self.makeRawPointData(nIn))
929  outPointMerged = transform.applyForward(inPoint)
930  outPointSeparate = transform2.applyForward(
931  transform1.applyForward(inPoint))
932  assert_allclose(toEndpoint.dataFromPoint(outPointMerged),
933  toEndpoint.dataFromPoint(outPointSeparate),
934  err_msg=msg)
935 
936  outPoint = toEndpoint.pointFromData(self.makeRawPointData(nOut))
937  inPointMerged = transform.applyInverse(outPoint)
938  inPointSeparate = transform1.applyInverse(
939  transform2.applyInverse(outPoint))
940  assert_allclose(
941  fromEndpoint.dataFromPoint(inPointMerged),
942  fromEndpoint.dataFromPoint(inPointSeparate),
943  err_msg=msg)
944 
945  # Mismatched number of axes should fail
946  if midName == "Generic":
947  nIn = self.goodNAxes[fromName][0]
948  nOut = self.goodNAxes[toName][0]
949  polyMap = makeTwoWayPolyMap(nIn, 3)
950  transform1 = TransformClass1(polyMap)
951  polyMap = makeTwoWayPolyMap(2, nOut)
952  transform2 = TransformClass2(polyMap)
953  with self.assertRaises(InvalidParameterError):
954  transform = transform1.then(transform2)
955 
956  # Mismatched types of endpoints should fail
957  if fromName != midName:
958  # Use TransformClass1 for both args to keep test logic simple
959  outName = midName
960  joinNAxes = set(self.goodNAxes[fromName]).intersection(
961  self.goodNAxes[outName])
962 
963  for nIn, nMid, nOut in itertools.product(self.goodNAxes[fromName],
964  joinNAxes,
965  self.goodNAxes[outName]):
966  polyMap = makeTwoWayPolyMap(nIn, nMid)
967  transform1 = TransformClass1(polyMap)
968  polyMap = makeTwoWayPolyMap(nMid, nOut)
969  transform2 = TransformClass1(polyMap)
970  with self.assertRaises(InvalidParameterError):
971  transform = transform1.then(transform2)
972 
973  def checkPersistence(self, transform):
974  """Check persistence of a transform
975  """
976  className = type(transform).__name__
977 
978  # check writeString and readString
979  transformStr = transform.writeString()
980  serialVersion, serialClassName, serialRest = transformStr.split(" ", 2)
981  self.assertEqual(int(serialVersion), 1)
982  self.assertEqual(serialClassName, className)
983  badStr1 = " ".join(["2", serialClassName, serialRest])
984  with self.assertRaises(lsst.pex.exceptions.InvalidParameterError):
985  transform.readString(badStr1)
986  badClassName = "x" + serialClassName
987  badStr2 = " ".join(["1", badClassName, serialRest])
988  with self.assertRaises(lsst.pex.exceptions.InvalidParameterError):
989  transform.readString(badStr2)
990  transformFromStr1 = transform.readString(transformStr)
991  self.assertEqual(type(transform), type(transformFromStr1))
992  self.assertEqual(transform.getFrameSet(), transformFromStr1.getFrameSet())
993 
994  # check transformFromString
995  transformFromStr2 = afwGeom.transformFromString(transformStr)
996  self.assertEqual(type(transform), type(transformFromStr2))
997  self.assertEqual(transform.getFrameSet(), transformFromStr2.getFrameSet())
998 
999  fromEndpoint = transform.fromEndpoint
1000  toEndpoint = transform.toEndpoint
1001  frameSet = transform.getFrameSet()
1002  nIn = frameSet.nIn
1003  nOut = frameSet.nOut
1004 
1005  if frameSet.hasForward:
1006  nPoints = 7 # arbitrary
1007  rawInArray = self.makeRawArrayData(nPoints, nIn)
1008  inArray = fromEndpoint.arrayFromData(rawInArray)
1009  outArray = transform.applyForward(inArray)
1010  outData = toEndpoint.dataFromArray(outArray)
1011  outArrayRoundTrip = transformFromStr1.applyForward(inArray)
1012  outDataRoundTrip = toEndpoint.dataFromArray(outArrayRoundTrip)
1013  assert_allclose(outData, outDataRoundTrip)
1014 
1015  if frameSet.hasInverse:
1016  nPoints = 7 # arbitrary
1017  rawOutArray = self.makeRawArrayData(nPoints, nOut)
1018  outArray = toEndpoint.arrayFromData(rawOutArray)
1019  inArray = transform.applyInverse(outArray)
1020  inData = fromEndpoint.dataFromArray(inArray)
1021  inArrayRoundTrip = transformFromStr1.applyInverse(outArray)
1022  inDataRoundTrip = fromEndpoint.dataFromArray(inArrayRoundTrip)
1023  assert_allclose(inData, inDataRoundTrip)
def __init__(self, frameSet, permuteBase, permuteCurr)
Definition: testUtils.py:155
def makeGoodFrame(cls, name, nAxes=None)
Definition: testUtils.py:336
def checkThen(self, fromName, midName, toName)
Definition: testUtils.py:893
def checkTransformFromFrameSet(self, fromName, toName)
Definition: testUtils.py:684
def makeRawArrayData(nPoints, nAxes, delta=0.123)
Definition: testUtils.py:255
def checkTransformation(self, transform, mapping, msg="")
Definition: testUtils.py:491
def checkInverseTransformation(self, forward, inverse, msg="")
Definition: testUtils.py:564
def checkGetJacobian(self, fromName, toName)
Definition: testUtils.py:861
def checkInverseFrameSet(self, TransformClass, frameIn, frameOut)
Definition: testUtils.py:823
Divide a box into nx by ny sub-boxes that tile the region.
Definition: testUtils.py:46
def __getitem__(self, indXY)
Return the box at the specified x,y index (a pair of ints)
Definition: testUtils.py:89
def checkGetInverse(self, fromName, toName)
Definition: testUtils.py:771
def __init__(self, box, numColRow)
Construct a BoxGrid.
Definition: testUtils.py:50
def __iter__(self)
Return an iterator over all boxes, where column varies most quickly.
Definition: testUtils.py:100
def checkInverseMapping(self, TransformClass, mapping, msg)
Definition: testUtils.py:803
def makeFrameSet(self, baseFrame, currFrame)
Definition: testUtils.py:388
def checkTransformFromMapping(self, fromName, toName)
Definition: testUtils.py:629