LSST Applications  21.0.0-172-gfb10e10a+18fedfabac,22.0.0+297cba6710,22.0.0+80564b0ff1,22.0.0+8d77f4f51a,22.0.0+a28f4c53b1,22.0.0+dcf3732eb2,22.0.1-1-g7d6de66+2a20fdde0d,22.0.1-1-g8e32f31+297cba6710,22.0.1-1-geca5380+7fa3b7d9b6,22.0.1-12-g44dc1dc+2a20fdde0d,22.0.1-15-g6a90155+515f58c32b,22.0.1-16-g9282f48+790f5f2caa,22.0.1-2-g92698f7+dcf3732eb2,22.0.1-2-ga9b0f51+7fa3b7d9b6,22.0.1-2-gd1925c9+bf4f0e694f,22.0.1-24-g1ad7a390+a9625a72a8,22.0.1-25-g5bf6245+3ad8ecd50b,22.0.1-25-gb120d7b+8b5510f75f,22.0.1-27-g97737f7+2a20fdde0d,22.0.1-32-gf62ce7b1+aa4237961e,22.0.1-4-g0b3f228+2a20fdde0d,22.0.1-4-g243d05b+871c1b8305,22.0.1-4-g3a563be+32dcf1063f,22.0.1-4-g44f2e3d+9e4ab0f4fa,22.0.1-42-gca6935d93+ba5e5ca3eb,22.0.1-5-g15c806e+85460ae5f3,22.0.1-5-g58711c4+611d128589,22.0.1-5-g75bb458+99c117b92f,22.0.1-6-g1c63a23+7fa3b7d9b6,22.0.1-6-g50866e6+84ff5a128b,22.0.1-6-g8d3140d+720564cf76,22.0.1-6-gd805d02+cc5644f571,22.0.1-8-ge5750ce+85460ae5f3,master-g6e05de7fdc+babf819c66,master-g99da0e417a+8d77f4f51a,w.2021.48
LSST Data Management Base Package
Public Member Functions | Public Attributes | List of all members
lsst.ip.isr.defects.Defects Class Reference
Inheritance diagram for lsst.ip.isr.defects.Defects:
lsst.ip.isr.calibType.IsrCalib

Public Member Functions

def __init__ (self, defectList=None, metadata=None, *normalize_on_init=True, **kwargs)
 
def __len__ (self)
 
def __getitem__ (self, index)
 
def __setitem__ (self, index, value)
 
def __iter__ (self)
 
def __delitem__ (self, index)
 
def __eq__ (self, other)
 
def __str__ (self)
 
def bulk_update (self)
 
def append (self, value)
 
def insert (self, index, value)
 
def copy (self)
 
def transpose (self)
 
def maskPixels (self, maskedImage, maskName="BAD")
 
def toFitsRegionTable (self)
 
def fromDict (cls, dictionary)
 
def toDict (self)
 
def toTable (self)
 
def fromTable (cls, tableList, normalize_on_init=True)
 
def readLsstDefectsFile (cls, filename, normalize_on_init=False)
 
def fromFootprintList (cls, fpList)
 
def fromMask (cls, maskedImage, maskName)
 
def requiredAttributes (self)
 
def requiredAttributes (self, value)
 
def getMetadata (self)
 
def setMetadata (self, metadata)
 
def updateMetadata (self, camera=None, detector=None, filterName=None, setCalibId=False, setCalibInfo=False, setDate=False, **kwargs)
 
def calibInfoFromDict (self, dictionary)
 
def determineCalibClass (cls, metadata, message)
 
def readText (cls, filename, **kwargs)
 
def writeText (self, filename, format="auto")
 
def readFits (cls, filename, **kwargs)
 
def writeFits (self, filename)
 
def fromDetector (self, detector)
 
def fromDict (cls, dictionary, **kwargs)
 
def fromTable (cls, tableList, **kwargs)
 
def validate (self, other=None)
 
def apply (self, target)
 

Public Attributes

 requiredAttributes
 
 log
 

Detailed Description

Calibration handler for collections of `lsst.meas.algorithms.Defect`.

Parameters
----------
defectList : iterable of `lsst.meas.algorithms.Defect`
             or `lsst.geom.BoxI`, optional
    Collections of defects to apply to the image.
metadata : `lsst.daf.base.PropertyList`, optional
    Metadata to associate with the defects.  Will be copied and
    overwrite existing metadata, if any. If not supplied the existing
    metadata will be reset.
normalize_on_init : `bool`
    If True, normalization is applied to the defects in ``defectList`` to
    remove duplicates, eliminate overlaps, etc.

Notes
-----
Defects are stored within this collection in a "reduced" or "normalized"
form: rather than simply storing the bounding boxes which are added to the
collection, we eliminate overlaps and duplicates. This normalization
procedure may introduce overhead when adding many new defects; it may be
temporarily disabled using the `Defects.bulk_update` context manager if
necessary.

The attributes stored in this calibration are:

_defects : `list` [`lsst.meas.algorithms.Defect`]
    The collection of Defect objects.
The calibration type used for ingest.

Definition at line 47 of file defects.py.

Constructor & Destructor Documentation

◆ __init__()

def lsst.ip.isr.defects.Defects.__init__ (   self,
  defectList = None,
  metadata = None,
normalize_on_init = True,
**  kwargs 
)

Definition at line 83 of file defects.py.

83  def __init__(self, defectList=None, metadata=None, *, normalize_on_init=True, **kwargs):
84  self._defects = []
85 
86  if defectList is not None:
87  self._bulk_update = True
88  for d in defectList:
89  self.append(d)
90  self._bulk_update = False
91 
92  if normalize_on_init:
93  self._normalize()
94 
95  super().__init__(**kwargs)
96  self.requiredAttributes.update(['_defects'])
97 

Member Function Documentation

◆ __delitem__()

def lsst.ip.isr.defects.Defects.__delitem__ (   self,
  index 
)

Definition at line 145 of file defects.py.

145  def __delitem__(self, index):
146  del self._defects[index]
147 

◆ __eq__()

def lsst.ip.isr.defects.Defects.__eq__ (   self,
  other 
)
Compare if two `Defects` are equal.

Two `Defects` are equal if their bounding boxes are equal and in
the same order.  Metadata content is ignored.

Reimplemented from lsst.ip.isr.calibType.IsrCalib.

Definition at line 148 of file defects.py.

148  def __eq__(self, other):
149  """Compare if two `Defects` are equal.
150 
151  Two `Defects` are equal if their bounding boxes are equal and in
152  the same order. Metadata content is ignored.
153  """
154  super().__eq__(other)
155 
156  if not isinstance(other, self.__class__):
157  return False
158 
159  # checking the bboxes with zip() only works if same length
160  if len(self) != len(other):
161  return False
162 
163  # Assume equal if bounding boxes are equal
164  for d1, d2 in zip(self, other):
165  if d1.getBBox() != d2.getBBox():
166  return False
167 
168  return True
169 

