Coverage for python/lsst/ip/isr/linearize.py: 88%
385 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-18 02:43 -0800
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-18 02:43 -0800
1#
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#
23__all__ = [
24 "Linearizer",
25 "LinearizeBase",
26 "LinearizeLookupTable",
27 "LinearizeSquared",
28 "LinearizeProportional",
29 "LinearizePolynomial",
30 "LinearizeSpline",
31 "LinearizeDoubleSpline",
32 "LinearizeNone",
33]
35import abc
36import numpy as np
37from scipy.interpolate import Akima1DInterpolator
39from astropy.table import Table
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
48class Linearizer(IsrCalib):
49 """Parameter set for linearization.
51 These parameters are included in `lsst.afw.cameraGeom.Amplifier`, but
52 should be accessible externally to allow for testing.
54 Parameters
55 ----------
56 table : `numpy.array`, optional
57 Lookup table; a 2-dimensional array of floats:
59 - one row for each row index (value of coef[0] in the amplifier)
60 - one column for each image value
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.
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).
77 Notes
78 -----
79 The linearizer attributes stored are:
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.
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
153 def __init__(self, table=None, **kwargs):
154 self.hasLinearity = False
155 self.override = False
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()
172 self.fitResidualsSigmaMad = dict()
173 self.fitResidualsUnmasked = dict()
174 self.fitResidualsModel = dict()
175 self.linearFit = dict()
176 self.linearityTurnoff = dict()
177 self.linearityMaxSignal = dict()
178 self.absoluteReferenceAmplifier = ""
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")
187 # The linearizer is always natively in adu because it
188 # is computed prior to computing gains.
189 self.linearityUnits = 'adu'
191 # Cached linearizers.
192 self._linearizers = {}
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'])
205 def updateMetadata(self, setDate=False, **kwargs):
206 """Update metadata keywords with new values.
208 This calls the base class's method after ensuring the required
209 calibration keywords will be saved.
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
224 super().updateMetadata(setDate=setDate, **kwargs)
226 def fromDetector(self, detector):
227 """Read linearity parameters from a detector.
229 Parameters
230 ----------
231 detector : `lsst.afw.cameraGeom.detector`
232 Input detector with parameters to use.
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
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()
252 # Detector linearizers (legacy) are assumed to be adu units.
253 self.linearityUnits = 'adu'
255 return self
257 @classmethod
258 def fromDict(cls, dictionary):
259 """Construct a calibration from a dictionary of properties
261 Parameters
262 ----------
263 dictionary : `dict`
264 Dictionary of properties
266 Returns
267 -------
268 calib : `lsst.ip.isr.Linearity`
269 Constructed calibration.
271 Raises
272 ------
273 RuntimeError
274 Raised if the supplied dictionary is for a different
275 calibration.
276 """
278 calib = cls()
280 if calib._OBSTYPE != dictionary['metadata']['OBSTYPE']: 280 ↛ 281line 280 didn't jump to line 281 because the condition on line 280 was never true
281 raise RuntimeError(f"Incorrect linearity supplied. Expected {calib._OBSTYPE}, "
282 f"found {dictionary['metadata']['OBSTYPE']}")
284 calib.setMetadata(dictionary['metadata'])
286 calib.hasLinearity = dictionary.get('hasLinearity',
287 dictionary['metadata'].get('HAS_LINEARITY', False))
288 calib.override = dictionary.get('override', True)
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')
295 if calib.hasLinearity: 295 ↛ 334line 295 didn't jump to line 334 because the condition on line 295 was always true
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)
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]))
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]))
323 calib.linearityTurnoff[ampName] = np.array(amp.get('linearityTurnoff', np.nan))
324 calib.linearityMaxSignal[ampName] = np.array(amp.get('linearityMaxSignal', np.nan))
326 calib.tableData = dictionary.get('tableData', None)
327 if calib.tableData:
328 calib.tableData = np.array(calib.tableData)
330 calib.absoluteReferenceAmplifier = dictionary.get(
331 'absoluteReferenceAmplifier', calib.absoluteReferenceAmplifier,
332 )
334 return calib
336 def toDict(self):
337 """Return linearity parameters as a dict.
339 Returns
340 -------
341 outDict : `dict`:
342 """
343 self.updateMetadata()
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()
379 outDict['absoluteReferenceAmplifier'] = self.absoluteReferenceAmplifier
381 return outDict
383 @classmethod
384 def fromTable(cls, tableList):
385 """Read linearity from a FITS file.
387 This method uses the `fromDict` method to create the
388 calibration, after constructing an appropriate dictionary from
389 the input tables.
391 Parameters
392 ----------
393 tableList : `list` [`astropy.table.Table`]
394 afwTable read from input file name.
396 Returns
397 -------
398 linearity : `~lsst.ip.isr.linearize.Linearizer``
399 Linearity parameters.
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]
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')
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])
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
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 }
472 if len(tableList) > 1:
473 tableData = tableList[1]
474 inDict['tableData'] = [record['LOOKUP_VALUES'] for record in tableData]
476 if 'ABS_REF_AMP' in coeffTable.columns: 476 ↛ 479line 476 didn't jump to line 479 because the condition on line 476 was always true
477 inDict['absoluteReferenceAmplifier'] = str(coeffTable['ABS_REF_AMP'][0])
478 else:
479 inDict['absoluteReferenceAmplifier'] = ''
481 return cls().fromDict(inDict)
483 def toTable(self):
484 """Construct a list of tables containing the information in this
485 calibration.
487 The list of tables should create an identical calibration
488 after being passed to this class's fromTable method.
490 Returns
491 -------
492 tableList : `list` [`astropy.table.Table`]
493 List of tables containing the linearity calibration
494 information.
495 """
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)
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
533 def getLinearityTypeByName(self, linearityTypeName):
534 """Determine the linearity class to use from the type name.
536 Parameters
537 ----------
538 linearityTypeName : str
539 String name of the linearity type that is needed.
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
558 def validate(self, detector=None, amplifier=None):
559 """Validate linearity for a detector/amplifier.
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.
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()): 579 ↛ 580line 579 didn't jump to line 580 because the condition on line 579 was never true
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())
594 if amplifier: 594 ↛ 595line 594 didn't jump to line 595 because the condition on line 594 was never true
595 amplifiersToCheck.extend(amplifier)
597 for amp in amplifiersToCheck:
598 ampName = amp.getName()
599 if ampName not in self.linearityCoeffs.keys(): 599 ↛ 600line 599 didn't jump to line 600 because the condition on line 599 was never true
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: 611 ↛ 615line 611 didn't jump to line 615 because the condition on line 611 was always true
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]))
618 def applyLinearity(self, image, detector=None, log=None, gains=None):
619 """Apply the linearity to an image.
621 If the linearity parameters are populated, use those,
622 otherwise use the values from the detector.
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: 642 ↛ 643line 642 didn't jump to line 643 because the condition on line 642 was never true
643 self.fromDetector(detector)
645 self.validate(detector)
647 # Check if the image is trimmed.
648 isTrimmed = None
649 if detector:
650 isTrimmed = isTrimmedImage(image, detector)
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])()
660 linearizer = self._linearizers[ampName]
662 numAmps += 1
664 if gains and self.linearityUnits == 'adu':
665 gainValue = gains[ampName]
666 else:
667 gainValue = 1.0
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
675 if linearizer is not None: 675 ↛ 655line 675 didn't jump to line 655 because the condition on line 675 was always true
676 match isTrimmed:
677 case True:
678 bbox = detector[ampName].getBBox()
679 case False:
680 bbox = detector[ampName].getRawBBox()
681 case None: 681 ↛ 684line 681 didn't jump to line 684 because the pattern on line 681 always matched
682 bbox = self.linearityBBox[ampName]
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: 692 ↛ 655line 692 didn't jump to line 655 because the condition on line 692 was always true
693 log.warning("Amplifier %s did not linearize.",
694 ampName)
695 return Struct(
696 numAmps=numAmps,
697 numLinearized=numLinearized,
698 numOutOfRange=numOutOfRange
699 )
702class LinearizeBase(metaclass=abc.ABCMeta):
703 """Abstract base class functor for correcting non-linearity.
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.
709 All linearity corrections should be defined in terms of an
710 additive correction, such that:
712 corrected_value = uncorrected_value + f(uncorrected_value)
713 """
714 LinearityType = None # linearity type, a string used for AmpInfoCatalogs
716 @abc.abstractmethod
717 def __call__(self, image, **kwargs):
718 """Correct non-linearity.
720 Parameters
721 ----------
722 image : `lsst.afw.image.Image`
723 Image to be corrected
724 kwargs : `dict`
725 Dictionary of parameter keywords:
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`).
734 Returns
735 -------
736 output : `bool`
737 If `True`, a correction was applied successfully.
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
748class LinearizeLookupTable(LinearizeBase):
749 """Correct non-linearity with a persisted lookup table.
751 The lookup table consists of entries such that given
752 "coefficients" c0, c1:
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]
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"
770 def __call__(self, image, **kwargs):
771 """Correct for non-linearity.
773 Parameters
774 ----------
775 image : `lsst.afw.image.Image`
776 Image to be corrected
777 kwargs : `dict`
778 Dictionary of parameter keywords:
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`).
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.
794 Raises
795 ------
796 RuntimeError:
797 Raised if the requested row index is out of the table
798 bounds.
799 """
800 numOutOfRange = 0
802 rowInd, colIndOffset = kwargs['coeffs'][0:2]
803 table = kwargs['table']
804 log = kwargs['log']
806 numTableRows = table.shape[0]
807 rowInd = int(rowInd)
808 if rowInd < 0 or rowInd > numTableRows: 808 ↛ 809line 808 didn't jump to line 809 because the condition on line 808 was never true
809 raise RuntimeError("LinearizeLookupTable rowInd=%s not in range[0, %s)" %
810 (rowInd, numTableRows))
811 tableRow = np.array(table[rowInd, :], dtype=image.getArray().dtype)
813 numOutOfRange += applyLookupTable(image, tableRow, colIndOffset)
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: 818 ↛ 821line 818 didn't jump to line 821 because the condition on line 818 was always true
819 return True, numOutOfRange
820 else:
821 return False, numOutOfRange
824class LinearizePolynomial(LinearizeBase):
825 """Correct non-linearity with a polynomial mode.
827 .. code-block::
829 corrImage = uncorrImage + sum_i c_i uncorrImage^(2 + i)
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:
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"
844 def __call__(self, image, **kwargs):
845 """Correct non-linearity.
847 Parameters
848 ----------
849 image : `lsst.afw.image.Image`
850 Image to be corrected
851 kwargs : `dict`
852 Dictionary of parameter keywords:
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`).
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'])): 869 ↛ 870line 869 didn't jump to line 870 because the condition on line 869 was never true
870 return False, 0
871 if not np.any(kwargs['coeffs']): 871 ↛ 872line 871 didn't jump to line 872 because the condition on line 871 was never true
872 return False, 0
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
880 return True, 0
883class LinearizeSquared(LinearizeBase):
884 """Correct non-linearity with a squared model.
886 corrImage = uncorrImage + c0*uncorrImage^2
888 where c0 is linearity coefficient 0 for each amplifier.
889 """
890 LinearityType = "Squared"
892 def __call__(self, image, **kwargs):
893 """Correct for non-linearity.
895 Parameters
896 ----------
897 image : `lsst.afw.image.Image`
898 Image to be corrected
899 kwargs : `dict`
900 Dictionary of parameter keywords:
902 ``coeffs``
903 Coefficient vector (`list` or `np.ndarray`).
904 ``log``
905 Logger to handle messages (`logging.Logger`).
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 """
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
924class SplineLUT:
925 """Turn a spline or double spline into a lookup table.
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.
945 # Build the LUT in ADU, to be gain independent.
947 interp1 = Akima1DInterpolator(centers1, values1, method="akima")
949 if centers1[0] != 0.0: 949 ↛ 950line 949 didn't jump to line 950 because the condition on line 949 was never true
950 raise ValueError("Spline1 should be anchored at zero.")
952 if centers2 is not None:
953 interp2 = Akima1DInterpolator(centers2, values2, method="akima")
954 if centers2[0] != 0.0: 954 ↛ 955line 954 didn't jump to line 955 because the condition on line 954 was never true
955 raise ValueError("Spline2 should be anchored at zero.")
957 x_max = max(centers1[-1], centers2[-1])
958 else:
959 x_max = centers1[-1]
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))
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 = {}
973 def _for_gain(self, gain):
974 """Scale LUT to the appropriate gain.
976 Parameters
977 ----------
978 gain : `float`
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
996 def __call__(self, array, gain=1.0):
997 """Get linearizer from LUT.
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): 1006 ↛ 1007line 1006 didn't jump to line 1007 because the condition on line 1006 was never true
1007 array[:] = np.nan
1008 return
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")
1019class LinearizeSpline(LinearizeBase):
1020 """Correct non-linearity with a spline model.
1022 corrImage = uncorrImage - Spline(coeffs, uncorrImage)
1024 Notes
1025 -----
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.
1031 """
1032 LinearityType = "Spline"
1033 _lut = None
1034 _bad_amp = False
1036 def __call__(self, image, **kwargs):
1037 """Correct for non-linearity.
1039 Parameters
1040 ----------
1041 image : `lsst.afw.image.Image`
1042 Image to be corrected
1043 kwargs : `dict`
1044 Dictionary of parameter keywords:
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.
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)
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: 1072 ↛ 1073line 1072 didn't jump to line 1073 because the condition on line 1072 was never true
1073 offset = values[0]
1074 values -= offset
1075 if centers[0] != 0.0: 1075 ↛ 1076line 1075 didn't jump to line 1076 because the condition on line 1075 was never true
1076 centers = np.concatenate(([0.0], centers))
1077 values = np.concatenate(([0.0], values))
1079 if np.any(~np.isfinite(centers)) or np.any(~np.isfinite(values)): 1079 ↛ 1081line 1079 didn't jump to line 1081 because the condition on line 1079 was never true
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)
1087 if self._bad_amp: 1087 ↛ 1088line 1087 didn't jump to line 1088 because the condition on line 1087 was never true
1088 image.array[:] = np.nan
1090 return False, 0
1092 self._lut(image.array, gain=gain)
1094 return True, 0
1097class LinearizeDoubleSpline(LinearizeBase):
1098 """Correct non-linearity with a spline model.
1100 corrImage1 = uncorrImage - Spline1(coeffs, uncorrImage)
1101 corrImage = corrImage1 - Spline2(coeffs, corrImage1)
1103 Notes
1104 -----
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.
1110 """
1111 LinearityType = "DoubleSpline"
1112 _lut = None
1113 _bad_amp = False
1115 def __call__(self, image, **kwargs):
1116 """Correct for non-linearity.
1118 Parameters
1119 ----------
1120 image : `lsst.afw.image.Image`
1121 Image to be corrected
1122 kwargs : `dict`
1123 Dictionary of parameter keywords:
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.
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)
1142 if self._lut is None:
1143 # The coeffs have [nNodes1, nNodes2,
1144 # nodes1, centers1,
1145 # nodes2, centers2]
1147 nNodes1 = int(coeffs[0])
1148 nNodes2 = int(coeffs[1])
1150 if nNodes1 > 0:
1151 splineCoeff1 = coeffs[2: 2 + 2*nNodes1]
1152 centers1, values1 = np.split(splineCoeff1, 2)
1154 if np.any(~np.isfinite(centers1)) or np.any(~np.isfinite(values1)): 1154 ↛ 1156line 1154 didn't jump to line 1156 because the condition on line 1154 was never true
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
1163 if nNodes2 > 0:
1164 splineCoeff2 = coeffs[2 + 2*nNodes1: 2 + 2*nNodes1 + 2*nNodes2]
1165 centers2, values2 = np.split(splineCoeff2, 2)
1167 if np.any(~np.isfinite(centers2)) or np.any(~np.isfinite(values2)): 1167 ↛ 1169line 1167 didn't jump to line 1169 because the condition on line 1167 was never true
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
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: 1180 ↛ 1183line 1180 didn't jump to line 1183 because the condition on line 1180 was always true
1181 self._lut = SplineLUT(centers2, values2)
1182 else:
1183 self._bad_amp = True
1184 self._lut = False
1186 if self._bad_amp: 1186 ↛ 1187line 1186 didn't jump to line 1187 because the condition on line 1186 was never true
1187 image.array[:] = np.nan
1188 return False, 0
1190 self._lut(image.array, gain=gain)
1192 return True, 0
1195class LinearizeProportional(LinearizeBase):
1196 """Do not correct non-linearity.
1197 """
1198 LinearityType = "Proportional"
1200 def __call__(self, image, **kwargs):
1201 """Do not correct for non-linearity.
1203 Parameters
1204 ----------
1205 image : `lsst.afw.image.Image`
1206 Image to be corrected
1207 kwargs : `dict`
1208 Dictionary of parameter keywords:
1210 ``coeffs``
1211 Coefficient vector (`list` or `np.ndarray`).
1212 ``log``
1213 Logger to handle messages (`logging.Logger`).
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
1225class LinearizeNone(LinearizeBase):
1226 """Do not correct non-linearity.
1227 """
1228 LinearityType = "None"
1230 def __call__(self, image, **kwargs):
1231 """Do not correct for non-linearity.
1233 Parameters
1234 ----------
1235 image : `lsst.afw.image.Image`
1236 Image to be corrected
1237 kwargs : `dict`
1238 Dictionary of parameter keywords:
1240 ``coeffs``
1241 Coefficient vector (`list` or `np.ndarray`).
1242 ``log``
1243 Logger to handle messages (`logging.Logger`).
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