LSST Applications  21.0.0+04719a4bac,21.0.0-1-ga51b5d4+f5e6047307,21.0.0-11-g2b59f77+a9c1acf22d,21.0.0-11-ga42c5b2+86977b0b17,21.0.0-12-gf4ce030+76814010d2,21.0.0-13-g1721dae+760e7a6536,21.0.0-13-g3a573fe+768d78a30a,21.0.0-15-g5a7caf0+f21cbc5713,21.0.0-16-g0fb55c1+b60e2d390c,21.0.0-19-g4cded4ca+71a93a33c0,21.0.0-2-g103fe59+bb20972958,21.0.0-2-g45278ab+04719a4bac,21.0.0-2-g5242d73+3ad5d60fb1,21.0.0-2-g7f82c8f+8babb168e8,21.0.0-2-g8f08a60+06509c8b61,21.0.0-2-g8faa9b5+616205b9df,21.0.0-2-ga326454+8babb168e8,21.0.0-2-gde069b7+5e4aea9c2f,21.0.0-2-gecfae73+1d3a86e577,21.0.0-2-gfc62afb+3ad5d60fb1,21.0.0-25-g1d57be3cd+e73869a214,21.0.0-3-g357aad2+ed88757d29,21.0.0-3-g4a4ce7f+3ad5d60fb1,21.0.0-3-g4be5c26+3ad5d60fb1,21.0.0-3-g65f322c+e0b24896a3,21.0.0-3-g7d9da8d+616205b9df,21.0.0-3-ge02ed75+a9c1acf22d,21.0.0-4-g591bb35+a9c1acf22d,21.0.0-4-g65b4814+b60e2d390c,21.0.0-4-gccdca77+0de219a2bc,21.0.0-4-ge8a399c+6c55c39e83,21.0.0-5-gd00fb1e+05fce91b99,21.0.0-6-gc675373+3ad5d60fb1,21.0.0-64-g1122c245+4fb2b8f86e,21.0.0-7-g04766d7+cd19d05db2,21.0.0-7-gdf92d54+04719a4bac,21.0.0-8-g5674e7b+d1bd76f71f,master-gac4afde19b+a9c1acf22d,w.2021.13
LSST Data Management Base Package
Public Member Functions | Public Attributes | List of all members
lsst.ip.isr.linearize.Linearizer Class Reference
Inheritance diagram for lsst.ip.isr.linearize.Linearizer:
lsst.ip.isr.calibType.IsrCalib

Public Member Functions

def __init__ (self, table=None, **kwargs)
 
def updateMetadata (self, setDate=False, **kwargs)
 
def fromDetector (self, detector)
 
def fromDict (cls, dictionary)
 
def toDict (self)
 
def fromTable (cls, tableList)
 
def toTable (self)
 
def getLinearityTypeByName (self, linearityTypeName)
 
def validate (self, detector=None, amplifier=None)
 
def applyLinearity (self, image, detector=None, log=None)
 
def requiredAttributes (self)
 
def requiredAttributes (self, value)
 
def __str__ (self)
 
def __eq__ (self, other)
 
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 readText (cls, filename, **kwargs)
 
def writeText (self, filename, format='auto')
 
def readFits (cls, filename, **kwargs)
 
def writeFits (self, filename)
 
def fromDict (cls, dictionary, **kwargs)
 
def fromTable (cls, tableList, **kwargs)
 
def validate (self, other=None)
 
def apply (self, target)
 

Public Attributes

 hasLinearity
 
 override
 
 ampNames
 
 linearityCoeffs
 
 linearityType
 
 linearityBBox
 
 fitParams
 
 fitParamsErr
 
 fitChiSq
 
 tableData
 
 requiredAttributes
 
 log
 

Detailed Description

Parameter set for linearization.

These parameters are included in cameraGeom.Amplifier, but
should be accessible externally to allow for testing.

Parameters
----------
table : `numpy.array`, optional
    Lookup table; a 2-dimensional array of floats:
        - one row for each row index (value of coef[0] in the amplifier)
        - one column for each image value
    To avoid copying the table the last index should vary fastest
    (numpy default "C" order)
detector : `lsst.afw.cameraGeom.Detector`, optional
    Detector object.  Passed to self.fromDetector() on init.
log : `lsst.log.Log`, optional
    Logger to handle messages.
kwargs : `dict`, optional
    Other keyword arguments to pass to the parent init.

Raises
------
RuntimeError :
    Raised if the supplied table is not 2D, or if the table has fewer
    columns than rows (indicating that the indices are swapped).

Notes
-----
The linearizer attributes stored are:

hasLinearity : `bool`
    Whether a linearity correction is defined for this detector.
override : `bool`
    Whether the detector parameters should be overridden.
ampNames : `list` [`str`]
    List of amplifier names to correct.
linearityCoeffs : `dict` [`str`, `numpy.array`]
    Coefficients to use in correction.  Indexed by amplifier
    names.  The format of the array depends on the type of
    correction to apply.
linearityType : `dict` [`str`, `str`]
    Type of correction to use, indexed by amplifier names.
linearityBBox : `dict` [`str`, `lsst.geom.Box2I`]
    Bounding box the correction is valid over, indexed by
    amplifier names.
fitParams : `dict` [`str`, `numpy.array`], optional
    Linearity fit parameters used to construct the correction
    coefficients, indexed as above.