◆ __getitem__()

def lsst.ip.isr.defects.Defects.__getitem__ (   self,
  index 
)

Definition at line 133 of file defects.py.

133  def __getitem__(self, index):
134  return self._defects[index]
135 

◆ __iter__()

def lsst.ip.isr.defects.Defects.__iter__ (   self)

Definition at line 142 of file defects.py.

142  def __iter__(self):
143  return iter(self._defects)
144 

◆ __len__()

def lsst.ip.isr.defects.Defects.__len__ (   self)

Definition at line 130 of file defects.py.

130  def __len__(self):
131  return len(self._defects)
132 

◆ __setitem__()

def lsst.ip.isr.defects.Defects.__setitem__ (   self,
  index,
  value 
)
Can be given a `~lsst.meas.algorithms.Defect` or a `lsst.geom.BoxI`

Definition at line 136 of file defects.py.

136  def __setitem__(self, index, value):
137  """Can be given a `~lsst.meas.algorithms.Defect` or a `lsst.geom.BoxI`
138  """
139  self._defects[index] = self._check_value(value)
140  self._normalize()
141 

◆ __str__()

def lsst.ip.isr.defects.Defects.__str__ (   self)

Reimplemented from lsst.ip.isr.calibType.IsrCalib.

Definition at line 170 of file defects.py.

170  def __str__(self):
171  baseStr = super().__str__()
172  return baseStr + ",".join(str(d.getBBox()) for d in self) + ")"
173 

◆ append()

def lsst.ip.isr.defects.Defects.append (   self,
  value 
)

Definition at line 219 of file defects.py.

219  def append(self, value):
220  self._defects.append(self._check_value(value))
221  self._normalize()
222 
std::shared_ptr< FrameSet > append(FrameSet const &first, FrameSet const &second)
Construct a FrameSet that performs two transformations in series.
Definition: functional.cc:33

◆ apply()

def lsst.ip.isr.calibType.IsrCalib.apply (   self,
  target 
)
inherited
Method to apply the calibration to the target object.

Parameters
----------
target : `object`
    Thing to validate against.

Returns
-------
valid : `bool`
    Returns true if the calibration was applied correctly.

Raises
------
NotImplementedError :
    Raised if not implemented.

Definition at line 612 of file calibType.py.

612  def apply(self, target):
613  """Method to apply the calibration to the target object.
614 
615  Parameters
616  ----------
617  target : `object`
618  Thing to validate against.
619 
620  Returns
621  -------
622  valid : `bool`
623  Returns true if the calibration was applied correctly.
624 
625  Raises
626  ------
627  NotImplementedError :
628  Raised if not implemented.
629  """
630  raise NotImplementedError("Must be implemented by subclass.")
631 
632 

◆ bulk_update()

def lsst.ip.isr.defects.Defects.bulk_update (   self)
Temporarily suspend normalization of the defect list.

Definition at line 209 of file defects.py.

209  def bulk_update(self):
210  """Temporarily suspend normalization of the defect list.
211  """
212  self._bulk_update = True
213  try:
214  yield
215  finally:
216  self._bulk_update = False
217  self._normalize()
218 

◆ calibInfoFromDict()

def lsst.ip.isr.calibType.IsrCalib.calibInfoFromDict (   self,
  dictionary 
)
inherited
Handle common keywords.

This isn't an ideal solution, but until all calibrations
expect to find everything in the metadata, they still need to
search through dictionaries.

Parameters
----------
dictionary : `dict` or `lsst.daf.base.PropertyList`
    Source for the common keywords.

Raises
------
RuntimeError :
    Raised if the dictionary does not match the expected OBSTYPE.

Definition at line 261 of file calibType.py.

261  def calibInfoFromDict(self, dictionary):
262  """Handle common keywords.
263 
264  This isn't an ideal solution, but until all calibrations
265  expect to find everything in the metadata, they still need to
266  search through dictionaries.
267 
268  Parameters
269  ----------
270  dictionary : `dict` or `lsst.daf.base.PropertyList`
271  Source for the common keywords.
272 
273  Raises
274  ------
275  RuntimeError :
276  Raised if the dictionary does not match the expected OBSTYPE.
277 
278  """
279 
280  def search(haystack, needles):
281  """Search dictionary 'haystack' for an entry in 'needles'
282  """
283  test = [haystack.get(x) for x in needles]
284  test = set([x for x in test if x is not None])
285  if len(test) == 0:
286  if "metadata" in haystack:
287  return search(haystack["metadata"], needles)
288  else:
289  return None
290  elif len(test) == 1:
291  value = list(test)[0]
292  if value == "":
293  return None
294  else:
295  return value
296  else:
297  raise ValueError(f"Too many values found: {len(test)} {test} {needles}")
298 
299  if "metadata" in dictionary:
300  metadata = dictionary["metadata"]
301 
302  if self._OBSTYPE != metadata["OBSTYPE"]:
303  raise RuntimeError(f"Incorrect calibration supplied. Expected {self._OBSTYPE}, "
304  f"found {metadata['OBSTYPE']}")
305 
306  self._instrument = search(dictionary, ["INSTRUME", "instrument"])
307  self._raftName = search(dictionary, ["RAFTNAME"])
308  self._slotName = search(dictionary, ["SLOTNAME"])
309  self._detectorId = search(dictionary, ["DETECTOR", "detectorId"])
310  self._detectorName = search(dictionary, ["DET_NAME", "DETECTOR_NAME", "detectorName"])
311  self._detectorSerial = search(dictionary, ["DET_SER", "DETECTOR_SERIAL", "detectorSerial"])
312  self._filter = search(dictionary, ["FILTER", "filterName"])
313  self._calibId = search(dictionary, ["CALIB_ID"])
314 
daf::base::PropertyList * list
Definition: fits.cc:913
daf::base::PropertySet * set
Definition: fits.cc:912

◆ copy()

def lsst.ip.isr.defects.Defects.copy (   self)
Copy the defects to a new list, creating new defects from the
bounding boxes.

Returns
-------
new : `Defects`
    New list with new `Defect` entries.

Notes
-----
This is not a shallow copy in that new `Defect` instances are
created from the original bounding boxes.  It's also not a deep
copy since the bounding boxes are not recreated.

Definition at line 227 of file defects.py.

227  def copy(self):
228  """Copy the defects to a new list, creating new defects from the
229  bounding boxes.
230 
231  Returns
232  -------
233  new : `Defects`
234  New list with new `Defect` entries.
235 
236  Notes
237  -----
238  This is not a shallow copy in that new `Defect` instances are
239  created from the original bounding boxes. It's also not a deep
240  copy since the bounding boxes are not recreated.
241  """
242  return self.__class__(d.getBBox() for d in self)
243 

◆ determineCalibClass()

