lsst.afw  14.0-52-g19103d347
fitsUtils.py
Go to the documentation of this file.
1 from __future__ import absolute_import, division, print_function
2 from builtins import object
3 import re
4 import warnings
5 import lsst.afw.image as afwImage
6 import lsst.afw.table as afwTable
7 from lsst.afw.fits import readMetadata
8 import lsst.afw.cameraGeom as afwCameraGeom
9 import lsst.afw.geom as afwGeom
10 
11 
12 def getByKey(metadata, key):
13  """Wrapper for getting a value from a metadata object by key.
14  @param[in] metadata metadata object to query for value
15  @param[in] key key to use for value lookup
16  @returns value associated with key, None if key does not exist
17  """
18  mdKeys = metadata.paramNames()
19  if key in mdKeys:
20  return metadata.get(key)
21  else:
22  return None
23 
24 
25 def setByKey(metadata, key, value, clobber):
26  """Wrapper for setting a value in a metadata object. Deals with case
27  where the key already exists.
28  @param[in, out] metadata metadata object ot modify in place.
29  @param[in] key key to associate with value
30  @param[in] value value to assign in the metadata object
31  @param[in] clobber Clobber the value if the key already exisists?
32  """
33  mdKeys = metadata.paramNames()
34  if key not in mdKeys or (key in mdKeys and clobber):
35  metadata.set(key, value)
36 
37 
38 class HeaderMap(dict):
39  """ Class to hold mapping of header cards to attributes"""
40 
41  def addEntry(self, keyname, attribute_name, default=None, transform=lambda x: x):
42  """Adds an entry to the registr
43  @param[in] keyname Key used to retrieve the header record
44  @param[in] attribute_name Name of the attribute to store the value in
45  @param[jn] default Default velue to store if the header card is not available
46  @param[in] transform Transform to apply to the header value before assigning it to the
47  attribute.
48  """
49  self.__setitem__(attribute_name, {'keyName': keyname,
50  'default': default,
51  'transform': transform})
52 
53  def setAttributes(self, obj, metadata, doRaise=True):
54  """Sets the attributes on the give object given a metadata object.
55  @param[in, out] obj Object on which to operate in place
56  @param[in] metadata Metadata object used for applying the mapping
57  @param[in] doRaise Raise exceptions on calling methods on the
58  input object that do not exist?
59  """
60  for key, attrDict in self.items():
61  try:
62  value = getByKey(metadata, attrDict['keyName'])
63  # if attrDict['keyName'] == "RDCRNR" and value == 0:
64  # import ipdb; ipdb.set_trace()
65  if value is not None:
66  self._applyVal(obj, value, key, attrDict['transform'])
67  else:
68  # Only apply transform if the metadata has a value for this key
69  # otherwise assume the default value is transformed.
70  value = attrDict['default']
71  self._applyVal(obj, value, key, lambda x: x)
72  except Exception as e:
73  if doRaise:
74  raise
75  else:
76  warnings.warn('WARNING: Failed to set %s attribute with %s value: %s' %
77  (key, value, str(e)))
78 
79  def _applyVal(self, obj, value, attrName, transform):
80  raise NotImplementedError('Must be implemented in sub-class')
81 
82 
84  """ Class to hold mapping of header cards to AmpInfoTable attributes
85  The amp info is stored using setters, thus calling the attribute as a function.
86  """
87 
88  def _applyVal(self, obj, value, attrName, transform):
89  getattr(obj, attrName)(transform(value))
90 
91 
93  """ Class to hold mapping of header cards to Detector attributes
94  Detector information is stored as attributes on a Config object.
95  """
96 
97  def _applyVal(self, obj, value, attrName, transform):
98  obj.__setattr__(attrName, transform(value))
99 
100 
101 class DetectorBuilder(object):
102  def __init__(self, detectorFileName, ampFileNameList, inAmpCoords=True, plateScale=1.,
103  radialCoeffs=(0., 1.), clobberMetadata=False, doRaise=True):
104  ''' @param[in] detectorFileName FITS file containing the detector description.
105  May use [] notation to specify an extension in an MEF.
106  @param[in] ampFileNameList List of FITS file names to use in building the amps.
107  May contain duplicate entries if the raw data are assembled.
108  @param[in] inAmpCoords Boolean, True if raw data are in amp coordinates, False if raw data
109  are assembled into pseudo detector pixel arrays
110  @param[in] plateScale Nominal platescale (arcsec/mm)
111  @param[in] radialCoeffs Radial distortion coefficients for a radial polynomial in normalized
112  units.
113  @param[in] clobberMetadata Clobber metadata from input files if
114  overridden in the _sanitizeMetadata method
115  @param[in] doRaise Raise exception if not all non-defaulted
116  keywords are defined? Default is True.
117  '''
118  self.inAmpCoords = inAmpCoords
121  self.detectorMetadata = readMetadata(detectorFileName)
123  self.detectorMetadata, clobber=clobberMetadata)
124  self.ampMetadataList = []
125  self.detector = None
126  self.doRaise = doRaise
127  for fileName in ampFileNameList:
128  self.ampMetadataList.append(readMetadata(fileName))
130  self.ampMetadataList[-1], clobber=clobberMetadata)
131  self.plateScale = plateScale
132  self.focalPlaneToField = self._makeRadialTransform(radialCoeffs)
133 
134  def _sanitizeHeaderMetadata(self, metadata, clobber):
135  """This method is called for all metadata and gives an opportunity to add/modify
136  header information for use downstream.
137  Override this method if more than the default is needed.
138  @param[in, out] metadata Metadata to read/modify
139  @param[in] clobber Clobber keys that exist with default keys?
140  """
141  self._defaultSanitization(metadata, clobber)
142 
143  def _defaultSanitization(self, metadata, clobber):
144  """Does the default sanitization of the header metadata.
145  @param[in,out] metadata Header metadata to extend/modify
146  @param[in] clobber Override values in existing header cards?
147  """
148 
149  if self.inAmpCoords:
150  # Deal with DTM to get flipX and flipY for assembly and add as 'FLIPX', 'FLIPY'
151  # The DTM array is a transformation matrix. As I understand it, it transforms between
152  # electronic and assembled coordintates. As such, a negative value in the DTM1_1 spot
153  # corresponds to a flip of the x-axis and a negative value in the DTM2_2 spot
154  # corresponds to a flip of the y-axis.
155  dtm1 = getByKey(metadata, 'DTM1_1')
156  dtm2 = getByKey(metadata, 'DTM2_2')
157  if dtm1 is not None and dtm2 is not None:
158  setByKey(metadata, 'FLIPX', dtm1 < 0, clobber)
159  setByKey(metadata, 'FLIPY', dtm2 < 0, clobber)
160  setByKey(metadata, 'RDCRNR', int(
161  afwTable.ReadoutCorner.LL), clobber)
162  else:
163  setByKey(metadata, 'FLIPX', False, clobber)
164  setByKey(metadata, 'FLIPY', True, clobber)
165  # I don't know how to figure out the read corner if already
166  # assembled
167  setByKey(metadata, 'RDCRNR', None, clobber)
168 
169  # Deal with NAXIS1, NAXIS2 to make rawBBox as 'RAWBBOX'
170  xext = getByKey(metadata, 'NAXIS1')
171  yext = getByKey(metadata, 'NAXIS2')
172  if xext is not None and yext is not None:
173  setByKey(metadata, 'RAWBBOX', '[%i:%i,%i:%i]'%(
174  1, xext, 1, yext), clobber)
175  # Deal with DTV1, DTV2 to make 'XYOFF
176  dtv1 = getByKey(metadata, 'DTV1')
177  dtv2 = getByKey(metadata, 'DTV2')
178  if dtv1 is not None and dtv2 is not None:
179  setByKey(metadata, 'XYOFF', [dtv1, dtv2], clobber)
180  # map biassec[1] to HOSCAN
181  # map biassec[3] to VOSCAN
182  # map biassec[2] to PRESCAN
183  if metadata.isArray('BIASSEC'):
184  keylist = ['HOSCAN', 'PRESCAN', 'VOSCAN']
185  biassecs = getByKey(metadata, 'BIASSEC')
186  for i, biassec in enumerate(biassecs):
187  setByKey(metadata, keylist[i], biassec, clobber)
188  else:
189  biassec = getByKey(metadata, 'BIASSEC')
190  if biassec is not None:
191  setByKey(metadata, 'HOSCAN', biassec, clobber)
192 
193  def _makeDefaultAmpMap(self):
194  """Make the default map from header information to amplifier information
195  @return The HeaderAmpMap object containing the mapping
196  """
197  hMap = HeaderAmpMap()
198  emptyBBox = afwGeom.BoxI()
199  mapList = [('EXTNAME', 'setName'),
200  ('DETSEC', 'setBBox', None, self._makeBbox),
201  ('GAIN', 'setGain', 1.),
202  ('RDNOISE', 'setReadNoise', 0.),
203  ('SATURATE', 'setSaturation', 2 << 15),
204  ('RDCRNR', 'setReadoutCorner', int(
205  afwTable.ReadoutCorner.LL), afwTable.ReadoutCorner),
206  ('LINCOEFF', 'setLinearityCoeffs', [0., 1.]),
207  ('LINTYPE', 'setLinearityType', 'POLY'),
208  ('RAWBBOX', 'setRawBBox', None, self._makeBbox),
209  ('DATASEC', 'setRawDataBBox', None, self._makeBbox),
210  ('FLIPX', 'setRawFlipX', False),
211  ('FLIPY', 'setRawFlipY', False),
212  ('XYOFF', 'setRawXYOffset', afwGeom.ExtentI(0, 0), self._makeExt),
213  ('HOSCAN', 'setRawHorizontalOverscanBBox',
214  emptyBBox, self._makeBbox),
215  ('VOSCAN', 'setRawVerticalOverscanBBox',
216  emptyBBox, self._makeBbox),
217  ('PRESCAN', 'setRawPrescanBBox', emptyBBox, self._makeBbox),
218  ]
219  for tup in mapList:
220  hMap.addEntry(*tup)
221  return hMap
222 
223  def _makeDefaultDetectorMap(self):
224  """Make the default map from header information to detector information
225  @return The HeaderDetectorMap object containing the mapping
226  """
227  hMap = HeaderDetectorMap()
228  mapList = [('CCDNAME', 'name', 'ccdName'),
229  ('DETSIZE', 'bbox_x0', 0, self._getBboxX0),
230  ('DETSIZE', 'bbox_y0', 0, self._getBboxY0),
231  ('DETSIZE', 'bbox_x1', 0, self._getBboxX1),
232  ('DETSIZE', 'bbox_y1', 0, self._getBboxY1),
233  ('DETID', 'id', 0),
234  # DetectorConfig.detectorType is of type `int`, not
235  # `DetectorType`
236  ('OBSTYPE', 'detectorType', int(
237  afwCameraGeom.DetectorType.SCIENCE)),
238  ('SERSTR', 'serial', 'none'),
239  ('XPOS', 'offset_x', 0.),
240  ('YPOS', 'offset_y', 0.),
241  ('XPIX', 'refpos_x', 0.),
242  ('YPIX', 'refpos_y', 0.),
243  ('YAWDEG', 'yawDeg', 0.),
244  ('PITCHDEG', 'pitchDeg', 0.),
245  ('ROLLDEG', 'rollDeg', 0.),
246  ('XPIXSIZE', 'pixelSize_x', 1.),
247  ('YPIXSIZE', 'pixelSize_y', 1.),
248  ('TRNSPOSE', 'transposeDetector', False),
249  ]
250  for tup in mapList:
251  hMap.addEntry(*tup)
252  return hMap
253 
254  def _makeExt(self, extArr):
255  """Helper function to make an extent from an array
256  @param[in] extArr Length 2 array to use in creating the Extent object
257  @return Extent2I constructed from the input list
258  """
259  return afwGeom.ExtentI(*extArr)
260 
261  def _makeBbox(self, boxString):
262  """Helper funtion to make a bounding box from a string representing a FITS style bounding box
263  @param[in] boxString String describing the bounding box
264  @return Box2I for the bounding box
265  """
266  # strip off brackets and split into parts
267  x1, x2, y1, y2 = [int(el) for el in re.split(
268  '[:,]', boxString.strip()[1:-1])]
269  box = afwGeom.BoxI(afwGeom.PointI(x1, y1), afwGeom.PointI(x2, y2))
270  # account for the difference between FITS convention and LSST convention for
271  # index of LLC.
272  box.shift(afwGeom.Extent2I(-1, -1))
273  return box
274 
275  def _getBboxX0(self, boxString):
276  return self._makeBbox(boxString).getMinX()
277 
278  def _getBboxX1(self, boxString):
279  return self._makeBbox(boxString).getMaxX()
280 
281  def _getBboxY0(self, boxString):
282  return self._makeBbox(boxString).getMinY()
283 
284  def _getBboxY1(self, boxString):
285  return self._makeBbox(boxString).getMaxY()
286 
287  def _makeRadialTransform(self, radialCoeffs):
288  """Helper function to get the radial transform given the radial polynomial coefficients given in
289  the constructor.
290  @param[in] radialCoeffs List of coefficients describing a polynomial radial distortion in
291  normalized units.
292  @return Transform object describing the radial distortion
293  """
294  pScaleRad = afwGeom.arcsecToRad(self.plateScale)
295  return afwGeom.makeRadialTransform([el/pScaleRad for el in radialCoeffs])
296 
297  def buildDetector(self):
298  """Take all the information and build a Detector object. The Detector object is necessary for doing
299  things like assembly.
300  @return Detector object
301  """
302  if self.detector is not None:
303  return self.detector
304 
305  schema = afwTable.AmpInfoTable.makeMinimalSchema()
306  ampInfo = afwTable.AmpInfoCatalog(schema)
307  for ampMetadata in self.ampMetadataList:
308  record = ampInfo.addNew()
309  self.defaultAmpMap.setAttributes(record, ampMetadata, self.doRaise)
310  record.setHasRawInfo(True)
311 
312  detConfig = afwCameraGeom.DetectorConfig()
313  self.defaultDetectorMap.setAttributes(
314  detConfig, self.detectorMetadata, self.doRaise)
315  self.detector = afwCameraGeom.makeDetector(
316  detConfig, ampInfo, self.focalPlaneToField)
317  return self.detector
318 
319  def makeCalib(self):
320  """PLaceholder for subclasses to implement construction of a calib to associate with the exposure.
321  @return empty afwImage.Calib object
322  """
323  return afwImage.Calib()
324 
325  def makeExposure(self, im, mask=None, variance=None):
326  """Method for constructing an exposure object from an image and the information contained in this
327  class to construct the Detector and Calib objects.
328  @param[in] im Image used to construct the exposure
329  @param[in] mask Optional mask plane as a <askU
330  @param[in] variance Optional variance plance as an image of the same type as im
331  @param[out] Exposure object
332  """
333  if mask is None:
334  mask = afwImage.Mask(im.getDimensions())
335  if variance is None:
336  variance = im
337  mi = afwImage.makeMaskedImage(im, mask, variance)
338  detector = self.buildDetector()
339 
340  calib = self.makeCalib()
341  exp = afwImage.makeExposure(mi)
342  exp.setCalib(calib)
343  exp.setDetector(detector)
344  return exp
def makeExposure(self, im, mask=None, variance=None)
Definition: fitsUtils.py:325
def _makeRadialTransform(self, radialCoeffs)
Definition: fitsUtils.py:287
def addEntry(self, keyname, attribute_name, default=None, transform=lambda x:x)
Definition: fitsUtils.py:41
std::shared_ptr< TransformPoint2ToPoint2 > makeRadialTransform(std::vector< double > const &forwardCoeffs, std::vector< double > const &inverseCoeffs)
A purely radial polynomial distortion.
Describe an exposure&#39;s calibration.
Definition: Calib.h:96
MaskedImage< ImagePixelT, MaskPixelT, VariancePixelT > * makeMaskedImage(typename std::shared_ptr< Image< ImagePixelT >> image, typename std::shared_ptr< Mask< MaskPixelT >> mask=Mask< MaskPixelT >(), typename std::shared_ptr< Image< VariancePixelT >> variance=Image< VariancePixelT >())
A function to return a MaskedImage of the correct type (cf.
Definition: MaskedImage.h:1268
def _defaultSanitization(self, metadata, clobber)
Definition: fitsUtils.py:143
An integer coordinate rectangle.
Definition: Box.h:55
std::shared_ptr< Exposure< ImagePixelT, MaskPixelT, VariancePixelT > > makeExposure(MaskedImage< ImagePixelT, MaskPixelT, VariancePixelT > &mimage, std::shared_ptr< geom::SkyWcs const > wcs=std::shared_ptr< geom::SkyWcs const >())
A function to return an Exposure of the correct type (cf.
Definition: Exposure.h:414
def _sanitizeHeaderMetadata(self, metadata, clobber)
Definition: fitsUtils.py:134
Represent a 2-dimensional array of bitmask pixels.
Definition: Mask.h:84
def getByKey(metadata, key)
Definition: fitsUtils.py:12
def _applyVal(self, obj, value, attrName, transform)
Definition: fitsUtils.py:79
constexpr double arcsecToRad(double x) noexcept
Definition: Angle.h:37
def setAttributes(self, obj, metadata, doRaise=True)
Definition: fitsUtils.py:53
table::Key< int > transform
def __init__(self, detectorFileName, ampFileNameList, inAmpCoords=True, plateScale=1., radialCoeffs=(0., 1.), clobberMetadata=False, doRaise=True)
Definition: fitsUtils.py:103
def setByKey(metadata, key, value, clobber)
Definition: fitsUtils.py:25