26 "LinearizeLookupTable",
28 "LinearizeProportional",
29 "LinearizePolynomial",
31 "LinearizeDoubleSpline",
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
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.
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.
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).
79 The linearizer attributes stored are:
82 Whether a linearity correction is defined for this detector.
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
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
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
116 fitResidualsUnmasked : `dict` [`str`, `np.ndarray`], optional
117 Same as fitResiduals, but all outliers are included and
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.
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
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
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``.
149 _OBSTYPE =
"LINEARIZER"
150 _SCHEMA =
'Gen3 Linearizer'
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")
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'])
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.
213 setDate : `bool`, optional
214 Update the CALIBDATE fields in the metadata to the current
215 time. Defaults to False.
217 Other keyword parameters to set in the metadata.
221 kwargs[
'HAS_TABLE'] = self.
tableData is not None
227 """Read linearity parameters from a detector.
231 detector : `lsst.afw.cameraGeom.detector`
232 Input detector with parameters to use.
236 calib : `lsst.ip.isr.Linearizer`
237 The calibration constructed from the detector.
245 for amp
in detector.getAmplifiers():
246 ampName = amp.getName()
259 """Construct a calibration from a dictionary of properties
264 Dictionary of properties
268 calib : `lsst.ip.isr.Linearity`
269 Constructed calibration.
274 Raised if the supplied dictionary is for a different
280 if calib._OBSTYPE != dictionary[
'metadata'][
'OBSTYPE']:
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)
293 calib.linearityUnits = dictionary.get(
'linearityUnits',
'adu')
295 if calib.hasLinearity:
296 for ampName
in dictionary[
'amplifiers']:
297 amp = dictionary[
'amplifiers'][ampName]
298 calib.ampNames.append(ampName)
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)
328 calib.tableData = np.array(calib.tableData)
330 calib.absoluteReferenceAmplifier = dictionary.get(
331 'absoluteReferenceAmplifier', calib.absoluteReferenceAmplifier,
337 """Return linearity parameters as a dict.
350 'amplifiers': dict(),
354 outDict[
'amplifiers'][ampName] = {
362 'inputMask': self.
inputMask[ampName].tolist(),
365 'fitParams': self.
fitParams[ampName].tolist(),
372 'linearFit': self.
linearFit[ampName].tolist(),
377 outDict[
'tableData'] = self.
tableData.tolist()
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
393 tableList : `list` [`astropy.table.Table`]
394 afwTable read from input file name.
398 linearity : `~lsst.ip.isr.linearize.Linearizer``
399 Linearity parameters.
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.
412 coeffTable = tableList[0]
414 metadata = coeffTable.meta
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 \
430 inputNormalization = record[
'INP_NORMALIZATION']
if 'INP_NORMALIZATION' in record.columns \
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 \
445 linearityMaxSignal = record[
'LINEARITY_MAX_SIGNAL']
if 'LINEARITY_MAX_SIGNAL' in record.columns \
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,
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:
477 inDict[
'absoluteReferenceAmplifier'] = str(coeffTable[
'ABS_REF_AMP'][0])
479 inDict[
'absoluteReferenceAmplifier'] =
''
484 """Construct a list of tables containing the information in this
487 The list of tables should create an identical calibration
488 after being passed to this class's fromTable method.
492 tableList : `list` [`astropy.table.Table`]
493 List of tables containing the linearity calibration
499 catalog = Table([{
'AMPLIFIER_NAME': ampName,
515 'RED_CHI_SQ': self.
fitChiSq[ampName],
526 tableList.append(catalog)
529 catalog = Table([{
'LOOKUP_VALUES': value}
for value
in self.
tableData])
530 tableList.append(catalog)
534 """Determine the linearity class to use from the type name.
538 linearityTypeName : str
539 String name of the linearity type that is needed.
543 linearityType : `~lsst.ip.isr.linearize.LinearizeBase`
544 The appropriate linearity class to use. If no matching class
545 is found, `None` is returned.
547 for t
in [LinearizeLookupTable,
550 LinearizeProportional,
552 LinearizeDoubleSpline,
554 if t.LinearityType == linearityTypeName:
559 """Validate linearity for a detector/amplifier.
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.
571 Raised if there is a mismatch in linearity parameters, and
572 the cameraGeom parameters are not being overridden.
574 amplifiersToCheck = []
577 raise RuntimeError(
"Detector names don't match: %s != %s" %
580 raise RuntimeError(
"Detector IDs don't match: %s != %s" %
589 raise RuntimeError(
"Detector number of amps = %s does not match saved value %s" %
590 (len(detector.getAmplifiers()),
592 amplifiersToCheck.extend(detector.getAmplifiers())
595 amplifiersToCheck.extend(amplifier)
597 for amp
in amplifiersToCheck:
598 ampName = amp.getName()
600 raise RuntimeError(
"Amplifier %s is not in linearity data" %
604 self.
log.debug(
"Overriding amplifier defined linearityType (%s) for %s",
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)):
612 self.
log.debug(
"Overriding amplifier defined linearityCoeffs (%s) for %s",
615 raise RuntimeError(
"Amplifier %s coeffs %s does not match saved value %s" %
619 """Apply the linearity to an image.
621 If the linearity parameters are populated, use those,
622 otherwise use the values from the detector.
626 image : `~lsst.afw.image.image`
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.
665 gainValue = gains[ampName]
670 if np.isnan(gainValue):
671 log.warning(
"Gain value for amp %s is NaN, skipping "
672 "linearization.", ampName)
675 if linearizer
is not None:
678 bbox = detector[ampName].getBBox()
680 bbox = detector[ampName].getRawBBox()
684 ampView = image.Factory(image, bbox)
685 success, outOfRange = linearizer(ampView, **{
'coeffs': self.
linearityCoeffs[ampName],
689 numOutOfRange += outOfRange
692 elif log
is not None:
693 log.warning(
"Amplifier %s did not linearize.",
697 numLinearized=numLinearized,
698 numOutOfRange=numOutOfRange
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)
718 """Correct non-linearity.
722 image : `lsst.afw.image.Image`
723 Image to be corrected
725 Dictionary of parameter keywords:
728 Coefficient vector (`list` or `np.ndarray`).
730 Lookup table data (`np.ndarray`).
732 Logger to handle messages (`logging.Logger`).
737 If `True`, a correction was applied successfully.
742 Raised if the linearity type listed in the
743 detector does not match the class type.
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:
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
768 LinearityType =
"LookupTable"
771 """Correct for non-linearity.
775 image : `lsst.afw.image.Image`
776 Image to be corrected
778 Dictionary of parameter keywords:
781 Columnation vector (`list` or `np.ndarray`).
783 Lookup table data (`np.ndarray`).
785 Logger to handle messages (`logging.Logger`).
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.
797 Raised if the requested row index is out of the table
802 rowInd, colIndOffset = kwargs[
'coeffs'][0:2]
803 table = kwargs[
'table']
806 numTableRows = table.shape[0]
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)
815 if numOutOfRange > 0
and log
is not None:
816 log.warning(
"%s pixels were out of range of the linearization table",
818 if numOutOfRange < image.getArray().size:
819 return True, numOutOfRange
821 return False, numOutOfRange
825 """Correct non-linearity with a polynomial mode.
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:
836 A coefficient multiplied by ``uncorrImage**0`` is equivalent to
837 bias level. Irrelevant for correcting non-linearity.
839 A coefficient multiplied by ``uncorrImage**1`` is proportional
840 to the gain. Not necessary for correcting non-linearity.
842 LinearityType =
"Polynomial"
845 """Correct non-linearity.
849 image : `lsst.afw.image.Image`
850 Image to be corrected
852 Dictionary of parameter keywords:
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).
860 Logger to handle messages (`logging.Logger`).
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.
869 if not np.any(np.isfinite(kwargs[
'coeffs'])):
871 if not np.any(kwargs[
'coeffs']):
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
884 """Correct non-linearity with a squared model.
886 corrImage = uncorrImage + c0*uncorrImage^2
888 where c0 is linearity coefficient 0 for each amplifier.
890 LinearityType =
"Squared"
893 """Correct for non-linearity.
897 image : `lsst.afw.image.Image`
898 Image to be corrected
900 Dictionary of parameter keywords:
903 Coefficient vector (`list` or `np.ndarray`).
905 Logger to handle messages (`logging.Logger`).
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.
915 sqCoeff = kwargs[
'coeffs'][0]
917 ampArr = image.getArray()
918 ampArr *= (1 + sqCoeff*ampArr)
925 """Turn a spline or double spline into a lookup table.
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.
942 def __init__(self, centers1, values1, centers2=None, values2=None, high_clip=0.01, n_step=2**20):
947 interp1 = Akima1DInterpolator(centers1, values1, method=
"akima")
949 if centers1[0] != 0.0:
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:
955 raise ValueError(
"Spline2 should be anchored at zero.")
957 x_max = max(centers1[-1], centers2[-1])
961 x = np.linspace(0.0, x_max, n_step)
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))
970 self.
dx = x[1] - x[0]
974 """Scale LUT to the appropriate gain.
983 table in electrons; scale used.
985 entry = self.
_cache.get(gain)
990 (gain * self.
corr_adu).astype(np.float32),
991 np.float32(1.0 / (gain * self.
dx)),
997 """Get linearizer from LUT.
1001 array : `np.ndarray`
1002 Array to linearize (in place).
1003 gain : `float`, optional
1006 if not np.isfinite(gain):
1012 t += np.float32(0.5)
1013 with np.errstate(invalid=
"ignore"):
1015 k = t.astype(np.int32)
1016 array -= table.take(k, mode=
"clip")
1020 """Correct non-linearity with a spline model.
1022 corrImage = uncorrImage - Spline(coeffs, uncorrImage)
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.
1032 LinearityType =
"Spline"
1037 """Correct for non-linearity.
1041 image : `lsst.afw.image.Image`
1042 Image to be corrected
1044 Dictionary of parameter keywords:
1047 Coefficient vector (`list` or `np.ndarray`).
1049 Logger to handle messages (`logging.Logger`).
1051 Gain value to apply.
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.
1060 splineCoeff = kwargs[
'coeffs']
1061 gain = kwargs.get(
'gain', 1.0)
1063 if self.
_lut is None:
1064 centers, values = np.split(splineCoeff, 2)
1067 centers = centers.copy()
1068 values = values.copy()
1075 if centers[0] != 0.0:
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)):
1088 image.array[:] = np.nan
1092 self.
_lut(image.array, gain=gain)
1098 """Correct non-linearity with a spline model.
1100 corrImage1 = uncorrImage - Spline1(coeffs, uncorrImage)
1101 corrImage = corrImage1 - Spline2(coeffs, corrImage1)
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.
1111 LinearityType =
"DoubleSpline"
1116 """Correct for non-linearity.
1120 image : `lsst.afw.image.Image`
1121 Image to be corrected
1123 Dictionary of parameter keywords:
1126 Coefficient vector (`list` or `np.ndarray`).
1128 Logger to handle messages (`logging.Logger`).
1130 Gain value to apply.
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.
1139 coeffs = kwargs[
'coeffs']
1140 gain = kwargs.get(
'gain', 1.0)
1142 if self.
_lut is None:
1147 nNodes1 = int(coeffs[0])
1148 nNodes2 = int(coeffs[1])
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)):
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)):
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:
1180 elif centers2
is not None:
1187 image.array[:] = np.nan
1190 self.
_lut(image.array, gain=gain)
1196 """Do not correct non-linearity.
1198 LinearityType =
"Proportional"
1201 """Do not correct for non-linearity.
1205 image : `lsst.afw.image.Image`
1206 Image to be corrected
1208 Dictionary of parameter keywords:
1211 Coefficient vector (`list` or `np.ndarray`).
1213 Logger to handle messages (`logging.Logger`).
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.
1226 """Do not correct non-linearity.
1228 LinearityType =
"None"
1231 """Do not correct for non-linearity.
1235 image : `lsst.afw.image.Image`
1236 Image to be corrected
1238 Dictionary of parameter keywords:
1241 Coefficient vector (`list` or `np.ndarray`).
1243 Logger to handle messages (`logging.Logger`).
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.
validate(self, other=None)
fromDetector(self, detector)
updateMetadata(self, camera=None, detector=None, filterName=None, setCalibId=False, setCalibInfo=False, setDate=False, **kwargs)
__call__(self, image, **kwargs)
__call__(self, image, **kwargs)
__call__(self, image, **kwargs)
__call__(self, image, **kwargs)
__call__(self, image, **kwargs)
__call__(self, image, **kwargs)
__call__(self, image, **kwargs)
__call__(self, image, **kwargs)
str absoluteReferenceAmplifier
getLinearityTypeByName(self, linearityTypeName)
fromDetector(self, detector)
fromTable(cls, tableList)
__init__(self, table=None, **kwargs)
updateMetadata(self, setDate=False, **kwargs)
fromDict(cls, dictionary)
applyLinearity(self, image, detector=None, log=None, gains=None)
validate(self, detector=None, amplifier=None)
__init__(self, centers1, values1, centers2=None, values2=None, high_clip=0.01, n_step=2 **20)
__call__(self, array, gain=1.0)
isTrimmedImage(image, detector)