def lsst.ip.isr.calibType.IsrCalib.determineCalibClass (   cls,
  metadata,
  message 
)
inherited
Attempt to find calibration class in metadata.

Parameters
----------
metadata : `dict` or `lsst.daf.base.PropertyList`
    Metadata possibly containing a calibration class entry.
message : `str`
    Message to include in any errors.

Returns
-------
calibClass : `object`
    The class to use to read the file contents.  Should be an
    `lsst.ip.isr.IsrCalib` subclass.

Raises
------
ValueError :
    Raised if the resulting calibClass is the base
    `lsst.ip.isr.IsrClass` (which does not implement the
    content methods).

Definition at line 316 of file calibType.py.

316  def determineCalibClass(cls, metadata, message):
317  """Attempt to find calibration class in metadata.
318 
319  Parameters
320  ----------
321  metadata : `dict` or `lsst.daf.base.PropertyList`
322  Metadata possibly containing a calibration class entry.
323  message : `str`
324  Message to include in any errors.
325 
326  Returns
327  -------
328  calibClass : `object`
329  The class to use to read the file contents. Should be an
330  `lsst.ip.isr.IsrCalib` subclass.
331 
332  Raises
333  ------
334  ValueError :
335  Raised if the resulting calibClass is the base
336  `lsst.ip.isr.IsrClass` (which does not implement the
337  content methods).
338  """
339  calibClassName = metadata.get("CALIBCLS")
340  calibClass = doImport(calibClassName) if calibClassName is not None else cls
341  if calibClass is IsrCalib:
342  raise ValueError(f"Cannot use base class to read calibration data: {msg}")
343  return calibClass
344 

◆ fromDetector()

def lsst.ip.isr.calibType.IsrCalib.fromDetector (   self,
  detector 
)
inherited
Modify the calibration parameters to match the supplied detector.

Parameters
----------
detector : `lsst.afw.cameraGeom.Detector`
    Detector to use to set parameters from.

Raises
------
NotImplementedError
    This needs to be implemented by subclasses for each
    calibration type.

Reimplemented in lsst.ip.isr.linearize.Linearizer.

Definition at line 495 of file calibType.py.

495  def fromDetector(self, detector):
496  """Modify the calibration parameters to match the supplied detector.
497 
498  Parameters
499  ----------
500  detector : `lsst.afw.cameraGeom.Detector`
501  Detector to use to set parameters from.
502 
503  Raises
504  ------
505  NotImplementedError
506  This needs to be implemented by subclasses for each
507  calibration type.
508  """
509  raise NotImplementedError("Must be implemented by subclass.")
510 

◆ fromDict() [1/2]

def lsst.ip.isr.defects.Defects.fromDict (   cls,
  dictionary 
)
Construct a calibration from a dictionary of properties.

Must be implemented by the specific calibration subclasses.

Parameters
----------
dictionary : `dict`
    Dictionary of properties.

Returns
-------
calib : `lsst.ip.isr.CalibType`
    Constructed calibration.

Raises
------
RuntimeError :
    Raised if the supplied dictionary is for a different
    calibration.

Definition at line 333 of file defects.py.

333  def fromDict(cls, dictionary):
334  """Construct a calibration from a dictionary of properties.
335 
336  Must be implemented by the specific calibration subclasses.
337 
338  Parameters
339  ----------
340  dictionary : `dict`
341  Dictionary of properties.
342 
343  Returns
344  -------
345  calib : `lsst.ip.isr.CalibType`
346  Constructed calibration.
347 
348  Raises
349  ------
350  RuntimeError :
351  Raised if the supplied dictionary is for a different
352  calibration.
353  """
354  calib = cls()
355 
356  if calib._OBSTYPE != dictionary['metadata']['OBSTYPE']:
357  raise RuntimeError(f"Incorrect crosstalk supplied. Expected {calib._OBSTYPE}, "
358  f"found {dictionary['metadata']['OBSTYPE']}")
359 
360  calib.setMetadata(dictionary['metadata'])
361  calib.calibInfoFromDict(dictionary)
362 
363  xCol = dictionary['x0']
364  yCol = dictionary['y0']
365  widthCol = dictionary['width']
366  heightCol = dictionary['height']
367 
368  with calib.bulk_update:
369  for x0, y0, width, height in zip(xCol, yCol, widthCol, heightCol):
370  calib.append(lsst.geom.Box2I(lsst.geom.Point2I(x0, y0),
371  lsst.geom.Extent2I(width, height)))
372  return calib
373 
An integer coordinate rectangle.
Definition: Box.h:55

◆ fromDict() [2/2]

def lsst.ip.isr.calibType.IsrCalib.fromDict (   cls,
  dictionary,
**  kwargs 
)
inherited
Construct a calibration from a dictionary of properties.

Must be implemented by the specific calibration subclasses.

Parameters
----------
dictionary : `dict`
    Dictionary of properties.
