lsst.afw  16.0-56-g615901931+1
testUtils.py
Go to the documentation of this file.
1 import os
2 
3 import numpy as np
4 
5 import lsst.utils
6 import lsst.geom
7 import lsst.afw.geom as afwGeom
8 import lsst.afw.table as afwTable
9 from lsst.utils.tests import inTestCase
10 from .cameraGeomLib import PIXELS, TAN_PIXELS, FIELD_ANGLE, FOCAL_PLANE, SCIENCE, ACTUAL_PIXELS, \
11  CameraSys, Detector, Orientation
12 from .cameraConfig import DetectorConfig, CameraConfig
13 from .cameraFactory import makeCameraFromCatalogs
14 from .makePixelToTanPixel import makePixelToTanPixel
15 from .transformConfig import TransformMapConfig
16 
17 __all__ = ["DetectorWrapper", "CameraWrapper"]
18 
19 
21  """!A Detector and the data used to construct it
22 
23  Intended for use with unit tests, thus saves a copy of all input parameters.
24  Does not support setting details of amplifiers.
25  """
26 
27  def __init__(self,
28  name="detector 1",
29  id=1,
30  detType=SCIENCE,
31  serial="xkcd722",
32  bbox=None, # do not use mutable objects as defaults
33  numAmps=3,
34  pixelSize=(0.02, 0.02),
35  ampExtent=(5, 6),
36  orientation=Orientation(),
37  plateScale=20.0,
38  radialDistortion=0.925,
39  crosstalk=None,
40  modFunc=None,
41  ):
42  """!Construct a DetectorWrapper
43 
44  @param[in] name detector name
45  @param[in] id detector ID (int)
46  @param[in] detType detector type (an lsst.afw.cameraGeom.DetectorType)
47  @param[in] serial serial "number" (a string)
48  @param[in] bbox bounding box; defaults to (0, 0), (1024x1024) (an lsst.geom.Box2I)
49  @param[in] numAmps number of amplifiers (int)
50  @param[in] pixelSize pixel size (mm) (an lsst.geom.Point2D)
51  @param[in] ampExtent dimensions of amplifier image bbox (an lsst.geom.Extent2I)
52  @param[in] orientation orientation of CCC in focal plane (lsst.afw.cameraGeom.Orientation)
53  @param[in] plateScale plate scale in arcsec/mm; 20.0 is for LSST
54  @param[in] radialDistortion radial distortion, in mm/rad^2
55  (the r^3 coefficient of the radial distortion polynomial
56  that converts FIELD_ANGLE in radians to FOCAL_PLANE in mm);
57  0.925 is the value Dave Monet measured for lsstSim data
58  @param[in] crosstalk crosstalk coefficient matrix
59  @param[in] modFunc a function that can modify attributes just before constructing the detector;
60  modFunc receives one argument: a DetectorWrapper with all attributes except detector set.
61  """
62  # note that (0., 0.) for the reference position is the center of the
63  # first pixel
64  self.name = name
65  self.id = int(id)
66  self.type = detType
67  self.serial = serial
68  if bbox is None:
69  bbox = lsst.geom.Box2I(lsst.geom.Point2I(0, 0), lsst.geom.Extent2I(1024, 1048))
70  self.bbox = bbox
71  self.pixelSize = lsst.geom.Extent2D(*pixelSize)
72  self.ampExtent = lsst.geom.Extent2I(*ampExtent)
73  self.plateScale = float(plateScale)
74  self.radialDistortion = float(radialDistortion)
75  schema = afwTable.AmpInfoTable.makeMinimalSchema()
76  self.ampInfo = afwTable.AmpInfoCatalog(schema)
77  for i in range(numAmps):
78  record = self.ampInfo.addNew()
79  ampName = "amp %d" % (i + 1,)
80  record.setName(ampName)
81  record.setBBox(lsst.geom.Box2I(lsst.geom.Point2I(-1, 1), self.ampExtent))
82  record.setGain(1.71234e3)
83  record.setReadNoise(0.521237e2)
84  record.setReadoutCorner(afwTable.LL)
85  record.setHasRawInfo(False)
86  self.orientation = orientation
87 
88  # compute TAN_PIXELS transform
89  pScaleRad = lsst.geom.arcsecToRad(self.plateScale)
90  radialDistortCoeffs = [0.0, 1.0/pScaleRad,
91  0.0, self.radialDistortion/pScaleRad]
92  focalPlaneToField = afwGeom.makeRadialTransform(radialDistortCoeffs)
93  pixelToTanPixel = makePixelToTanPixel(
94  bbox=self.bbox,
95  orientation=self.orientation,
96  focalPlaneToField=focalPlaneToField,
97  pixelSizeMm=self.pixelSize,
98  )
99 
100  self.transMap = {
101  FOCAL_PLANE: self.orientation.makePixelFpTransform(self.pixelSize),
102  CameraSys(TAN_PIXELS, self.name): pixelToTanPixel,
103  CameraSys(ACTUAL_PIXELS, self.name): afwGeom.makeRadialTransform([0, 0.95, 0.01]),
104  }
105  if crosstalk is None:
106  crosstalk = [[0.0 for _ in range(numAmps)] for _ in range(numAmps)]
107  self.crosstalk = crosstalk
108  if modFunc:
109  modFunc(self)
111  self.name,
112  self.id,
113  self.type,
114  self.serial,
115  self.bbox,
116  self.ampInfo,
117  self.orientation,
118  self.pixelSize,
119  self.transMap,
120  np.array(self.crosstalk, dtype=np.float32),
121  )
122 
123 
125  """A simple Camera and the data used to construct it
126 
127  Intended for use with unit tests, thus saves some interesting information.
128  """
129 
130  def __init__(self, plateScale=20.0, radialDistortion=0.925, isLsstLike=False):
131  """!Construct a CameraWrapper
132 
133  @param[in] plateScale plate scale in arcsec/mm; 20.0 is for LSST
134  @param[in] radialDistortion radial distortion, in mm/rad^2
135  (the r^3 coefficient of the radial distortion polynomial
136  that converts FIELD_ANGLE in radians to FOCAL_PLANE in mm);
137  0.925 is the value Dave Monet measured for lsstSim data
138  @param[in] isLsstLike make repository products with one raw image per amplifier (True)
139  or with one raw image per detector (False)
140  """
141  afwDir = lsst.utils.getPackageDir("afw")
142  self._afwTestDataDir = os.path.join(afwDir, "python", "lsst", "afw",
143  "cameraGeom", "testData")
144 
145  # Info to store for unit tests
146  self.plateScale = float(plateScale)
147  self.radialDistortion = float(radialDistortion)
149  self.detectorIdList = []
150  self.ampInfoDict = {}
151 
152  self.camConfig, self.ampCatalogDict = self.makeTestRepositoryItems(
153  isLsstLike)
155  self.camConfig, self.ampCatalogDict)
156 
157  @property
158  def nDetectors(self):
159  """!Return the number of detectors"""
160  return len(self.detectorNameList)
161 
162  def makeDetectorConfigs(self, detFile):
163  """!Construct a list of DetectorConfig, one per detector
164  """
165  detectors = []
166  self.detectorNameList = []
167  self.detectorIdList = []
168  with open(detFile) as fh:
169  names = fh.readline().rstrip().lstrip("#").split("|")
170  for l in fh:
171  els = l.rstrip().split("|")
172  detectorProps = dict([(name, el)
173  for name, el in zip(names, els)])
174  detectors.append(detectorProps)
175  detectorConfigs = []
176  for i, detector in enumerate(detectors):
177  detectorId = (i + 1) * 10 # to avoid simple 0, 1, 2...
178  detectorName = detector['name']
179  detConfig = DetectorConfig()
180  detConfig.name = detectorName
181  detConfig.id = detectorId
182  detConfig.bbox_x0 = 0
183  detConfig.bbox_y0 = 0
184  detConfig.bbox_x1 = int(detector['npix_x']) - 1
185  detConfig.bbox_y1 = int(detector['npix_y']) - 1
186  detConfig.serial = str(detector['serial'])
187  detConfig.detectorType = int(detector['detectorType'])
188  detConfig.offset_x = float(detector['x'])
189  detConfig.offset_y = float(detector['y'])
190  detConfig.refpos_x = float(detector['refPixPos_x'])
191  detConfig.refpos_y = float(detector['refPixPos_y'])
192  detConfig.yawDeg = float(detector['yaw'])
193  detConfig.pitchDeg = float(detector['pitch'])
194  detConfig.rollDeg = float(detector['roll'])
195  detConfig.pixelSize_x = float(detector['pixelSize'])
196  detConfig.pixelSize_y = float(detector['pixelSize'])
197  detConfig.transposeDetector = False
198  detConfig.transformDict.nativeSys = PIXELS.getSysName()
199  detectorConfigs.append(detConfig)
200  self.detectorNameList.append(detectorName)
201  self.detectorIdList.append(detectorId)
202  return detectorConfigs
203 
204  def makeAmpCatalogs(self, ampFile, isLsstLike=False):
205  """!Construct a list of AmpInfoCatalog, one per detector
206 
207  @param[in] ampFile path to amplifier data file
208  @param[in] isLsstLike if True then there is one raw image per amplifier;
209  if False then there is one raw image per detector
210  """
211  readoutMap = {
212  'LL': afwTable.ReadoutCorner.LL,
213  'LR': afwTable.ReadoutCorner.LR,
214  'UR': afwTable.ReadoutCorner.UR,
215  'UL': afwTable.ReadoutCorner.UL,
216  }
217  amps = []
218  with open(ampFile) as fh:
219  names = fh.readline().rstrip().lstrip("#").split("|")
220  for l in fh:
221  els = l.rstrip().split("|")
222  ampProps = dict([(name, el) for name, el in zip(names, els)])
223  amps.append(ampProps)
224  ampTablesDict = {}
225  schema = afwTable.AmpInfoTable.makeMinimalSchema()
226  linThreshKey = schema.addField('linearityThreshold', type=np.float64)
227  linMaxKey = schema.addField('linearityMaximum', type=np.float64)
228  linUnitsKey = schema.addField('linearityUnits', type=str, size=9)
229  self.ampInfoDict = {}
230  for amp in amps:
231  if amp['ccd_name'] in ampTablesDict:
232  ampCatalog = ampTablesDict[amp['ccd_name']]
233  self.ampInfoDict[amp['ccd_name']]['namps'] += 1
234  else:
235  ampCatalog = afwTable.AmpInfoCatalog(schema)
236  ampTablesDict[amp['ccd_name']] = ampCatalog
237  self.ampInfoDict[amp['ccd_name']] = {'namps': 1, 'linInfo': {}}
238  record = ampCatalog.addNew()
239  bbox = lsst.geom.Box2I(lsst.geom.Point2I(int(amp['trimmed_xmin']),
240  int(amp['trimmed_ymin'])),
241  lsst.geom.Point2I(int(amp['trimmed_xmax']),
242  int(amp['trimmed_ymax'])))
243  rawBbox = lsst.geom.Box2I(lsst.geom.Point2I(int(amp['raw_xmin']),
244  int(amp['raw_ymin'])),
245  lsst.geom.Point2I(int(amp['raw_xmax']),
246  int(amp['raw_ymax'])))
247  rawDataBbox = lsst.geom.Box2I(
248  lsst.geom.Point2I(int(amp['raw_data_xmin']),
249  int(amp['raw_data_ymin'])),
250  lsst.geom.Point2I(int(amp['raw_data_xmax']),
251  int(amp['raw_data_ymax'])))
252  rawHOverscanBbox = lsst.geom.Box2I(
253  lsst.geom.Point2I(int(amp['hoscan_xmin']),
254  int(amp['hoscan_ymin'])),
255  lsst.geom.Point2I(int(amp['hoscan_xmax']),
256  int(amp['hoscan_ymax'])))
257  rawVOverscanBbox = lsst.geom.Box2I(
258  lsst.geom.Point2I(int(amp['voscan_xmin']),
259  int(amp['voscan_ymin'])),
260  lsst.geom.Point2I(int(amp['voscan_xmax']),
261  int(amp['voscan_ymax'])))
262  rawPrescanBbox = lsst.geom.Box2I(
263  lsst.geom.Point2I(int(amp['pscan_xmin']),
264  int(amp['pscan_ymin'])),
265  lsst.geom.Point2I(int(amp['pscan_xmax']),
266  int(amp['pscan_ymax'])))
267  xoffset = int(amp['x_offset'])
268  yoffset = int(amp['y_offset'])
269  flipx = bool(int(amp['flipx']))
270  flipy = bool(int(amp['flipy']))
271  readcorner = 'LL'
272  if not isLsstLike:
273  offext = lsst.geom.Extent2I(xoffset, yoffset)
274  if flipx:
275  xExt = rawBbox.getDimensions().getX()
276  rawBbox.flipLR(xExt)
277  rawDataBbox.flipLR(xExt)
278  rawHOverscanBbox.flipLR(xExt)
279  rawVOverscanBbox.flipLR(xExt)
280  rawPrescanBbox.flipLR(xExt)
281  if flipy:
282  yExt = rawBbox.getDimensions().getY()
283  rawBbox.flipTB(yExt)
284  rawDataBbox.flipTB(yExt)
285  rawHOverscanBbox.flipTB(yExt)
286  rawVOverscanBbox.flipTB(yExt)
287  rawPrescanBbox.flipTB(yExt)
288  if not flipx and not flipy:
289  readcorner = 'LL'
290  elif flipx and not flipy:
291  readcorner = 'LR'
292  elif flipx and flipy:
293  readcorner = 'UR'
294  elif not flipx and flipy:
295  readcorner = 'UL'
296  else:
297  raise RuntimeError("Couldn't find read corner")
298 
299  flipx = False
300  flipy = False
301  rawBbox.shift(offext)
302  rawDataBbox.shift(offext)
303  rawHOverscanBbox.shift(offext)
304  rawVOverscanBbox.shift(offext)
305  rawPrescanBbox.shift(offext)
306  xoffset = 0
307  yoffset = 0
308  offset = lsst.geom.Extent2I(xoffset, yoffset)
309  record.setBBox(bbox)
310  record.setRawXYOffset(offset)
311  record.setName(str(amp['name']))
312  record.setReadoutCorner(readoutMap[readcorner])
313  record.setGain(float(amp['gain']))
314  record.setReadNoise(float(amp['readnoise']))
315  record.setLinearityCoeffs([float(amp['lin_coeffs']), ])
316  record.setLinearityType(str(amp['lin_type']))
317  record.setHasRawInfo(True)
318  record.setRawFlipX(flipx)
319  record.setRawFlipY(flipy)
320  record.setRawBBox(rawBbox)
321  record.setRawDataBBox(rawDataBbox)
322  record.setRawHorizontalOverscanBBox(rawHOverscanBbox)
323  record.setRawVerticalOverscanBBox(rawVOverscanBbox)
324  record.setRawPrescanBBox(rawPrescanBbox)
325  record.set(linThreshKey, float(amp['lin_thresh']))
326  record.set(linMaxKey, float(amp['lin_max']))
327  record.set(linUnitsKey, str(amp['lin_units']))
328  # The current schema assumes third order coefficients
329  saveCoeffs = (float(amp['lin_coeffs']),)
330  saveCoeffs += (np.nan, np.nan, np.nan)
331  self.ampInfoDict[amp['ccd_name']]['linInfo'][amp['name']] = \
332  {'lincoeffs': saveCoeffs, 'lintype': str(amp['lin_type']),
333  'linthresh': float(amp['lin_thresh']), 'linmax': float(amp['lin_max']),
334  'linunits': str(amp['lin_units'])}
335  return ampTablesDict
336 
337  def makeTestRepositoryItems(self, isLsstLike=False):
338  """!Make camera config and amp catalog dictionary, using default detector and amp files
339 
340  @param[in] isLsstLike if True then there is one raw image per amplifier;
341  if False then there is one raw image per detector
342  """
343  detFile = os.path.join(self._afwTestDataDir, "testCameraDetectors.dat")
344  detectorConfigs = self.makeDetectorConfigs(detFile)
345  ampFile = os.path.join(self._afwTestDataDir, "testCameraAmps.dat")
346  ampCatalogDict = self.makeAmpCatalogs(ampFile, isLsstLike=isLsstLike)
347  camConfig = CameraConfig()
348  camConfig.name = "testCamera%s"%('LSST' if isLsstLike else 'SC')
349  camConfig.detectorList = dict((i, detConfig)
350  for i, detConfig in enumerate(detectorConfigs))
351  camConfig.plateScale = self.plateScale
352  pScaleRad = lsst.geom.arcsecToRad(self.plateScale)
353  radialDistortCoeffs = [0.0, 1.0/pScaleRad,
354  0.0, self.radialDistortion/pScaleRad]
355  tConfig = afwGeom.TransformConfig()
356  tConfig.transform.name = 'inverted'
357  radialClass = afwGeom.transformRegistry['radial']
358  tConfig.transform.active.transform.retarget(radialClass)
359  tConfig.transform.active.transform.coeffs = radialDistortCoeffs
360  tmc = TransformMapConfig()
361  tmc.nativeSys = FOCAL_PLANE.getSysName()
362  tmc.transforms = {FIELD_ANGLE.getSysName(): tConfig}
363  camConfig.transformDict = tmc
364  return camConfig, ampCatalogDict
365 
366 
367 @inTestCase
368 def compare2DFunctions(self, func1, func2, minVal=-10, maxVal=None, nVal=5):
369  """Compare two Point2D(Point2D) functions by evaluating them over a
370  range of values.
371  """
372  if maxVal is None:
373  maxVal = -minVal
374  dVal = (maxVal - minVal) / (nVal - 1)
375  for xInd in range(nVal):
376  x = minVal + (xInd * dVal)
377  for yInd in range(nVal):
378  y = minVal + (yInd * dVal)
379  fromPoint = lsst.geom.Point2D(x, y)
380  res1 = func1(fromPoint)
381  res2 = func2(fromPoint)
382  self.assertPairsAlmostEqual(res1, res2)
383 
384 
385 @inTestCase
386 def assertTransformMapsEqual(self, map1, map2, **kwds):
387  """Compare two TransformMaps.
388  """
389  self.assertEqual(list(map1), list(map2)) # compares the sets of CameraSys
390  for sysFrom in map1:
391  for sysTo in map1:
392  with self.subTest(sysFrom=sysFrom, sysTo=sysTo):
393  transform1 = map1.getTransform(sysFrom, sysTo)
394  transform2 = map2.getTransform(sysFrom, sysTo)
395  self.compare2DFunctions(transform1.applyForward, transform2.applyForward, **kwds)
396  self.compare2DFunctions(transform1.applyInverse, transform2.applyInverse, **kwds)
397 
398 
399 @inTestCase
400 def assertDetectorsEqual(self, detector1, detector2, **kwds):
401  """Compare two Detectors.
402  """
403  self.assertEqual(detector1.getName(), detector2.getName())
404  self.assertEqual(detector1.getId(), detector2.getId())
405  self.assertEqual(detector1.getSerial(), detector2.getSerial())
406  self.assertEqual(detector1.getBBox(), detector2.getBBox())
407  self.assertEqual(detector1.getPixelSize(), detector2.getPixelSize())
408  orientationIn = detector1.getOrientation()
409  orientationOut = detector2.getOrientation()
410  self.assertEqual(orientationIn.getFpPosition(), orientationOut.getFpPosition())
411  self.assertEqual(orientationIn.getReferencePoint(), orientationOut.getReferencePoint())
412  self.assertEqual(orientationIn.getYaw(), orientationOut.getYaw())
413  self.assertEqual(orientationIn.getPitch(), orientationOut.getPitch())
414  self.assertEqual(orientationIn.getRoll(), orientationOut.getRoll())
415  self.assertFloatsEqual(detector1.getCrosstalk(), detector2.getCrosstalk())
416  self.assertTransformMapsEqual(detector1.getTransformMap(), detector2.getTransformMap(), **kwds)
417 
418 
419 @inTestCase
420 def assertDetectorCollectionsEqual(self, collection1, collection2, **kwds):
421  """Compare two DetectorCollections.
422  """
423  self.assertCountEqual(list(collection1.getNameIter()), list(collection2.getNameIter()))
424  for k in collection1.getNameIter():
425  self.assertDetectorsEqual(collection1[k], collection2[k], **kwds)
426 
427 
428 @inTestCase
429 def assertCamerasEqual(self, camera1, camera2, **kwds):
430  """Compare two Camers.
431  """
432  self.assertDetectorCollectionsEqual(camera1, camera2, **kwds)
433  self.assertTransformMapsEqual(camera1.getTransformMap(), camera2.getTransformMap())
434  self.assertEqual(camera1.getName(), camera2.getName())
435  self.assertEqual(camera1.getPupilFactoryName(), camera2.getPupilFactoryName())
def assertDetectorCollectionsEqual(self, collection1, collection2, kwds)
Definition: testUtils.py:420
Camera coordinate system; used as a key in in TransformMap.
Definition: CameraSys.h:83
def makeTestRepositoryItems(self, isLsstLike=False)
Make camera config and amp catalog dictionary, using default detector and amp files.
Definition: testUtils.py:337
def makeCameraFromCatalogs(cameraConfig, ampInfoCatDict, pupilFactoryClass=PupilFactory)
A configuration that represents (and can be used to construct) a Detector.
Definition: cameraConfig.py:8
def __init__(self, name="detector 1", id=1, detType=SCIENCE, serial="xkcd722", bbox=None, numAmps=3, pixelSize=(0.02, 0.02), ampExtent=(5, 6), orientation=Orientation(), plateScale=20.0, radialDistortion=0.925, crosstalk=None, modFunc=None)
Construct a DetectorWrapper.
Definition: testUtils.py:41
def assertDetectorsEqual(self, detector1, detector2, kwds)
Definition: testUtils.py:400
A Detector and the data used to construct it.
Definition: testUtils.py:20
def assertTransformMapsEqual(self, map1, map2, kwds)
Definition: testUtils.py:386
Describe a detector's orientation in the focal plane.
Definition: Orientation.h:52
std::string getPackageDir(std::string const &packageName)
def nDetectors(self)
Return the number of detectors.
Definition: testUtils.py:158
def assertCamerasEqual(self, camera1, camera2, kwds)
Definition: testUtils.py:429
def makeAmpCatalogs(self, ampFile, isLsstLike=False)
Construct a list of AmpInfoCatalog, one per detector.
Definition: testUtils.py:204
def compare2DFunctions(self, func1, func2, minVal=-10, maxVal=None, nVal=5)
Definition: testUtils.py:368
Information about a CCD or other imaging detector.
Definition: Detector.h:61
def makePixelToTanPixel(bbox, orientation, focalPlaneToField, pixelSizeMm)
Make a Transform whose forward direction converts PIXELS to TAN_PIXELS for one detector.
A configuration that represents (and can be used to construct) a Camera.
Definition: cameraConfig.py:64
daf::base::PropertyList * list
Definition: fits.cc:833
constexpr double arcsecToRad(double x) noexcept
def makeDetectorConfigs(self, detFile)
Construct a list of DetectorConfig, one per detector.
Definition: testUtils.py:162
def __init__(self, plateScale=20.0, radialDistortion=0.925, isLsstLike=False)
Construct a CameraWrapper.
Definition: testUtils.py:130