fitParamsErr : `dict` [`str`, `numpy.array`], optional
    Uncertainty values of the linearity fit parameters used to
    construct the correction coefficients, indexed as above.
fitChiSq : `dict` [`str`, `float`], optional
    Chi-squared value of the linearity fit, indexed as above.
tableData : `numpy.array`, optional
    Lookup table data for the linearity correction.

Definition at line 38 of file linearize.py.

Constructor & Destructor Documentation

◆ __init__()

def lsst.ip.isr.linearize.Linearizer.__init__ (   self,
  table = None,
**  kwargs 
)

Definition at line 99 of file linearize.py.

99  def __init__(self, table=None, **kwargs):
100  self.hasLinearity = False
101  self.override = False
102 
103  self.ampNames = list()
104  self.linearityCoeffs = dict()
105  self.linearityType = dict()
106  self.linearityBBox = dict()
107 
108  self.fitParams = dict()
109  self.fitParamsErr = dict()
110  self.fitChiSq = dict()
111 
112  self.tableData = None
113  if table is not None:
114  if len(table.shape) != 2:
115  raise RuntimeError("table shape = %s; must have two dimensions" % (table.shape,))
116  if table.shape[1] < table.shape[0]:
117  raise RuntimeError("table shape = %s; indices are switched" % (table.shape,))
118  self.tableData = np.array(table, order="C")
119 
120  super().__init__(**kwargs)
121  self.requiredAttributes.update(['hasLinearity', 'override',
122  'ampNames',
123  'linearityCoeffs', 'linearityType', 'linearityBBox',
124  'fitParams', 'fitParamsErr', 'fitChiSq',
125  'tableData'])
126 
daf::base::PropertyList * list
Definition: fits.cc:913

Member Function Documentation

◆ __eq__()

def lsst.ip.isr.calibType.IsrCalib.__eq__ (   self,
  other 
)
inherited
Calibration equivalence.

Subclasses will need to check specific sub-properties.  The
default is only to check common entries.

Reimplemented in lsst.ip.isr.ptcDataset.PhotonTransferCurveDataset, lsst.ip.isr.defects.Defects, and lsst.ip.isr.calibType.IsrProvenance.

Definition at line 91 of file calibType.py.

91  def __eq__(self, other):
92  """Calibration equivalence.
93 
94  Subclasses will need to check specific sub-properties. The
95  default is only to check common entries.
96  """
97  if not isinstance(other, self.__class__):
98  return False
99 
100  for attr in self._requiredAttributes:
101  if getattr(self, attr) != getattr(other, attr):
102  return False
103 
104  return True
105 

◆ __str__()

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

Reimplemented in lsst.ip.isr.defects.Defects, and lsst.ip.isr.calibType.IsrProvenance.

Definition at line 88 of file calibType.py.

88  def __str__(self):
89  return f"{self.__class__.__name__}(obstype={self._OBSTYPE}, detector={self._detectorName}, )"
90 

◆ 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 549 of file calibType.py.

549  def apply(self, target):
550  """Method to apply the calibration to the target object.
551 
552  Parameters
553  ----------
554  target : `object`
555  Thing to validate against.
556 
557  Returns
558  -------
559  valid : `bool`
560  Returns true if the calibration was applied correctly.
561 
562  Raises
563  ------
564  NotImplementedError :
565  Raised if not implemented.
566  """
567  raise NotImplementedError("Must be implemented by subclass.")
568 
569 

◆ applyLinearity()

def lsst.ip.isr.linearize.Linearizer.applyLinearity (   self,
  image,
  detector = None,
  log = None 
)
Apply the linearity to an image.

If the linearity parameters are populated, use those,
otherwise use the values from the detector.

Parameters
----------
image : `~lsst.afw.image.image`
    Image to correct.
detector : `~lsst.afw.cameraGeom.detector`
    Detector to use for linearity parameters if not already
    populated.
log : `~lsst.log.Log`, optional
    Log object to use for logging.

Definition at line 428 of file linearize.py.

428  def applyLinearity(self, image, detector=None, log=None):
429  """Apply the linearity to an image.
430 
431  If the linearity parameters are populated, use those,
432  otherwise use the values from the detector.
433 
434  Parameters
435  ----------
436  image : `~lsst.afw.image.image`
437  Image to correct.
438  detector : `~lsst.afw.cameraGeom.detector`
439  Detector to use for linearity parameters if not already
440  populated.
441  log : `~lsst.log.Log`, optional
442  Log object to use for logging.
443  """
444  if log is None:
445  log = self.log
446  if detector and not self.hasLinearity:
447  self.fromDetector(detector)
448 
449  self.validate(detector)
450 
451  numAmps = 0
452  numLinearized = 0
453  numOutOfRange = 0
454  for ampName in self.linearityType.keys():
455  linearizer = self.getLinearityTypeByName(self.linearityType[ampName])
456  numAmps += 1
457  if linearizer is not None:
458  ampView = image.Factory(image, self.linearityBBox[ampName])
459  success, outOfRange = linearizer()(ampView, **{'coeffs': self.linearityCoeffs[ampName],
460  'table': self.tableData,
461  'log': self.log})
462  numOutOfRange += outOfRange
463  if success:
464  numLinearized += 1
465  elif log is not None:
466  log.warn("Amplifier %s did not linearize.",
467  ampName)
468  return Struct(
469  numAmps=numAmps,
470  numLinearized=numLinearized,
471  numOutOfRange=numOutOfRange
472  )
473 
474 