kwargs : `dict` or collections.abc.Mapping`, optional
    Set of key=value options.

Returns
------
calib : `lsst.ip.isr.CalibType`
    Constructed calibration.

Raises
------
NotImplementedError :
    Raised if not implemented.

Definition at line 512 of file calibType.py.

512  def fromDict(cls, dictionary, **kwargs):
513  """Construct a calibration from a dictionary of properties.
514 
515  Must be implemented by the specific calibration subclasses.
516 
517  Parameters
518  ----------
519  dictionary : `dict`
520  Dictionary of properties.
521  kwargs : `dict` or collections.abc.Mapping`, optional
522  Set of key=value options.
523 
524  Returns
525  ------
526  calib : `lsst.ip.isr.CalibType`
527  Constructed calibration.
528 
529  Raises
530  ------
531  NotImplementedError :
532  Raised if not implemented.
533  """
534  raise NotImplementedError("Must be implemented by subclass.")
535 

◆ fromFootprintList()

def lsst.ip.isr.defects.Defects.fromFootprintList (   cls,
  fpList 
)
Compute a defect list from a footprint list, optionally growing
the footprints.

Parameters
----------
fpList : `list` of `lsst.afw.detection.Footprint`
    Footprint list to process.

Returns
-------
defects : `Defects`
    List of defects.

Definition at line 642 of file defects.py.

642  def fromFootprintList(cls, fpList):
643  """Compute a defect list from a footprint list, optionally growing
644  the footprints.
645 
646  Parameters
647  ----------
648  fpList : `list` of `lsst.afw.detection.Footprint`
649  Footprint list to process.
650 
651  Returns
652  -------
653  defects : `Defects`
654  List of defects.
655  """
656  # normalize_on_init is set to False to avoid recursively calling
657  # fromMask/fromFootprintList in Defects.__init__.
658  return cls(itertools.chain.from_iterable(lsst.afw.detection.footprintToBBoxList(fp)
659  for fp in fpList), normalize_on_init=False)
660 
std::vector< lsst::geom::Box2I > footprintToBBoxList(Footprint const &footprint)
Return a list of BBoxs, whose union contains exactly the pixels in the footprint, neither more nor le...
Definition: Footprint.cc:352

◆ fromMask()

def lsst.ip.isr.defects.Defects.fromMask (   cls,
  maskedImage,
  maskName 
)
Compute a defect list from a specified mask plane.

Parameters
----------
maskedImage : `lsst.afw.image.MaskedImage`
    Image to process.
maskName : `str` or `list`
    Mask plane name, or list of names to convert.

Returns
-------
defects : `Defects`
    Defect list constructed from masked pixels.

Definition at line 662 of file defects.py.

662  def fromMask(cls, maskedImage, maskName):
663  """Compute a defect list from a specified mask plane.
664 
665  Parameters
666  ----------
667  maskedImage : `lsst.afw.image.MaskedImage`
668  Image to process.
669  maskName : `str` or `list`
670  Mask plane name, or list of names to convert.
671 
672  Returns
673  -------
674  defects : `Defects`
675  Defect list constructed from masked pixels.
676  """
677  mask = maskedImage.getMask()
678  thresh = lsst.afw.detection.Threshold(mask.getPlaneBitMask(maskName),
679  lsst.afw.detection.Threshold.BITMASK)
680  fpList = lsst.afw.detection.FootprintSet(mask, thresh).getFootprints()
681  return cls.fromFootprintList(fpList)
A set of Footprints, associated with a MaskedImage.
Definition: FootprintSet.h:53
A Threshold is used to pass a threshold value to detection algorithms.
Definition: Threshold.h:43

◆ fromTable() [1/2]

def lsst.ip.isr.calibType.IsrCalib.fromTable (   cls,
  tableList,
**  kwargs 
)
inherited
Construct a calibration from a dictionary of properties.

Must be implemented by the specific calibration subclasses.

Parameters
----------
tableList : `list` [`lsst.afw.table.Table`]
    List of tables of properties.
kwargs : `dict` or collections.abc.Mapping`, optional
    Set of key=value options.

Returns
------
calib : `lsst.ip.isr.CalibType`
    Constructed calibration.

Raises
------
NotImplementedError :
    Raised if not implemented.

Definition at line 555 of file calibType.py.

555  def fromTable(cls, tableList, **kwargs):
556  """Construct a calibration from a dictionary of properties.
557 
558  Must be implemented by the specific calibration subclasses.
559 
560  Parameters
561  ----------
562  tableList : `list` [`lsst.afw.table.Table`]
563  List of tables of properties.
564  kwargs : `dict` or collections.abc.Mapping`, optional
565  Set of key=value options.
566 
567  Returns
568  ------
569  calib : `lsst.ip.isr.CalibType`
570  Constructed calibration.
571 
572  Raises
573  ------
574  NotImplementedError :
575  Raised if not implemented.
576  """
577  raise NotImplementedError("Must be implemented by subclass.")
578 

◆ fromTable() [2/2]

def lsst.ip.isr.defects.Defects.fromTable (   cls,
  tableList,
  normalize_on_init = True 
)
Construct a `Defects` from the contents of a
`~lsst.afw.table.BaseCatalog`.

Parameters
----------
table : `lsst.afw.table.BaseCatalog`
    Table with one row per defect.
normalize_on_init : `bool`, optional
    If `True`, normalization is applied to the defects listed in the
    table to remove duplicates, eliminate overlaps, etc. Otherwise
    the defects in the returned object exactly match those in the
    table.

Returns
-------
defects : `Defects`
    A `Defects` list.

Notes
-----
Two table formats are recognized.  The first is the
`FITS regions <https://fits.gsfc.nasa.gov/registry/region.html>`_
definition tabular format written by `toFitsRegionTable` where the
pixel origin is corrected from FITS 1-based to a 0-based origin.
The second is the legacy defects format using columns ``x0``, ``y0``
(bottom left hand pixel of box in 0-based coordinates), ``width``
and ``height``.

The FITS standard regions can only read BOX, POINT, or ROTBOX with
a zero degree rotation.

Definition at line 493 of file defects.py.

493  def fromTable(cls, tableList, normalize_on_init=True):
494  """Construct a `Defects` from the contents of a
495  `~lsst.afw.table.BaseCatalog`.
496 
497  Parameters
498  ----------
499  table : `lsst.afw.table.BaseCatalog`
500  Table with one row per defect.
501  normalize_on_init : `bool`, optional
502  If `True`, normalization is applied to the defects listed in the
503  table to remove duplicates, eliminate overlaps, etc. Otherwise
504  the defects in the returned object exactly match those in the
505  table.
506 
507  Returns
508  -------
509  defects : `Defects`
510  A `Defects` list.
511 
512  Notes
513  -----
514  Two table formats are recognized. The first is the
515  `FITS regions <https://fits.gsfc.nasa.gov/registry/region.html>`_
516  definition tabular format written by `toFitsRegionTable` where the
517  pixel origin is corrected from FITS 1-based to a 0-based origin.
518  The second is the legacy defects format using columns ``x0``, ``y0``
519  (bottom left hand pixel of box in 0-based coordinates), ``width``
520  and ``height``.
521 
522  The FITS standard regions can only read BOX, POINT, or ROTBOX with
523  a zero degree rotation.
524  """
525  table = tableList[0]
526  defectList = []
527 
528  schema = table.columns
529  # Check schema to see which definitions we have
530  if "X" in schema and "Y" in schema and "R" in schema and "SHAPE" in schema:
531  # This is a FITS region style table
532  isFitsRegion = True
533  elif "x0" in schema and "y0" in schema and "width" in schema and "height" in schema:
534  # This is a classic LSST-style defect table
535  isFitsRegion = False
536  else:
537  raise ValueError("Unsupported schema for defects extraction")
538 
539  for record in table:
540  if isFitsRegion:
541  # Coordinates can be arrays (some shapes in the standard
542  # require this)
543  # Correct for FITS 1-based origin
544  xcen = cls._get_values(record['X']) - 1.0
545  ycen = cls._get_values(record['Y']) - 1.0
546  shape = record['SHAPE'].upper().rstrip()
547  if shape == "BOX":
549  lsst.geom.Extent2I(cls._get_values(record['R'],
550  n=2)))
551  elif shape == "POINT":
552  # Handle the case where we have an externally created
553  # FITS file.
554  box = lsst.geom.Point2I(xcen, ycen)
555  elif shape == "ROTBOX":
556  # Astropy regions always writes ROTBOX
557  rotang = cls._get_values(record['ROTANG'])
558  # We can support 0 or 90 deg
559  if math.isclose(rotang % 90.0, 0.0):
560  # Two values required
561  r = cls._get_values(record['R'], n=2)
562  if math.isclose(rotang % 180.0, 0.0):
563  width = r[0]
564  height = r[1]
565  else:
566  width = r[1]
567  height = r[0]
569  lsst.geom.Extent2I(width, height))
570  else:
571  log.warning("Defect can not be defined using ROTBOX with non-aligned rotation angle")
572  continue
573  else:
574  log.warning("Defect lists can only be defined using BOX or POINT not %s", shape)
575  continue
576 
577  else:
578  # This is a classic LSST-style defect table
579  box = lsst.geom.Box2I(lsst.geom.Point2I(record['x0'], record['y0']),
580  lsst.geom.Extent2I(record['width'], record['height']))
581 
582  defectList.append(box)
583 
584  defects = cls(defectList, normalize_on_init=normalize_on_init)
585  newMeta = dict(table.meta)
586  defects.updateMetadata(setCalibInfo=True, **newMeta)
587 
588  return defects
589 
static Box2I makeCenteredBox(Point2D const &center, Extent const &size)
Create a box centered as closely as possible on a particular point.
Definition: Box.cc:97

