lsst.ip.isr g9e598d6448+8c28d2aaf4
Loading...
Searching...
No Matches
linearize.py
Go to the documentation of this file.
2# LSST Data Management System
3# Copyright 2016 AURA/LSST.
4#
5# This product includes software developed by the
6# LSST Project (http://www.lsst.org/).
7#
8# This program is free software: you can redistribute it and/or modify
9# it under the terms of the GNU General Public License as published by
10# the Free Software Foundation, either version 3 of the License, or
11# (at your option) any later version.
12#
13# This program is distributed in the hope that it will be useful,
14# but WITHOUT ANY WARRANTY; without even the implied warranty of
15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16# GNU General Public License for more details.
17#
18# You should have received a copy of the LSST License Statement and
19# the GNU General Public License along with this program. If not,
20# see <http://www.lsstcorp.org/LegalNotices/>.
21#
22
23__all__ = [
24 "Linearizer",
25 "LinearizeBase",
26 "LinearizeLookupTable",
27 "LinearizeSquared",
28 "LinearizeProportional",
29 "LinearizePolynomial",
30 "LinearizeSpline",
31 "LinearizeDoubleSpline",
32 "LinearizeNone",
33]
34
35import abc
36import numpy as np
37from scipy.interpolate import Akima1DInterpolator
38
39from astropy.table import Table
40
41from lsst.pipe.base import Struct
42from lsst.geom import Box2I, Point2I, Extent2I
43from .applyLookupTable import applyLookupTable
44from .calibType import IsrCalib
45from .isrFunctions import isTrimmedImage
46
47
49 """Parameter set for linearization.
50
51 These parameters are included in `lsst.afw.cameraGeom.Amplifier`, but
52 should be accessible externally to allow for testing.
53
54 Parameters
55 ----------
56 table : `numpy.array`, optional
57 Lookup table; a 2-dimensional array of floats:
58
59 - one row for each row index (value of coef[0] in the amplifier)
60 - one column for each image value
61
62 To avoid copying the table the last index should vary fastest
63 (numpy default "C" order)
64 detector : `lsst.afw.cameraGeom.Detector`, optional
65 Detector object. Passed to self.fromDetector() on init.
66 log : `logging.Logger`, optional
67 Logger to handle messages.
68 kwargs : `dict`, optional
69 Other keyword arguments to pass to the parent init.
70
71 Raises
72 ------
73 RuntimeError
74 Raised if the supplied table is not 2D, or if the table has fewer
75 columns than rows (indicating that the indices are swapped).
76
77 Notes
78 -----
79 The linearizer attributes stored are:
80
81 hasLinearity : `bool`
82 Whether a linearity correction is defined for this detector.
83 override : `bool`
84 Whether the detector parameters should be overridden.
85 ampNames : `list` [`str`]
86 List of amplifier names to correct.
87 inputGain : `dict` [`str`, `float`]
88 Dictionary keyed by amplifirer name containing the input
89 gain from the PTC used to construct this linearizer.
90 inputTurnoff : `dict` [`str`, `float`]
91 Dictionary keyed by amplifier name containing the input
92 turnoff from the PTC used to construct this linearizer.
93 linearityCoeffs : `dict` [`str`, `np.ndarray`]
94 Coefficients to use in correction. Indexed by amplifier
95 names. The format of the array depends on the type of
96 correction to apply.
97 linearityType : `dict` [`str`, `str`]
98 Type of correction to use, indexed by amplifier names.
99 linearityBBox : `dict` [`str`, `lsst.geom.Box2I`]
100 Bounding box the correction is valid over, indexed by
101 amplifier names.
102 fitParams : `dict` [`str`, `np.ndarray`], optional
103 Linearity fit parameters used to construct the correction
104 coefficients, indexed as above.
105 fitParamsErr : `dict` [`str`, `np.ndarray`], optional
106 Uncertainty values of the linearity fit parameters used to
107 construct the correction coefficients, indexed as above.
108 fitChiSq : `dict` [`str`, `float`], optional
109 Chi-squared value of the linearity fit, indexed as above.
110 fitResiduals : `dict` [`str`, `np.ndarray`], optional
111 Residuals of the fit, indexed as above. Used for
112 calculating photodiode corrections
113 fitResidualsSigmaMad : `dict` [`str`, `float`], optional
114 Robust median-absolute-deviation of fit residuals, scaled
115 by the signal level.
116 fitResidualsUnmasked : `dict` [`str`, `np.ndarray`], optional
117 Same as fitResiduals, but all outliers are included and
118 not masked as nans.
119 fitResidualsModel : `dict` [`str`, `np.ndarray`], optional
120 The model count level for each of the fitResiduals.
121 linearFit : The linear fit to the low flux region of the curve.
122 [intercept, slope].
123 tableData : `np.ndarray`, optional
124 Lookup table data for the linearity correction.
125 inputAbscissa : `dict` [`str`, `np.ndarray`], optional
126 Input abscissa used to construct linearizer (usually photodiode
127 or exposure time).
128 inputOrdinate : `dict` [`str`, `np.ndarray`], optional
129 Input ordinate used to construct linearizer (raw mean counts).
130 inputMask : `dict` [`str`, `np.ndarray`], optional
131 Input mask used for the fitting.
132 inputGroupingIndex : `dict` [`str`, `np.ndarray`], optional
133 Input grouping index used for fitting.
134 inputNormalization : `dict` [`str`, `np.ndarray`], optional
135 Input normalization that was applied to the abscissa for
136 each pair from the PTC used for the linearization fit.
137 absoluteReferenceAmplifier : `str`, optional
138 Amplifier used for the reference for absolute linearization
139 (DoubleSpline) mode.
140
141 Version 1.4 adds ``linearityTurnoff`` and ``linearityMaxSignal``.
142 Version 1.5 adds ``fitResidualsUnmasked``, ``inputAbscissa``,
143 ``inputOrdinate``, ``inputMask``, ``inputGroupingIndex``,
144 ``fitResidualsModel``, and ``inputNormalization``.
145 Version 1.6 adds ``absoluteReferenceAmplifier``.
146 Version 1.7 adds ``inputGain``.
147 Version 1.8 adds ``inputTurnoff``.
148 """
149 _OBSTYPE = "LINEARIZER"
150 _SCHEMA = 'Gen3 Linearizer'
151 _VERSION = 1.8
152
153 def __init__(self, table=None, **kwargs):
154 self.hasLinearity = False
155 self.override = False
156
157 self.ampNames = list()
158 self.inputGain = dict()
159 self.inputTurnoff = dict()
160 self.linearityCoeffs = dict()
161 self.linearityType = dict()
162 self.linearityBBox = dict()
163 self.inputAbscissa = dict()
164 self.inputOrdinate = dict()
165 self.inputMask = dict()
166 self.inputGroupingIndex = dict()
167 self.inputNormalization = dict()
168 self.fitParams = dict()
169 self.fitParamsErr = dict()
170 self.fitChiSq = dict()
171 self.fitResiduals = dict()
174 self.fitResidualsModel = dict()
175 self.linearFit = dict()
176 self.linearityTurnoff = dict()
177 self.linearityMaxSignal = dict()
179 self.tableData = None
180 if table is not None:
181 if len(table.shape) != 2:
182 raise RuntimeError("table shape = %s; must have two dimensions" % (table.shape,))
183 if table.shape[1] < table.shape[0]:
184 raise RuntimeError("table shape = %s; indices are switched" % (table.shape,))
185 self.tableData = np.array(table, order="C")
186
187 # The linearizer is always natively in adu because it
188 # is computed prior to computing gains.
189 self.linearityUnits = 'adu'
190
191 # Cached linearizers.
192 self._linearizers = {}
193
194 super().__init__(**kwargs)
195 self.requiredAttributes.update(['hasLinearity', 'override',
196 'ampNames', 'inputGain', 'inputTurnoff',
197 'linearityCoeffs', 'linearityType', 'linearityBBox',
198 'fitParams', 'fitParamsErr', 'fitChiSq',
199 'fitResiduals', 'fitResidualsSigmaMad', 'linearFit', 'tableData',
200 'units', 'linearityTurnoff', 'linearityMaxSignal',
201 'fitResidualsUnmasked', 'inputAbscissa', 'inputOrdinate',
202 'inputMask', 'inputGroupingIndex', 'fitResidualsModel',
203 'inputNormalization', 'absoluteReferenceAmplifier'])
204
205 def updateMetadata(self, setDate=False, **kwargs):
206 """Update metadata keywords with new values.
207
208 This calls the base class's method after ensuring the required
209 calibration keywords will be saved.
210
211 Parameters
212 ----------
213 setDate : `bool`, optional
214 Update the CALIBDATE fields in the metadata to the current
215 time. Defaults to False.
216 kwargs :
217 Other keyword parameters to set in the metadata.
218 """
219 kwargs['HAS_LINEARITY'] = self.hasLinearity
220 kwargs['OVERRIDE'] = self.override
221 kwargs['HAS_TABLE'] = self.tableData is not None
222 kwargs['LINEARITY_UNITS'] = self.linearityUnits
223
224 super().updateMetadata(setDate=setDate, **kwargs)
225
226 def fromDetector(self, detector):
227 """Read linearity parameters from a detector.
228
229 Parameters
230 ----------
231 detector : `lsst.afw.cameraGeom.detector`
232 Input detector with parameters to use.
233
234 Returns
235 -------
236 calib : `lsst.ip.isr.Linearizer`
237 The calibration constructed from the detector.
238 """
239 self._detectorName = detector.getName()
240 self._detectorSerial = detector.getSerial()
241 self._detectorId = detector.getId()
242 self.hasLinearity = True
243
244 # Do not translate Threshold, Maximum, Units.
245 for amp in detector.getAmplifiers():
246 ampName = amp.getName()
247 self.ampNames.append(ampName)
248 self.linearityType[ampName] = amp.getLinearityType()
249 self.linearityCoeffs[ampName] = amp.getLinearityCoeffs()
250 self.linearityBBox[ampName] = amp.getBBox()
251
252 # Detector linearizers (legacy) are assumed to be adu units.
253 self.linearityUnits = 'adu'
254
255 return self
256
257 @classmethod
258 def fromDict(cls, dictionary):
259 """Construct a calibration from a dictionary of properties
260
261 Parameters
262 ----------
263 dictionary : `dict`
264 Dictionary of properties
265
266 Returns
267 -------
268 calib : `lsst.ip.isr.Linearity`
269 Constructed calibration.
270
271 Raises
272 ------
273 RuntimeError
274 Raised if the supplied dictionary is for a different
275 calibration.
276 """
277
278 calib = cls()
279
280 if calib._OBSTYPE != dictionary['metadata']['OBSTYPE']:
281 raise RuntimeError(f"Incorrect linearity supplied. Expected {calib._OBSTYPE}, "
282 f"found {dictionary['metadata']['OBSTYPE']}")
283
284 calib.setMetadata(dictionary['metadata'])
285
286 calib.hasLinearity = dictionary.get('hasLinearity',
287 dictionary['metadata'].get('HAS_LINEARITY', False))
288 calib.override = dictionary.get('override', True)
289
290 # Old linearizers which do not have linearityUnits are
291 # assumed to be adu because that's all that has been
292 # supported.
293 calib.linearityUnits = dictionary.get('linearityUnits', 'adu')
294
295 if calib.hasLinearity:
296 for ampName in dictionary['amplifiers']:
297 amp = dictionary['amplifiers'][ampName]
298 calib.ampNames.append(ampName)
299 # If gain = None on isrFunction.gainContext(),
300 # the default amp geometry gains are used
301 # in IsrTask*
302 calib.inputGain[ampName] = amp.get('inputGain', np.nan)
303 calib.inputTurnoff[ampName] = amp.get('inputTurnoff', np.inf)
304 calib.linearityCoeffs[ampName] = np.array(amp.get('linearityCoeffs', [0.0]))
305 calib.linearityType[ampName] = amp.get('linearityType', 'None')
306 calib.linearityBBox[ampName] = amp.get('linearityBBox', None)
307
308 calib.inputAbscissa[ampName] = np.array(amp.get('inputAbscissa', [0.0]))
309 calib.inputOrdinate[ampName] = np.array(amp.get('inputOrdinate', [0.0]))
310 calib.inputMask[ampName] = np.array(amp.get('inputMask', [False]))
311 calib.inputGroupingIndex[ampName] = np.array(amp.get('inputGroupingIndex', [0.0]))
312 calib.inputNormalization[ampName] = np.array(amp.get('inputNormalization', [1.0]))
313
314 calib.fitParams[ampName] = np.array(amp.get('fitParams', [0.0]))
315 calib.fitParamsErr[ampName] = np.array(amp.get('fitParamsErr', [0.0]))
316 calib.fitChiSq[ampName] = amp.get('fitChiSq', np.nan)
317 calib.fitResiduals[ampName] = np.array(amp.get('fitResiduals', [0.0]))
318 calib.fitResidualsSigmaMad[ampName] = np.array(amp.get('fitResidualsSigmaMad', np.nan))
319 calib.fitResidualsUnmasked[ampName] = np.array(amp.get('fitResidualsUnmasked', [0.0]))
320 calib.fitResidualsModel[ampName] = np.array(amp.get('fitResidualsModel', [0.0]))
321 calib.linearFit[ampName] = np.array(amp.get('linearFit', [0.0]))
322
323 calib.linearityTurnoff[ampName] = np.array(amp.get('linearityTurnoff', np.nan))
324 calib.linearityMaxSignal[ampName] = np.array(amp.get('linearityMaxSignal', np.nan))
325
326 calib.tableData = dictionary.get('tableData', None)
327 if calib.tableData:
328 calib.tableData = np.array(calib.tableData)
329
330 calib.absoluteReferenceAmplifier = dictionary.get(
331 'absoluteReferenceAmplifier', calib.absoluteReferenceAmplifier,
332 )
333
334 return calib
335
336 def toDict(self):
337 """Return linearity parameters as a dict.
338
339 Returns
340 -------
341 outDict : `dict`:
342 """
343 self.updateMetadata()
344
345 outDict = {'metadata': self.getMetadata(),
346 'detectorName': self._detectorName,
347 'detectorSerial': self._detectorSerial,
348 'detectorId': self._detectorId,
349 'hasTable': self.tableData is not None,
350 'amplifiers': dict(),
351 'linearityUnits': self.linearityUnits,
352 }
353 for ampName in self.linearityType:
354 outDict['amplifiers'][ampName] = {
355 'inputGain': self.inputGain[ampName],
356 'inputTurnoff': self.inputTurnoff[ampName],
357 'linearityType': self.linearityType[ampName],
358 'linearityCoeffs': self.linearityCoeffs[ampName].tolist(),
359 'linearityBBox': self.linearityBBox[ampName],
360 'inputAbscissa': self.inputAbscissa[ampName].tolist(),
361 'inputOrdinate': self.inputOrdinate[ampName].tolist(),
362 'inputMask': self.inputMask[ampName].tolist(),
363 'inputGroupingIndex': self.inputGroupingIndex[ampName].tolist(),
364 'inputNormalization': self.inputNormalization[ampName].tolist(),
365 'fitParams': self.fitParams[ampName].tolist(),
366 'fitParamsErr': self.fitParamsErr[ampName].tolist(),
367 'fitChiSq': self.fitChiSq[ampName],
368 'fitResiduals': self.fitResiduals[ampName].tolist(),
369 'fitResidualsSigmaMad': self.fitResidualsSigmaMad[ampName],
370 'fitResidualsUnmasked': self.fitResidualsUnmasked[ampName].tolist(),
371 'fitResidualsModel': self.fitResidualsModel[ampName].tolist(),
372 'linearFit': self.linearFit[ampName].tolist(),
373 'linearityTurnoff': self.linearityTurnoff[ampName],
374 'linearityMaxSignal': self.linearityMaxSignal[ampName],
375 }
376 if self.tableData is not None:
377 outDict['tableData'] = self.tableData.tolist()
378
379 outDict['absoluteReferenceAmplifier'] = self.absoluteReferenceAmplifier
380
381 return outDict
382
383 @classmethod
384 def fromTable(cls, tableList):
385 """Read linearity from a FITS file.
386
387 This method uses the `fromDict` method to create the
388 calibration, after constructing an appropriate dictionary from
389 the input tables.
390
391 Parameters
392 ----------
393 tableList : `list` [`astropy.table.Table`]
394 afwTable read from input file name.
395
396 Returns
397 -------
398 linearity : `~lsst.ip.isr.linearize.Linearizer``
399 Linearity parameters.
400
401 Notes
402 -----
403 The method reads a FITS file with 1 or 2 extensions. The metadata is
404 read from the header of extension 1, which must exist. Then the table
405 is loaded, and the ['AMPLIFIER_NAME', 'TYPE', 'COEFFS', 'BBOX_X0',
406 'BBOX_Y0', 'BBOX_DX', 'BBOX_DY'] columns are read and used to set each
407 dictionary by looping over rows.
408 Extension 2 is then attempted to read in the try block (which only
409 exists for lookup tables). It has a column named 'LOOKUP_VALUES' that
410 contains a vector of the lookup entries in each row.
411 """
412 coeffTable = tableList[0]
413
414 metadata = coeffTable.meta
415 inDict = dict()
416 inDict['metadata'] = metadata
417 inDict['hasLinearity'] = metadata.get('HAS_LINEARITY', False)
418 inDict['amplifiers'] = dict()
419 inDict['linearityUnits'] = metadata.get('LINEARITY_UNITS', 'adu')
420
421 for record in coeffTable:
422 ampName = record['AMPLIFIER_NAME']
423 inputGain = record['INPUT_GAIN'] if 'INPUT_GAIN' in record.columns else np.nan
424 inputTurnoff = record['INPUT_TURNOFF'] if 'INPUT_TURNOFF' in record.columns else np.inf
425 inputAbscissa = record['INP_ABSCISSA'] if 'INP_ABSCISSA' in record.columns else np.array([0.0])
426 inputOrdinate = record['INP_ORDINATE'] if 'INP_ORDINATE' in record.columns else np.array([0.0])
427 inputMask = record['INP_MASK'] if 'INP_MASK' in record.columns else np.array([False])
428 inputGroupingIndex = record['INP_GROUPING_INDEX'] if 'INP_GROUPING_INDEX' in record.columns \
429 else np.array([0])
430 inputNormalization = record['INP_NORMALIZATION'] if 'INP_NORMALIZATION' in record.columns \
431 else np.array([1.0])
432 fitParams = record['FIT_PARAMS'] if 'FIT_PARAMS' in record.columns else np.array([0.0])
433 fitParamsErr = record['FIT_PARAMS_ERR'] if 'FIT_PARAMS_ERR' in record.columns else np.array([0.0])
434 fitChiSq = record['RED_CHI_SQ'] if 'RED_CHI_SQ' in record.columns else np.nan
435 fitResiduals = record['FIT_RES'] if 'FIT_RES' in record.columns else np.array([0.0])
436 fitResidualsSigmaMad = record['FIT_RES_SIGMAD'] if 'FIT_RES_SIGMAD' in record.columns else np.nan
437 fitResidualsUnmasked = record['FIT_RES_UNMASKED'] \
438 if 'FIT_RES_UNMASKED' in record.columns else np.array([0.0])
439 fitResidualsModel = record['FIT_RES_MODEL'] \
440 if 'FIT_RES_MODEL' in record.columns else np.array([0.0])
441 linearFit = record['LIN_FIT'] if 'LIN_FIT' in record.columns else np.array([0.0])
442
443 linearityTurnoff = record['LINEARITY_TURNOFF'] if 'LINEARITY_TURNOFF' in record.columns \
444 else np.nan
445 linearityMaxSignal = record['LINEARITY_MAX_SIGNAL'] if 'LINEARITY_MAX_SIGNAL' in record.columns \
446 else np.nan
447
448 inDict['amplifiers'][ampName] = {
449 'inputGain': inputGain,
450 'inputTurnoff': inputTurnoff,
451 'linearityType': record['TYPE'],
452 'linearityCoeffs': record['COEFFS'],
453 'linearityBBox': Box2I(Point2I(record['BBOX_X0'], record['BBOX_Y0']),
454 Extent2I(record['BBOX_DX'], record['BBOX_DY'])),
455 'inputAbscissa': inputAbscissa,
456 'inputOrdinate': inputOrdinate,
457 'inputMask': inputMask,
458 'inputGroupingIndex': inputGroupingIndex,
459 'inputNormalization': inputNormalization,
460 'fitParams': fitParams,
461 'fitParamsErr': fitParamsErr,
462 'fitChiSq': fitChiSq,
463 'fitResiduals': fitResiduals,
464 'fitResidualsSigmaMad': fitResidualsSigmaMad,
465 'fitResidualsUnmasked': fitResidualsUnmasked,
466 'fitResidualsModel': fitResidualsModel,
467 'linearFit': linearFit,
468 'linearityTurnoff': linearityTurnoff,
469 'linearityMaxSignal': linearityMaxSignal,
470 }
471
472 if len(tableList) > 1:
473 tableData = tableList[1]
474 inDict['tableData'] = [record['LOOKUP_VALUES'] for record in tableData]
475
476 if 'ABS_REF_AMP' in coeffTable.columns:
477 inDict['absoluteReferenceAmplifier'] = str(coeffTable['ABS_REF_AMP'][0])
478 else:
479 inDict['absoluteReferenceAmplifier'] = ''
480
481 return cls().fromDict(inDict)
482
483 def toTable(self):
484 """Construct a list of tables containing the information in this
485 calibration.
486
487 The list of tables should create an identical calibration
488 after being passed to this class's fromTable method.
489
490 Returns
491 -------
492 tableList : `list` [`astropy.table.Table`]
493 List of tables containing the linearity calibration
494 information.
495 """
496
497 tableList = []
498 self.updateMetadata()
499 catalog = Table([{'AMPLIFIER_NAME': ampName,
500 'INPUT_GAIN': self.inputGain[ampName],
501 'INPUT_TURNOFF': self.inputTurnoff[ampName],
502 'TYPE': self.linearityType[ampName],
503 'COEFFS': self.linearityCoeffs[ampName],
504 'BBOX_X0': self.linearityBBox[ampName].getMinX(),
505 'BBOX_Y0': self.linearityBBox[ampName].getMinY(),
506 'BBOX_DX': self.linearityBBox[ampName].getWidth(),
507 'BBOX_DY': self.linearityBBox[ampName].getHeight(),
508 'INP_ABSCISSA': self.inputAbscissa[ampName],
509 'INP_ORDINATE': self.inputOrdinate[ampName],
510 'INP_MASK': self.inputMask[ampName],
511 'INP_GROUPING_INDEX': self.inputGroupingIndex[ampName],
512 'INP_NORMALIZATION': self.inputNormalization[ampName],
513 'FIT_PARAMS': self.fitParams[ampName],
514 'FIT_PARAMS_ERR': self.fitParamsErr[ampName],
515 'RED_CHI_SQ': self.fitChiSq[ampName],
516 'FIT_RES': self.fitResiduals[ampName],
517 'FIT_RES_SIGMAD': self.fitResidualsSigmaMad[ampName],
518 'FIT_RES_UNMASKED': self.fitResidualsUnmasked[ampName],
519 'FIT_RES_MODEL': self.fitResidualsModel[ampName],
520 'LIN_FIT': self.linearFit[ampName],
521 'LINEARITY_TURNOFF': self.linearityTurnoff[ampName],
522 'LINEARITY_MAX_SIGNAL': self.linearityMaxSignal[ampName],
523 'ABS_REF_AMP': self.absoluteReferenceAmplifier,
524 } for ampName in self.ampNames])
525 catalog.meta = self.getMetadata().toDict()
526 tableList.append(catalog)
527
528 if self.tableData is not None:
529 catalog = Table([{'LOOKUP_VALUES': value} for value in self.tableData])
530 tableList.append(catalog)
531 return tableList
532
533 def getLinearityTypeByName(self, linearityTypeName):
534 """Determine the linearity class to use from the type name.
535
536 Parameters
537 ----------
538 linearityTypeName : str
539 String name of the linearity type that is needed.
540
541 Returns
542 -------
543 linearityType : `~lsst.ip.isr.linearize.LinearizeBase`
544 The appropriate linearity class to use. If no matching class
545 is found, `None` is returned.
546 """
547 for t in [LinearizeLookupTable,
548 LinearizeSquared,
549 LinearizePolynomial,
550 LinearizeProportional,
551 LinearizeSpline,
552 LinearizeDoubleSpline,
553 LinearizeNone]:
554 if t.LinearityType == linearityTypeName:
555 return t
556 return None
557
558 def validate(self, detector=None, amplifier=None):
559 """Validate linearity for a detector/amplifier.
560
561 Parameters
562 ----------
563 detector : `lsst.afw.cameraGeom.Detector`, optional
564 Detector to validate, along with its amplifiers.
565 amplifier : `lsst.afw.cameraGeom.Amplifier`, optional
566 Single amplifier to validate.
567
568 Raises
569 ------
570 RuntimeError
571 Raised if there is a mismatch in linearity parameters, and
572 the cameraGeom parameters are not being overridden.
573 """
574 amplifiersToCheck = []
575 if detector:
576 if self._detectorName != detector.getName():
577 raise RuntimeError("Detector names don't match: %s != %s" %
578 (self._detectorName, detector.getName()))
579 if int(self._detectorId) != int(detector.getId()):
580 raise RuntimeError("Detector IDs don't match: %s != %s" %
581 (int(self._detectorId), int(detector.getId())))
582 # TODO: DM-38778: This check fails on LATISS due to an
583 # error in the camera configuration.
584 # if self._detectorSerial != detector.getSerial():
585 # raise RuntimeError(
586 # "Detector serial numbers don't match: %s != %s" %
587 # (self._detectorSerial, detector.getSerial()))
588 if len(detector.getAmplifiers()) != len(self.linearityCoeffs.keys()):
589 raise RuntimeError("Detector number of amps = %s does not match saved value %s" %
590 (len(detector.getAmplifiers()),
591 len(self.linearityCoeffs.keys())))
592 amplifiersToCheck.extend(detector.getAmplifiers())
593
594 if amplifier:
595 amplifiersToCheck.extend(amplifier)
596
597 for amp in amplifiersToCheck:
598 ampName = amp.getName()
599 if ampName not in self.linearityCoeffs.keys():
600 raise RuntimeError("Amplifier %s is not in linearity data" %
601 (ampName, ))
602 if amp.getLinearityType() != self.linearityType[ampName]:
603 if self.override:
604 self.log.debug("Overriding amplifier defined linearityType (%s) for %s",
605 self.linearityType[ampName], ampName)
606 else:
607 raise RuntimeError("Amplifier %s type %s does not match saved value %s" %
608 (ampName, amp.getLinearityType(), self.linearityType[ampName]))
609 if (amp.getLinearityCoeffs().shape != self.linearityCoeffs[ampName].shape or not
610 np.allclose(amp.getLinearityCoeffs(), self.linearityCoeffs[ampName], equal_nan=True)):
611 if self.override:
612 self.log.debug("Overriding amplifier defined linearityCoeffs (%s) for %s",
613 self.linearityCoeffs[ampName], ampName)
614 else:
615 raise RuntimeError("Amplifier %s coeffs %s does not match saved value %s" %
616 (ampName, amp.getLinearityCoeffs(), self.linearityCoeffs[ampName]))
617
618 def applyLinearity(self, image, detector=None, log=None, gains=None):
619 """Apply the linearity to an image.
620
621 If the linearity parameters are populated, use those,
622 otherwise use the values from the detector.
623
624 Parameters
625 ----------
626 image : `~lsst.afw.image.image`
627 Image to correct.
628 detector : `~lsst.afw.cameraGeom.detector`, optional
629 Detector to use to determine exposure trimmed state. If
630 supplied, but no other linearity information is provided
631 by the calibration, then the static solution stored in the
632 detector will be used.
633 log : `~logging.Logger`, optional
634 Log object to use for logging.
635 gains : `dict` [`str`, `float`], optional
636 Dictionary of amp name to gain. If this is provided then
637 linearity terms will be converted from adu to electrons.
638 Only used for Spline linearity corrections.
639 """
640 if log is None:
641 log = self.log
642 if detector and not self.hasLinearity:
643 self.fromDetector(detector)
644
645 self.validate(detector)
646
647 # Check if the image is trimmed.
648 isTrimmed = None
649 if detector:
650 isTrimmed = isTrimmedImage(image, detector)
651
652 numAmps = 0
653 numLinearized = 0
654 numOutOfRange = 0
655 for ampName in self.linearityType.keys():
656 # Cache the linearizers.
657 if ampName not in self._linearizers:
658 self._linearizers[ampName] = self.getLinearityTypeByName(self.linearityType[ampName])()
659
660 linearizer = self._linearizers[ampName]
661
662 numAmps += 1
663
664 if gains and self.linearityUnits == 'adu':
665 gainValue = gains[ampName]
666 else:
667 gainValue = 1.0
668
669 # If the gain is NaN, then this is a no-op
670 if np.isnan(gainValue):
671 log.warning("Gain value for amp %s is NaN, skipping "
672 "linearization.", ampName)
673 continue
674
675 if linearizer is not None:
676 match isTrimmed:
677 case True:
678 bbox = detector[ampName].getBBox()
679 case False:
680 bbox = detector[ampName].getRawBBox()
681 case None:
682 bbox = self.linearityBBox[ampName]
683
684 ampView = image.Factory(image, bbox)
685 success, outOfRange = linearizer(ampView, **{'coeffs': self.linearityCoeffs[ampName],
686 'table': self.tableData,
687 'log': self.log,
688 'gain': gainValue})
689 numOutOfRange += outOfRange
690 if success:
691 numLinearized += 1
692 elif log is not None:
693 log.warning("Amplifier %s did not linearize.",
694 ampName)
695 return Struct(
696 numAmps=numAmps,
697 numLinearized=numLinearized,
698 numOutOfRange=numOutOfRange
699 )
700
701
702class LinearizeBase(metaclass=abc.ABCMeta):
703 """Abstract base class functor for correcting non-linearity.
704
705 Subclasses must define ``__call__`` and set class variable
706 LinearityType to a string that will be used for linearity type in
707 the cameraGeom.Amplifier.linearityType field.
708
709 All linearity corrections should be defined in terms of an
710 additive correction, such that:
711
712 corrected_value = uncorrected_value + f(uncorrected_value)
713 """
714 LinearityType = None # linearity type, a string used for AmpInfoCatalogs
715
716 @abc.abstractmethod
717 def __call__(self, image, **kwargs):
718 """Correct non-linearity.
719
720 Parameters
721 ----------
722 image : `lsst.afw.image.Image`
723 Image to be corrected
724 kwargs : `dict`
725 Dictionary of parameter keywords:
726
727 ``coeffs``
728 Coefficient vector (`list` or `np.ndarray`).
729 ``table``
730 Lookup table data (`np.ndarray`).
731 ``log``
732 Logger to handle messages (`logging.Logger`).
733
734 Returns
735 -------
736 output : `bool`
737 If `True`, a correction was applied successfully.
738
739 Raises
740 ------
741 RuntimeError:
742 Raised if the linearity type listed in the
743 detector does not match the class type.
744 """
745 pass
746
747
748class LinearizeLookupTable(LinearizeBase):
749 """Correct non-linearity with a persisted lookup table.
750
751 The lookup table consists of entries such that given
752 "coefficients" c0, c1:
753
754 for each i,j of image:
755 rowInd = int(c0)
756 colInd = int(c1 + uncorrImage[i,j])
757 corrImage[i,j] = uncorrImage[i,j] + table[rowInd, colInd]
758
759 - c0: row index; used to identify which row of the table to use
760 (typically one per amplifier, though one can have multiple
761 amplifiers use the same table)
762 - c1: column index offset; added to the uncorrected image value
763 before truncation; this supports tables that can handle
764 negative image values; also, if the c1 ends with .5 then
765 the nearest index is used instead of truncating to the
766 next smaller index
767 """
768 LinearityType = "LookupTable"
769
770 def __call__(self, image, **kwargs):
771 """Correct for non-linearity.
772
773 Parameters
774 ----------
775 image : `lsst.afw.image.Image`
776 Image to be corrected
777 kwargs : `dict`
778 Dictionary of parameter keywords:
779
780 ``coeffs``
781 Columnation vector (`list` or `np.ndarray`).
782 ``table``
783 Lookup table data (`np.ndarray`).
784 ``log``
785 Logger to handle messages (`logging.Logger`).
786
787 Returns
788 -------
789 output : `tuple` [`bool`, `int`]
790 If true, a correction was applied successfully. The
791 integer indicates the number of pixels that were
792 uncorrectable by being out of range.
793
794 Raises
795 ------
796 RuntimeError:
797 Raised if the requested row index is out of the table
798 bounds.
799 """
800 numOutOfRange = 0
801
802 rowInd, colIndOffset = kwargs['coeffs'][0:2]
803 table = kwargs['table']
804 log = kwargs['log']
805
806 numTableRows = table.shape[0]
807 rowInd = int(rowInd)
808 if rowInd < 0 or rowInd > numTableRows:
809 raise RuntimeError("LinearizeLookupTable rowInd=%s not in range[0, %s)" %
810 (rowInd, numTableRows))
811 tableRow = np.array(table[rowInd, :], dtype=image.getArray().dtype)
812
813 numOutOfRange += applyLookupTable(image, tableRow, colIndOffset)
814
815 if numOutOfRange > 0 and log is not None:
816 log.warning("%s pixels were out of range of the linearization table",
817 numOutOfRange)
818 if numOutOfRange < image.getArray().size:
819 return True, numOutOfRange
820 else:
821 return False, numOutOfRange
822
823
825 """Correct non-linearity with a polynomial mode.
826
827 .. code-block::
828
829 corrImage = uncorrImage + sum_i c_i uncorrImage^(2 + i)
830
831 where ``c_i`` are the linearity coefficients for each amplifier.
832 Lower order coefficients are not included as they duplicate other
833 calibration parameters:
834
835 ``k0``
836 A coefficient multiplied by ``uncorrImage**0`` is equivalent to
837 bias level. Irrelevant for correcting non-linearity.
838 ``k1``
839 A coefficient multiplied by ``uncorrImage**1`` is proportional
840 to the gain. Not necessary for correcting non-linearity.
841 """
842 LinearityType = "Polynomial"
843
844 def __call__(self, image, **kwargs):
845 """Correct non-linearity.
846
847 Parameters
848 ----------
849 image : `lsst.afw.image.Image`
850 Image to be corrected
851 kwargs : `dict`
852 Dictionary of parameter keywords:
853
854 ``coeffs``
855 Coefficient vector (`list` or `np.ndarray`).
856 If the order of the polynomial is n, this list
857 should have a length of n-1 ("k0" and "k1" are
858 not needed for the correction).
859 ``log``
860 Logger to handle messages (`logging.Logger`).
861
862 Returns
863 -------
864 output : `tuple` [`bool`, `int`]
865 If true, a correction was applied successfully. The
866 integer indicates the number of pixels that were
867 uncorrectable by being out of range.
868 """
869 if not np.any(np.isfinite(kwargs['coeffs'])):
870 return False, 0
871 if not np.any(kwargs['coeffs']):
872 return False, 0
873
874 ampArray = image.getArray()
875 correction = np.zeros_like(ampArray)
876 for order, coeff in enumerate(kwargs['coeffs'], start=2):
877 correction += coeff * np.power(ampArray, order)
878 ampArray += correction
879
880 return True, 0
881
882
884 """Correct non-linearity with a squared model.
885
886 corrImage = uncorrImage + c0*uncorrImage^2
887
888 where c0 is linearity coefficient 0 for each amplifier.
889 """
890 LinearityType = "Squared"
891
892 def __call__(self, image, **kwargs):
893 """Correct for non-linearity.
894
895 Parameters
896 ----------
897 image : `lsst.afw.image.Image`
898 Image to be corrected
899 kwargs : `dict`
900 Dictionary of parameter keywords:
901
902 ``coeffs``
903 Coefficient vector (`list` or `np.ndarray`).
904 ``log``
905 Logger to handle messages (`logging.Logger`).
906
907 Returns
908 -------
909 output : `tuple` [`bool`, `int`]
910 If true, a correction was applied successfully. The
911 integer indicates the number of pixels that were
912 uncorrectable by being out of range.
913 """
914
915 sqCoeff = kwargs['coeffs'][0]
916 if sqCoeff != 0:
917 ampArr = image.getArray()
918 ampArr *= (1 + sqCoeff*ampArr)
919 return True, 0
920 else:
921 return False, 0
922
923
925 """Turn a spline or double spline into a lookup table.
926
927 Parameters
928 ----------
929 centers1 : `np.ndarray`
930 Akima spline centers for first spline (ADU).
931 values1 : `np.ndarray`
932 Akima spline values for first spline (ADU).
933 centers2 : `np.ndarray`, optional
934 Akima spline centers for second spline (ADU).
935 values2 : `np.ndarray`, optional
936 Akima spline values for second spline (ADU).
937 high_clip : `float`, optional
938 Clip to use at the high end (for backwards compatibility).
939 n_step : `int`, optional
940 Number of steps in the LUT.
941 """
942 def __init__(self, centers1, values1, centers2=None, values2=None, high_clip=0.01, n_step=2**20):
943 # Built once in ADU; gain-independent.
944
945 # Build the LUT in ADU, to be gain independent.
946
947 interp1 = Akima1DInterpolator(centers1, values1, method="akima")
948
949 if centers1[0] != 0.0:
950 raise ValueError("Spline1 should be anchored at zero.")
951
952 if centers2 is not None:
953 interp2 = Akima1DInterpolator(centers2, values2, method="akima")
954 if centers2[0] != 0.0:
955 raise ValueError("Spline2 should be anchored at zero.")
956
957 x_max = max(centers1[-1], centers2[-1])
958 else:
959 x_max = centers1[-1]
960
961 x = np.linspace(0.0, x_max, n_step)
962 u = x.copy()
963 u -= interp1(np.clip(u, centers1[0], centers1[-1] - high_clip))
964 if centers2 is not None:
965 u -= interp2(np.clip(u, centers2[0], centers2[-1] - high_clip))
966
967 # Total correction (float64)
968 self.corr_adu = x - u
969 self.x_max = x_max
970 self.dx = x[1] - x[0]
971 self._cache = {}
972
973 def _for_gain(self, gain):
974 """Scale LUT to the appropriate gain.
975
976 Parameters
977 ----------
978 gain : `float`
979
980 Returns
981 -------
982 entry : `tuple`
983 table in electrons; scale used.
984 """
985 entry = self._cache.get(gain)
986 if entry is None:
987 # Only allow one gain entry.
988 self._cache = {}
989 entry = (
990 (gain * self.corr_adu).astype(np.float32), # table in electrons
991 np.float32(1.0 / (gain * self.dx)), # scale
992 )
993 self._cache[gain] = entry
994 return entry
995
996 def __call__(self, array, gain=1.0):
997 """Get linearizer from LUT.
998
999 Parameters
1000 ----------
1001 array : `np.ndarray`
1002 Array to linearize (in place).
1003 gain : `float`, optional
1004 Gain to scale.
1005 """
1006 if not np.isfinite(gain):
1007 array[:] = np.nan
1008 return
1009
1010 table, scale = self._for_gain(gain)
1011 t = array * scale
1012 t += np.float32(0.5)
1013 with np.errstate(invalid="ignore"):
1014 # NaN/inf -> int cast warns
1015 k = t.astype(np.int32)
1016 array -= table.take(k, mode="clip")
1017
1018
1020 """Correct non-linearity with a spline model.
1021
1022 corrImage = uncorrImage - Spline(coeffs, uncorrImage)
1023
1024 Notes
1025 -----
1026
1027 The spline fit calculates a correction as a function of the
1028 expected linear flux term. Because of this, the correction needs
1029 to be subtracted from the observed flux.
1030
1031 """
1032 LinearityType = "Spline"
1033 _lut = None
1034 _bad_amp = False
1035
1036 def __call__(self, image, **kwargs):
1037 """Correct for non-linearity.
1038
1039 Parameters
1040 ----------
1041 image : `lsst.afw.image.Image`
1042 Image to be corrected
1043 kwargs : `dict`
1044 Dictionary of parameter keywords:
1045
1046 ``coeffs``
1047 Coefficient vector (`list` or `np.ndarray`).
1048 ``log``
1049 Logger to handle messages (`logging.Logger`).
1050 ``gain``
1051 Gain value to apply.
1052
1053 Returns
1054 -------
1055 output : `tuple` [`bool`, `int`]
1056 If true, a correction was applied successfully. The
1057 integer indicates the number of pixels that were
1058 uncorrectable by being out of range.
1059 """
1060 splineCoeff = kwargs['coeffs']
1061 gain = kwargs.get('gain', 1.0)
1062
1063 if self._lut is None:
1064 centers, values = np.split(splineCoeff, 2)
1065 # Note that we must do a copy here because the input array
1066 # may not be volatile memory.
1067 centers = centers.copy()
1068 values = values.copy()
1069 # If the spline is not anchored at zero, remove the offset
1070 # found at the lowest flux available, and add an anchor at
1071 # flux=0.0 if there's no entry at that point.
1072 if values[0] != 0:
1073 offset = values[0]
1074 values -= offset
1075 if centers[0] != 0.0:
1076 centers = np.concatenate(([0.0], centers))
1077 values = np.concatenate(([0.0], values))
1078
1079 if np.any(~np.isfinite(centers)) or np.any(~np.isfinite(values)):
1080 # This cannot be used; turns everything into nans.
1081 self._bad_amp = True
1082 # Put in a sentinel (not-None) value for the LUT.
1083 self._lut = False
1084 else:
1085 self._lut = SplineLUT(centers, values, high_clip=0.1)
1086
1087 if self._bad_amp:
1088 image.array[:] = np.nan
1089
1090 return False, 0
1091
1092 self._lut(image.array, gain=gain)
1093
1094 return True, 0
1095
1096
1098 """Correct non-linearity with a spline model.
1099
1100 corrImage1 = uncorrImage - Spline1(coeffs, uncorrImage)
1101 corrImage = corrImage1 - Spline2(coeffs, corrImage1)
1102
1103 Notes
1104 -----
1105
1106 The spline fit calculates a correction as a function of the
1107 expected linear flux term. Because of this, the correction needs
1108 to be subtracted from the observed flux.
1109
1110 """
1111 LinearityType = "DoubleSpline"
1112 _lut = None
1113 _bad_amp = False
1114
1115 def __call__(self, image, **kwargs):
1116 """Correct for non-linearity.
1117
1118 Parameters
1119 ----------
1120 image : `lsst.afw.image.Image`
1121 Image to be corrected
1122 kwargs : `dict`
1123 Dictionary of parameter keywords:
1124
1125 ``coeffs``
1126 Coefficient vector (`list` or `np.ndarray`).
1127 ``log``
1128 Logger to handle messages (`logging.Logger`).
1129 ``gain``
1130 Gain value to apply.
1131
1132 Returns
1133 -------
1134 output : `tuple` [`bool`, `int`]
1135 If true, a correction was applied successfully. The
1136 integer indicates the number of pixels that were
1137 uncorrectable by being out of range.
1138 """
1139 coeffs = kwargs['coeffs']
1140 gain = kwargs.get('gain', 1.0)
1141
1142 if self._lut is None:
1143 # The coeffs have [nNodes1, nNodes2,
1144 # nodes1, centers1,
1145 # nodes2, centers2]
1146
1147 nNodes1 = int(coeffs[0])
1148 nNodes2 = int(coeffs[1])
1149
1150 if nNodes1 > 0:
1151 splineCoeff1 = coeffs[2: 2 + 2*nNodes1]
1152 centers1, values1 = np.split(splineCoeff1, 2)
1153
1154 if np.any(~np.isfinite(centers1)) or np.any(~np.isfinite(values1)):
1155 # This cannot be used; turns everything into nans.
1156 self._bad_amp = True
1157 # Put in a sentinel (not-None) value for the LUT.
1158 self._lut = False
1159 else:
1160 centers1 = None
1161 values1 = None
1162
1163 if nNodes2 > 0:
1164 splineCoeff2 = coeffs[2 + 2*nNodes1: 2 + 2*nNodes1 + 2*nNodes2]
1165 centers2, values2 = np.split(splineCoeff2, 2)
1166
1167 if np.any(~np.isfinite(centers2)) or np.any(~np.isfinite(values2)):
1168 # This cannot be used; turns everything into nans.
1169 self._bad_amp = True
1170 # Put in a sentinel (not-None) value for the LUT.
1171 self._lut = False
1172 else:
1173 centers2 = None
1174 values2 = None
1175
1176 if centers1 is not None and centers2 is not None:
1177 self._lut = SplineLUT(centers1, values1, centers2=centers2, values2=values2)
1178 elif centers1 is not None:
1179 self._lut = SplineLUT(centers1, values1)
1180 elif centers2 is not None:
1181 self._lut = SplineLUT(centers2, values2)
1182 else:
1183 self._bad_amp = True
1184 self._lut = False
1185
1186 if self._bad_amp:
1187 image.array[:] = np.nan
1188 return False, 0
1189
1190 self._lut(image.array, gain=gain)
1191
1192 return True, 0
1193
1194
1196 """Do not correct non-linearity.
1197 """
1198 LinearityType = "Proportional"
1199
1200 def __call__(self, image, **kwargs):
1201 """Do not correct for non-linearity.
1202
1203 Parameters
1204 ----------
1205 image : `lsst.afw.image.Image`
1206 Image to be corrected
1207 kwargs : `dict`
1208 Dictionary of parameter keywords:
1209
1210 ``coeffs``
1211 Coefficient vector (`list` or `np.ndarray`).
1212 ``log``
1213 Logger to handle messages (`logging.Logger`).
1214
1215 Returns
1216 -------
1217 output : `tuple` [`bool`, `int`]
1218 If true, a correction was applied successfully. The
1219 integer indicates the number of pixels that were
1220 uncorrectable by being out of range.
1221 """
1222 return True, 0
1223
1224
1226 """Do not correct non-linearity.
1227 """
1228 LinearityType = "None"
1229
1230 def __call__(self, image, **kwargs):
1231 """Do not correct for non-linearity.
1232
1233 Parameters
1234 ----------
1235 image : `lsst.afw.image.Image`
1236 Image to be corrected
1237 kwargs : `dict`
1238 Dictionary of parameter keywords:
1239
1240 ``coeffs``
1241 Coefficient vector (`list` or `np.ndarray`).
1242 ``log``
1243 Logger to handle messages (`logging.Logger`).
1244
1245 Returns
1246 -------
1247 output : `tuple` [`bool`, `int`]
1248 If true, a correction was applied successfully. The
1249 integer indicates the number of pixels that were
1250 uncorrectable by being out of range.
1251 """
1252 return True, 0
updateMetadata(self, camera=None, detector=None, filterName=None, setCalibId=False, setCalibInfo=False, setDate=False, **kwargs)
Definition calibType.py:210
__call__(self, image, **kwargs)
Definition linearize.py:717
__call__(self, image, **kwargs)
getLinearityTypeByName(self, linearityTypeName)
Definition linearize.py:533
__init__(self, table=None, **kwargs)
Definition linearize.py:153
updateMetadata(self, setDate=False, **kwargs)
Definition linearize.py:205
applyLinearity(self, image, detector=None, log=None, gains=None)
Definition linearize.py:618
validate(self, detector=None, amplifier=None)
Definition linearize.py:558
__init__(self, centers1, values1, centers2=None, values2=None, high_clip=0.01, n_step=2 **20)
Definition linearize.py:942
__call__(self, array, gain=1.0)
Definition linearize.py:996
isTrimmedImage(image, detector)