◆ 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 229 of file calibType.py.

229  def calibInfoFromDict(self, dictionary):
230  """Handle common keywords.
231 
232  This isn't an ideal solution, but until all calibrations
233  expect to find everything in the metadata, they still need to
234  search through dictionaries.
235 
236  Parameters
237  ----------
238  dictionary : `dict` or `lsst.daf.base.PropertyList`
239  Source for the common keywords.
240 
241  Raises
242  ------
243  RuntimeError :
244  Raised if the dictionary does not match the expected OBSTYPE.
245 
246  """
247 
248  def search(haystack, needles):
249  """Search dictionary 'haystack' for an entry in 'needles'
250  """
251  test = [haystack.get(x) for x in needles]
252  test = set([x for x in test if x is not None])
253  if len(test) == 0:
254  if 'metadata' in haystack:
255  return search(haystack['metadata'], needles)
256  else:
257  return None
258  elif len(test) == 1:
259  value = list(test)[0]
260  if value == '':
261  return None
262  else:
263  return value
264  else:
265  raise ValueError(f"Too many values found: {len(test)} {test} {needles}")
266 
267  if 'metadata' in dictionary:
268  metadata = dictionary['metadata']
269 
270  if self._OBSTYPE != metadata['OBSTYPE']:
271  raise RuntimeError(f"Incorrect calibration supplied. Expected {self._OBSTYPE}, "
272  f"found {metadata['OBSTYPE']}")
273 
274  self._instrument = search(dictionary, ['INSTRUME', 'instrument'])
275  self._raftName = search(dictionary, ['RAFTNAME'])
276  self._slotName = search(dictionary, ['SLOTNAME'])
277  self._detectorId = search(dictionary, ['DETECTOR', 'detectorId'])
278  self._detectorName = search(dictionary, ['DET_NAME', 'DETECTOR_NAME', 'detectorName'])
279  self._detectorSerial = search(dictionary, ['DET_SER', 'DETECTOR_SERIAL', 'detectorSerial'])
280  self._filter = search(dictionary, ['FILTER', 'filterName'])
281  self._calibId = search(dictionary, ['CALIB_ID'])
282 
daf::base::PropertySet * set
Definition: fits.cc:912

◆ fromDetector()

def lsst.ip.isr.linearize.Linearizer.fromDetector (   self,
  detector 
)
Read linearity parameters from a detector.

Parameters
----------
detector : `lsst.afw.cameraGeom.detector`
    Input detector with parameters to use.

Returns
-------
calib : `lsst.ip.isr.Linearizer`
    The calibration constructed from the detector.

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

Definition at line 147 of file linearize.py.

147  def fromDetector(self, detector):
148  """Read linearity parameters from a detector.
149 
150  Parameters
151  ----------
152  detector : `lsst.afw.cameraGeom.detector`
153  Input detector with parameters to use.
154 
155  Returns
156  -------
157  calib : `lsst.ip.isr.Linearizer`
158  The calibration constructed from the detector.
159  """
160  self._detectorName = detector.getName()
161  self._detectorSerial = detector.getSerial()
162  self._detectorId = detector.getId()
163  self.hasLinearity = True
164 
165  # Do not translate Threshold, Maximum, Units.
166  for amp in detector.getAmplifiers():
167  ampName = amp.getName()
168  self.ampNames.append(ampName)
169  self.linearityType[ampName] = amp.getLinearityType()
170  self.linearityCoeffs[ampName] = amp.getLinearityCoeffs()
171  self.linearityBBox[ampName] = amp.getBBox()
172 
173  return self
174 
std::shared_ptr< FrameSet > append(FrameSet const &first, FrameSet const &second)
Construct a FrameSet that performs two transformations in series.
Definition: functional.cc:33

◆ fromDict() [1/2]

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

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

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

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

Definition at line 176 of file linearize.py.

176  def fromDict(cls, dictionary):
177  """Construct a calibration from a dictionary of properties
178 
179  Parameters
180  ----------
181  dictionary : `dict`
182  Dictionary of properties
183 
184  Returns
185  -------
186  calib : `lsst.ip.isr.Linearity`
187  Constructed calibration.
188 
189  Raises
190  ------
191  RuntimeError
192  Raised if the supplied dictionary is for a different
193  calibration.
194  """
195 
196  calib = cls()
197 
198  if calib._OBSTYPE != dictionary['metadata']['OBSTYPE']:
199  raise RuntimeError(f"Incorrect linearity supplied. Expected {calib._OBSTYPE}, "
200  f"found {dictionary['metadata']['OBSTYPE']}")
201 
202  calib.setMetadata(dictionary['metadata'])
203 
204  calib.hasLinearity = dictionary.get('hasLinearity',
205  dictionary['metadata'].get('HAS_LINEARITY', False))
206  calib.override = dictionary.get('override', True)
207 
208  if calib.hasLinearity:
209  for ampName in dictionary['amplifiers']:
210  amp = dictionary['amplifiers'][ampName]
211  calib.ampNames.append(ampName)
212  calib.linearityCoeffs[ampName] = np.array(amp.get('linearityCoeffs', [0.0]))
213  calib.linearityType[ampName] = amp.get('linearityType', 'None')
214  calib.linearityBBox[ampName] = amp.get('linearityBBox', None)
215 
216  calib.fitParams[ampName] = np.array(amp.get('fitParams', [0.0]))
217  calib.fitParamsErr[ampName] = np.array(amp.get('fitParamsErr', [0.0]))
218  calib.fitChiSq[ampName] = amp.get('fitChiSq', np.nan)
219 
220  calib.tableData = dictionary.get('tableData', None)
221  if calib.tableData:
222  calib.tableData = np.array(calib.tableData)
223 
224  return calib
225 