◆ getMetadata()

def lsst.ip.isr.calibType.IsrCalib.getMetadata (   self)
inherited
Retrieve metadata associated with this calibration.

Returns
-------
meta : `lsst.daf.base.PropertyList`
    Metadata. The returned `~lsst.daf.base.PropertyList` can be
    modified by the caller and the changes will be written to
    external files.

Definition at line 145 of file calibType.py.

145  def getMetadata(self):
146  """Retrieve metadata associated with this calibration.
147 
148  Returns
149  -------
150  meta : `lsst.daf.base.PropertyList`
151  Metadata. The returned `~lsst.daf.base.PropertyList` can be
152  modified by the caller and the changes will be written to
153  external files.
154  """
155  return self._metadata
156 

◆ insert()

def lsst.ip.isr.defects.Defects.insert (   self,
  index,
  value 
)

Definition at line 223 of file defects.py.

223  def insert(self, index, value):
224  self._defects.insert(index, self._check_value(value))
225  self._normalize()
226 

◆ maskPixels()

def lsst.ip.isr.defects.Defects.maskPixels (   self,
  maskedImage,
  maskName = "BAD" 
)
Set mask plane based on these defects.

Parameters
----------
maskedImage : `lsst.afw.image.MaskedImage`
    Image to process.  Only the mask plane is updated.
maskName : str, optional
    Mask plane name to use.

Definition at line 261 of file defects.py.

261  def maskPixels(self, maskedImage, maskName="BAD"):
262  """Set mask plane based on these defects.
263 
264  Parameters
265  ----------
266  maskedImage : `lsst.afw.image.MaskedImage`
267  Image to process. Only the mask plane is updated.
268  maskName : str, optional
269  Mask plane name to use.
270  """
271  # mask bad pixels
272  mask = maskedImage.getMask()
273  bitmask = mask.getPlaneBitMask(maskName)
274  for defect in self:
275  bbox = defect.getBBox()
276  lsst.afw.geom.SpanSet(bbox).clippedTo(mask.getBBox()).setMask(mask, bitmask)
277 
A compact representation of a collection of pixels.
Definition: SpanSet.h:78

◆ readFits()

def lsst.ip.isr.calibType.IsrCalib.readFits (   cls,
  filename,
**  kwargs 
)
inherited
Read calibration data from a FITS file.

Parameters
----------
filename : `str`
    Filename to read data from.
