228 """Construct a calibration from a dictionary of properties.
230 Must be implemented by the specific calibration subclasses.
235 Dictionary of properties.
239 calib : `lsst.ip.isr.CalibType`
240 Constructed calibration.
245 Raised if the supplied dictionary is for a different
250 if calib._OBSTYPE != dictionary[
'metadata'][
'OBSTYPE']:
251 raise RuntimeError(f
"Incorrect crosstalk supplied. Expected {calib._OBSTYPE}, "
252 f
"found {dictionary['metadata']['OBSTYPE']}")
254 calib.setMetadata(dictionary[
'metadata'])
256 if 'detectorName' in dictionary:
257 calib._detectorName = dictionary.get(
'detectorName')
258 elif 'DETECTOR_NAME' in dictionary:
259 calib._detectorName = dictionary.get(
'DETECTOR_NAME')
260 elif 'DET_NAME' in dictionary[
'metadata']:
261 calib._detectorName = dictionary[
'metadata'][
'DET_NAME']
263 calib._detectorName =
None
265 if 'detectorSerial' in dictionary:
266 calib._detectorSerial = dictionary.get(
'detectorSerial')
267 elif 'DETECTOR_SERIAL' in dictionary:
268 calib._detectorSerial = dictionary.get(
'DETECTOR_SERIAL')
269 elif 'DET_SER' in dictionary[
'metadata']:
270 calib._detectorSerial = dictionary[
'metadata'][
'DET_SER']
272 calib._detectorSerial =
None
274 if 'detectorId' in dictionary:
275 calib._detectorId = dictionary.get(
'detectorId')
276 elif 'DETECTOR' in dictionary:
277 calib._detectorId = dictionary.get(
'DETECTOR')
278 elif 'DETECTOR' in dictionary[
'metadata']:
279 calib._detectorId = dictionary[
'metadata'][
'DETECTOR']
280 elif calib._detectorSerial:
281 calib._detectorId = calib._detectorSerial
283 calib._detectorId =
None
285 if 'instrument' in dictionary:
286 calib._instrument = dictionary.get(
'instrument')
287 elif 'INSTRUME' in dictionary[
'metadata']:
288 calib._instrument = dictionary[
'metadata'][
'INSTRUME']
290 calib._instrument =
None
292 calib.hasCrosstalk = dictionary.get(
'hasCrosstalk',
293 dictionary[
'metadata'].get(
'HAS_CROSSTALK',
False))
294 if calib.hasCrosstalk:
295 calib.nAmp = dictionary.get(
'nAmp', dictionary[
'metadata'].get(
'NAMP', 0))
296 calib.crosstalkShape = (calib.nAmp, calib.nAmp)
297 calib.coeffs = np.array(dictionary[
'coeffs']).reshape(calib.crosstalkShape)
298 calib.crosstalkRatiosUnits = dictionary.get(
299 'crosstalkRatiosUnits',
300 dictionary[
'metadata'].get(
'CROSSTALK_RATIOS_UNITS',
'adu'))
301 if 'coeffErr' in dictionary:
302 calib.coeffErr = np.array(dictionary[
'coeffErr']).reshape(calib.crosstalkShape)
304 calib.coeffErr = np.zeros_like(calib.coeffs)
305 if 'coeffNum' in dictionary:
306 calib.coeffNum = np.array(dictionary[
'coeffNum']).reshape(calib.crosstalkShape)
308 calib.coeffNum = np.zeros_like(calib.coeffs, dtype=int)
309 if 'coeffValid' in dictionary:
310 calib.coeffValid = np.array(dictionary[
'coeffValid']).reshape(calib.crosstalkShape)
312 calib.coeffValid = np.ones_like(calib.coeffs, dtype=bool)
313 if 'coeffsSqr' in dictionary:
314 calib.coeffsSqr = np.array(dictionary[
'coeffsSqr']).reshape(calib.crosstalkShape)
316 calib.coeffsSqr = np.zeros_like(calib.coeffs)
317 if 'coeffErrSqr' in dictionary:
318 calib.coeffErrSqr = np.array(dictionary[
'coeffErrSqr']).reshape(calib.crosstalkShape)
320 calib.coeffErrSqr = np.zeros_like(calib.coeffs)
321 if 'ampGainRatios' in dictionary:
322 calib.ampGainRatios = np.array(dictionary[
'ampGainRatios']).reshape(calib.crosstalkShape)
324 calib.ampGainRatios = np.zeros_like(calib.coeffs)
325 if 'fitGains' in dictionary:
328 fitGains = np.array(dictionary[
'fitGains'])
329 if len(fitGains) == 1:
331 calib.fitGains = np.zeros(calib.nAmp)
333 calib.fitGains = np.array(dictionary[
'fitGains']).reshape(calib.nAmp)
335 calib.fitGains = np.zeros(calib.nAmp)
337 calib.interChip = dictionary.get(
'interChip',
None)
339 for detector
in calib.interChip:
340 coeffVector = calib.interChip[detector]
341 calib.interChip[detector] = np.array(coeffVector).reshape(calib.crosstalkShape)
343 calib.updateMetadata()
589 crosstalkCoeffsSqr=None, crosstalkCoeffsValid=None,
590 badPixels=["BAD"], minPixelToMask=45000, doSubtrahendMasking=False,
591 doCrosstalkMask=True, crosstalkStr="CROSSTALK", isTrimmed=None,
592 backgroundMethod="None", doSqrCrosstalk=False, fullAmplifier=False,
593 parallelOverscan=None, detectorConfig=None, badAmpDict=None,
594 ignoreVariance=False, doUseFastPath=True):
595 """Subtract the crosstalk from thisExposure, optionally using a
598 We set the mask plane indicated by ``crosstalkStr`` in a
599 target amplifier for pixels in a source amplifier that exceed
600 ``minPixelToMask``, if ``doSubtrahendMasking`` is False. With
601 that enabled, the mask is only set if the absolute value of
602 the correction applied exceeds ``minPixelToMask``. Note that
603 the correction is applied to all pixels in the amplifier, but
604 only those that have a substantial crosstalk are masked with
607 The uncorrected image is used as a template for correction. This is
608 good enough if the crosstalk is small (e.g., coefficients < ~ 1e-3),
609 but if it's larger you may want to iterate.
613 thisExposure : `lsst.afw.image.Exposure`
614 Exposure for which to subtract crosstalk.
615 sourceExposure : `lsst.afw.image.Exposure`, optional
616 Exposure to use as the source of the crosstalk. If not set,
617 thisExposure is used as the source (intra-detector crosstalk).
618 crosstalkCoeffs : `numpy.ndarray`, optional.
619 Coefficients to use to correct crosstalk.
620 crosstalkCoeffsSqr : `numpy.ndarray`, optional.
621 Quadratic coefficients to use to correct crosstalk.
622 crosstalkCoeffsValid : `numpy.ndarray`, optional
623 Boolean array that is True where coefficients are valid.
624 badPixels : `list` of `str`, optional
625 Mask planes to ignore.
626 minPixelToMask : `float`, optional
627 Minimum pixel value to set the ``crosstalkStr`` mask
628 plane. If doSubtrahendMasking is True, this is calculated
629 from the absolute magnitude of the subtrahend image.
630 Otherwise, this sets the minimum source value to use to
632 doCrosstalkMask : `bool`, optional
633 If true, the crosstalk mask will be computed. Otherwise,
634 no crosstalk mask will be computed which is slightly faster.
635 doSubtrahendMasking : `bool`, optional
636 If true, the mask is calculated from the properties of the
637 subtrahend image, not from the brightness of the source
638 pixel. Not used if doCrosstalkMask is False.
639 crosstalkStr : `str`, optional
640 Mask plane name for pixels greatly modified by crosstalk
641 (above minPixelToMask).
642 isTrimmed : `bool`, optional
643 This option has been deprecated and does not do anything.
644 It will be removed after v29.
645 backgroundMethod : `str`, optional
646 Method used to subtract the background. "AMP" uses
647 amplifier-by-amplifier background levels, "DETECTOR" uses full
648 exposure/maskedImage levels. Any other value results in no
649 background subtraction.
650 doSqrCrosstalk: `bool`, optional
651 Should the quadratic crosstalk coefficients be used for the
652 crosstalk correction?
653 fullAmplifier : `bool`, optional
654 Use full amplifier and not just imaging region.
655 parallelOverscan : `bool`, optional
656 This option is deprecated and will be removed after v29.
657 detectorConfig : `lsst.ip.isr.overscanDetectorConfig`, optional
658 Per-amplifier configs to use if parallelOverscan is True.
659 This option is deprecated and will be removed after v29.
660 badAmpDict : `dict` [`str`, `bool`], optional
661 Dictionary to identify bad amplifiers that should not be
662 source or target for crosstalk correction.
663 ignoreVariance : `bool`, optional
664 Ignore the variance plane when doing crosstalk correction?
665 doUseFastPath : `bool`, optional
666 Use the fast-path crosstalk processing if ignoring variance
667 and no background subtraction?
672 For a given image I, we want to find the crosstalk subtrahend
675 The subtrahend image is the sum of all crosstalk contributions
676 that appear in I, so we can build it up by amplifier. Each
677 amplifier A in image I sees the contributions from all other
678 amplifiers B_v != A. For the current linear model, we set `sImage`
679 equal to the segment of the subtrahend image CT corresponding to
680 amplifier A, and then build it up as:
681 simage_linear = sum_v coeffsA_v * (B_v - bkg_v) where coeffsA_v
682 is the vector of crosstalk coefficients for sources that cause
683 images in amplifier A. The bkg_v term in this equation is
684 identically 0.0 for all cameras except obs_subaru (and is only
685 non-zero there for historical reasons).
686 To include the non-linear term, we can again add to the subtrahend
687 image using the same loop, as:
689 simage_nonlinear = sum_v (coeffsA_v * B_v) + (NLcoeffsA_v * B_v * B_v)
690 = sum_v linear_term_v + nonlinear_term_v
692 where coeffsA_v is the linear term, and NLcoeffsA_v are the quadratic
693 component. For LSSTCam, it has been observed that the linear_term_v >>
696 targetMaskedImage = thisExposure.maskedImage
697 targetDetector = thisExposure.getDetector()
699 self.
fromDetector(targetDetector, coeffVector=crosstalkCoeffs)
702 if isTrimmed
is not None:
704 "The isTrimmed option has been deprecated and will be removed after v29.",
710 if parallelOverscan
is not None:
712 "The parallelOverscan option has been deprecated and will be removed after v29.",
715 if detectorConfig
is not None:
717 "The detectorConfig option has been deprecated and will be removed after v29.",
721 numAmps = len(targetDetector)
722 if numAmps != self.
nAmp:
723 raise RuntimeError(f
"Crosstalk built for {self.nAmp} in {self._detectorName}, received "
724 f
"{numAmps} in {targetDetector.getName()}")
726 if doSqrCrosstalk
and crosstalkCoeffsSqr
is None:
727 raise RuntimeError(
"Attempted to perform NL crosstalk correction without NL "
728 "crosstalk coefficients.")
730 if fullAmplifier
and (backgroundMethod !=
"None"):
731 raise RuntimeError(
"Cannot do full amplifier with background subtraction.")
734 sourceMaskedImage = sourceExposure.maskedImage
735 sourceDetector = sourceExposure.getDetector()
737 sourceMaskedImage = targetMaskedImage
738 sourceDetector = targetDetector
740 if crosstalkCoeffs
is not None:
741 coeffs = np.asarray(crosstalkCoeffs).copy()
743 coeffs = np.asarray(self.
coeffs).copy()
744 self.
log.debug(
"CT COEFF: %s", coeffs)
747 coeffsSqr = np.asarray(crosstalkCoeffsSqr).copy()
748 self.
log.debug(
"CT COEFF SQR: %s", coeffsSqr)
750 coeffsSqr = np.zeros_like(coeffs)
753 badCoeffs = ~np.isfinite(coeffs) | (coeffs == 0.0)
754 coeffs[badCoeffs] = 0.0
755 coeffsSqr[badCoeffs] = 0.0
756 if crosstalkCoeffsValid
is not None:
757 coeffs[~crosstalkCoeffsValid] = 0.0
758 coeffsSqr[~crosstalkCoeffsValid] = 0.0
761 for index, amp
in enumerate(sourceDetector):
762 if badAmpDict[amp.getName()]:
763 coeffs[index, :] = 0.0
764 coeffs[:, index] = 0.0
767 backgrounds = {amp.getName(): 0.0
for amp
in sourceDetector}
768 useBackgrounds =
False
769 if backgroundMethod ==
"AMP":
770 useBackgrounds =
True
778 for amp
in sourceDetector
780 elif backgroundMethod ==
"DETECTOR":
781 useBackgrounds =
True
783 backgrounds = {amp.getName(): background
for amp
in sourceDetector}
786 sourceCrosstalkPlane = sourceMaskedImage.mask.addMaskPlane(crosstalkStr)
787 if sourceExposure
is not None:
788 targetCrosstalkPlane = targetMaskedImage.mask.addMaskPlane(crosstalkStr)
790 targetCrosstalkPlane = sourceCrosstalkPlane
795 if doCrosstalkMask
and not doSubtrahendMasking:
798 toMask = (sourceMaskedImage.image.array >= (minPixelToMask + thresholdBackground))
799 sourceMaskedImage.mask.array[toMask] |= sourceMaskedImage.mask.getPlaneBitMask(crosstalkStr)
801 crosstalk = sourceMaskedImage.mask.getPlaneBitMask(crosstalkStr)
805 subtrahend = targetMaskedImage.Factory(targetMaskedImage.getBBox())
806 subtrahend.set((0, 0, 0))
810 imageOnly = ignoreVariance
and (doSubtrahendMasking
or not doCrosstalkMask)
812 if imageOnly
and not useBackgrounds
and doUseFastPath:
815 X_FLIP = {lsst.afw.cameraGeom.ReadoutCorner.LL:
False,
816 lsst.afw.cameraGeom.ReadoutCorner.LR:
True,
817 lsst.afw.cameraGeom.ReadoutCorner.UL:
False,
818 lsst.afw.cameraGeom.ReadoutCorner.UR:
True}
819 Y_FLIP = {lsst.afw.cameraGeom.ReadoutCorner.LL:
False,
820 lsst.afw.cameraGeom.ReadoutCorner.LR:
False,
821 lsst.afw.cameraGeom.ReadoutCorner.UL:
True,
822 lsst.afw.cameraGeom.ReadoutCorner.UR:
True}
824 c = amp.getReadoutCorner()
825 return a[::-1
if Y_FLIP[c]
else 1, ::-1
if X_FLIP[c]
else 1]
827 N = len(sourceDetector)
830 ny, nx = bbox.getHeight(), bbox.getWidth()
831 srcArr = sourceMaskedImage.image.array
832 A = np.empty((2*N, ny*nx), dtype=np.float32)
833 for s, amp
in enumerate(sourceDetector):
835 A[s].reshape(ny, nx)[:] = _flip(srcArr[bbox.slices], amp)
836 if np.any(coeffsSqr):
837 np.multiply(A[:N], A[:N], out=A[N:])
838 M = np.concatenate([coeffs, coeffsSqr]).T.astype(np.float32)
839 with threadpool_limits(limits=1, user_api=
"blas"):
842 with threadpool_limits(limits=1, user_api=
"blas"):
843 C = coeffs.T.astype(np.float32) @ A[:N]
845 subArr = subtrahend.image.array
846 for t, amp
in enumerate(targetDetector):
848 subArr[bbox.slices] = _flip(C[t].reshape(ny, nx), amp)
851 for sourceIndex, sourceAmp
in enumerate(sourceDetector):
852 for targetIndex, targetAmp
in enumerate(targetDetector):
853 coeff = coeffs[sourceIndex, targetIndex]
854 coeffSqr = coeffsSqr[sourceIndex, targetIndex]
865 sourceMaskedImage.image,
869 fullAmplifier=fullAmplifier,
872 targetImage = subtrahend[targetBBox].image
879 fullAmplifier=fullAmplifier,
881 targetImage = subtrahend[targetBBox]
884 sourceImage.mask.array[:] &= crosstalk
886 if backgrounds[sourceAmp.getName()] != 0.0:
887 sourceImage -= backgrounds[sourceAmp.getName()]
892 targetImage.scaledPlus(coeff, sourceImage)
894 sourceImage.scaledMultiplies(1.0, sourceImage)
895 targetImage.scaledPlus(coeffSqr, sourceImage)
899 sourceMaskedImage.mask.clearMaskPlane(sourceCrosstalkPlane)
900 if sourceExposure
is not None:
901 targetMaskedImage.mask.clearMaskPlane(targetCrosstalkPlane)
903 if doCrosstalkMask
and doSubtrahendMasking:
912 subtrahend.mask.clearMaskPlane(targetCrosstalkPlane)
922 subtrahendBackgrounds = {}
923 for amp
in targetDetector:
927 ampData = subtrahend[bbox]
928 background = np.median(ampData.image.array[::4, ::4])
929 subtrahendBackgrounds[amp.getName()] = background
930 ampData.image.array[:, :] -= background
931 self.
log.debug(f
"Subtrahend background level: {amp.getName()} {background}")
933 toMask = (subtrahend.image.array >= minPixelToMask) | (subtrahend.image.array <= -minPixelToMask)
934 subtrahend.mask.array[toMask] |= subtrahend.mask.getPlaneBitMask(crosstalkStr)
937 for amp
in targetDetector:
939 ampData = subtrahend[bbox]
940 background = subtrahendBackgrounds[amp.getName()]
941 ampData.image.array[:, :] += background
947 targetMaskedImage -= subtrahend