32 from contextlib
import contextmanager
33 from lsstDebug
import getDebugFrame
43 from .
import isrFunctions
45 from .
import linearize
46 from .defects
import Defects
48 from .assembleCcdTask
import AssembleCcdTask
49 from .crosstalk
import CrosstalkTask, CrosstalkCalib
50 from .fringe
import FringeTask
51 from .isr
import maskNans
52 from .masking
import MaskingTask
53 from .overscan
import OverscanCorrectionTask
54 from .straylight
import StrayLightTask
55 from .vignette
import VignetteTask
56 from lsst.daf.butler
import DimensionGraph
59 __all__ = [
"IsrTask",
"IsrTaskConfig",
"RunIsrTask",
"RunIsrConfig"]
63 """Lookup function to identify crosstalkSource entries.
65 This should return an empty list under most circumstances. Only
66 when inter-chip crosstalk has been identified should this be
69 This will be unused until DM-25348 resolves the quantum graph
76 registry : `lsst.daf.butler.Registry`
77 Butler registry to query.
78 quantumDataId : `lsst.daf.butler.ExpandedDataCoordinate`
79 Data id to transform to identify crosstalkSources. The
80 ``detector`` entry will be stripped.
81 collections : `lsst.daf.butler.CollectionSearch`
82 Collections to search through.
86 results : `list` [`lsst.daf.butler.DatasetRef`]
87 List of datasets that match the query that will be used as
90 newDataId = quantumDataId.subset(DimensionGraph(registry.dimensions, names=[
"instrument",
"exposure"]))
91 results = list(registry.queryDatasets(datasetType,
92 collections=collections,
100 dimensions={
"instrument",
"exposure",
"detector"},
101 defaultTemplates={}):
102 ccdExposure = cT.Input(
104 doc=
"Input exposure to process.",
105 storageClass=
"Exposure",
106 dimensions=[
"instrument",
"exposure",
"detector"],
108 camera = cT.PrerequisiteInput(
110 storageClass=
"Camera",
111 doc=
"Input camera to construct complete exposures.",
112 dimensions=[
"instrument"],
116 crosstalk = cT.PrerequisiteInput(
118 doc=
"Input crosstalk object",
119 storageClass=
"CrosstalkCalib",
120 dimensions=[
"instrument",
"detector"],
125 crosstalkSources = cT.PrerequisiteInput(
126 name=
"isrOverscanCorrected",
127 doc=
"Overscan corrected input images.",
128 storageClass=
"Exposure",
129 dimensions=[
"instrument",
"exposure",
"detector"],
132 lookupFunction=crosstalkSourceLookup,
134 bias = cT.PrerequisiteInput(
136 doc=
"Input bias calibration.",
137 storageClass=
"ExposureF",
138 dimensions=[
"instrument",
"detector"],
141 dark = cT.PrerequisiteInput(
143 doc=
"Input dark calibration.",
144 storageClass=
"ExposureF",
145 dimensions=[
"instrument",
"detector"],
148 flat = cT.PrerequisiteInput(
150 doc=
"Input flat calibration.",
151 storageClass=
"ExposureF",
152 dimensions=[
"instrument",
"physical_filter",
"detector"],
155 fringes = cT.PrerequisiteInput(
157 doc=
"Input fringe calibration.",
158 storageClass=
"ExposureF",
159 dimensions=[
"instrument",
"physical_filter",
"detector"],
162 strayLightData = cT.PrerequisiteInput(
164 doc=
"Input stray light calibration.",
165 storageClass=
"StrayLightData",
166 dimensions=[
"instrument",
"physical_filter",
"detector"],
169 bfKernel = cT.PrerequisiteInput(
171 doc=
"Input brighter-fatter kernel.",
172 storageClass=
"NumpyArray",
173 dimensions=[
"instrument"],
176 newBFKernel = cT.PrerequisiteInput(
177 name=
'brighterFatterKernel',
178 doc=
"Newer complete kernel + gain solutions.",
179 storageClass=
"BrighterFatterKernel",
180 dimensions=[
"instrument",
"detector"],
183 defects = cT.PrerequisiteInput(
185 doc=
"Input defect tables.",
186 storageClass=
"Defects",
187 dimensions=[
"instrument",
"detector"],
190 linearizer = cT.PrerequisiteInput(
192 storageClass=
"Linearizer",
193 doc=
"Linearity correction calibration.",
194 dimensions=[
"instrument",
"detector"],
197 opticsTransmission = cT.PrerequisiteInput(
198 name=
"transmission_optics",
199 storageClass=
"TransmissionCurve",
200 doc=
"Transmission curve due to the optics.",
201 dimensions=[
"instrument"],
204 filterTransmission = cT.PrerequisiteInput(
205 name=
"transmission_filter",
206 storageClass=
"TransmissionCurve",
207 doc=
"Transmission curve due to the filter.",
208 dimensions=[
"instrument",
"physical_filter"],
211 sensorTransmission = cT.PrerequisiteInput(
212 name=
"transmission_sensor",
213 storageClass=
"TransmissionCurve",
214 doc=
"Transmission curve due to the sensor.",
215 dimensions=[
"instrument",
"detector"],
218 atmosphereTransmission = cT.PrerequisiteInput(
219 name=
"transmission_atmosphere",
220 storageClass=
"TransmissionCurve",
221 doc=
"Transmission curve due to the atmosphere.",
222 dimensions=[
"instrument"],
225 illumMaskedImage = cT.PrerequisiteInput(
227 doc=
"Input illumination correction.",
228 storageClass=
"MaskedImageF",
229 dimensions=[
"instrument",
"physical_filter",
"detector"],
233 outputExposure = cT.Output(
235 doc=
"Output ISR processed exposure.",
236 storageClass=
"Exposure",
237 dimensions=[
"instrument",
"exposure",
"detector"],
239 preInterpExposure = cT.Output(
240 name=
'preInterpISRCCD',
241 doc=
"Output ISR processed exposure, with pixels left uninterpolated.",
242 storageClass=
"ExposureF",
243 dimensions=[
"instrument",
"exposure",
"detector"],
245 outputOssThumbnail = cT.Output(
247 doc=
"Output Overscan-subtracted thumbnail image.",
248 storageClass=
"Thumbnail",
249 dimensions=[
"instrument",
"exposure",
"detector"],
251 outputFlattenedThumbnail = cT.Output(
252 name=
"FlattenedThumb",
253 doc=
"Output flat-corrected thumbnail image.",
254 storageClass=
"Thumbnail",
255 dimensions=[
"instrument",
"exposure",
"detector"],
261 if config.doBias
is not True:
262 self.prerequisiteInputs.discard(
"bias")
263 if config.doLinearize
is not True:
264 self.prerequisiteInputs.discard(
"linearizer")
265 if config.doCrosstalk
is not True:
266 self.inputs.discard(
"crosstalkSources")
267 self.prerequisiteInputs.discard(
"crosstalk")
268 if config.doBrighterFatter
is not True:
269 self.prerequisiteInputs.discard(
"bfKernel")
270 self.prerequisiteInputs.discard(
"newBFKernel")
271 if config.doDefect
is not True:
272 self.prerequisiteInputs.discard(
"defects")
273 if config.doDark
is not True:
274 self.prerequisiteInputs.discard(
"dark")
275 if config.doFlat
is not True:
276 self.prerequisiteInputs.discard(
"flat")
277 if config.doAttachTransmissionCurve
is not True:
278 self.prerequisiteInputs.discard(
"opticsTransmission")
279 self.prerequisiteInputs.discard(
"filterTransmission")
280 self.prerequisiteInputs.discard(
"sensorTransmission")
281 self.prerequisiteInputs.discard(
"atmosphereTransmission")
282 if config.doUseOpticsTransmission
is not True:
283 self.prerequisiteInputs.discard(
"opticsTransmission")
284 if config.doUseFilterTransmission
is not True:
285 self.prerequisiteInputs.discard(
"filterTransmission")
286 if config.doUseSensorTransmission
is not True:
287 self.prerequisiteInputs.discard(
"sensorTransmission")
288 if config.doUseAtmosphereTransmission
is not True:
289 self.prerequisiteInputs.discard(
"atmosphereTransmission")
290 if config.doIlluminationCorrection
is not True:
291 self.prerequisiteInputs.discard(
"illumMaskedImage")
293 if config.doWrite
is not True:
294 self.outputs.discard(
"outputExposure")
295 self.outputs.discard(
"preInterpExposure")
296 self.outputs.discard(
"outputFlattenedThumbnail")
297 self.outputs.discard(
"outputOssThumbnail")
298 if config.doSaveInterpPixels
is not True:
299 self.outputs.discard(
"preInterpExposure")
300 if config.qa.doThumbnailOss
is not True:
301 self.outputs.discard(
"outputOssThumbnail")
302 if config.qa.doThumbnailFlattened
is not True:
303 self.outputs.discard(
"outputFlattenedThumbnail")
307 pipelineConnections=IsrTaskConnections):
308 """Configuration parameters for IsrTask.
310 Items are grouped in the order in which they are executed by the task.
312 datasetType = pexConfig.Field(
314 doc=
"Dataset type for input data; users will typically leave this alone, "
315 "but camera-specific ISR tasks will override it",
319 fallbackFilterName = pexConfig.Field(
321 doc=
"Fallback default filter name for calibrations.",
324 useFallbackDate = pexConfig.Field(
326 doc=
"Pass observation date when using fallback filter.",
329 expectWcs = pexConfig.Field(
332 doc=
"Expect input science images to have a WCS (set False for e.g. spectrographs)."
334 fwhm = pexConfig.Field(
336 doc=
"FWHM of PSF in arcseconds.",
339 qa = pexConfig.ConfigField(
341 doc=
"QA related configuration options.",
345 doConvertIntToFloat = pexConfig.Field(
347 doc=
"Convert integer raw images to floating point values?",
352 doSaturation = pexConfig.Field(
354 doc=
"Mask saturated pixels? NB: this is totally independent of the"
355 " interpolation option - this is ONLY setting the bits in the mask."
356 " To have them interpolated make sure doSaturationInterpolation=True",
359 saturatedMaskName = pexConfig.Field(
361 doc=
"Name of mask plane to use in saturation detection and interpolation",
364 saturation = pexConfig.Field(
366 doc=
"The saturation level to use if no Detector is present in the Exposure (ignored if NaN)",
367 default=float(
"NaN"),
369 growSaturationFootprintSize = pexConfig.Field(
371 doc=
"Number of pixels by which to grow the saturation footprints",
376 doSuspect = pexConfig.Field(
378 doc=
"Mask suspect pixels?",
381 suspectMaskName = pexConfig.Field(
383 doc=
"Name of mask plane to use for suspect pixels",
386 numEdgeSuspect = pexConfig.Field(
388 doc=
"Number of edge pixels to be flagged as untrustworthy.",
391 edgeMaskLevel = pexConfig.ChoiceField(
393 doc=
"Mask edge pixels in which coordinate frame: DETECTOR or AMP?",
396 'DETECTOR':
'Mask only the edges of the full detector.',
397 'AMP':
'Mask edges of each amplifier.',
402 doSetBadRegions = pexConfig.Field(
404 doc=
"Should we set the level of all BAD patches of the chip to the chip's average value?",
407 badStatistic = pexConfig.ChoiceField(
409 doc=
"How to estimate the average value for BAD regions.",
412 "MEANCLIP":
"Correct using the (clipped) mean of good data",
413 "MEDIAN":
"Correct using the median of the good data",
418 doOverscan = pexConfig.Field(
420 doc=
"Do overscan subtraction?",
423 overscan = pexConfig.ConfigurableField(
424 target=OverscanCorrectionTask,
425 doc=
"Overscan subtraction task for image segments.",
428 overscanFitType = pexConfig.ChoiceField(
430 doc=
"The method for fitting the overscan bias level.",
433 "POLY":
"Fit ordinary polynomial to the longest axis of the overscan region",
434 "CHEB":
"Fit Chebyshev polynomial to the longest axis of the overscan region",
435 "LEG":
"Fit Legendre polynomial to the longest axis of the overscan region",
436 "NATURAL_SPLINE":
"Fit natural spline to the longest axis of the overscan region",
437 "CUBIC_SPLINE":
"Fit cubic spline to the longest axis of the overscan region",
438 "AKIMA_SPLINE":
"Fit Akima spline to the longest axis of the overscan region",
439 "MEAN":
"Correct using the mean of the overscan region",
440 "MEANCLIP":
"Correct using a clipped mean of the overscan region",
441 "MEDIAN":
"Correct using the median of the overscan region",
442 "MEDIAN_PER_ROW":
"Correct using the median per row of the overscan region",
444 deprecated=(
"Please configure overscan via the OverscanCorrectionConfig interface."
445 " This option will no longer be used, and will be removed after v20.")
447 overscanOrder = pexConfig.Field(
449 doc=(
"Order of polynomial or to fit if overscan fit type is a polynomial, "
450 "or number of spline knots if overscan fit type is a spline."),
452 deprecated=(
"Please configure overscan via the OverscanCorrectionConfig interface."
453 " This option will no longer be used, and will be removed after v20.")
455 overscanNumSigmaClip = pexConfig.Field(
457 doc=
"Rejection threshold (sigma) for collapsing overscan before fit",
459 deprecated=(
"Please configure overscan via the OverscanCorrectionConfig interface."
460 " This option will no longer be used, and will be removed after v20.")
462 overscanIsInt = pexConfig.Field(
464 doc=
"Treat overscan as an integer image for purposes of overscan.FitType=MEDIAN"
465 " and overscan.FitType=MEDIAN_PER_ROW.",
467 deprecated=(
"Please configure overscan via the OverscanCorrectionConfig interface."
468 " This option will no longer be used, and will be removed after v20.")
471 overscanNumLeadingColumnsToSkip = pexConfig.Field(
473 doc=
"Number of columns to skip in overscan, i.e. those closest to amplifier",
476 overscanNumTrailingColumnsToSkip = pexConfig.Field(
478 doc=
"Number of columns to skip in overscan, i.e. those farthest from amplifier",
481 overscanMaxDev = pexConfig.Field(
483 doc=
"Maximum deviation from the median for overscan",
484 default=1000.0, check=
lambda x: x > 0
486 overscanBiasJump = pexConfig.Field(
488 doc=
"Fit the overscan in a piecewise-fashion to correct for bias jumps?",
491 overscanBiasJumpKeyword = pexConfig.Field(
493 doc=
"Header keyword containing information about devices.",
494 default=
"NO_SUCH_KEY",
496 overscanBiasJumpDevices = pexConfig.ListField(
498 doc=
"List of devices that need piecewise overscan correction.",
501 overscanBiasJumpLocation = pexConfig.Field(
503 doc=
"Location of bias jump along y-axis.",
508 doAssembleCcd = pexConfig.Field(
511 doc=
"Assemble amp-level exposures into a ccd-level exposure?"
513 assembleCcd = pexConfig.ConfigurableField(
514 target=AssembleCcdTask,
515 doc=
"CCD assembly task",
519 doAssembleIsrExposures = pexConfig.Field(
522 doc=
"Assemble amp-level calibration exposures into ccd-level exposure?"
524 doTrimToMatchCalib = pexConfig.Field(
527 doc=
"Trim raw data to match calibration bounding boxes?"
531 doBias = pexConfig.Field(
533 doc=
"Apply bias frame correction?",
536 biasDataProductName = pexConfig.Field(
538 doc=
"Name of the bias data product",
541 doBiasBeforeOverscan = pexConfig.Field(
543 doc=
"Reverse order of overscan and bias correction.",
548 doVariance = pexConfig.Field(
550 doc=
"Calculate variance?",
553 gain = pexConfig.Field(
555 doc=
"The gain to use if no Detector is present in the Exposure (ignored if NaN)",
556 default=float(
"NaN"),
558 readNoise = pexConfig.Field(
560 doc=
"The read noise to use if no Detector is present in the Exposure",
563 doEmpiricalReadNoise = pexConfig.Field(
566 doc=
"Calculate empirical read noise instead of value from AmpInfo data?"
570 doLinearize = pexConfig.Field(
572 doc=
"Correct for nonlinearity of the detector's response?",
577 doCrosstalk = pexConfig.Field(
579 doc=
"Apply intra-CCD crosstalk correction?",
582 doCrosstalkBeforeAssemble = pexConfig.Field(
584 doc=
"Apply crosstalk correction before CCD assembly, and before trimming?",
587 crosstalk = pexConfig.ConfigurableField(
588 target=CrosstalkTask,
589 doc=
"Intra-CCD crosstalk correction",
593 doDefect = pexConfig.Field(
595 doc=
"Apply correction for CCD defects, e.g. hot pixels?",
598 doNanMasking = pexConfig.Field(
600 doc=
"Mask NAN pixels?",
603 doWidenSaturationTrails = pexConfig.Field(
605 doc=
"Widen bleed trails based on their width?",
610 doBrighterFatter = pexConfig.Field(
613 doc=
"Apply the brighter fatter correction"
615 brighterFatterLevel = pexConfig.ChoiceField(
618 doc=
"The level at which to correct for brighter-fatter.",
620 "AMP":
"Every amplifier treated separately.",
621 "DETECTOR":
"One kernel per detector",
624 brighterFatterMaxIter = pexConfig.Field(
627 doc=
"Maximum number of iterations for the brighter fatter correction"
629 brighterFatterThreshold = pexConfig.Field(
632 doc=
"Threshold used to stop iterating the brighter fatter correction. It is the "
633 " absolute value of the difference between the current corrected image and the one"
634 " from the previous iteration summed over all the pixels."
636 brighterFatterApplyGain = pexConfig.Field(
639 doc=
"Should the gain be applied when applying the brighter fatter correction?"
641 brighterFatterMaskGrowSize = pexConfig.Field(
644 doc=
"Number of pixels to grow the masks listed in config.maskListToInterpolate "
645 " when brighter-fatter correction is applied."
649 doDark = pexConfig.Field(
651 doc=
"Apply dark frame correction?",
654 darkDataProductName = pexConfig.Field(
656 doc=
"Name of the dark data product",
661 doStrayLight = pexConfig.Field(
663 doc=
"Subtract stray light in the y-band (due to encoder LEDs)?",
666 strayLight = pexConfig.ConfigurableField(
667 target=StrayLightTask,
668 doc=
"y-band stray light correction"
672 doFlat = pexConfig.Field(
674 doc=
"Apply flat field correction?",
677 flatDataProductName = pexConfig.Field(
679 doc=
"Name of the flat data product",
682 flatScalingType = pexConfig.ChoiceField(
684 doc=
"The method for scaling the flat on the fly.",
687 "USER":
"Scale by flatUserScale",
688 "MEAN":
"Scale by the inverse of the mean",
689 "MEDIAN":
"Scale by the inverse of the median",
692 flatUserScale = pexConfig.Field(
694 doc=
"If flatScalingType is 'USER' then scale flat by this amount; ignored otherwise",
697 doTweakFlat = pexConfig.Field(
699 doc=
"Tweak flats to match observed amplifier ratios?",
704 doApplyGains = pexConfig.Field(
706 doc=
"Correct the amplifiers for their gains instead of applying flat correction",
709 normalizeGains = pexConfig.Field(
711 doc=
"Normalize all the amplifiers in each CCD to have the same median value.",
716 doFringe = pexConfig.Field(
718 doc=
"Apply fringe correction?",
721 fringe = pexConfig.ConfigurableField(
723 doc=
"Fringe subtraction task",
725 fringeAfterFlat = pexConfig.Field(
727 doc=
"Do fringe subtraction after flat-fielding?",
732 doMeasureBackground = pexConfig.Field(
734 doc=
"Measure the background level on the reduced image?",
739 doCameraSpecificMasking = pexConfig.Field(
741 doc=
"Mask camera-specific bad regions?",
744 masking = pexConfig.ConfigurableField(
751 doInterpolate = pexConfig.Field(
753 doc=
"Interpolate masked pixels?",
756 doSaturationInterpolation = pexConfig.Field(
758 doc=
"Perform interpolation over pixels masked as saturated?"
759 " NB: This is independent of doSaturation; if that is False this plane"
760 " will likely be blank, resulting in a no-op here.",
763 doNanInterpolation = pexConfig.Field(
765 doc=
"Perform interpolation over pixels masked as NaN?"
766 " NB: This is independent of doNanMasking; if that is False this plane"
767 " will likely be blank, resulting in a no-op here.",
770 doNanInterpAfterFlat = pexConfig.Field(
772 doc=(
"If True, ensure we interpolate NaNs after flat-fielding, even if we "
773 "also have to interpolate them before flat-fielding."),
776 maskListToInterpolate = pexConfig.ListField(
778 doc=
"List of mask planes that should be interpolated.",
779 default=[
'SAT',
'BAD',
'UNMASKEDNAN'],
781 doSaveInterpPixels = pexConfig.Field(
783 doc=
"Save a copy of the pre-interpolated pixel values?",
788 fluxMag0T1 = pexConfig.DictField(
791 doc=
"The approximate flux of a zero-magnitude object in a one-second exposure, per filter.",
792 default=dict((f, pow(10.0, 0.4*m))
for f, m
in ((
"Unknown", 28.0),
795 defaultFluxMag0T1 = pexConfig.Field(
797 doc=
"Default value for fluxMag0T1 (for an unrecognized filter).",
798 default=pow(10.0, 0.4*28.0)
802 doVignette = pexConfig.Field(
804 doc=
"Apply vignetting parameters?",
807 vignette = pexConfig.ConfigurableField(
809 doc=
"Vignetting task.",
813 doAttachTransmissionCurve = pexConfig.Field(
816 doc=
"Construct and attach a wavelength-dependent throughput curve for this CCD image?"
818 doUseOpticsTransmission = pexConfig.Field(
821 doc=
"Load and use transmission_optics (if doAttachTransmissionCurve is True)?"
823 doUseFilterTransmission = pexConfig.Field(
826 doc=
"Load and use transmission_filter (if doAttachTransmissionCurve is True)?"
828 doUseSensorTransmission = pexConfig.Field(
831 doc=
"Load and use transmission_sensor (if doAttachTransmissionCurve is True)?"
833 doUseAtmosphereTransmission = pexConfig.Field(
836 doc=
"Load and use transmission_atmosphere (if doAttachTransmissionCurve is True)?"
840 doIlluminationCorrection = pexConfig.Field(
843 doc=
"Perform illumination correction?"
845 illuminationCorrectionDataProductName = pexConfig.Field(
847 doc=
"Name of the illumination correction data product.",
850 illumScale = pexConfig.Field(
852 doc=
"Scale factor for the illumination correction.",
855 illumFilters = pexConfig.ListField(
858 doc=
"Only perform illumination correction for these filters."
862 doWrite = pexConfig.Field(
864 doc=
"Persist postISRCCD?",
871 raise ValueError(
"You may not specify both doFlat and doApplyGains")
873 raise ValueError(
"You may not specify both doBiasBeforeOverscan and doTrimToMatchCalib")
882 class IsrTask(pipeBase.PipelineTask, pipeBase.CmdLineTask):
883 """Apply common instrument signature correction algorithms to a raw frame.
885 The process for correcting imaging data is very similar from
886 camera to camera. This task provides a vanilla implementation of
887 doing these corrections, including the ability to turn certain
888 corrections off if they are not needed. The inputs to the primary
889 method, `run()`, are a raw exposure to be corrected and the
890 calibration data products. The raw input is a single chip sized
891 mosaic of all amps including overscans and other non-science
892 pixels. The method `runDataRef()` identifies and defines the
893 calibration data products, and is intended for use by a
894 `lsst.pipe.base.cmdLineTask.CmdLineTask` and takes as input only a
895 `daf.persistence.butlerSubset.ButlerDataRef`. This task may be
896 subclassed for different camera, although the most camera specific
897 methods have been split into subtasks that can be redirected
900 The __init__ method sets up the subtasks for ISR processing, using
901 the defaults from `lsst.ip.isr`.
906 Positional arguments passed to the Task constructor. None used at this time.
907 kwargs : `dict`, optional
908 Keyword arguments passed on to the Task constructor. None used at this time.
910 ConfigClass = IsrTaskConfig
915 self.makeSubtask(
"assembleCcd")
916 self.makeSubtask(
"crosstalk")
917 self.makeSubtask(
"strayLight")
918 self.makeSubtask(
"fringe")
919 self.makeSubtask(
"masking")
920 self.makeSubtask(
"overscan")
921 self.makeSubtask(
"vignette")
924 inputs = butlerQC.get(inputRefs)
927 inputs[
'detectorNum'] = inputRefs.ccdExposure.dataId[
'detector']
928 except Exception
as e:
929 raise ValueError(
"Failure to find valid detectorNum value for Dataset %s: %s." %
932 inputs[
'isGen3'] =
True
934 detector = inputs[
'ccdExposure'].getDetector()
936 if self.config.doCrosstalk
is True:
939 if 'crosstalk' in inputs
and inputs[
'crosstalk']
is not None:
940 if not isinstance(inputs[
'crosstalk'], CrosstalkCalib):
941 inputs[
'crosstalk'] = CrosstalkCalib.fromTable(inputs[
'crosstalk'])
943 coeffVector = (self.config.crosstalk.crosstalkValues
944 if self.config.crosstalk.useConfigCoefficients
else None)
945 crosstalkCalib =
CrosstalkCalib().fromDetector(detector, coeffVector=coeffVector)
946 inputs[
'crosstalk'] = crosstalkCalib
947 if inputs[
'crosstalk'].interChip
and len(inputs[
'crosstalk'].interChip) > 0:
948 if 'crosstalkSources' not in inputs:
949 self.log.warn(
"No crosstalkSources found for chip with interChip terms!")
952 if 'linearizer' in inputs:
953 if isinstance(inputs[
'linearizer'], dict):
955 linearizer.fromYaml(inputs[
'linearizer'])
956 self.log.warn(
"Dictionary linearizers will be deprecated in DM-28741.")
957 elif isinstance(inputs[
'linearizer'], numpy.ndarray):
961 self.log.warn(
"Bare lookup table linearizers will be deprecated in DM-28741.")
963 linearizer = inputs[
'linearizer']
964 linearizer.log = self.log
965 inputs[
'linearizer'] = linearizer
968 self.log.warn(
"Constructing linearizer from cameraGeom information.")
970 if self.config.doDefect
is True:
971 if "defects" in inputs
and inputs[
'defects']
is not None:
974 if not isinstance(inputs[
"defects"], Defects):
975 inputs[
"defects"] = Defects.fromTable(inputs[
"defects"])
979 if self.config.doBrighterFatter:
980 brighterFatterKernel = inputs.pop(
'newBFKernel',
None)
981 if brighterFatterKernel
is None:
982 brighterFatterKernel = inputs.get(
'bfKernel',
None)
984 if brighterFatterKernel
is not None and not isinstance(brighterFatterKernel, numpy.ndarray):
985 detId = detector.getId()
986 inputs[
'bfGains'] = brighterFatterKernel.gain
989 if self.config.brighterFatterLevel ==
'DETECTOR':
990 if brighterFatterKernel.detectorKernel:
991 inputs[
'bfKernel'] = brighterFatterKernel.detectorKernel[detId]
992 elif brighterFatterKernel.detectorKernelFromAmpKernels:
993 inputs[
'bfKernel'] = brighterFatterKernel.detectorKernelFromAmpKernels[detId]
995 raise RuntimeError(
"Failed to extract kernel from new-style BF kernel.")
998 raise NotImplementedError(
"Per-amplifier brighter-fatter correction not implemented")
1000 if self.config.doFringe
is True and self.fringe.
checkFilter(inputs[
'ccdExposure']):
1001 expId = inputs[
'ccdExposure'].getInfo().getVisitInfo().getExposureId()
1002 inputs[
'fringes'] = self.fringe.loadFringes(inputs[
'fringes'],
1004 assembler=self.assembleCcd
1005 if self.config.doAssembleIsrExposures
else None)
1007 inputs[
'fringes'] = pipeBase.Struct(fringes=
None)
1009 if self.config.doStrayLight
is True and self.strayLight.
checkFilter(inputs[
'ccdExposure']):
1010 if 'strayLightData' not in inputs:
1011 inputs[
'strayLightData'] =
None
1013 outputs = self.
runrun(**inputs)
1014 butlerQC.put(outputs, outputRefs)
1017 """Retrieve necessary frames for instrument signature removal.
1019 Pre-fetching all required ISR data products limits the IO
1020 required by the ISR. Any conflict between the calibration data
1021 available and that needed for ISR is also detected prior to
1022 doing processing, allowing it to fail quickly.
1026 dataRef : `daf.persistence.butlerSubset.ButlerDataRef`
1027 Butler reference of the detector data to be processed
1028 rawExposure : `afw.image.Exposure`
1029 The raw exposure that will later be corrected with the
1030 retrieved calibration data; should not be modified in this
1035 result : `lsst.pipe.base.Struct`
1036 Result struct with components (which may be `None`):
1037 - ``bias``: bias calibration frame (`afw.image.Exposure`)
1038 - ``linearizer``: functor for linearization (`ip.isr.linearize.LinearizeBase`)
1039 - ``crosstalkSources``: list of possible crosstalk sources (`list`)
1040 - ``dark``: dark calibration frame (`afw.image.Exposure`)
1041 - ``flat``: flat calibration frame (`afw.image.Exposure`)
1042 - ``bfKernel``: Brighter-Fatter kernel (`numpy.ndarray`)
1043 - ``defects``: list of defects (`lsst.ip.isr.Defects`)
1044 - ``fringes``: `lsst.pipe.base.Struct` with components:
1045 - ``fringes``: fringe calibration frame (`afw.image.Exposure`)
1046 - ``seed``: random seed derived from the ccdExposureId for random
1047 number generator (`uint32`).
1048 - ``opticsTransmission``: `lsst.afw.image.TransmissionCurve`
1049 A ``TransmissionCurve`` that represents the throughput of the optics,
1050 to be evaluated in focal-plane coordinates.
1051 - ``filterTransmission`` : `lsst.afw.image.TransmissionCurve`
1052 A ``TransmissionCurve`` that represents the throughput of the filter
1053 itself, to be evaluated in focal-plane coordinates.
1054 - ``sensorTransmission`` : `lsst.afw.image.TransmissionCurve`
1055 A ``TransmissionCurve`` that represents the throughput of the sensor
1056 itself, to be evaluated in post-assembly trimmed detector coordinates.
1057 - ``atmosphereTransmission`` : `lsst.afw.image.TransmissionCurve`
1058 A ``TransmissionCurve`` that represents the throughput of the
1059 atmosphere, assumed to be spatially constant.
1060 - ``strayLightData`` : `object`
1061 An opaque object containing calibration information for
1062 stray-light correction. If `None`, no correction will be
1064 - ``illumMaskedImage`` : illumination correction image (`lsst.afw.image.MaskedImage`)
1068 NotImplementedError :
1069 Raised if a per-amplifier brighter-fatter kernel is requested by the configuration.
1072 dateObs = rawExposure.getInfo().getVisitInfo().getDate()
1073 dateObs = dateObs.toPython().isoformat()
1074 except RuntimeError:
1075 self.log.warn(
"Unable to identify dateObs for rawExposure.")
1078 ccd = rawExposure.getDetector()
1079 filterLabel = rawExposure.getFilterLabel()
1080 rawExposure.mask.addMaskPlane(
"UNMASKEDNAN")
1081 biasExposure = (self.
getIsrExposuregetIsrExposure(dataRef, self.config.biasDataProductName)
1082 if self.config.doBias
else None)
1084 linearizer = (dataRef.get(
"linearizer", immediate=
True)
1086 if linearizer
is not None and not isinstance(linearizer, numpy.ndarray):
1087 linearizer.log = self.log
1088 if isinstance(linearizer, numpy.ndarray):
1091 crosstalkCalib =
None
1092 if self.config.doCrosstalk:
1094 crosstalkCalib = dataRef.get(
"crosstalk", immediate=
True)
1096 coeffVector = (self.config.crosstalk.crosstalkValues
1097 if self.config.crosstalk.useConfigCoefficients
else None)
1098 crosstalkCalib =
CrosstalkCalib().fromDetector(ccd, coeffVector=coeffVector)
1099 crosstalkSources = (self.crosstalk.prepCrosstalk(dataRef, crosstalkCalib)
1100 if self.config.doCrosstalk
else None)
1102 darkExposure = (self.
getIsrExposuregetIsrExposure(dataRef, self.config.darkDataProductName)
1103 if self.config.doDark
else None)
1104 flatExposure = (self.
getIsrExposuregetIsrExposure(dataRef, self.config.flatDataProductName,
1106 if self.config.doFlat
else None)
1108 brighterFatterKernel =
None
1109 brighterFatterGains =
None
1110 if self.config.doBrighterFatter
is True:
1115 brighterFatterKernel = dataRef.get(
"brighterFatterKernel")
1116 brighterFatterGains = brighterFatterKernel.gain
1117 self.log.info(
"New style bright-fatter kernel (brighterFatterKernel) loaded")
1120 brighterFatterKernel = dataRef.get(
"bfKernel")
1121 self.log.info(
"Old style bright-fatter kernel (np.array) loaded")
1123 brighterFatterKernel =
None
1124 if brighterFatterKernel
is not None and not isinstance(brighterFatterKernel, numpy.ndarray):
1127 if self.config.brighterFatterLevel ==
'DETECTOR':
1128 if brighterFatterKernel.detectorKernel:
1129 brighterFatterKernel = brighterFatterKernel.detectorKernel[ccd.getId()]
1130 elif brighterFatterKernel.detectorKernelFromAmpKernels:
1131 brighterFatterKernel = brighterFatterKernel.detectorKernelFromAmpKernels[ccd.getId()]
1133 raise RuntimeError(
"Failed to extract kernel from new-style BF kernel.")
1136 raise NotImplementedError(
"Per-amplifier brighter-fatter correction not implemented")
1138 defectList = (dataRef.get(
"defects")
1139 if self.config.doDefect
else None)
1140 fringeStruct = (self.fringe.readFringes(dataRef, assembler=self.assembleCcd
1141 if self.config.doAssembleIsrExposures
else None)
1142 if self.config.doFringe
and self.fringe.
checkFilter(rawExposure)
1143 else pipeBase.Struct(fringes=
None))
1145 if self.config.doAttachTransmissionCurve:
1146 opticsTransmission = (dataRef.get(
"transmission_optics")
1147 if self.config.doUseOpticsTransmission
else None)
1148 filterTransmission = (dataRef.get(
"transmission_filter")
1149 if self.config.doUseFilterTransmission
else None)
1150 sensorTransmission = (dataRef.get(
"transmission_sensor")
1151 if self.config.doUseSensorTransmission
else None)
1152 atmosphereTransmission = (dataRef.get(
"transmission_atmosphere")
1153 if self.config.doUseAtmosphereTransmission
else None)
1155 opticsTransmission =
None
1156 filterTransmission =
None
1157 sensorTransmission =
None
1158 atmosphereTransmission =
None
1160 if self.config.doStrayLight:
1161 strayLightData = self.strayLight.
readIsrData(dataRef, rawExposure)
1163 strayLightData =
None
1166 self.config.illuminationCorrectionDataProductName).getMaskedImage()
1167 if (self.config.doIlluminationCorrection
1168 and filterLabel
in self.config.illumFilters)
1172 return pipeBase.Struct(bias=biasExposure,
1173 linearizer=linearizer,
1174 crosstalk=crosstalkCalib,
1175 crosstalkSources=crosstalkSources,
1178 bfKernel=brighterFatterKernel,
1179 bfGains=brighterFatterGains,
1181 fringes=fringeStruct,
1182 opticsTransmission=opticsTransmission,
1183 filterTransmission=filterTransmission,
1184 sensorTransmission=sensorTransmission,
1185 atmosphereTransmission=atmosphereTransmission,
1186 strayLightData=strayLightData,
1187 illumMaskedImage=illumMaskedImage
1190 @pipeBase.timeMethod
1191 def run(self, ccdExposure, camera=None, bias=None, linearizer=None,
1192 crosstalk=None, crosstalkSources=None,
1193 dark=None, flat=None, bfKernel=None, bfGains=None, defects=None,
1194 fringes=pipeBase.Struct(fringes=
None), opticsTransmission=
None, filterTransmission=
None,
1195 sensorTransmission=
None, atmosphereTransmission=
None,
1196 detectorNum=
None, strayLightData=
None, illumMaskedImage=
None,
1199 """Perform instrument signature removal on an exposure.
1201 Steps included in the ISR processing, in order performed, are:
1202 - saturation and suspect pixel masking
1203 - overscan subtraction
1204 - CCD assembly of individual amplifiers
1206 - variance image construction
1207 - linearization of non-linear response
1209 - brighter-fatter correction
1212 - stray light subtraction
1214 - masking of known defects and camera specific features
1215 - vignette calculation
1216 - appending transmission curve and distortion model
1220 ccdExposure : `lsst.afw.image.Exposure`
1221 The raw exposure that is to be run through ISR. The
1222 exposure is modified by this method.
1223 camera : `lsst.afw.cameraGeom.Camera`, optional
1224 The camera geometry for this exposure. Required if ``isGen3`` is
1225 `True` and one or more of ``ccdExposure``, ``bias``, ``dark``, or
1226 ``flat`` does not have an associated detector.
1227 bias : `lsst.afw.image.Exposure`, optional
1228 Bias calibration frame.
1229 linearizer : `lsst.ip.isr.linearize.LinearizeBase`, optional
1230 Functor for linearization.
1231 crosstalk : `lsst.ip.isr.crosstalk.CrosstalkCalib`, optional
1232 Calibration for crosstalk.
1233 crosstalkSources : `list`, optional
1234 List of possible crosstalk sources.
1235 dark : `lsst.afw.image.Exposure`, optional
1236 Dark calibration frame.
1237 flat : `lsst.afw.image.Exposure`, optional
1238 Flat calibration frame.
1239 bfKernel : `numpy.ndarray`, optional
1240 Brighter-fatter kernel.
1241 bfGains : `dict` of `float`, optional
1242 Gains used to override the detector's nominal gains for the
1243 brighter-fatter correction. A dict keyed by amplifier name for
1244 the detector in question.
1245 defects : `lsst.ip.isr.Defects`, optional
1247 fringes : `lsst.pipe.base.Struct`, optional
1248 Struct containing the fringe correction data, with
1250 - ``fringes``: fringe calibration frame (`afw.image.Exposure`)
1251 - ``seed``: random seed derived from the ccdExposureId for random
1252 number generator (`uint32`)
1253 opticsTransmission: `lsst.afw.image.TransmissionCurve`, optional
1254 A ``TransmissionCurve`` that represents the throughput of the optics,
1255 to be evaluated in focal-plane coordinates.
1256 filterTransmission : `lsst.afw.image.TransmissionCurve`
1257 A ``TransmissionCurve`` that represents the throughput of the filter
1258 itself, to be evaluated in focal-plane coordinates.
1259 sensorTransmission : `lsst.afw.image.TransmissionCurve`
1260 A ``TransmissionCurve`` that represents the throughput of the sensor
1261 itself, to be evaluated in post-assembly trimmed detector coordinates.
1262 atmosphereTransmission : `lsst.afw.image.TransmissionCurve`
1263 A ``TransmissionCurve`` that represents the throughput of the
1264 atmosphere, assumed to be spatially constant.
1265 detectorNum : `int`, optional
1266 The integer number for the detector to process.
1267 isGen3 : bool, optional
1268 Flag this call to run() as using the Gen3 butler environment.
1269 strayLightData : `object`, optional
1270 Opaque object containing calibration information for stray-light
1271 correction. If `None`, no correction will be performed.
1272 illumMaskedImage : `lsst.afw.image.MaskedImage`, optional
1273 Illumination correction image.
1277 result : `lsst.pipe.base.Struct`
1278 Result struct with component:
1279 - ``exposure`` : `afw.image.Exposure`
1280 The fully ISR corrected exposure.
1281 - ``outputExposure`` : `afw.image.Exposure`
1282 An alias for `exposure`
1283 - ``ossThumb`` : `numpy.ndarray`
1284 Thumbnail image of the exposure after overscan subtraction.
1285 - ``flattenedThumb`` : `numpy.ndarray`
1286 Thumbnail image of the exposure after flat-field correction.
1291 Raised if a configuration option is set to True, but the
1292 required calibration data has not been specified.
1296 The current processed exposure can be viewed by setting the
1297 appropriate lsstDebug entries in the `debug.display`
1298 dictionary. The names of these entries correspond to some of
1299 the IsrTaskConfig Boolean options, with the value denoting the
1300 frame to use. The exposure is shown inside the matching
1301 option check and after the processing of that step has
1302 finished. The steps with debug points are:
1313 In addition, setting the "postISRCCD" entry displays the
1314 exposure after all ISR processing has finished.
1322 if detectorNum
is None:
1323 raise RuntimeError(
"Must supply the detectorNum if running as Gen3.")
1325 ccdExposure = self.
ensureExposureensureExposure(ccdExposure, camera, detectorNum)
1326 bias = self.
ensureExposureensureExposure(bias, camera, detectorNum)
1327 dark = self.
ensureExposureensureExposure(dark, camera, detectorNum)
1328 flat = self.
ensureExposureensureExposure(flat, camera, detectorNum)
1330 if isinstance(ccdExposure, ButlerDataRef):
1331 return self.
runDataRefrunDataRef(ccdExposure)
1333 ccd = ccdExposure.getDetector()
1334 filterLabel = ccdExposure.getFilterLabel()
1337 assert not self.config.doAssembleCcd,
"You need a Detector to run assembleCcd."
1338 ccd = [
FakeAmp(ccdExposure, self.config)]
1341 if self.config.doBias
and bias
is None:
1342 raise RuntimeError(
"Must supply a bias exposure if config.doBias=True.")
1343 if self.
doLinearizedoLinearize(ccd)
and linearizer
is None:
1344 raise RuntimeError(
"Must supply a linearizer if config.doLinearize=True for this detector.")
1345 if self.config.doBrighterFatter
and bfKernel
is None:
1346 raise RuntimeError(
"Must supply a kernel if config.doBrighterFatter=True.")
1347 if self.config.doDark
and dark
is None:
1348 raise RuntimeError(
"Must supply a dark exposure if config.doDark=True.")
1349 if self.config.doFlat
and flat
is None:
1350 raise RuntimeError(
"Must supply a flat exposure if config.doFlat=True.")
1351 if self.config.doDefect
and defects
is None:
1352 raise RuntimeError(
"Must supply defects if config.doDefect=True.")
1353 if (self.config.doFringe
and filterLabel
in self.fringe.config.filters
1354 and fringes.fringes
is None):
1359 raise RuntimeError(
"Must supply fringe exposure as a pipeBase.Struct.")
1360 if (self.config.doIlluminationCorrection
and filterLabel
in self.config.illumFilters
1361 and illumMaskedImage
is None):
1362 raise RuntimeError(
"Must supply an illumcor if config.doIlluminationCorrection=True.")
1365 if self.config.doConvertIntToFloat:
1366 self.log.info(
"Converting exposure to floating point values.")
1369 if self.config.doBias
and self.config.doBiasBeforeOverscan:
1370 self.log.info(
"Applying bias correction.")
1371 isrFunctions.biasCorrection(ccdExposure.getMaskedImage(), bias.getMaskedImage(),
1372 trimToFit=self.config.doTrimToMatchCalib)
1373 self.
debugViewdebugView(ccdExposure,
"doBias")
1379 if ccdExposure.getBBox().contains(amp.getBBox()):
1381 badAmp = self.
maskAmplifiermaskAmplifier(ccdExposure, amp, defects)
1383 if self.config.doOverscan
and not badAmp:
1386 self.log.debug(
"Corrected overscan for amplifier %s.", amp.getName())
1387 if overscanResults
is not None and \
1388 self.config.qa
is not None and self.config.qa.saveStats
is True:
1389 if isinstance(overscanResults.overscanFit, float):
1390 qaMedian = overscanResults.overscanFit
1391 qaStdev = float(
"NaN")
1393 qaStats = afwMath.makeStatistics(overscanResults.overscanFit,
1394 afwMath.MEDIAN | afwMath.STDEVCLIP)
1395 qaMedian = qaStats.getValue(afwMath.MEDIAN)
1396 qaStdev = qaStats.getValue(afwMath.STDEVCLIP)
1398 self.metadata.set(f
"FIT MEDIAN {amp.getName()}", qaMedian)
1399 self.metadata.set(f
"FIT STDEV {amp.getName()}", qaStdev)
1400 self.log.debug(
" Overscan stats for amplifer %s: %f +/- %f",
1401 amp.getName(), qaMedian, qaStdev)
1404 qaStatsAfter = afwMath.makeStatistics(overscanResults.overscanImage,
1405 afwMath.MEDIAN | afwMath.STDEVCLIP)
1406 qaMedianAfter = qaStatsAfter.getValue(afwMath.MEDIAN)
1407 qaStdevAfter = qaStatsAfter.getValue(afwMath.STDEVCLIP)
1409 self.metadata.set(f
"RESIDUAL MEDIAN {amp.getName()}", qaMedianAfter)
1410 self.metadata.set(f
"RESIDUAL STDEV {amp.getName()}", qaStdevAfter)
1411 self.log.debug(
" Overscan stats for amplifer %s after correction: %f +/- %f",
1412 amp.getName(), qaMedianAfter, qaStdevAfter)
1414 ccdExposure.getMetadata().set(
'OVERSCAN',
"Overscan corrected")
1417 self.log.warn(
"Amplifier %s is bad.", amp.getName())
1418 overscanResults =
None
1420 overscans.append(overscanResults
if overscanResults
is not None else None)
1422 self.log.info(
"Skipped OSCAN for %s.", amp.getName())
1424 if self.config.doCrosstalk
and self.config.doCrosstalkBeforeAssemble:
1425 self.log.info(
"Applying crosstalk correction.")
1426 self.crosstalk.
run(ccdExposure, crosstalk=crosstalk,
1427 crosstalkSources=crosstalkSources)
1428 self.
debugViewdebugView(ccdExposure,
"doCrosstalk")
1430 if self.config.doAssembleCcd:
1431 self.log.info(
"Assembling CCD from amplifiers.")
1432 ccdExposure = self.assembleCcd.assembleCcd(ccdExposure)
1434 if self.config.expectWcs
and not ccdExposure.getWcs():
1435 self.log.warn(
"No WCS found in input exposure.")
1436 self.
debugViewdebugView(ccdExposure,
"doAssembleCcd")
1439 if self.config.qa.doThumbnailOss:
1440 ossThumb = isrQa.makeThumbnail(ccdExposure, isrQaConfig=self.config.qa)
1442 if self.config.doBias
and not self.config.doBiasBeforeOverscan:
1443 self.log.info(
"Applying bias correction.")
1444 isrFunctions.biasCorrection(ccdExposure.getMaskedImage(), bias.getMaskedImage(),
1445 trimToFit=self.config.doTrimToMatchCalib)
1446 self.
debugViewdebugView(ccdExposure,
"doBias")
1448 if self.config.doVariance:
1449 for amp, overscanResults
in zip(ccd, overscans):
1450 if ccdExposure.getBBox().contains(amp.getBBox()):
1451 self.log.debug(
"Constructing variance map for amplifer %s.", amp.getName())
1452 ampExposure = ccdExposure.Factory(ccdExposure, amp.getBBox())
1453 if overscanResults
is not None:
1455 overscanImage=overscanResults.overscanImage)
1459 if self.config.qa
is not None and self.config.qa.saveStats
is True:
1460 qaStats = afwMath.makeStatistics(ampExposure.getVariance(),
1461 afwMath.MEDIAN | afwMath.STDEVCLIP)
1462 self.metadata.set(f
"ISR VARIANCE {amp.getName()} MEDIAN",
1463 qaStats.getValue(afwMath.MEDIAN))
1464 self.metadata.set(f
"ISR VARIANCE {amp.getName()} STDEV",
1465 qaStats.getValue(afwMath.STDEVCLIP))
1466 self.log.debug(
" Variance stats for amplifer %s: %f +/- %f.",
1467 amp.getName(), qaStats.getValue(afwMath.MEDIAN),
1468 qaStats.getValue(afwMath.STDEVCLIP))
1471 self.log.info(
"Applying linearizer.")
1472 linearizer.applyLinearity(image=ccdExposure.getMaskedImage().getImage(),
1473 detector=ccd, log=self.log)
1475 if self.config.doCrosstalk
and not self.config.doCrosstalkBeforeAssemble:
1476 self.log.info(
"Applying crosstalk correction.")
1477 self.crosstalk.
run(ccdExposure, crosstalk=crosstalk,
1478 crosstalkSources=crosstalkSources, isTrimmed=
True)
1479 self.
debugViewdebugView(ccdExposure,
"doCrosstalk")
1483 if self.config.doDefect:
1484 self.log.info(
"Masking defects.")
1485 self.
maskDefectmaskDefect(ccdExposure, defects)
1487 if self.config.numEdgeSuspect > 0:
1488 self.log.info(
"Masking edges as SUSPECT.")
1489 self.
maskEdgesmaskEdges(ccdExposure, numEdgePixels=self.config.numEdgeSuspect,
1490 maskPlane=
"SUSPECT", level=self.config.edgeMaskLevel)
1492 if self.config.doNanMasking:
1493 self.log.info(
"Masking NAN value pixels.")
1494 self.
maskNanmaskNan(ccdExposure)
1496 if self.config.doWidenSaturationTrails:
1497 self.log.info(
"Widening saturation trails.")
1498 isrFunctions.widenSaturationTrails(ccdExposure.getMaskedImage().getMask())
1500 if self.config.doCameraSpecificMasking:
1501 self.log.info(
"Masking regions for camera specific reasons.")
1502 self.masking.
run(ccdExposure)
1504 if self.config.doBrighterFatter:
1513 interpExp = ccdExposure.clone()
1514 with self.
flatContextflatContext(interpExp, flat, dark):
1515 isrFunctions.interpolateFromMask(
1516 maskedImage=interpExp.getMaskedImage(),
1517 fwhm=self.config.fwhm,
1518 growSaturatedFootprints=self.config.growSaturationFootprintSize,
1519 maskNameList=self.config.maskListToInterpolate
1521 bfExp = interpExp.clone()
1523 self.log.info(
"Applying brighter fatter correction using kernel type %s / gains %s.",
1524 type(bfKernel), type(bfGains))
1525 bfResults = isrFunctions.brighterFatterCorrection(bfExp, bfKernel,
1526 self.config.brighterFatterMaxIter,
1527 self.config.brighterFatterThreshold,
1528 self.config.brighterFatterApplyGain,
1530 if bfResults[1] == self.config.brighterFatterMaxIter:
1531 self.log.warn(
"Brighter fatter correction did not converge, final difference %f.",
1534 self.log.info(
"Finished brighter fatter correction in %d iterations.",
1536 image = ccdExposure.getMaskedImage().getImage()
1537 bfCorr = bfExp.getMaskedImage().getImage()
1538 bfCorr -= interpExp.getMaskedImage().getImage()
1547 self.log.info(
"Ensuring image edges are masked as SUSPECT to the brighter-fatter kernel size.")
1548 self.
maskEdgesmaskEdges(ccdExposure, numEdgePixels=numpy.max(bfKernel.shape) // 2,
1551 if self.config.brighterFatterMaskGrowSize > 0:
1552 self.log.info(
"Growing masks to account for brighter-fatter kernel convolution.")
1553 for maskPlane
in self.config.maskListToInterpolate:
1554 isrFunctions.growMasks(ccdExposure.getMask(),
1555 radius=self.config.brighterFatterMaskGrowSize,
1556 maskNameList=maskPlane,
1557 maskValue=maskPlane)
1559 self.
debugViewdebugView(ccdExposure,
"doBrighterFatter")
1561 if self.config.doDark:
1562 self.log.info(
"Applying dark correction.")
1564 self.
debugViewdebugView(ccdExposure,
"doDark")
1566 if self.config.doFringe
and not self.config.fringeAfterFlat:
1567 self.log.info(
"Applying fringe correction before flat.")
1568 self.fringe.
run(ccdExposure, **fringes.getDict())
1569 self.
debugViewdebugView(ccdExposure,
"doFringe")
1571 if self.config.doStrayLight
and self.strayLight.check(ccdExposure):
1572 self.log.info(
"Checking strayLight correction.")
1573 self.strayLight.
run(ccdExposure, strayLightData)
1574 self.
debugViewdebugView(ccdExposure,
"doStrayLight")
1576 if self.config.doFlat:
1577 self.log.info(
"Applying flat correction.")
1579 self.
debugViewdebugView(ccdExposure,
"doFlat")
1581 if self.config.doApplyGains:
1582 self.log.info(
"Applying gain correction instead of flat.")
1583 isrFunctions.applyGains(ccdExposure, self.config.normalizeGains)
1585 if self.config.doFringe
and self.config.fringeAfterFlat:
1586 self.log.info(
"Applying fringe correction after flat.")
1587 self.fringe.
run(ccdExposure, **fringes.getDict())
1589 if self.config.doVignette:
1590 self.log.info(
"Constructing Vignette polygon.")
1593 if self.config.vignette.doWriteVignettePolygon:
1596 if self.config.doAttachTransmissionCurve:
1597 self.log.info(
"Adding transmission curves.")
1598 isrFunctions.attachTransmissionCurve(ccdExposure, opticsTransmission=opticsTransmission,
1599 filterTransmission=filterTransmission,
1600 sensorTransmission=sensorTransmission,
1601 atmosphereTransmission=atmosphereTransmission)
1603 flattenedThumb =
None
1604 if self.config.qa.doThumbnailFlattened:
1605 flattenedThumb = isrQa.makeThumbnail(ccdExposure, isrQaConfig=self.config.qa)
1607 if self.config.doIlluminationCorrection
and filterLabel
in self.config.illumFilters:
1608 self.log.info(
"Performing illumination correction.")
1609 isrFunctions.illuminationCorrection(ccdExposure.getMaskedImage(),
1610 illumMaskedImage, illumScale=self.config.illumScale,
1611 trimToFit=self.config.doTrimToMatchCalib)
1614 if self.config.doSaveInterpPixels:
1615 preInterpExp = ccdExposure.clone()
1630 if self.config.doSetBadRegions:
1631 badPixelCount, badPixelValue = isrFunctions.setBadRegions(ccdExposure)
1632 if badPixelCount > 0:
1633 self.log.info(
"Set %d BAD pixels to %f.", badPixelCount, badPixelValue)
1635 if self.config.doInterpolate:
1636 self.log.info(
"Interpolating masked pixels.")
1637 isrFunctions.interpolateFromMask(
1638 maskedImage=ccdExposure.getMaskedImage(),
1639 fwhm=self.config.fwhm,
1640 growSaturatedFootprints=self.config.growSaturationFootprintSize,
1641 maskNameList=list(self.config.maskListToInterpolate)
1646 if self.config.doMeasureBackground:
1647 self.log.info(
"Measuring background level.")
1650 if self.config.qa
is not None and self.config.qa.saveStats
is True:
1652 ampExposure = ccdExposure.Factory(ccdExposure, amp.getBBox())
1653 qaStats = afwMath.makeStatistics(ampExposure.getImage(),
1654 afwMath.MEDIAN | afwMath.STDEVCLIP)
1655 self.metadata.set(
"ISR BACKGROUND {} MEDIAN".format(amp.getName()),
1656 qaStats.getValue(afwMath.MEDIAN))
1657 self.metadata.set(
"ISR BACKGROUND {} STDEV".format(amp.getName()),
1658 qaStats.getValue(afwMath.STDEVCLIP))
1659 self.log.debug(
" Background stats for amplifer %s: %f +/- %f",
1660 amp.getName(), qaStats.getValue(afwMath.MEDIAN),
1661 qaStats.getValue(afwMath.STDEVCLIP))
1663 self.
debugViewdebugView(ccdExposure,
"postISRCCD")
1665 return pipeBase.Struct(
1666 exposure=ccdExposure,
1668 flattenedThumb=flattenedThumb,
1670 preInterpolatedExposure=preInterpExp,
1671 outputExposure=ccdExposure,
1672 outputOssThumbnail=ossThumb,
1673 outputFlattenedThumbnail=flattenedThumb,
1676 @pipeBase.timeMethod
1678 """Perform instrument signature removal on a ButlerDataRef of a Sensor.
1680 This method contains the `CmdLineTask` interface to the ISR
1681 processing. All IO is handled here, freeing the `run()` method
1682 to manage only pixel-level calculations. The steps performed
1684 - Read in necessary detrending/isr/calibration data.
1685 - Process raw exposure in `run()`.
1686 - Persist the ISR-corrected exposure as "postISRCCD" if
1687 config.doWrite=True.
1691 sensorRef : `daf.persistence.butlerSubset.ButlerDataRef`
1692 DataRef of the detector data to be processed
1696 result : `lsst.pipe.base.Struct`
1697 Result struct with component:
1698 - ``exposure`` : `afw.image.Exposure`
1699 The fully ISR corrected exposure.
1704 Raised if a configuration option is set to True, but the
1705 required calibration data does not exist.
1708 self.log.info(
"Performing ISR on sensor %s.", sensorRef.dataId)
1710 ccdExposure = sensorRef.get(self.config.datasetType)
1712 camera = sensorRef.get(
"camera")
1713 isrData = self.
readIsrDatareadIsrData(sensorRef, ccdExposure)
1715 result = self.
runrun(ccdExposure, camera=camera, **isrData.getDict())
1717 if self.config.doWrite:
1718 sensorRef.put(result.exposure,
"postISRCCD")
1719 if result.preInterpolatedExposure
is not None:
1720 sensorRef.put(result.preInterpolatedExposure,
"postISRCCD_uninterpolated")
1721 if result.ossThumb
is not None:
1722 isrQa.writeThumbnail(sensorRef, result.ossThumb,
"ossThumb")
1723 if result.flattenedThumb
is not None:
1724 isrQa.writeThumbnail(sensorRef, result.flattenedThumb,
"flattenedThumb")
1729 """Retrieve a calibration dataset for removing instrument signature.
1734 dataRef : `daf.persistence.butlerSubset.ButlerDataRef`
1735 DataRef of the detector data to find calibration datasets
1738 Type of dataset to retrieve (e.g. 'bias', 'flat', etc).
1739 dateObs : `str`, optional
1740 Date of the observation. Used to correct butler failures
1741 when using fallback filters.
1743 If True, disable butler proxies to enable error handling
1744 within this routine.
1748 exposure : `lsst.afw.image.Exposure`
1749 Requested calibration frame.
1754 Raised if no matching calibration frame can be found.
1757 exp = dataRef.get(datasetType, immediate=immediate)
1758 except Exception
as exc1:
1759 if not self.config.fallbackFilterName:
1760 raise RuntimeError(
"Unable to retrieve %s for %s: %s." % (datasetType, dataRef.dataId, exc1))
1762 if self.config.useFallbackDate
and dateObs:
1763 exp = dataRef.get(datasetType, filter=self.config.fallbackFilterName,
1764 dateObs=dateObs, immediate=immediate)
1766 exp = dataRef.get(datasetType, filter=self.config.fallbackFilterName, immediate=immediate)
1767 except Exception
as exc2:
1768 raise RuntimeError(
"Unable to retrieve %s for %s, even with fallback filter %s: %s AND %s." %
1769 (datasetType, dataRef.dataId, self.config.fallbackFilterName, exc1, exc2))
1770 self.log.warn(
"Using fallback calibration from filter %s.", self.config.fallbackFilterName)
1772 if self.config.doAssembleIsrExposures:
1773 exp = self.assembleCcd.assembleCcd(exp)
1777 """Ensure that the data returned by Butler is a fully constructed exposure.
1779 ISR requires exposure-level image data for historical reasons, so if we did
1780 not recieve that from Butler, construct it from what we have, modifying the
1785 inputExp : `lsst.afw.image.Exposure`, `lsst.afw.image.DecoratedImageU`, or
1786 `lsst.afw.image.ImageF`
1787 The input data structure obtained from Butler.
1788 camera : `lsst.afw.cameraGeom.camera`
1789 The camera associated with the image. Used to find the appropriate
1792 The detector this exposure should match.
1796 inputExp : `lsst.afw.image.Exposure`
1797 The re-constructed exposure, with appropriate detector parameters.
1802 Raised if the input data cannot be used to construct an exposure.
1804 if isinstance(inputExp, afwImage.DecoratedImageU):
1805 inputExp = afwImage.makeExposure(afwImage.makeMaskedImage(inputExp))
1806 elif isinstance(inputExp, afwImage.ImageF):
1807 inputExp = afwImage.makeExposure(afwImage.makeMaskedImage(inputExp))
1808 elif isinstance(inputExp, afwImage.MaskedImageF):
1809 inputExp = afwImage.makeExposure(inputExp)
1810 elif isinstance(inputExp, afwImage.Exposure):
1812 elif inputExp
is None:
1816 raise TypeError(
"Input Exposure is not known type in isrTask.ensureExposure: %s." %
1819 if inputExp.getDetector()
is None:
1820 inputExp.setDetector(camera[detectorNum])
1825 """Convert exposure image from uint16 to float.
1827 If the exposure does not need to be converted, the input is
1828 immediately returned. For exposures that are converted to use
1829 floating point pixels, the variance is set to unity and the
1834 exposure : `lsst.afw.image.Exposure`
1835 The raw exposure to be converted.
1839 newexposure : `lsst.afw.image.Exposure`
1840 The input ``exposure``, converted to floating point pixels.
1845 Raised if the exposure type cannot be converted to float.
1848 if isinstance(exposure, afwImage.ExposureF):
1850 self.log.debug(
"Exposure already of type float.")
1852 if not hasattr(exposure,
"convertF"):
1853 raise RuntimeError(
"Unable to convert exposure (%s) to float." % type(exposure))
1855 newexposure = exposure.convertF()
1856 newexposure.variance[:] = 1
1857 newexposure.mask[:] = 0x0
1862 """Identify bad amplifiers, saturated and suspect pixels.
1866 ccdExposure : `lsst.afw.image.Exposure`
1867 Input exposure to be masked.
1868 amp : `lsst.afw.table.AmpInfoCatalog`
1869 Catalog of parameters defining the amplifier on this
1871 defects : `lsst.ip.isr.Defects`
1872 List of defects. Used to determine if the entire
1878 If this is true, the entire amplifier area is covered by
1879 defects and unusable.
1882 maskedImage = ccdExposure.getMaskedImage()
1888 if defects
is not None:
1889 badAmp = bool(sum([v.getBBox().contains(amp.getBBox())
for v
in defects]))
1894 dataView = afwImage.MaskedImageF(maskedImage, amp.getRawBBox(),
1896 maskView = dataView.getMask()
1897 maskView |= maskView.getPlaneBitMask(
"BAD")
1904 if self.config.doSaturation
and not badAmp:
1905 limits.update({self.config.saturatedMaskName: amp.getSaturation()})
1906 if self.config.doSuspect
and not badAmp:
1907 limits.update({self.config.suspectMaskName: amp.getSuspectLevel()})
1908 if math.isfinite(self.config.saturation):
1909 limits.update({self.config.saturatedMaskName: self.config.saturation})
1911 for maskName, maskThreshold
in limits.items():
1912 if not math.isnan(maskThreshold):
1913 dataView = maskedImage.Factory(maskedImage, amp.getRawBBox())
1914 isrFunctions.makeThresholdMask(
1915 maskedImage=dataView,
1916 threshold=maskThreshold,
1922 maskView = afwImage.Mask(maskedImage.getMask(), amp.getRawDataBBox(),
1924 maskVal = maskView.getPlaneBitMask([self.config.saturatedMaskName,
1925 self.config.suspectMaskName])
1926 if numpy.all(maskView.getArray() & maskVal > 0):
1928 maskView |= maskView.getPlaneBitMask(
"BAD")
1933 """Apply overscan correction in place.
1935 This method does initial pixel rejection of the overscan
1936 region. The overscan can also be optionally segmented to
1937 allow for discontinuous overscan responses to be fit
1938 separately. The actual overscan subtraction is performed by
1939 the `lsst.ip.isr.isrFunctions.overscanCorrection` function,
1940 which is called here after the amplifier is preprocessed.
1944 ccdExposure : `lsst.afw.image.Exposure`
1945 Exposure to have overscan correction performed.
1946 amp : `lsst.afw.cameraGeom.Amplifer`
1947 The amplifier to consider while correcting the overscan.
1951 overscanResults : `lsst.pipe.base.Struct`
1952 Result struct with components:
1953 - ``imageFit`` : scalar or `lsst.afw.image.Image`
1954 Value or fit subtracted from the amplifier image data.
1955 - ``overscanFit`` : scalar or `lsst.afw.image.Image`
1956 Value or fit subtracted from the overscan image data.
1957 - ``overscanImage`` : `lsst.afw.image.Image`
1958 Image of the overscan region with the overscan
1959 correction applied. This quantity is used to estimate
1960 the amplifier read noise empirically.
1965 Raised if the ``amp`` does not contain raw pixel information.
1969 lsst.ip.isr.isrFunctions.overscanCorrection
1971 if amp.getRawHorizontalOverscanBBox().isEmpty():
1972 self.log.info(
"ISR_OSCAN: No overscan region. Not performing overscan correction.")
1975 statControl = afwMath.StatisticsControl()
1976 statControl.setAndMask(ccdExposure.mask.getPlaneBitMask(
"SAT"))
1979 dataBBox = amp.getRawDataBBox()
1980 oscanBBox = amp.getRawHorizontalOverscanBBox()
1984 prescanBBox = amp.getRawPrescanBBox()
1985 if (oscanBBox.getBeginX() > prescanBBox.getBeginX()):
1986 dx0 += self.config.overscanNumLeadingColumnsToSkip
1987 dx1 -= self.config.overscanNumTrailingColumnsToSkip
1989 dx0 += self.config.overscanNumTrailingColumnsToSkip
1990 dx1 -= self.config.overscanNumLeadingColumnsToSkip
1996 if ((self.config.overscanBiasJump
1997 and self.config.overscanBiasJumpLocation)
1998 and (ccdExposure.getMetadata().exists(self.config.overscanBiasJumpKeyword)
1999 and ccdExposure.getMetadata().getScalar(self.config.overscanBiasJumpKeyword)
in
2000 self.config.overscanBiasJumpDevices)):
2001 if amp.getReadoutCorner()
in (ReadoutCorner.LL, ReadoutCorner.LR):
2002 yLower = self.config.overscanBiasJumpLocation
2003 yUpper = dataBBox.getHeight() - yLower
2005 yUpper = self.config.overscanBiasJumpLocation
2006 yLower = dataBBox.getHeight() - yUpper
2024 oscanBBox.getHeight())))
2027 for imageBBox, overscanBBox
in zip(imageBBoxes, overscanBBoxes):
2028 ampImage = ccdExposure.maskedImage[imageBBox]
2029 overscanImage = ccdExposure.maskedImage[overscanBBox]
2031 overscanArray = overscanImage.image.array
2032 median = numpy.ma.median(numpy.ma.masked_where(overscanImage.mask.array, overscanArray))
2033 bad = numpy.where(numpy.abs(overscanArray - median) > self.config.overscanMaxDev)
2034 overscanImage.mask.array[bad] = overscanImage.mask.getPlaneBitMask(
"SAT")
2036 statControl = afwMath.StatisticsControl()
2037 statControl.setAndMask(ccdExposure.mask.getPlaneBitMask(
"SAT"))
2039 overscanResults = self.overscan.
run(ampImage.getImage(), overscanImage, amp)
2042 levelStat = afwMath.MEDIAN
2043 sigmaStat = afwMath.STDEVCLIP
2045 sctrl = afwMath.StatisticsControl(self.config.qa.flatness.clipSigma,
2046 self.config.qa.flatness.nIter)
2047 metadata = ccdExposure.getMetadata()
2048 ampNum = amp.getName()
2050 if isinstance(overscanResults.overscanFit, float):
2051 metadata.set(
"ISR_OSCAN_LEVEL%s" % ampNum, overscanResults.overscanFit)
2052 metadata.set(
"ISR_OSCAN_SIGMA%s" % ampNum, 0.0)
2054 stats = afwMath.makeStatistics(overscanResults.overscanFit, levelStat | sigmaStat, sctrl)
2055 metadata.set(
"ISR_OSCAN_LEVEL%s" % ampNum, stats.getValue(levelStat))
2056 metadata.set(
"ISR_OSCAN_SIGMA%s" % ampNum, stats.getValue(sigmaStat))
2058 return overscanResults
2061 """Set the variance plane using the amplifier gain and read noise
2063 The read noise is calculated from the ``overscanImage`` if the
2064 ``doEmpiricalReadNoise`` option is set in the configuration; otherwise
2065 the value from the amplifier data is used.
2069 ampExposure : `lsst.afw.image.Exposure`
2070 Exposure to process.
2071 amp : `lsst.afw.table.AmpInfoRecord` or `FakeAmp`
2072 Amplifier detector data.
2073 overscanImage : `lsst.afw.image.MaskedImage`, optional.
2074 Image of overscan, required only for empirical read noise.
2078 lsst.ip.isr.isrFunctions.updateVariance
2080 maskPlanes = [self.config.saturatedMaskName, self.config.suspectMaskName]
2081 gain = amp.getGain()
2083 if math.isnan(gain):
2085 self.log.warn(
"Gain set to NAN! Updating to 1.0 to generate Poisson variance.")
2088 self.log.warn(
"Gain for amp %s == %g <= 0; setting to %f.",
2089 amp.getName(), gain, patchedGain)
2092 if self.config.doEmpiricalReadNoise
and overscanImage
is None:
2093 self.log.info(
"Overscan is none for EmpiricalReadNoise.")
2095 if self.config.doEmpiricalReadNoise
and overscanImage
is not None:
2096 stats = afwMath.StatisticsControl()
2097 stats.setAndMask(overscanImage.mask.getPlaneBitMask(maskPlanes))
2098 readNoise = afwMath.makeStatistics(overscanImage, afwMath.STDEVCLIP, stats).getValue()
2099 self.log.info(
"Calculated empirical read noise for amp %s: %f.",
2100 amp.getName(), readNoise)
2102 readNoise = amp.getReadNoise()
2104 isrFunctions.updateVariance(
2105 maskedImage=ampExposure.getMaskedImage(),
2107 readNoise=readNoise,
2111 """Apply dark correction in place.
2115 exposure : `lsst.afw.image.Exposure`
2116 Exposure to process.
2117 darkExposure : `lsst.afw.image.Exposure`
2118 Dark exposure of the same size as ``exposure``.
2119 invert : `Bool`, optional
2120 If True, re-add the dark to an already corrected image.
2125 Raised if either ``exposure`` or ``darkExposure`` do not
2126 have their dark time defined.
2130 lsst.ip.isr.isrFunctions.darkCorrection
2132 expScale = exposure.getInfo().getVisitInfo().getDarkTime()
2133 if math.isnan(expScale):
2134 raise RuntimeError(
"Exposure darktime is NAN.")
2135 if darkExposure.getInfo().getVisitInfo()
is not None \
2136 and not math.isnan(darkExposure.getInfo().getVisitInfo().getDarkTime()):
2137 darkScale = darkExposure.getInfo().getVisitInfo().getDarkTime()
2141 self.log.warn(
"darkExposure.getInfo().getVisitInfo() does not exist. Using darkScale = 1.0.")
2144 isrFunctions.darkCorrection(
2145 maskedImage=exposure.getMaskedImage(),
2146 darkMaskedImage=darkExposure.getMaskedImage(),
2148 darkScale=darkScale,
2150 trimToFit=self.config.doTrimToMatchCalib
2154 """Check if linearization is needed for the detector cameraGeom.
2156 Checks config.doLinearize and the linearity type of the first
2161 detector : `lsst.afw.cameraGeom.Detector`
2162 Detector to get linearity type from.
2166 doLinearize : `Bool`
2167 If True, linearization should be performed.
2169 return self.config.doLinearize
and \
2170 detector.getAmplifiers()[0].getLinearityType() != NullLinearityType
2173 """Apply flat correction in place.
2177 exposure : `lsst.afw.image.Exposure`
2178 Exposure to process.
2179 flatExposure : `lsst.afw.image.Exposure`
2180 Flat exposure of the same size as ``exposure``.
2181 invert : `Bool`, optional
2182 If True, unflatten an already flattened image.
2186 lsst.ip.isr.isrFunctions.flatCorrection
2188 isrFunctions.flatCorrection(
2189 maskedImage=exposure.getMaskedImage(),
2190 flatMaskedImage=flatExposure.getMaskedImage(),
2191 scalingType=self.config.flatScalingType,
2192 userScale=self.config.flatUserScale,
2194 trimToFit=self.config.doTrimToMatchCalib
2198 """Detect saturated pixels and mask them using mask plane config.saturatedMaskName, in place.
2202 exposure : `lsst.afw.image.Exposure`
2203 Exposure to process. Only the amplifier DataSec is processed.
2204 amp : `lsst.afw.table.AmpInfoCatalog`
2205 Amplifier detector data.
2209 lsst.ip.isr.isrFunctions.makeThresholdMask
2211 if not math.isnan(amp.getSaturation()):
2212 maskedImage = exposure.getMaskedImage()
2213 dataView = maskedImage.Factory(maskedImage, amp.getRawBBox())
2214 isrFunctions.makeThresholdMask(
2215 maskedImage=dataView,
2216 threshold=amp.getSaturation(),
2218 maskName=self.config.saturatedMaskName,
2222 """Interpolate over saturated pixels, in place.
2224 This method should be called after `saturationDetection`, to
2225 ensure that the saturated pixels have been identified in the
2226 SAT mask. It should also be called after `assembleCcd`, since
2227 saturated regions may cross amplifier boundaries.
2231 exposure : `lsst.afw.image.Exposure`
2232 Exposure to process.
2236 lsst.ip.isr.isrTask.saturationDetection
2237 lsst.ip.isr.isrFunctions.interpolateFromMask
2239 isrFunctions.interpolateFromMask(
2240 maskedImage=exposure.getMaskedImage(),
2241 fwhm=self.config.fwhm,
2242 growSaturatedFootprints=self.config.growSaturationFootprintSize,
2243 maskNameList=list(self.config.saturatedMaskName),
2247 """Detect suspect pixels and mask them using mask plane config.suspectMaskName, in place.
2251 exposure : `lsst.afw.image.Exposure`
2252 Exposure to process. Only the amplifier DataSec is processed.
2253 amp : `lsst.afw.table.AmpInfoCatalog`
2254 Amplifier detector data.
2258 lsst.ip.isr.isrFunctions.makeThresholdMask
2262 Suspect pixels are pixels whose value is greater than amp.getSuspectLevel().
2263 This is intended to indicate pixels that may be affected by unknown systematics;
2264 for example if non-linearity corrections above a certain level are unstable
2265 then that would be a useful value for suspectLevel. A value of `nan` indicates
2266 that no such level exists and no pixels are to be masked as suspicious.
2268 suspectLevel = amp.getSuspectLevel()
2269 if math.isnan(suspectLevel):
2272 maskedImage = exposure.getMaskedImage()
2273 dataView = maskedImage.Factory(maskedImage, amp.getRawBBox())
2274 isrFunctions.makeThresholdMask(
2275 maskedImage=dataView,
2276 threshold=suspectLevel,
2278 maskName=self.config.suspectMaskName,
2282 """Mask defects using mask plane "BAD", in place.
2286 exposure : `lsst.afw.image.Exposure`
2287 Exposure to process.
2288 defectBaseList : `lsst.ip.isr.Defects` or `list` of
2289 `lsst.afw.image.DefectBase`.
2290 List of defects to mask.
2294 Call this after CCD assembly, since defects may cross amplifier boundaries.
2296 maskedImage = exposure.getMaskedImage()
2297 if not isinstance(defectBaseList, Defects):
2299 defectList =
Defects(defectBaseList)
2301 defectList = defectBaseList
2302 defectList.maskPixels(maskedImage, maskName=
"BAD")
2304 def maskEdges(self, exposure, numEdgePixels=0, maskPlane="SUSPECT", level='DETECTOR'):
2305 """Mask edge pixels with applicable mask plane.
2309 exposure : `lsst.afw.image.Exposure`
2310 Exposure to process.
2311 numEdgePixels : `int`, optional
2312 Number of edge pixels to mask.
2313 maskPlane : `str`, optional
2314 Mask plane name to use.
2315 level : `str`, optional
2316 Level at which to mask edges.
2318 maskedImage = exposure.getMaskedImage()
2319 maskBitMask = maskedImage.getMask().getPlaneBitMask(maskPlane)
2321 if numEdgePixels > 0:
2322 if level ==
'DETECTOR':
2323 boxes = [maskedImage.getBBox()]
2324 elif level ==
'AMP':
2325 boxes = [amp.getBBox()
for amp
in exposure.getDetector()]
2329 subImage = maskedImage[box]
2330 box.grow(-numEdgePixels)
2332 SourceDetectionTask.setEdgeBits(
2338 """Mask and interpolate defects using mask plane "BAD", in place.
2342 exposure : `lsst.afw.image.Exposure`
2343 Exposure to process.
2344 defectBaseList : `lsst.ip.isr.Defects` or `list` of
2345 `lsst.afw.image.DefectBase`.
2346 List of defects to mask and interpolate.
2350 lsst.ip.isr.isrTask.maskDefect
2352 self.
maskDefectmaskDefect(exposure, defectBaseList)
2353 self.
maskEdgesmaskEdges(exposure, numEdgePixels=self.config.numEdgeSuspect,
2354 maskPlane=
"SUSPECT", level=self.config.edgeMaskLevel)
2355 isrFunctions.interpolateFromMask(
2356 maskedImage=exposure.getMaskedImage(),
2357 fwhm=self.config.fwhm,
2358 growSaturatedFootprints=0,
2359 maskNameList=[
"BAD"],
2363 """Mask NaNs using mask plane "UNMASKEDNAN", in place.
2367 exposure : `lsst.afw.image.Exposure`
2368 Exposure to process.
2372 We mask over all NaNs, including those that are masked with
2373 other bits (because those may or may not be interpolated over
2374 later, and we want to remove all NaNs). Despite this
2375 behaviour, the "UNMASKEDNAN" mask plane is used to preserve
2376 the historical name.
2378 maskedImage = exposure.getMaskedImage()
2381 maskedImage.getMask().addMaskPlane(
"UNMASKEDNAN")
2382 maskVal = maskedImage.getMask().getPlaneBitMask(
"UNMASKEDNAN")
2383 numNans =
maskNans(maskedImage, maskVal)
2384 self.metadata.set(
"NUMNANS", numNans)
2386 self.log.warn(
"There were %d unmasked NaNs.", numNans)
2389 """"Mask and interpolate NaNs using mask plane "UNMASKEDNAN", in place.
2393 exposure : `lsst.afw.image.Exposure`
2394 Exposure to process.
2398 lsst.ip.isr.isrTask.maskNan
2401 isrFunctions.interpolateFromMask(
2402 maskedImage=exposure.getMaskedImage(),
2403 fwhm=self.config.fwhm,
2404 growSaturatedFootprints=0,
2405 maskNameList=[
"UNMASKEDNAN"],
2409 """Measure the image background in subgrids, for quality control purposes.
2413 exposure : `lsst.afw.image.Exposure`
2414 Exposure to process.
2415 IsrQaConfig : `lsst.ip.isr.isrQa.IsrQaConfig`
2416 Configuration object containing parameters on which background
2417 statistics and subgrids to use.
2419 if IsrQaConfig
is not None:
2420 statsControl = afwMath.StatisticsControl(IsrQaConfig.flatness.clipSigma,
2421 IsrQaConfig.flatness.nIter)
2422 maskVal = exposure.getMaskedImage().getMask().getPlaneBitMask([
"BAD",
"SAT",
"DETECTED"])
2423 statsControl.setAndMask(maskVal)
2424 maskedImage = exposure.getMaskedImage()
2425 stats = afwMath.makeStatistics(maskedImage, afwMath.MEDIAN | afwMath.STDEVCLIP, statsControl)
2426 skyLevel = stats.getValue(afwMath.MEDIAN)
2427 skySigma = stats.getValue(afwMath.STDEVCLIP)
2428 self.log.info(
"Flattened sky level: %f +/- %f.", skyLevel, skySigma)
2429 metadata = exposure.getMetadata()
2430 metadata.set(
'SKYLEVEL', skyLevel)
2431 metadata.set(
'SKYSIGMA', skySigma)
2434 stat = afwMath.MEANCLIP
if IsrQaConfig.flatness.doClip
else afwMath.MEAN
2435 meshXHalf = int(IsrQaConfig.flatness.meshX/2.)
2436 meshYHalf = int(IsrQaConfig.flatness.meshY/2.)
2437 nX = int((exposure.getWidth() + meshXHalf) / IsrQaConfig.flatness.meshX)
2438 nY = int((exposure.getHeight() + meshYHalf) / IsrQaConfig.flatness.meshY)
2439 skyLevels = numpy.zeros((nX, nY))
2442 yc = meshYHalf + j * IsrQaConfig.flatness.meshY
2444 xc = meshXHalf + i * IsrQaConfig.flatness.meshX
2446 xLLC = xc - meshXHalf
2447 yLLC = yc - meshYHalf
2448 xURC = xc + meshXHalf - 1
2449 yURC = yc + meshYHalf - 1
2452 miMesh = maskedImage.Factory(exposure.getMaskedImage(), bbox, afwImage.LOCAL)
2454 skyLevels[i, j] = afwMath.makeStatistics(miMesh, stat, statsControl).getValue()
2456 good = numpy.where(numpy.isfinite(skyLevels))
2457 skyMedian = numpy.median(skyLevels[good])
2458 flatness = (skyLevels[good] - skyMedian) / skyMedian
2459 flatness_rms = numpy.std(flatness)
2460 flatness_pp = flatness.max() - flatness.min()
if len(flatness) > 0
else numpy.nan
2462 self.log.info(
"Measuring sky levels in %dx%d grids: %f.", nX, nY, skyMedian)
2463 self.log.info(
"Sky flatness in %dx%d grids - pp: %f rms: %f.",
2464 nX, nY, flatness_pp, flatness_rms)
2466 metadata.set(
'FLATNESS_PP', float(flatness_pp))
2467 metadata.set(
'FLATNESS_RMS', float(flatness_rms))
2468 metadata.set(
'FLATNESS_NGRIDS',
'%dx%d' % (nX, nY))
2469 metadata.set(
'FLATNESS_MESHX', IsrQaConfig.flatness.meshX)
2470 metadata.set(
'FLATNESS_MESHY', IsrQaConfig.flatness.meshY)
2473 """Set an approximate magnitude zero point for the exposure.
2477 exposure : `lsst.afw.image.Exposure`
2478 Exposure to process.
2480 filterLabel = exposure.getFilterLabel()
2481 if filterLabel
in self.config.fluxMag0T1:
2482 fluxMag0 = self.config.fluxMag0T1[filterLabel]
2484 self.log.warn(
"No rough magnitude zero point set for filter %s.", filterLabel)
2485 fluxMag0 = self.config.defaultFluxMag0T1
2487 expTime = exposure.getInfo().getVisitInfo().getExposureTime()
2489 self.log.warn(
"Non-positive exposure time; skipping rough zero point.")
2492 self.log.info(
"Setting rough magnitude zero point: %f", 2.5*math.log10(fluxMag0*expTime))
2493 exposure.setPhotoCalib(afwImage.makePhotoCalibFromCalibZeroPoint(fluxMag0*expTime, 0.0))
2496 """Set the valid polygon as the intersection of fpPolygon and the ccd corners.
2500 ccdExposure : `lsst.afw.image.Exposure`
2501 Exposure to process.
2502 fpPolygon : `lsst.afw.geom.Polygon`
2503 Polygon in focal plane coordinates.
2506 ccd = ccdExposure.getDetector()
2507 fpCorners = ccd.getCorners(FOCAL_PLANE)
2508 ccdPolygon = Polygon(fpCorners)
2511 intersect = ccdPolygon.intersectionSingle(fpPolygon)
2514 ccdPoints = ccd.transform(intersect, FOCAL_PLANE, PIXELS)
2515 validPolygon = Polygon(ccdPoints)
2516 ccdExposure.getInfo().setValidPolygon(validPolygon)
2520 """Context manager that applies and removes flats and darks,
2521 if the task is configured to apply them.
2525 exp : `lsst.afw.image.Exposure`
2526 Exposure to process.
2527 flat : `lsst.afw.image.Exposure`
2528 Flat exposure the same size as ``exp``.
2529 dark : `lsst.afw.image.Exposure`, optional
2530 Dark exposure the same size as ``exp``.
2534 exp : `lsst.afw.image.Exposure`
2535 The flat and dark corrected exposure.
2537 if self.config.doDark
and dark
is not None:
2539 if self.config.doFlat:
2544 if self.config.doFlat:
2546 if self.config.doDark
and dark
is not None:
2550 """Utility function to examine ISR exposure at different stages.
2554 exposure : `lsst.afw.image.Exposure`
2557 State of processing to view.
2559 frame = getDebugFrame(self._display, stepname)
2561 display = getDisplay(frame)
2562 display.scale(
'asinh',
'zscale')
2563 display.mtv(exposure)
2564 prompt =
"Press Enter to continue [c]... "
2566 ans = input(prompt).lower()
2567 if ans
in (
"",
"c",):
2572 """A Detector-like object that supports returning gain and saturation level
2574 This is used when the input exposure does not have a detector.
2578 exposure : `lsst.afw.image.Exposure`
2579 Exposure to generate a fake amplifier for.
2580 config : `lsst.ip.isr.isrTaskConfig`
2581 Configuration to apply to the fake amplifier.
2585 self.
_bbox_bbox = exposure.getBBox(afwImage.LOCAL)
2587 self.
_gain_gain = config.gain
2592 return self.
_bbox_bbox
2595 return self.
_bbox_bbox
2601 return self.
_gain_gain
2614 isr = pexConfig.ConfigurableField(target=IsrTask, doc=
"Instrument signature removal")
2618 """Task to wrap the default IsrTask to allow it to be retargeted.
2620 The standard IsrTask can be called directly from a command line
2621 program, but doing so removes the ability of the task to be
2622 retargeted. As most cameras override some set of the IsrTask
2623 methods, this would remove those data-specific methods in the
2624 output post-ISR images. This wrapping class fixes the issue,
2625 allowing identical post-ISR images to be generated by both the
2626 processCcd and isrTask code.
2628 ConfigClass = RunIsrConfig
2629 _DefaultName =
"runIsr"
2633 self.makeSubtask(
"isr")
2639 dataRef : `lsst.daf.persistence.ButlerDataRef`
2640 data reference of the detector data to be processed
2644 result : `pipeBase.Struct`
2645 Result struct with component:
2647 - exposure : `lsst.afw.image.Exposure`
2648 Post-ISR processed exposure.
def getRawHorizontalOverscanBBox(self)
def getSuspectLevel(self)
_RawHorizontalOverscanBBox
def __init__(self, exposure, config)
doSaturationInterpolation
def __init__(self, *config=None)
def flatCorrection(self, exposure, flatExposure, invert=False)
def maskAndInterpolateNan(self, exposure)
def saturationInterpolation(self, exposure)
def runDataRef(self, sensorRef)
def maskNan(self, exposure)
def maskAmplifier(self, ccdExposure, amp, defects)
def debugView(self, exposure, stepname)
def getIsrExposure(self, dataRef, datasetType, dateObs=None, immediate=True)
def saturationDetection(self, exposure, amp)
def maskDefect(self, exposure, defectBaseList)
def __init__(self, **kwargs)
def runQuantum(self, butlerQC, inputRefs, outputRefs)
def maskEdges(self, exposure, numEdgePixels=0, maskPlane="SUSPECT", level='DETECTOR')
def overscanCorrection(self, ccdExposure, amp)
def measureBackground(self, exposure, IsrQaConfig=None)
def roughZeroPoint(self, exposure)
def maskAndInterpolateDefects(self, exposure, defectBaseList)
def setValidPolygonIntersect(self, ccdExposure, fpPolygon)
def readIsrData(self, dataRef, rawExposure)
def ensureExposure(self, inputExp, camera, detectorNum)
def updateVariance(self, ampExposure, amp, overscanImage=None)
def doLinearize(self, detector)
def flatContext(self, exp, flat, dark=None)
def convertIntToFloat(self, exposure)
def suspectDetection(self, exposure, amp)
def run(self, ccdExposure, camera=None, bias=None, linearizer=None, crosstalk=None, crosstalkSources=None, dark=None, flat=None, bfKernel=None, bfGains=None, defects=None, fringes=pipeBase.Struct(fringes=None), opticsTransmission=None, filterTransmission=None, sensorTransmission=None, atmosphereTransmission=None, detectorNum=None, strayLightData=None, illumMaskedImage=None, isGen3=False)
def darkCorrection(self, exposure, darkExposure, invert=False)
def __init__(self, *args, **kwargs)
def runDataRef(self, dataRef)
def checkFilter(exposure, filterList, log)
def crosstalkSourceLookup(datasetType, registry, quantumDataId, collections)
size_t maskNans(afw::image::MaskedImage< PixelT > const &mi, afw::image::MaskPixel maskVal, afw::image::MaskPixel allow=0)
Mask NANs in an image.