kwargs : `dict` or collections.abc.Mapping`, optional
    Set of key=value pairs to pass to the ``fromTable``
    method.

Returns
-------
calib : `lsst.ip.isr.IsrCalib`
    Calibration contained within the file.

Definition at line 432 of file calibType.py.

432  def readFits(cls, filename, **kwargs):
433  """Read calibration data from a FITS file.
434 
435  Parameters
436  ----------
437  filename : `str`
438  Filename to read data from.
439  kwargs : `dict` or collections.abc.Mapping`, optional
440  Set of key=value pairs to pass to the ``fromTable``
441  method.
442 
443  Returns
444  -------
445  calib : `lsst.ip.isr.IsrCalib`
446  Calibration contained within the file.
447  """
448  tableList = []
449  tableList.append(Table.read(filename, hdu=1))
450  extNum = 2 # Fits indices start at 1, we've read one already.
451  keepTrying = True
452 
453  while keepTrying:
454  with warnings.catch_warnings():
455  warnings.simplefilter("error")
456  try:
457  newTable = Table.read(filename, hdu=extNum)
458  tableList.append(newTable)
459  extNum += 1
460  except Exception:
461  keepTrying = False
462 
463  for table in tableList:
464  for k, v in table.meta.items():
465  if isinstance(v, fits.card.Undefined):
466  table.meta[k] = None
467 
468  calibClass = cls.determineCalibClass(tableList[0].meta, "readFits")
469  return calibClass.fromTable(tableList, **kwargs)
470 

◆ readLsstDefectsFile()

def lsst.ip.isr.defects.Defects.readLsstDefectsFile (   cls,
  filename,
  normalize_on_init = False 
)
Read defects information from a legacy LSST format text file.

Parameters
----------
filename : `str`
    Name of text file containing the defect information.

normalize_on_init : `bool`, optional
    If `True`, normalization is applied to the defects listed in the
    table to remove duplicates, eliminate overlaps, etc. Otherwise
    the defects in the returned object exactly match those in the
    table.

Returns
-------
defects : `Defects`
    The defects.

Notes
-----
These defect text files are used as the human readable definitions
of defects in calibration data definition repositories.  The format
is to use four columns defined as follows:

x0 : `int`
    X coordinate of bottom left corner of box.
y0 : `int`
    Y coordinate of bottom left corner of box.
width : `int`
    X extent of the box.
height : `int`
    Y extent of the box.

Files of this format were used historically to represent defects
in simple text form.  Use `Defects.readText` and `Defects.writeText`
to use the more modern format.

Definition at line 591 of file defects.py.

591  def readLsstDefectsFile(cls, filename, normalize_on_init=False):
592  """Read defects information from a legacy LSST format text file.
593 
594  Parameters
595  ----------
596  filename : `str`
597  Name of text file containing the defect information.
598 
599  normalize_on_init : `bool`, optional
600  If `True`, normalization is applied to the defects listed in the
601  table to remove duplicates, eliminate overlaps, etc. Otherwise
602  the defects in the returned object exactly match those in the
603  table.
604 
605  Returns
606  -------
607  defects : `Defects`
608  The defects.
609 
610  Notes
611  -----
612  These defect text files are used as the human readable definitions
613  of defects in calibration data definition repositories. The format
614  is to use four columns defined as follows:
615 
616  x0 : `int`
617  X coordinate of bottom left corner of box.
618  y0 : `int`
619  Y coordinate of bottom left corner of box.
620  width : `int`
621  X extent of the box.
622  height : `int`
623  Y extent of the box.
624 
625  Files of this format were used historically to represent defects
626  in simple text form. Use `Defects.readText` and `Defects.writeText`
627  to use the more modern format.
628  """
629  # Use loadtxt so that ValueError is thrown if the file contains a
630  # non-integer value. genfromtxt converts bad values to -1.
631  defect_array = np.loadtxt(filename,
632  dtype=[("x0", "int"), ("y0", "int"),
633  ("x_extent", "int"), ("y_extent", "int")])
634 
635  defects = (lsst.geom.Box2I(lsst.geom.Point2I(row["x0"], row["y0"]),
636  lsst.geom.Extent2I(row["x_extent"], row["y_extent"]))
637  for row in defect_array)
638 
639  return cls(defects, normalize_on_init=normalize_on_init)
640 

◆ readText()

def lsst.ip.isr.calibType.IsrCalib.readText (   cls,
  filename,
**  kwargs 
)
inherited
Read calibration representation from a yaml/ecsv file.

Parameters
----------
filename : `str`
    Name of the file containing the calibration definition.
kwargs : `dict` or collections.abc.Mapping`, optional
    Set of key=value pairs to pass to the ``fromDict`` or
    ``fromTable`` methods.

Returns
-------
calib : `~lsst.ip.isr.IsrCalibType`
    Calibration class.

Raises
------
RuntimeError :
    Raised if the filename does not end in ".ecsv" or ".yaml".

Definition at line 346 of file calibType.py.

346  def readText(cls, filename, **kwargs):
347  """Read calibration representation from a yaml/ecsv file.
348 
349  Parameters
350  ----------
351  filename : `str`
352  Name of the file containing the calibration definition.
353  kwargs : `dict` or collections.abc.Mapping`, optional
354  Set of key=value pairs to pass to the ``fromDict`` or
355  ``fromTable`` methods.
356 
357  Returns
358  -------
359  calib : `~lsst.ip.isr.IsrCalibType`
360  Calibration class.
361 
362  Raises
363  ------
364  RuntimeError :
365  Raised if the filename does not end in ".ecsv" or ".yaml".
366  """
367  if filename.endswith((".ecsv", ".ECSV")):
368  data = Table.read(filename, format="ascii.ecsv")
369  calibClass = cls.determineCalibClass(data.meta, "readText/ECSV")
370  return calibClass.fromTable([data], **kwargs)
371  elif filename.endswith((".yaml", ".YAML")):
372  with open(filename, "r") as f:
373  data = yaml.load(f, Loader=yaml.CLoader)
374  calibClass = cls.determineCalibClass(data["metadata"], "readText/YAML")
375  return calibClass.fromDict(data, **kwargs)
376  else:
377  raise RuntimeError(f"Unknown filename extension: {filename}")
378 

◆ requiredAttributes() [1/2]

def lsst.ip.isr.calibType.IsrCalib.requiredAttributes (   self)
inherited

Definition at line 138 of file calibType.py.

138  def requiredAttributes(self):
139  return self._requiredAttributes
140 

◆ requiredAttributes() [2/2]

def lsst.ip.isr.calibType.IsrCalib.requiredAttributes (   self,
  value 
)
inherited

Definition at line 142 of file calibType.py.

142  def requiredAttributes(self, value):
143  self._requiredAttributes = value
144 

◆ setMetadata()

def lsst.ip.isr.calibType.IsrCalib.setMetadata (   self,
  metadata 
)
inherited
Store a copy of the supplied metadata with this calibration.

Parameters
----------
metadata : `lsst.daf.base.PropertyList`
    Metadata to associate with the calibration.  Will be copied and
    overwrite existing metadata.

Definition at line 157 of file calibType.py.

157  def setMetadata(self, metadata):
158  """Store a copy of the supplied metadata with this calibration.
159 
160  Parameters
161  ----------
162  metadata : `lsst.daf.base.PropertyList`
163  Metadata to associate with the calibration. Will be copied and
164  overwrite existing metadata.
165  """
166  if metadata is not None:
167  self._metadata.update(metadata)
168 
169  # Ensure that we have the obs type required by calibration ingest
170  self._metadata["OBSTYPE"] = self._OBSTYPE
171  self._metadata[self._OBSTYPE + "_SCHEMA"] = self._SCHEMA
172  self._metadata[self._OBSTYPE + "_VERSION"] = self._VERSION
173 
174  if isinstance(metadata, dict):
175  self.calibInfoFromDict(metadata)
176  elif isinstance(metadata, PropertyList):
177  self.calibInfoFromDict(metadata.toDict())
178 

◆ toDict()

def lsst.ip.isr.defects.Defects.toDict (   self)
Return a dictionary containing the calibration properties.

The dictionary should be able to be round-tripped through
`fromDict`.

Returns
-------
dictionary : `dict`
    Dictionary of properties.

Reimplemented from lsst.ip.isr.calibType.IsrCalib.

Definition at line 374 of file defects.py.

374  def toDict(self):
375  """Return a dictionary containing the calibration properties.
376 
377  The dictionary should be able to be round-tripped through
378  `fromDict`.
379 
380  Returns
381  -------
382  dictionary : `dict`
383  Dictionary of properties.
384  """
385  self.updateMetadata()
386 
387  outDict = {}
388  metadata = self.getMetadata()
389  outDict['metadata'] = metadata
390 
391  xCol = []
392  yCol = []
393  widthCol = []
394  heightCol = []
395 
396  nrows = len(self._defects)
397  if nrows:
398  for defect in self._defects:
399  box = defect.getBBox()
400  xCol.append(box.getBeginX())
401  yCol.append(box.getBeginY())
402  widthCol.append(box.getWidth())
403  heightCol.append(box.getHeight())
404 
405  outDict['x0'] = xCol
406  outDict['y0'] = yCol
407  outDict['width'] = widthCol
408  outDict['height'] = heightCol
409 
410  return outDict
411 

◆ toFitsRegionTable()

def lsst.ip.isr.defects.Defects.toFitsRegionTable (   self)
Convert defect list to `~lsst.afw.table.BaseCatalog` using the
FITS region standard.

Returns
-------
table : `lsst.afw.table.BaseCatalog`
    Defects in tabular form.

Notes
-----
The table created uses the
`FITS regions <https://fits.gsfc.nasa.gov/registry/region.html>`_
definition tabular format.  The ``X`` and ``Y`` coordinates are
converted to FITS Physical coordinates that have origin pixel (1, 1)
rather than the (0, 0) used in LSST software.

Definition at line 278 of file defects.py.

