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