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