278  def toFitsRegionTable(self):
279  """Convert defect list to `~lsst.afw.table.BaseCatalog` using the
280  FITS region standard.
281 
282  Returns
283  -------
284  table : `lsst.afw.table.BaseCatalog`
285  Defects in tabular form.
286 
287  Notes
288  -----
289  The table created uses the
290  `FITS regions <https://fits.gsfc.nasa.gov/registry/region.html>`_
291  definition tabular format. The ``X`` and ``Y`` coordinates are
292  converted to FITS Physical coordinates that have origin pixel (1, 1)
293  rather than the (0, 0) used in LSST software.
294  """
295  self.updateMetadata()
296  nrows = len(self._defects)
297 
298  if nrows:
299  # Adding entire columns is more efficient than adding
300  # each element separately
301  xCol = []
302  yCol = []
303  rCol = []
304  shapes = []
305  for i, defect in enumerate(self._defects):
306  box = defect.getBBox()
307  center = box.getCenter()
308  # Correct for the FITS 1-based offset
309  xCol.append(center.getX() + 1.0)
310  yCol.append(center.getY() + 1.0)
311 
312  width = box.width
313  height = box.height
314 
315  if width == 1 and height == 1:
316  # Call this a point
317  shapeType = "POINT"
318  else:
319  shapeType = "BOX"
320 
321  # Strings have to be added per row
322  shapes.append(shapeType)
323 
324  rCol.append(np.array([width, height], dtype=np.float64))
325 
326  table = astropy.table.Table({'X': xCol, 'Y': yCol, 'SHAPE': shapes,
327  'R': rCol, 'ROTANG': np.zeros(nrows),
328  'COMPONENT': np.arange(nrows)})
329  table.meta = self.getMetadata().toDict()
330  return table
331 

◆ toTable()

def lsst.ip.isr.defects.Defects.toTable (   self)
Convert defects to a simple table form that we use to write
to text files.

Returns
-------
table : `lsst.afw.table.BaseCatalog`
    Defects in simple tabular form.

Notes
-----
These defect tables are used as the human readable definitions
of defects in calibration data definition repositories.  The format
is to use four columns defined as follows:

x0 : `int`
    X coordinate of bottom left corner of box.
y0 : `int`
    Y coordinate of bottom left corner of box.
width : `int`
    X extent of the box.
height : `int`
    Y extent of the box.

Reimplemented from lsst.ip.isr.calibType.IsrCalib.

Definition at line 412 of file defects.py.

412  def toTable(self):
413  """Convert defects to a simple table form that we use to write
414  to text files.
415 
416  Returns
417  -------
418  table : `lsst.afw.table.BaseCatalog`
419  Defects in simple tabular form.
420 
421  Notes
422  -----
423  These defect tables are used as the human readable definitions
424  of defects in calibration data definition repositories. The format
425  is to use four columns defined as follows:
426 
427  x0 : `int`
428  X coordinate of bottom left corner of box.
429  y0 : `int`
430  Y coordinate of bottom left corner of box.
431  width : `int`
432  X extent of the box.
433  height : `int`
434  Y extent of the box.
435  """
436  tableList = []
437  self.updateMetadata()
438 
439  xCol = []
440  yCol = []
441  widthCol = []
442  heightCol = []
443 
444  nrows = len(self._defects)
445  if nrows:
446  for defect in self._defects:
447  box = defect.getBBox()
448  xCol.append(box.getBeginX())
449  yCol.append(box.getBeginY())
450  widthCol.append(box.getWidth())
451  heightCol.append(box.getHeight())
452 
453  catalog = astropy.table.Table({'x0': xCol, 'y0': yCol, 'width': widthCol, 'height': heightCol})
454  inMeta = self.getMetadata().toDict()
455  outMeta = {k: v for k, v in inMeta.items() if v is not None}
456  catalog.meta = outMeta
457  tableList.append(catalog)
458 
459  return tableList
460 

◆ transpose()

def lsst.ip.isr.defects.Defects.transpose (   self)
Make a transposed copy of this defect list.

Returns
-------
retDefectList : `Defects`
    Transposed list of defects.

Definition at line 244 of file defects.py.

244  def transpose(self):
245  """Make a transposed copy of this defect list.
246 
247  Returns
248  -------
249  retDefectList : `Defects`
250  Transposed list of defects.
251  """
252  retDefectList = self.__class__()
253  for defect in self:
254  bbox = defect.getBBox()
255  dimensions = bbox.getDimensions()
256  nbbox = lsst.geom.Box2I(lsst.geom.Point2I(bbox.getMinY(), bbox.getMinX()),
257  lsst.geom.Extent2I(dimensions[1], dimensions[0]))
258  retDefectList.append(nbbox)
259  return retDefectList
260 

◆ updateMetadata()

def lsst.ip.isr.calibType.IsrCalib.updateMetadata (   self,
  camera = None,
  detector = None,
  filterName = None,
  setCalibId = False,
  setCalibInfo = False,
  setDate = False,
**  kwargs 
)
inherited
Update metadata keywords with new values.

Parameters
----------
camera : `lsst.afw.cameraGeom.Camera`, optional
    Reference camera to use to set _instrument field.
detector : `lsst.afw.cameraGeom.Detector`, optional
    Reference detector to use to set _detector* fields.
filterName : `str`, optional
    Filter name to assign to this calibration.
setCalibId : `bool`, optional
    Construct the _calibId field from other fields.
setCalibInfo : `bool`, optional
    Set calibration parameters from metadata.
setDate : `bool`, optional
    Ensure the metadata CALIBDATE fields are set to the current datetime.
kwargs : `dict` or `collections.abc.Mapping`, optional
    Set of key=value pairs to assign to the metadata.

Definition at line 179 of file calibType.py.

