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