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