181  **kwargs):
182  """Update metadata keywords with new values.
183 
184  Parameters
185  ----------
186  camera : `lsst.afw.cameraGeom.Camera`, optional
187  Reference camera to use to set _instrument field.
188  detector : `lsst.afw.cameraGeom.Detector`, optional
189  Reference detector to use to set _detector* fields.
190  filterName : `str`, optional
191  Filter name to assign to this calibration.
192  setCalibId : `bool`, optional
193  Construct the _calibId field from other fields.
194  setCalibInfo : `bool`, optional
195  Set calibration parameters from metadata.
196  setDate : `bool`, optional
197  Ensure the metadata CALIBDATE fields are set to the current datetime.
198  kwargs : `dict` or `collections.abc.Mapping`, optional
199  Set of key=value pairs to assign to the metadata.
200  """
201  mdOriginal = self.getMetadata()
202  mdSupplemental = dict()
203 
204  for k, v in kwargs.items():
205  if isinstance(v, fits.card.Undefined):
206  kwargs[k] = None
207 
208  if setCalibInfo:
209  self.calibInfoFromDict(kwargs)
210 
211  if camera:
212  self._instrument = camera.getName()
213 
214  if detector:
215  self._detectorName = detector.getName()
216  self._detectorSerial = detector.getSerial()
217  self._detectorId = detector.getId()
218  if "_" in self._detectorName:
219  (self._raftName, self._slotName) = self._detectorName.split("_")
220 
221  if filterName:
222  # TOD0 DM-28093: I think this whole comment can go away, if we
223  # always use physicalLabel everywhere in ip_isr.
224  # If set via:
225  # exposure.getInfo().getFilter().getName()
226  # then this will hold the abstract filter.
227  self._filter = filterName
228 
229  if setDate:
230  date = datetime.datetime.now()
231  mdSupplemental["CALIBDATE"] = date.isoformat()
232  mdSupplemental["CALIB_CREATION_DATE"] = date.date().isoformat()
233  mdSupplemental["CALIB_CREATION_TIME"] = date.time().isoformat()
234 
235  if setCalibId:
236  values = []
237  values.append(f"instrument={self._instrument}") if self._instrument else None
238  values.append(f"raftName={self._raftName}") if self._raftName else None
239  values.append(f"detectorName={self._detectorName}") if self._detectorName else None
240  values.append(f"detector={self._detectorId}") if self._detectorId else None
241  values.append(f"filter={self._filter}") if self._filter else None
242 
243  calibDate = mdOriginal.get("CALIBDATE", mdSupplemental.get("CALIBDATE", None))
244  values.append(f"calibDate={calibDate}") if calibDate else None
245 
246  self._calibId = " ".join(values)
247 
248  self._metadata["INSTRUME"] = self._instrument if self._instrument else None
249  self._metadata["RAFTNAME"] = self._raftName if self._raftName else None
250  self._metadata["SLOTNAME"] = self._slotName if self._slotName else None
251  self._metadata["DETECTOR"] = self._detectorId
252  self._metadata["DET_NAME"] = self._detectorName if self._detectorName else None
253  self._metadata["DET_SER"] = self._detectorSerial if self._detectorSerial else None
254  self._metadata["FILTER"] = self._filter if self._filter else None
255  self._metadata["CALIB_ID"] = self._calibId if self._calibId else None
256  self._metadata["CALIBCLS"] = get_full_type_name(self)
257 
258  mdSupplemental.update(kwargs)
259  mdOriginal.update(mdSupplemental)
260 

◆ validate()

def lsst.ip.isr.calibType.IsrCalib.validate (   self,
  other = None 
)
inherited
Validate that this calibration is defined and can be used.

Parameters
----------
other : `object`, optional
    Thing to validate against.

Returns
-------
valid : `bool`
    Returns true if the calibration is valid and appropriate.

Definition at line 597 of file calibType.py.

597  def validate(self, other=None):
598  """Validate that this calibration is defined and can be used.
599 
600  Parameters
601  ----------
602  other : `object`, optional
603  Thing to validate against.
604 
605  Returns
606  -------
607  valid : `bool`
608  Returns true if the calibration is valid and appropriate.
609  """
610  return False
611 

◆ writeFits()

def lsst.ip.isr.calibType.IsrCalib.writeFits (   self,
  filename 
)
inherited
Write calibration data to a FITS file.

Parameters
----------
filename : `str`
    Filename to write data to.

Returns
-------
used : `str`
    The name of the file used to write the data.

Definition at line 471 of file calibType.py.

471  def writeFits(self, filename):
472  """Write calibration data to a FITS file.
473 
474  Parameters
475  ----------
476  filename : `str`
477  Filename to write data to.
478 
479  Returns
480  -------
481  used : `str`
482  The name of the file used to write the data.
483 
484  """
485  tableList = self.toTable()
486  with warnings.catch_warnings():
487  warnings.filterwarnings("ignore", category=Warning, module="astropy.io")
488  astropyList = [fits.table_to_hdu(table) for table in tableList]
489  astropyList.insert(0, fits.PrimaryHDU())
490 
491  writer = fits.HDUList(astropyList)
492  writer.writeto(filename, overwrite=True)
493  return filename
494 
def writeFits(filename, stamps, metadata, type_name, write_mask, write_variance, write_archive=False)
Definition: stamps.py:42

◆ writeText()

def lsst.ip.isr.calibType.IsrCalib.writeText (   self,
  filename,
  format = "auto" 
)
inherited
Write the calibration data to a text file.

Parameters
----------
filename : `str`
    Name of the file to write.
format : `str`
    Format to write the file as.  Supported values are:
        ``"auto"`` : Determine filetype from filename.
        ``"yaml"`` : Write as yaml.
        ``"ecsv"`` : Write as ecsv.
Returns
-------
used : `str`
    The name of the file used to write the data.  This may
    differ from the input if the format is explicitly chosen.

Raises
------
RuntimeError :
    Raised if filename does not end in a known extension, or
    if all information cannot be written.

Notes
-----
The file is written to YAML/ECSV format and will include any
associated metadata.

Definition at line 379 of file calibType.py.

379  def writeText(self, filename, format="auto"):
380  """Write the calibration data to a text file.
381 
382  Parameters
383  ----------
384  filename : `str`
385  Name of the file to write.
386  format : `str`
387  Format to write the file as. Supported values are:
388  ``"auto"`` : Determine filetype from filename.
389  ``"yaml"`` : Write as yaml.
390  ``"ecsv"`` : Write as ecsv.
391  Returns
392  -------
393  used : `str`
394  The name of the file used to write the data. This may
395  differ from the input if the format is explicitly chosen.
396 
397  Raises
398  ------
399  RuntimeError :
400  Raised if filename does not end in a known extension, or
401  if all information cannot be written.
402 
403  Notes
404  -----
405  The file is written to YAML/ECSV format and will include any
406  associated metadata.
407  """
408  if format == "yaml" or (format == "auto" and filename.lower().endswith((".yaml", ".YAML"))):
409  outDict = self.toDict()
410  path, ext = os.path.splitext(filename)
411  filename = path + ".yaml"
412  with open(filename, "w") as f:
413  yaml.dump(outDict, f)
414  elif format == "ecsv" or (format == "auto" and filename.lower().endswith((".ecsv", ".ECSV"))):
415  tableList = self.toTable()
416  if len(tableList) > 1:
417  # ECSV doesn't support multiple tables per file, so we
418  # can only write the first table.
419  raise RuntimeError(f"Unable to persist {len(tableList)}tables in ECSV format.")
420 
421  table = tableList[0]
422  path, ext = os.path.splitext(filename)
423  filename = path + ".ecsv"
424  table.write(filename, format="ascii.ecsv")
425  else:
426  raise RuntimeError(f"Attempt to write to a file {filename} "
427  "that does not end in '.yaml' or '.ecsv'")
428 
429  return filename
430 

Member Data Documentation

◆ log

lsst.ip.isr.calibType.IsrCalib.log
inherited

Definition at line 86 of file calibType.py.

◆ requiredAttributes

lsst.ip.isr.calibType.IsrCalib.requiredAttributes
inherited

Definition at line 81 of file calibType.py.


The documentation for this class was generated from the following file: