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