lsst.afw  13.0-95-g793934f
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
testUtils.py
Go to the documentation of this file.
1 from __future__ import absolute_import, division, print_function
2 from builtins import str
3 from builtins import zip
4 from builtins import range
5 from builtins import object
6 import os
7 
8 import numpy as np
9 
10 import lsst.utils
11 import lsst.afw.geom as afwGeom
12 import lsst.afw.table as afwTable
13 from .cameraGeomLib import PIXELS, TAN_PIXELS, FIELD_ANGLE, FOCAL_PLANE, SCIENCE, ACTUAL_PIXELS, \
14  CameraSys, Detector, Orientation
15 from .cameraConfig import DetectorConfig, CameraConfig
16 from .cameraFactory import makeCameraFromCatalogs
17 from .makePixelToTanPixel import makePixelToTanPixel
18 from .transformConfig import TransformMapConfig
19 
20 __all__ = ["DetectorWrapper", "CameraWrapper"]
21 
22 
23 class DetectorWrapper(object):
24  """!A Detector and the data used to construct it
25 
26  Intended for use with unit tests, thus saves a copy of all input parameters.
27  Does not support setting details of amplifiers.
28  """
29 
30  def __init__(self,
31  name="detector 1",
32  id=1,
33  detType=SCIENCE,
34  serial="xkcd722",
35  bbox=None, # do not use mutable objects as defaults
36  numAmps=3,
37  pixelSize=(0.02, 0.02),
38  ampExtent=(5, 6),
39  orientation=Orientation(),
40  plateScale=20.0,
41  radialDistortion=0.925,
42  modFunc=None,
43  ):
44  """!Construct a DetectorWrapper
45 
46  @param[in] name detector name
47  @param[in] id detector ID (int)
48  @param[in] detType detector type (an lsst.afw.cameraGeom.DetectorType)
49  @param[in] serial serial "number" (a string)
50  @param[in] bbox bounding box; defaults to (0, 0), (1024x1024) (an lsst.afw.geom.Box2I)
51  @param[in] numAmps number of amplifiers (int)
52  @param[in] pixelSize pixel size (mm) (an lsst.afw.geom.Point2D)
53  @param[in] ampExtent dimensions of amplifier image bbox (an lsst.afw.geom.Extent2I)
54  @param[in] orientation orientation of CCC in focal plane (lsst.afw.cameraGeom.Orientation)
55  @param[in] plateScale plate scale in arcsec/mm; 20.0 is for LSST
56  @param[in] radialDistortion radial distortion, in mm/rad^2
57  (the r^3 coefficient of the radial distortion polynomial
58  that converts FIELD_ANGLE in radians to FOCAL_PLANE in mm);
59  0.925 is the value Dave Monet measured for lsstSim data
60  @param[in] modFunc a function that can modify attributes just before constructing the detector;
61  modFunc receives one argument: a DetectorWrapper with all attributes except detector set.
62  """
63  # note that (0., 0.) for the reference position is the center of the
64  # first pixel
65  self.name = name
66  self.id = int(id)
67  self.type = detType
68  self.serial = serial
69  if bbox is None:
71  0, 0), afwGeom.Extent2I(1024, 1048))
72  self.bbox = bbox
73  self.pixelSize = afwGeom.Extent2D(*pixelSize)
74  self.ampExtent = afwGeom.Extent2I(*ampExtent)
75  self.plateScale = float(plateScale)
76  self.radialDistortion = float(radialDistortion)
77  schema = afwTable.AmpInfoTable.makeMinimalSchema()
78  self.ampInfo = afwTable.AmpInfoCatalog(schema)
79  for i in range(numAmps):
80  record = self.ampInfo.addNew()
81  ampName = "amp %d" % (i + 1,)
82  record.setName(ampName)
83  record.setBBox(afwGeom.Box2I(
84  afwGeom.Point2I(-1, 1), self.ampExtent))
85  record.setGain(1.71234e3)
86  record.setReadNoise(0.521237e2)
87  record.setReadoutCorner(afwTable.LL)
88  record.setHasRawInfo(False)
89  self.orientation = orientation
90 
91  # compute TAN_PIXELS transform
92  pScaleRad = afwGeom.arcsecToRad(self.plateScale)
93  radialDistortCoeffs = [0.0, 1.0/pScaleRad,
94  0.0, self.radialDistortion/pScaleRad]
95  focalPlaneToField = afwGeom.makeRadialTransform(radialDistortCoeffs)
96  pixelToTanPixel = makePixelToTanPixel(
97  bbox = self.bbox,
98  orientation = self.orientation,
99  focalPlaneToField = focalPlaneToField,
100  pixelSizeMm = self.pixelSize,
101  )
102 
103  self.transMap = {
104  FOCAL_PLANE: self.orientation.makePixelFpTransform(self.pixelSize),
105  CameraSys(TAN_PIXELS, self.name): pixelToTanPixel,
106  CameraSys(ACTUAL_PIXELS, self.name): afwGeom.makeRadialTransform([0, 0.95, 0.01]),
107  }
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  )
121 
122 
123 class CameraWrapper(object):
124  """A simple Camera and the data used to construct it
125 
126  Intended for use with unit tests, thus saves some interesting information.
127  """
128 
129  def __init__(self, plateScale=20.0, radialDistortion=0.925, isLsstLike=False):
130  """!Construct a CameraWrapper
131 
132  @param[in] plateScale plate scale in arcsec/mm; 20.0 is for LSST
133  @param[in] radialDistortion radial distortion, in mm/rad^2
134  (the r^3 coefficient of the radial distortion polynomial
135  that converts FIELD_ANGLE in radians to FOCAL_PLANE in mm);
136  0.925 is the value Dave Monet measured for lsstSim data
137  @param[in] isLsstLike make repository products with one raw image per amplifier (True)
138  or with one raw image per detector (False)
139  """
140  afwDir = lsst.utils.getPackageDir("afw")
141  self._afwTestDir = os.path.join(afwDir, "tests")
142 
143  # Info to store for unit tests
144  self.plateScale = float(plateScale)
145  self.radialDistortion = float(radialDistortion)
147  self.detectorIdList = []
148  self.ampInfoDict = {}
149 
150  self.camConfig, self.ampCatalogDict = self.makeTestRepositoryItems(
151  isLsstLike)
153  self.camConfig, self.ampCatalogDict)
154 
155  @property
156  def nDetectors(self):
157  """!Return the number of detectors"""
158  return len(self.detectorNameList)
159 
160  def makeDetectorConfigs(self, detFile):
161  """!Construct a list of DetectorConfig, one per detector
162  """
163  detectors = []
164  self.detectorNameList = []
165  self.detectorIdList = []
166  with open(detFile) as fh:
167  names = fh.readline().rstrip().lstrip("#").split("|")
168  for l in fh:
169  els = l.rstrip().split("|")
170  detectorProps = dict([(name, el)
171  for name, el in zip(names, els)])
172  detectors.append(detectorProps)
173  detectorConfigs = []
174  for i, detector in enumerate(detectors):
175  detectorId = (i + 1) * 10 # to avoid simple 0, 1, 2...
176  detectorName = detector['name']
177  detConfig = DetectorConfig()
178  detConfig.name = detectorName
179  detConfig.id = detectorId
180  detConfig.bbox_x0 = 0
181  detConfig.bbox_y0 = 0
182  detConfig.bbox_x1 = int(detector['npix_x']) - 1
183  detConfig.bbox_y1 = int(detector['npix_y']) - 1
184  detConfig.serial = str(detector['serial'])
185  detConfig.detectorType = int(detector['detectorType'])
186  detConfig.offset_x = float(detector['x'])
187  detConfig.offset_y = float(detector['y'])
188  detConfig.refpos_x = float(detector['refPixPos_x'])
189  detConfig.refpos_y = float(detector['refPixPos_y'])
190  detConfig.yawDeg = float(detector['yaw'])
191  detConfig.pitchDeg = float(detector['pitch'])
192  detConfig.rollDeg = float(detector['roll'])
193  detConfig.pixelSize_x = float(detector['pixelSize'])
194  detConfig.pixelSize_y = float(detector['pixelSize'])
195  detConfig.transposeDetector = False
196  detConfig.transformDict.nativeSys = PIXELS.getSysName()
197  detectorConfigs.append(detConfig)
198  self.detectorNameList.append(detectorName)
199  self.detectorIdList.append(detectorId)
200  return detectorConfigs
201 
202  def makeAmpCatalogs(self, ampFile, isLsstLike=False):
203  """!Construct a list of AmpInfoCatalog, one per detector
204 
205  @param[in] ampFile path to amplifier data file
206  @param[in] isLsstLike if True then there is one raw image per amplifier;
207  if False then there is one raw image per detector
208  """
209  readoutMap = {
210  'LL': afwTable.ReadoutCorner.LL,
211  'LR': afwTable.ReadoutCorner.LR,
212  'UR': afwTable.ReadoutCorner.UR,
213  'UL': afwTable.ReadoutCorner.UL,
214  }
215  amps = []
216  with open(ampFile) as fh:
217  names = fh.readline().rstrip().lstrip("#").split("|")
218  for l in fh:
219  els = l.rstrip().split("|")
220  ampProps = dict([(name, el) for name, el in zip(names, els)])
221  amps.append(ampProps)
222  ampTablesDict = {}
223  schema = afwTable.AmpInfoTable.makeMinimalSchema()
224  linThreshKey = schema.addField('linearityThreshold', type=np.float64)
225  linMaxKey = schema.addField('linearityMaximum', type=np.float64)
226  linUnitsKey = schema.addField('linearityUnits', type=str, size=9)
227  self.ampInfoDict = {}
228  for amp in amps:
229  if amp['ccd_name'] in ampTablesDict:
230  ampCatalog = ampTablesDict[amp['ccd_name']]
231  self.ampInfoDict[amp['ccd_name']]['namps'] += 1
232  else:
233  ampCatalog = afwTable.AmpInfoCatalog(schema)
234  ampTablesDict[amp['ccd_name']] = ampCatalog
235  self.ampInfoDict[amp['ccd_name']] = {'namps': 1, 'linInfo': {}}
236  record = ampCatalog.addNew()
237  bbox = afwGeom.Box2I(afwGeom.Point2I(int(amp['trimmed_xmin']),
238  int(amp['trimmed_ymin'])),
239  afwGeom.Point2I(int(amp['trimmed_xmax']),
240  int(amp['trimmed_ymax'])))
241  rawBbox = afwGeom.Box2I(afwGeom.Point2I(int(amp['raw_xmin']),
242  int(amp['raw_ymin'])),
243  afwGeom.Point2I(int(amp['raw_xmax']),
244  int(amp['raw_ymax'])))
245  rawDataBbox = afwGeom.Box2I(
246  afwGeom.Point2I(int(amp['raw_data_xmin']),
247  int(amp['raw_data_ymin'])),
248  afwGeom.Point2I(int(amp['raw_data_xmax']),
249  int(amp['raw_data_ymax'])))
250  rawHOverscanBbox = afwGeom.Box2I(
251  afwGeom.Point2I(int(amp['hoscan_xmin']),
252  int(amp['hoscan_ymin'])),
253  afwGeom.Point2I(int(amp['hoscan_xmax']),
254  int(amp['hoscan_ymax'])))
255  rawVOverscanBbox = afwGeom.Box2I(
256  afwGeom.Point2I(int(amp['voscan_xmin']),
257  int(amp['voscan_ymin'])),
258  afwGeom.Point2I(int(amp['voscan_xmax']),
259  int(amp['voscan_ymax'])))
260  rawPrescanBbox = afwGeom.Box2I(
261  afwGeom.Point2I(int(amp['pscan_xmin']),
262  int(amp['pscan_ymin'])),
263  afwGeom.Point2I(int(amp['pscan_xmax']),
264  int(amp['pscan_ymax'])))
265  xoffset = int(amp['x_offset'])
266  yoffset = int(amp['y_offset'])
267  flipx = bool(int(amp['flipx']))
268  flipy = bool(int(amp['flipy']))
269  readcorner = 'LL'
270  if not isLsstLike:
271  offext = afwGeom.Extent2I(xoffset, yoffset)
272  if flipx:
273  xExt = rawBbox.getDimensions().getX()
274  rawBbox.flipLR(xExt)
275  rawDataBbox.flipLR(xExt)
276  rawHOverscanBbox.flipLR(xExt)
277  rawVOverscanBbox.flipLR(xExt)
278  rawPrescanBbox.flipLR(xExt)
279  if flipy:
280  yExt = rawBbox.getDimensions().getY()
281  rawBbox.flipTB(yExt)
282  rawDataBbox.flipTB(yExt)
283  rawHOverscanBbox.flipTB(yExt)
284  rawVOverscanBbox.flipTB(yExt)
285  rawPrescanBbox.flipTB(yExt)
286  if not flipx and not flipy:
287  readcorner = 'LL'
288  elif flipx and not flipy:
289  readcorner = 'LR'
290  elif flipx and flipy:
291  readcorner = 'UR'
292  elif not flipx and flipy:
293  readcorner = 'UL'
294  else:
295  raise RuntimeError("Couldn't find read corner")
296 
297  flipx = False
298  flipy = False
299  rawBbox.shift(offext)
300  rawDataBbox.shift(offext)
301  rawHOverscanBbox.shift(offext)
302  rawVOverscanBbox.shift(offext)
303  rawPrescanBbox.shift(offext)
304  xoffset = 0
305  yoffset = 0
306  offset = afwGeom.Extent2I(xoffset, yoffset)
307  record.setBBox(bbox)
308  record.setRawXYOffset(offset)
309  record.setName(str(amp['name']))
310  record.setReadoutCorner(readoutMap[readcorner])
311  record.setGain(float(amp['gain']))
312  record.setReadNoise(float(amp['readnoise']))
313  record.setLinearityCoeffs([float(amp['lin_coeffs']), ])
314  record.setLinearityType(str(amp['lin_type']))
315  record.setHasRawInfo(True)
316  record.setRawFlipX(flipx)
317  record.setRawFlipY(flipy)
318  record.setRawBBox(rawBbox)
319  record.setRawDataBBox(rawDataBbox)
320  record.setRawHorizontalOverscanBBox(rawHOverscanBbox)
321  record.setRawVerticalOverscanBBox(rawVOverscanBbox)
322  record.setRawPrescanBBox(rawPrescanBbox)
323  record.set(linThreshKey, float(amp['lin_thresh']))
324  record.set(linMaxKey, float(amp['lin_max']))
325  record.set(linUnitsKey, str(amp['lin_units']))
326  # The current schema assumes third order coefficients
327  saveCoeffs = (float(amp['lin_coeffs']),)
328  saveCoeffs += (np.nan, np.nan, np.nan)
329  self.ampInfoDict[amp['ccd_name']]['linInfo'][amp['name']] = \
330  {'lincoeffs': saveCoeffs, 'lintype': str(amp['lin_type']),
331  'linthresh': float(amp['lin_thresh']), 'linmax': float(amp['lin_max']),
332  'linunits': str(amp['lin_units'])}
333  return ampTablesDict
334 
335  def makeTestRepositoryItems(self, isLsstLike=False):
336  """!Make camera config and amp catalog dictionary, using default detector and amp files
337 
338  @param[in] isLsstLike if True then there is one raw image per amplifier;
339  if False then there is one raw image per detector
340  """
341  detFile = os.path.join(self._afwTestDir, "testCameraDetectors.dat")
342  detectorConfigs = self.makeDetectorConfigs(detFile)
343  ampFile = os.path.join(self._afwTestDir, "testCameraAmps.dat")
344  ampCatalogDict = self.makeAmpCatalogs(ampFile, isLsstLike=isLsstLike)
345  camConfig = CameraConfig()
346  camConfig.name = "testCamera%s"%('LSST' if isLsstLike else 'SC')
347  camConfig.detectorList = dict((i, detConfig)
348  for i, detConfig in enumerate(detectorConfigs))
349  camConfig.plateScale = self.plateScale
350  pScaleRad = afwGeom.arcsecToRad(self.plateScale)
351  radialDistortCoeffs = [0.0, 1.0/pScaleRad,
352  0.0, self.radialDistortion/pScaleRad]
353  tConfig = afwGeom.TransformConfig()
354  tConfig.transform.name = 'inverted'
355  radialClass = afwGeom.transformRegistry['radial']
356  tConfig.transform.active.transform.retarget(radialClass)
357  tConfig.transform.active.transform.coeffs = radialDistortCoeffs
358  tmc = TransformMapConfig()
359  tmc.nativeSys = FOCAL_PLANE.getSysName()
360  tmc.transforms = {FIELD_ANGLE.getSysName(): tConfig}
361  camConfig.transformDict = tmc
362  return camConfig, ampCatalogDict
Camera coordinate system; used as a key in in TransformMap.
Definition: CameraSys.h:77
def __init__
Construct a CameraWrapper.
Definition: testUtils.py:129
TransformPoint2ToPoint2 makeRadialTransform(std::vector< double > const &forwardCoeffs, std::vector< double > const &inverseCoeffs)
A purely radial polynomial distortion.
def makeTestRepositoryItems
Make camera config and amp catalog dictionary, using default detector and amp files.
Definition: testUtils.py:335
def nDetectors
Return the number of detectors.
Definition: testUtils.py:156
A Detector and the data used to construct it.
Definition: testUtils.py:23
def __init__
Construct a DetectorWrapper.
Definition: testUtils.py:43
An integer coordinate rectangle.
Definition: Box.h:55
Describe a detector&#39;s orientation in the focal plane.
Definition: Orientation.h:51
def makePixelToTanPixel
Make a Transform whose forward direction converts PIXEL to TAN_PIXEL for one detector.
def makeDetectorConfigs
Construct a list of DetectorConfig, one per detector.
Definition: testUtils.py:160
def makeAmpCatalogs
Construct a list of AmpInfoCatalog, one per detector.
Definition: testUtils.py:202
Information about a CCD or other imaging detector.
Definition: Detector.h:64
def makeCameraFromCatalogs
Construct a Camera instance from a dictionary of detector name: AmpInfoCatalog.
constexpr double arcsecToRad(double x) noexcept
Definition: Angle.h:37