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