lsst.afw  15.0-17-g0b88e3da8+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._afwTestDataDir = os.path.join(afwDir, "python", "lsst", "afw",
148  "cameraGeom", "testData")
149 
150  # Info to store for unit tests
151  self.plateScale = float(plateScale)
152  self.radialDistortion = float(radialDistortion)
154  self.detectorIdList = []
155  self.ampInfoDict = {}
156 
157  self.camConfig, self.ampCatalogDict = self.makeTestRepositoryItems(
158  isLsstLike)
160  self.camConfig, self.ampCatalogDict)
161 
162  @property
163  def nDetectors(self):
164  """!Return the number of detectors"""
165  return len(self.detectorNameList)
166 
167  def makeDetectorConfigs(self, detFile):
168  """!Construct a list of DetectorConfig, one per detector
169  """
170  detectors = []
171  self.detectorNameList = []
172  self.detectorIdList = []
173  with open(detFile) as fh:
174  names = fh.readline().rstrip().lstrip("#").split("|")
175  for l in fh:
176  els = l.rstrip().split("|")
177  detectorProps = dict([(name, el)
178  for name, el in zip(names, els)])
179  detectors.append(detectorProps)
180  detectorConfigs = []
181  for i, detector in enumerate(detectors):
182  detectorId = (i + 1) * 10 # to avoid simple 0, 1, 2...
183  detectorName = detector['name']
184  detConfig = DetectorConfig()
185  detConfig.name = detectorName
186  detConfig.id = detectorId
187  detConfig.bbox_x0 = 0
188  detConfig.bbox_y0 = 0
189  detConfig.bbox_x1 = int(detector['npix_x']) - 1
190  detConfig.bbox_y1 = int(detector['npix_y']) - 1
191  detConfig.serial = str(detector['serial'])
192  detConfig.detectorType = int(detector['detectorType'])
193  detConfig.offset_x = float(detector['x'])
194  detConfig.offset_y = float(detector['y'])
195  detConfig.refpos_x = float(detector['refPixPos_x'])
196  detConfig.refpos_y = float(detector['refPixPos_y'])
197  detConfig.yawDeg = float(detector['yaw'])
198  detConfig.pitchDeg = float(detector['pitch'])
199  detConfig.rollDeg = float(detector['roll'])
200  detConfig.pixelSize_x = float(detector['pixelSize'])
201  detConfig.pixelSize_y = float(detector['pixelSize'])
202  detConfig.transposeDetector = False
203  detConfig.transformDict.nativeSys = PIXELS.getSysName()
204  detectorConfigs.append(detConfig)
205  self.detectorNameList.append(detectorName)
206  self.detectorIdList.append(detectorId)
207  return detectorConfigs
208 
209  def makeAmpCatalogs(self, ampFile, isLsstLike=False):
210  """!Construct a list of AmpInfoCatalog, one per detector
211 
212  @param[in] ampFile path to amplifier data file
213  @param[in] isLsstLike if True then there is one raw image per amplifier;
214  if False then there is one raw image per detector
215  """
216  readoutMap = {
217  'LL': afwTable.ReadoutCorner.LL,
218  'LR': afwTable.ReadoutCorner.LR,
219  'UR': afwTable.ReadoutCorner.UR,
220  'UL': afwTable.ReadoutCorner.UL,
221  }
222  amps = []
223  with open(ampFile) as fh:
224  names = fh.readline().rstrip().lstrip("#").split("|")
225  for l in fh:
226  els = l.rstrip().split("|")
227  ampProps = dict([(name, el) for name, el in zip(names, els)])
228  amps.append(ampProps)
229  ampTablesDict = {}
230  schema = afwTable.AmpInfoTable.makeMinimalSchema()
231  linThreshKey = schema.addField('linearityThreshold', type=np.float64)
232  linMaxKey = schema.addField('linearityMaximum', type=np.float64)
233  linUnitsKey = schema.addField('linearityUnits', type=str, size=9)
234  self.ampInfoDict = {}
235  for amp in amps:
236  if amp['ccd_name'] in ampTablesDict:
237  ampCatalog = ampTablesDict[amp['ccd_name']]
238  self.ampInfoDict[amp['ccd_name']]['namps'] += 1
239  else:
240  ampCatalog = afwTable.AmpInfoCatalog(schema)
241  ampTablesDict[amp['ccd_name']] = ampCatalog
242  self.ampInfoDict[amp['ccd_name']] = {'namps': 1, 'linInfo': {}}
243  record = ampCatalog.addNew()
244  bbox = afwGeom.Box2I(afwGeom.Point2I(int(amp['trimmed_xmin']),
245  int(amp['trimmed_ymin'])),
246  afwGeom.Point2I(int(amp['trimmed_xmax']),
247  int(amp['trimmed_ymax'])))
248  rawBbox = afwGeom.Box2I(afwGeom.Point2I(int(amp['raw_xmin']),
249  int(amp['raw_ymin'])),
250  afwGeom.Point2I(int(amp['raw_xmax']),
251  int(amp['raw_ymax'])))
252  rawDataBbox = afwGeom.Box2I(
253  afwGeom.Point2I(int(amp['raw_data_xmin']),
254  int(amp['raw_data_ymin'])),
255  afwGeom.Point2I(int(amp['raw_data_xmax']),
256  int(amp['raw_data_ymax'])))
257  rawHOverscanBbox = afwGeom.Box2I(
258  afwGeom.Point2I(int(amp['hoscan_xmin']),
259  int(amp['hoscan_ymin'])),
260  afwGeom.Point2I(int(amp['hoscan_xmax']),
261  int(amp['hoscan_ymax'])))
262  rawVOverscanBbox = afwGeom.Box2I(
263  afwGeom.Point2I(int(amp['voscan_xmin']),
264  int(amp['voscan_ymin'])),
265  afwGeom.Point2I(int(amp['voscan_xmax']),
266  int(amp['voscan_ymax'])))
267  rawPrescanBbox = afwGeom.Box2I(
268  afwGeom.Point2I(int(amp['pscan_xmin']),
269  int(amp['pscan_ymin'])),
270  afwGeom.Point2I(int(amp['pscan_xmax']),
271  int(amp['pscan_ymax'])))
272  xoffset = int(amp['x_offset'])
273  yoffset = int(amp['y_offset'])
274  flipx = bool(int(amp['flipx']))
275  flipy = bool(int(amp['flipy']))
276  readcorner = 'LL'
277  if not isLsstLike:
278  offext = afwGeom.Extent2I(xoffset, yoffset)
279  if flipx:
280  xExt = rawBbox.getDimensions().getX()
281  rawBbox.flipLR(xExt)
282  rawDataBbox.flipLR(xExt)
283  rawHOverscanBbox.flipLR(xExt)
284  rawVOverscanBbox.flipLR(xExt)
285  rawPrescanBbox.flipLR(xExt)
286  if flipy:
287  yExt = rawBbox.getDimensions().getY()
288  rawBbox.flipTB(yExt)
289  rawDataBbox.flipTB(yExt)
290  rawHOverscanBbox.flipTB(yExt)
291  rawVOverscanBbox.flipTB(yExt)
292  rawPrescanBbox.flipTB(yExt)
293  if not flipx and not flipy:
294  readcorner = 'LL'
295  elif flipx and not flipy:
296  readcorner = 'LR'
297  elif flipx and flipy:
298  readcorner = 'UR'
299  elif not flipx and flipy:
300  readcorner = 'UL'
301  else:
302  raise RuntimeError("Couldn't find read corner")
303 
304  flipx = False
305  flipy = False
306  rawBbox.shift(offext)
307  rawDataBbox.shift(offext)
308  rawHOverscanBbox.shift(offext)
309  rawVOverscanBbox.shift(offext)
310  rawPrescanBbox.shift(offext)
311  xoffset = 0
312  yoffset = 0
313  offset = afwGeom.Extent2I(xoffset, yoffset)
314  record.setBBox(bbox)
315  record.setRawXYOffset(offset)
316  record.setName(str(amp['name']))
317  record.setReadoutCorner(readoutMap[readcorner])
318  record.setGain(float(amp['gain']))
319  record.setReadNoise(float(amp['readnoise']))
320  record.setLinearityCoeffs([float(amp['lin_coeffs']), ])
321  record.setLinearityType(str(amp['lin_type']))
322  record.setHasRawInfo(True)
323  record.setRawFlipX(flipx)
324  record.setRawFlipY(flipy)
325  record.setRawBBox(rawBbox)
326  record.setRawDataBBox(rawDataBbox)
327  record.setRawHorizontalOverscanBBox(rawHOverscanBbox)
328  record.setRawVerticalOverscanBBox(rawVOverscanBbox)
329  record.setRawPrescanBBox(rawPrescanBbox)
330  record.set(linThreshKey, float(amp['lin_thresh']))
331  record.set(linMaxKey, float(amp['lin_max']))
332  record.set(linUnitsKey, str(amp['lin_units']))
333  # The current schema assumes third order coefficients
334  saveCoeffs = (float(amp['lin_coeffs']),)
335  saveCoeffs += (np.nan, np.nan, np.nan)
336  self.ampInfoDict[amp['ccd_name']]['linInfo'][amp['name']] = \
337  {'lincoeffs': saveCoeffs, 'lintype': str(amp['lin_type']),
338  'linthresh': float(amp['lin_thresh']), 'linmax': float(amp['lin_max']),
339  'linunits': str(amp['lin_units'])}
340  return ampTablesDict
341 
342  def makeTestRepositoryItems(self, isLsstLike=False):
343  """!Make camera config and amp catalog dictionary, using default detector and amp files
344 
345  @param[in] isLsstLike if True then there is one raw image per amplifier;
346  if False then there is one raw image per detector
347  """
348  detFile = os.path.join(self._afwTestDataDir, "testCameraDetectors.dat")
349  detectorConfigs = self.makeDetectorConfigs(detFile)
350  ampFile = os.path.join(self._afwTestDataDir, "testCameraAmps.dat")
351  ampCatalogDict = self.makeAmpCatalogs(ampFile, isLsstLike=isLsstLike)
352  camConfig = CameraConfig()
353  camConfig.name = "testCamera%s"%('LSST' if isLsstLike else 'SC')
354  camConfig.detectorList = dict((i, detConfig)
355  for i, detConfig in enumerate(detectorConfigs))
356  camConfig.plateScale = self.plateScale
357  pScaleRad = afwGeom.arcsecToRad(self.plateScale)
358  radialDistortCoeffs = [0.0, 1.0/pScaleRad,
359  0.0, self.radialDistortion/pScaleRad]
360  tConfig = afwGeom.TransformConfig()
361  tConfig.transform.name = 'inverted'
362  radialClass = afwGeom.transformRegistry['radial']
363  tConfig.transform.active.transform.retarget(radialClass)
364  tConfig.transform.active.transform.coeffs = radialDistortCoeffs
365  tmc = TransformMapConfig()
366  tmc.nativeSys = FOCAL_PLANE.getSysName()
367  tmc.transforms = {FIELD_ANGLE.getSysName(): tConfig}
368  camConfig.transformDict = tmc
369  return camConfig, ampCatalogDict
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:342
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
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'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:163
def makeAmpCatalogs(self, ampFile, isLsstLike=False)
Construct a list of AmpInfoCatalog, one per detector.
Definition: testUtils.py:209
std::shared_ptr< TransformPoint2ToPoint2 > makeRadialTransform(std::vector< double > const &forwardCoeffs, std::vector< double > const &inverseCoeffs)
A purely radial polynomial distortion.
Information about a CCD or other imaging detector.
Definition: Detector.h:63
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: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:167
def __init__(self, plateScale=20.0, radialDistortion=0.925, isLsstLike=False)
Construct a CameraWrapper.
Definition: testUtils.py:135