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