◆ 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 449 of file calibType.py.

449  def fromDict(cls, dictionary, **kwargs):
450  """Construct a calibration from a dictionary of properties.
451 
452  Must be implemented by the specific calibration subclasses.
453 
454  Parameters
455  ----------
456  dictionary : `dict`
457  Dictionary of properties.
458  kwargs : `dict` or collections.abc.Mapping`, optional
459  Set of key=value options.
460 
461  Returns
462  ------
463  calib : `lsst.ip.isr.CalibType`
464  Constructed calibration.
465 
466  Raises
467  ------
468  NotImplementedError :
469  Raised if not implemented.
470  """
471  raise NotImplementedError("Must be implemented by subclass.")
472 

◆ fromTable() [1/2]

def lsst.ip.isr.linearize.Linearizer.fromTable (   cls,
  tableList 
)
Read linearity from a FITS file.

This method uses the `fromDict` method to create the
calibration, after constructing an appropriate dictionary from
the input tables.

Parameters
----------
tableList : `list` [`astropy.table.Table`]
    afwTable read from input file name.

Returns
-------
linearity : `~lsst.ip.isr.linearize.Linearizer``
    Linearity parameters.

Notes
-----
The method reads a FITS file with 1 or 2 extensions. The metadata is read from the header of
extension 1, which must exist.  Then the table is loaded, and  the ['AMPLIFIER_NAME', 'TYPE',
'COEFFS', 'BBOX_X0', 'BBOX_Y0', 'BBOX_DX', 'BBOX_DY'] columns are read and used to
set each dictionary by looping over rows.
Eextension 2 is then attempted to read in the try block (which only exists for lookup tables).
It has a column named 'LOOKUP_VALUES' that contains a vector of the lookup entries in each row.

Definition at line 255 of file linearize.py.

255  def fromTable(cls, tableList):
256  """Read linearity from a FITS file.
257 
258  This method uses the `fromDict` method to create the
259  calibration, after constructing an appropriate dictionary from
260  the input tables.
261 
262  Parameters
263  ----------
264  tableList : `list` [`astropy.table.Table`]
265  afwTable read from input file name.
266 
267  Returns
268  -------
269  linearity : `~lsst.ip.isr.linearize.Linearizer``
270  Linearity parameters.
271 
272  Notes
273  -----
274  The method reads a FITS file with 1 or 2 extensions. The metadata is read from the header of
275  extension 1, which must exist. Then the table is loaded, and the ['AMPLIFIER_NAME', 'TYPE',
276  'COEFFS', 'BBOX_X0', 'BBOX_Y0', 'BBOX_DX', 'BBOX_DY'] columns are read and used to
277  set each dictionary by looping over rows.
278  Eextension 2 is then attempted to read in the try block (which only exists for lookup tables).
279  It has a column named 'LOOKUP_VALUES' that contains a vector of the lookup entries in each row.
280 
281  """
282  coeffTable = tableList[0]
283 
284  metadata = coeffTable.meta
285  inDict = dict()
286  inDict['metadata'] = metadata
287  inDict['hasLinearity'] = metadata.get('HAS_LINEARITY', False)
288  inDict['amplifiers'] = dict()
289 
290  for record in coeffTable:
291  ampName = record['AMPLIFIER_NAME']
292 
293  fitParams = record['FIT_PARAMS'] if 'FIT_PARAMS' in record.columns else np.array([0.0])
294  fitParamsErr = record['FIT_PARAMS_ERR'] if 'FIT_PARAMS_ERR' in record.columns else np.array([0.0])
295  fitChiSq = record['RED_CHI_SQ'] if 'RED_CHI_SQ' in record.columns else np.nan
296 
297  inDict['amplifiers'][ampName] = {
298  'linearityType': record['TYPE'],
299  'linearityCoeffs': record['COEFFS'],
300  'linearityBBox': Box2I(Point2I(record['BBOX_X0'], record['BBOX_Y0']),
301  Extent2I(record['BBOX_DX'], record['BBOX_DY'])),
302  'fitParams': fitParams,
303  'fitParamsErr': fitParamsErr,
304  'fitChiSq': fitChiSq,
305  }
306 
307  if len(tableList) > 1:
308  tableData = tableList[1]
309  inDict['tableData'] = [record['LOOKUP_VALUES'] for record in tableData]
310 
311  return cls().fromDict(inDict)
312 
Extent< int, 2 > Extent2I
Definition: Extent.h:397
Point< int, 2 > Point2I
Definition: Point.h:321

◆ fromTable() [2/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 492 of file calibType.py.

492  def fromTable(cls, tableList, **kwargs):
493  """Construct a calibration from a dictionary of properties.
494 
495  Must be implemented by the specific calibration subclasses.
496 
497  Parameters
498  ----------
499  tableList : `list` [`lsst.afw.table.Table`]
500  List of tables of properties.
501  kwargs : `dict` or collections.abc.Mapping`, optional
502  Set of key=value options.
503 
504  Returns
505  ------
506  calib : `lsst.ip.isr.CalibType`
507  Constructed calibration.
508 
509  Raises
510  ------
511  NotImplementedError :
512  Raised if not implemented.
513  """
514  raise NotImplementedError("Must be implemented by subclass.")
515 

◆ getLinearityTypeByName()

def lsst.ip.isr.linearize.Linearizer.getLinearityTypeByName (   self,
  linearityTypeName 
)
Determine the linearity class to use from the type name.

Parameters
----------
linearityTypeName : str
    String name of the linearity type that is needed.

Returns
-------
linearityType : `~lsst.ip.isr.linearize.LinearizeBase`
    The appropriate linearity class to use.  If no matching class
    is found, `None` is returned.

Definition at line 347 of file linearize.py.

347  def getLinearityTypeByName(self, linearityTypeName):
348  """Determine the linearity class to use from the type name.
349 
350  Parameters
351  ----------
352  linearityTypeName : str
353  String name of the linearity type that is needed.
354 
355  Returns
356  -------
357  linearityType : `~lsst.ip.isr.linearize.LinearizeBase`
358  The appropriate linearity class to use. If no matching class
359  is found, `None` is returned.
360  """
361  for t in [LinearizeLookupTable,
362  LinearizeSquared,
363  LinearizePolynomial,
364  LinearizeProportional,
365  LinearizeSpline,
366  LinearizeNone]:
367  if t.LinearityType == linearityTypeName:
368  return t
369  return None
370 

◆ 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 114 of file calibType.py.

114  def getMetadata(self):
115  """Retrieve metadata associated with this calibration.
116 
117  Returns
118  -------
119  meta : `lsst.daf.base.PropertyList`
120  Metadata. The returned `~lsst.daf.base.PropertyList` can be
121  modified by the caller and the changes will be written to
122  external files.
123  """
124  return self._metadata
125 

◆ 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 370 of file calibType.py.

370  def readFits(cls, filename, **kwargs):
371  """Read calibration data from a FITS file.
372 
373  Parameters
374  ----------
375  filename : `str`
376  Filename to read data from.
377  kwargs : `dict` or collections.abc.Mapping`, optional
378  Set of key=value pairs to pass to the ``fromTable``
379  method.
380 
381  Returns
382  -------
383  calib : `lsst.ip.isr.IsrCalib`
384  Calibration contained within the file.
385  """
386  tableList = []
387  tableList.append(Table.read(filename, hdu=1))
388  extNum = 2 # Fits indices start at 1, we've read one already.
389  keepTrying = True
390 
391  while keepTrying:
392  with warnings.catch_warnings():
393  warnings.simplefilter("error")
394  try:
395  newTable = Table.read(filename, hdu=extNum)
396  tableList.append(newTable)
397  extNum += 1
398  except Exception:
399  keepTrying = False
400 
401  for table in tableList:
402  for k, v in table.meta.items():
403  if isinstance(v, fits.card.Undefined):
404  table.meta[k] = None
405 
406  return cls.fromTable(tableList, **kwargs)
407 

◆ 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 284 of file calibType.py.

284  def readText(cls, filename, **kwargs):
285  """Read calibration representation from a yaml/ecsv file.
286 
287  Parameters
288  ----------
289  filename : `str`
290  Name of the file containing the calibration definition.
291  kwargs : `dict` or collections.abc.Mapping`, optional
292  Set of key=value pairs to pass to the ``fromDict`` or
293  ``fromTable`` methods.
294 
295  Returns
296  -------
297  calib : `~lsst.ip.isr.IsrCalibType`
298  Calibration class.
299 
300  Raises
301  ------
302  RuntimeError :
303  Raised if the filename does not end in ".ecsv" or ".yaml".
304  """
305  if filename.endswith((".ecsv", ".ECSV")):
306  data = Table.read(filename, format='ascii.ecsv')
307  return cls.fromTable([data], **kwargs)
308 
309  elif filename.endswith((".yaml", ".YAML")):
310  with open(filename, 'r') as f:
311  data = yaml.load(f, Loader=yaml.CLoader)
312  return cls.fromDict(data, **kwargs)
313  else:
314  raise RuntimeError(f"Unknown filename extension: {filename}")
315 

◆ requiredAttributes() [1/2]

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

Definition at line 107 of file calibType.py.

107  def requiredAttributes(self):
108  return self._requiredAttributes
109 

◆ requiredAttributes() [2/2]

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

Definition at line 111 of file calibType.py.

111  def requiredAttributes(self, value):
112  self._requiredAttributes = value
113 

◆ 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 126 of file calibType.py.

126  def setMetadata(self, metadata):
127  """Store a copy of the supplied metadata with this calibration.
128 
129  Parameters
130  ----------
131  metadata : `lsst.daf.base.PropertyList`
132  Metadata to associate with the calibration. Will be copied and
133  overwrite existing metadata.
134  """
135  if metadata is not None:
136  self._metadata.update(metadata)
137 
138  # Ensure that we have the obs type required by calibration ingest
139  self._metadata["OBSTYPE"] = self._OBSTYPE
140  self._metadata[self._OBSTYPE + "_SCHEMA"] = self._SCHEMA
141  self._metadata[self._OBSTYPE + "_VERSION"] = self._VERSION
142 
143  if isinstance(metadata, dict):
144  self.calibInfoFromDict(metadata)
145  elif isinstance(metadata, PropertyList):
146  self.calibInfoFromDict(metadata.toDict())
147 

◆ toDict()

def lsst.ip.isr.linearize.Linearizer.toDict (   self)
Return linearity parameters as a dict.

Returns
-------
outDict : `dict`:

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

Definition at line 226 of file linearize.py.

226  def toDict(self):
227  """Return linearity parameters as a dict.
228 
229  Returns
230  -------
231  outDict : `dict`:
232  """
233  self.updateMetadata()
234 
235  outDict = {'metadata': self.getMetadata(),
236  'detectorName': self._detectorName,
237  'detectorSerial': self._detectorSerial,
238  'detectorId': self._detectorId,
239  'hasTable': self.tableData is not None,
240  'amplifiers': dict(),
241  }
242  for ampName in self.linearityType:
243  outDict['amplifiers'][ampName] = {'linearityType': self.linearityType[ampName],
244  'linearityCoeffs': self.linearityCoeffs[ampName].tolist(),
245  'linearityBBox': self.linearityBBox[ampName],
246  'fitParams': self.fitParams[ampName].tolist(),
247  'fitParamsErr': self.fitParamsErr[ampName].tolist(),
248  'fitChiSq': self.fitChiSq[ampName]}
249  if self.tableData is not None:
250  outDict['tableData'] = self.tableData.tolist()
251 
252  return outDict
253 

◆ toTable()

def lsst.ip.isr.linearize.Linearizer.toTable (   self)
Construct a list of tables containing the information in this calibration

The list of tables should create an identical calibration
after being passed to this class's fromTable method.

Returns
-------
tableList : `list` [`astropy.table.Table`]
    List of tables containing the linearity calibration
    information.

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

Definition at line 313 of file linearize.py.

313  def toTable(self):
314  """Construct a list of tables containing the information in this calibration
315 
316  The list of tables should create an identical calibration
317  after being passed to this class's fromTable method.
318 
319  Returns
320  -------
321  tableList : `list` [`astropy.table.Table`]
322  List of tables containing the linearity calibration
323  information.
324  """
325 
326  tableList = []
327  self.updateMetadata()
328  catalog = Table([{'AMPLIFIER_NAME': ampName,
329  'TYPE': self.linearityType[ampName],
330  'COEFFS': self.linearityCoeffs[ampName],
331  'BBOX_X0': self.linearityBBox[ampName].getMinX(),
332  'BBOX_Y0': self.linearityBBox[ampName].getMinY(),
333  'BBOX_DX': self.linearityBBox[ampName].getWidth(),
334  'BBOX_DY': self.linearityBBox[ampName].getHeight(),
335  'FIT_PARAMS': self.fitParams[ampName],
336  'FIT_PARAMS_ERR': self.fitParamsErr[ampName],
337  'RED_CHI_SQ': self.fitChiSq[ampName],
338  } for ampName in self.ampNames])
339  catalog.meta = self.getMetadata().toDict()
340  tableList.append(catalog)
341 
342  if self.tableData is not None:
343  catalog = Table([{'LOOKUP_VALUES': value} for value in self.tableData])
344  tableList.append(catalog)
345  return(tableList)
346 

◆ updateMetadata() [1/2]

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 148 of file calibType.py.

150  **kwargs):
151  """Update metadata keywords with new values.
152 
153  Parameters
154  ----------
155  camera : `lsst.afw.cameraGeom.Camera`, optional
156  Reference camera to use to set _instrument field.
157  detector : `lsst.afw.cameraGeom.Detector`, optional
158  Reference detector to use to set _detector* fields.
159  filterName : `str`, optional
160  Filter name to assign to this calibration.
161  setCalibId : `bool`, optional
162  Construct the _calibId field from other fields.
163  setCalibInfo : `bool`, optional
164  Set calibration parameters from metadata.
165  setDate : `bool`, optional
166  Ensure the metadata CALIBDATE fields are set to the current datetime.
167  kwargs : `dict` or `collections.abc.Mapping`, optional
168  Set of key=value pairs to assign to the metadata.
169  """
170  mdOriginal = self.getMetadata()
171  mdSupplemental = dict()
172 
173  for k, v in kwargs.items():
174  if isinstance(v, fits.card.Undefined):
175  kwargs[k] = None
176 
177  if setCalibInfo:
178  self.calibInfoFromDict(kwargs)
179 
180  if camera:
181  self._instrument = camera.getName()
182 
183  if detector:
184  self._detectorName = detector.getName()
185  self._detectorSerial = detector.getSerial()
186  self._detectorId = detector.getId()
187  if "_" in self._detectorName:
188  (self._raftName, self._slotName) = self._detectorName.split("_")
189 
190  if filterName:
191  # TOD0 DM-28093: I think this whole comment can go away, if we
192  # always use physicalLabel everywhere in ip_isr.
193  # If set via:
194  # exposure.getInfo().getFilter().getName()
195  # then this will hold the abstract filter.
196  self._filter = filterName
197 
198  if setDate:
199  date = datetime.datetime.now()
200  mdSupplemental['CALIBDATE'] = date.isoformat()
201  mdSupplemental['CALIB_CREATION_DATE'] = date.date().isoformat()
202  mdSupplemental['CALIB_CREATION_TIME'] = date.time().isoformat()
203 
204  if setCalibId:
205  values = []
206  values.append(f"instrument={self._instrument}") if self._instrument else None
207  values.append(f"raftName={self._raftName}") if self._raftName else None
208  values.append(f"detectorName={self._detectorName}") if self._detectorName else None
209  values.append(f"detector={self._detectorId}") if self._detectorId else None
210  values.append(f"filter={self._filter}") if self._filter else None
211 
212  calibDate = mdOriginal.get('CALIBDATE', mdSupplemental.get('CALIBDATE', None))
213  values.append(f"calibDate={calibDate}") if calibDate else None
214 
215  self._calibId = " ".join(values)
216 
217  self._metadata["INSTRUME"] = self._instrument if self._instrument else None
218  self._metadata["RAFTNAME"] = self._raftName if self._raftName else None
219  self._metadata["SLOTNAME"] = self._slotName if self._slotName else None
220  self._metadata["DETECTOR"] = self._detectorId
221  self._metadata["DET_NAME"] = self._detectorName if self._detectorName else None
222  self._metadata["DET_SER"] = self._detectorSerial if self._detectorSerial else None
223  self._metadata["FILTER"] = self._filter if self._filter else None
224  self._metadata["CALIB_ID"] = self._calibId if self._calibId else None
225 
226  mdSupplemental.update(kwargs)
227  mdOriginal.update(mdSupplemental)
228 

◆ updateMetadata() [2/2]

def lsst.ip.isr.linearize.Linearizer.updateMetadata (   self,
  setDate = False,
**  kwargs 
)
Update metadata keywords with new values.

This calls the base class's method after ensuring the required
calibration keywords will be saved.

Parameters
----------
setDate : `bool`, optional
    Update the CALIBDATE fields in the metadata to the current
    time. Defaults to False.
kwargs :
    Other keyword parameters to set in the metadata.

Definition at line 127 of file linearize.py.

127  def updateMetadata(self, setDate=False, **kwargs):
128  """Update metadata keywords with new values.
129 
130  This calls the base class's method after ensuring the required
131  calibration keywords will be saved.
132 
133  Parameters
134  ----------
135  setDate : `bool`, optional
136  Update the CALIBDATE fields in the metadata to the current
137  time. Defaults to False.
138  kwargs :
139  Other keyword parameters to set in the metadata.
140  """
141  kwargs['HAS_LINEARITY'] = self.hasLinearity
142  kwargs['OVERRIDE'] = self.override
143  kwargs['HAS_TABLE'] = self.tableData is not None
144 
145  super().updateMetadata(setDate=setDate, **kwargs)
146 

◆ validate() [1/2]

def lsst.ip.isr.linearize.Linearizer.validate (   self,
  detector = None,
  amplifier = None 
)
Validate linearity for a detector/amplifier.

Parameters
----------
detector : `lsst.afw.cameraGeom.Detector`, optional
    Detector to validate, along with its amplifiers.
amplifier : `lsst.afw.cameraGeom.Amplifier`, optional
    Single amplifier to validate.

Raises
------
RuntimeError :
    Raised if there is a mismatch in linearity parameters, and
    the cameraGeom parameters are not being overridden.

Definition at line 371 of file linearize.py.

371  def validate(self, detector=None, amplifier=None):
372  """Validate linearity for a detector/amplifier.
373 
374  Parameters
375  ----------
376  detector : `lsst.afw.cameraGeom.Detector`, optional
377  Detector to validate, along with its amplifiers.
378  amplifier : `lsst.afw.cameraGeom.Amplifier`, optional
379  Single amplifier to validate.
380 
381  Raises
382  ------
383  RuntimeError :
384  Raised if there is a mismatch in linearity parameters, and
385  the cameraGeom parameters are not being overridden.
386  """
387  amplifiersToCheck = []
388  if detector:
389  if self._detectorName != detector.getName():
390  raise RuntimeError("Detector names don't match: %s != %s" %
391  (self._detectorName, detector.getName()))
392  if int(self._detectorId) != int(detector.getId()):
393  raise RuntimeError("Detector IDs don't match: %s != %s" %
394  (int(self._detectorId), int(detector.getId())))
395  if self._detectorSerial != detector.getSerial():
396  raise RuntimeError("Detector serial numbers don't match: %s != %s" %
397  (self._detectorSerial, detector.getSerial()))
398  if len(detector.getAmplifiers()) != len(self.linearityCoeffs.keys()):
399  raise RuntimeError("Detector number of amps = %s does not match saved value %s" %
400  (len(detector.getAmplifiers()),
401  len(self.linearityCoeffs.keys())))
402  amplifiersToCheck.extend(detector.getAmplifiers())
403 
404  if amplifier:
405  amplifiersToCheck.extend(amplifier)
406 
407  for amp in amplifiersToCheck:
408  ampName = amp.getName()
409  if ampName not in self.linearityCoeffs.keys():
410  raise RuntimeError("Amplifier %s is not in linearity data" %
411  (ampName, ))
412  if amp.getLinearityType() != self.linearityType[ampName]:
413  if self.override:
414  self.log.warn("Overriding amplifier defined linearityType (%s) for %s",
415  self.linearityType[ampName], ampName)
416  else:
417  raise RuntimeError("Amplifier %s type %s does not match saved value %s" %
418  (ampName, amp.getLinearityType(), self.linearityType[ampName]))
419  if (amp.getLinearityCoeffs().shape != self.linearityCoeffs[ampName].shape or not
420  np.allclose(amp.getLinearityCoeffs(), self.linearityCoeffs[ampName], equal_nan=True)):
421  if self.override:
422  self.log.warn("Overriding amplifier defined linearityCoeffs (%s) for %s",
423  self.linearityCoeffs[ampName], ampName)
424  else:
425  raise RuntimeError("Amplifier %s coeffs %s does not match saved value %s" %
426  (ampName, amp.getLinearityCoeffs(), self.linearityCoeffs[ampName]))
427 

◆ validate() [2/2]

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 534 of file calibType.py.

534  def validate(self, other=None):
535  """Validate that this calibration is defined and can be used.
536 
537  Parameters
538  ----------
539  other : `object`, optional
540  Thing to validate against.
541 
542  Returns
543  -------
544  valid : `bool`
545  Returns true if the calibration is valid and appropriate.
546  """
547  return False
548 

◆ 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 408 of file calibType.py.

408  def writeFits(self, filename):
409  """Write calibration data to a FITS file.
410 
411  Parameters
412  ----------
413  filename : `str`
414  Filename to write data to.
415 
416  Returns
417  -------
418  used : `str`
419  The name of the file used to write the data.
420 
421  """
422  tableList = self.toTable()
423  with warnings.catch_warnings():
424  warnings.filterwarnings("ignore", category=Warning, module="astropy.io")
425  astropyList = [fits.table_to_hdu(table) for table in tableList]
426  astropyList.insert(0, fits.PrimaryHDU())
427 
428  writer = fits.HDUList(astropyList)
429  writer.writeto(filename, overwrite=True)
430  return filename
431 
def writeFits(filename, stamp_ims, metadata, type_name, write_mask, write_variance)
Definition: stamps.py:40

◆ 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 316 of file calibType.py.

316  def writeText(self, filename, format='auto'):
317  """Write the calibration data to a text file.
318 
319  Parameters
320  ----------
321  filename : `str`
322  Name of the file to write.
323  format : `str`
324  Format to write the file as. Supported values are:
325  ``"auto"`` : Determine filetype from filename.
326  ``"yaml"`` : Write as yaml.
327  ``"ecsv"`` : Write as ecsv.
328  Returns
329  -------
330  used : `str`
331  The name of the file used to write the data. This may
332  differ from the input if the format is explicitly chosen.
333 
334  Raises
335  ------
336  RuntimeError :
337  Raised if filename does not end in a known extension, or
338  if all information cannot be written.
339 
340  Notes
341  -----
342  The file is written to YAML/ECSV format and will include any
343  associated metadata.
344 
345  """
346  if format == 'yaml' or (format == 'auto' and filename.lower().endswith((".yaml", ".YAML"))):
347  outDict = self.toDict()
348  path, ext = os.path.splitext(filename)
349  filename = path + ".yaml"
350  with open(filename, 'w') as f:
351  yaml.dump(outDict, f)
352  elif format == 'ecsv' or (format == 'auto' and filename.lower().endswith((".ecsv", ".ECSV"))):
353  tableList = self.toTable()
354  if len(tableList) > 1:
355  # ECSV doesn't support multiple tables per file, so we
356  # can only write the first table.
357  raise RuntimeError(f"Unable to persist {len(tableList)}tables in ECSV format.")
358 
359  table = tableList[0]
360  path, ext = os.path.splitext(filename)
361  filename = path + ".ecsv"
362  table.write(filename, format="ascii.ecsv")
363  else:
364  raise RuntimeError(f"Attempt to write to a file {filename} "
365  "that does not end in '.yaml' or '.ecsv'")
366 
367  return filename
368 

Member Data Documentation

◆ ampNames

lsst.ip.isr.linearize.Linearizer.ampNames

Definition at line 103 of file linearize.py.

◆ fitChiSq

lsst.ip.isr.linearize.Linearizer.fitChiSq

Definition at line 110 of file linearize.py.

◆ fitParams

lsst.ip.isr.linearize.Linearizer.fitParams

Definition at line 108 of file linearize.py.

◆ fitParamsErr

lsst.ip.isr.linearize.Linearizer.fitParamsErr

Definition at line 109 of file linearize.py.

◆ hasLinearity

lsst.ip.isr.linearize.Linearizer.hasLinearity

Definition at line 100 of file linearize.py.

◆ linearityBBox

lsst.ip.isr.linearize.Linearizer.linearityBBox

Definition at line 106 of file linearize.py.

◆ linearityCoeffs

lsst.ip.isr.linearize.Linearizer.linearityCoeffs

Definition at line 104 of file linearize.py.

◆ linearityType

lsst.ip.isr.linearize.Linearizer.linearityType

Definition at line 105 of file linearize.py.

◆ log

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

Definition at line 82 of file calibType.py.

◆ override

lsst.ip.isr.linearize.Linearizer.override

Definition at line 101 of file linearize.py.

◆ requiredAttributes

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

Definition at line 77 of file calibType.py.

◆ tableData

lsst.ip.isr.linearize.Linearizer.tableData

Definition at line 112 of file linearize.py.


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