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