Coverage for python/lsst/ip/isr/isrTask.py: 16%
936 statements
« prev ^ index » next coverage.py v7.3.2, created at 2023-11-18 11:29 +0000
« prev ^ index » next coverage.py v7.3.2, created at 2023-11-18 11:29 +0000
1# This file is part of ip_isr.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (https://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <https://www.gnu.org/licenses/>.
22__all__ = ["IsrTask", "IsrTaskConfig"]
24import math
25import numpy
27import lsst.geom
28import lsst.afw.image as afwImage
29import lsst.afw.math as afwMath
30import lsst.pex.config as pexConfig
31import lsst.pipe.base as pipeBase
32import lsst.pipe.base.connectionTypes as cT
34from contextlib import contextmanager
35from lsstDebug import getDebugFrame
37from lsst.afw.cameraGeom import NullLinearityType
38from lsst.afw.display import getDisplay
39from lsst.meas.algorithms.detection import SourceDetectionTask
40from lsst.utils.timer import timeMethod
42from . import isrFunctions
43from . import isrQa
44from . import linearize
45from .defects import Defects
47from .assembleCcdTask import AssembleCcdTask
48from .crosstalk import CrosstalkTask, CrosstalkCalib
49from .fringe import FringeTask
50from .isr import maskNans
51from .masking import MaskingTask
52from .overscan import OverscanCorrectionTask
53from .straylight import StrayLightTask
54from .vignette import VignetteTask
55from .ampOffset import AmpOffsetTask
56from .deferredCharge import DeferredChargeTask
57from .isrStatistics import IsrStatisticsTask
58from .ptcDataset import PhotonTransferCurveDataset
59from lsst.daf.butler import DimensionGraph
62def crosstalkSourceLookup(datasetType, registry, quantumDataId, collections):
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
67 populated.
69 Parameters
70 ----------
71 datasetType : `str`
72 Dataset to lookup.
73 registry : `lsst.daf.butler.Registry`
74 Butler registry to query.
75 quantumDataId : `lsst.daf.butler.ExpandedDataCoordinate`
76 Data id to transform to identify crosstalkSources. The
77 ``detector`` entry will be stripped.
78 collections : `lsst.daf.butler.CollectionSearch`
79 Collections to search through.
81 Returns
82 -------
83 results : `list` [`lsst.daf.butler.DatasetRef`]
84 List of datasets that match the query that will be used as
85 crosstalkSources.
86 """
87 newDataId = quantumDataId.subset(DimensionGraph(registry.dimensions, names=["instrument", "exposure"]))
88 results = set(registry.queryDatasets(datasetType, collections=collections, dataId=newDataId,
89 findFirst=True))
90 # In some contexts, calling `.expanded()` to expand all data IDs in the
91 # query results can be a lot faster because it vectorizes lookups. But in
92 # this case, expandDataId shouldn't need to hit the database at all in the
93 # steady state, because only the detector record is unknown and those are
94 # cached in the registry.
95 return [ref.expanded(registry.expandDataId(ref.dataId, records=newDataId.records)) for ref in results]
98class IsrTaskConnections(pipeBase.PipelineTaskConnections,
99 dimensions={"instrument", "exposure", "detector"},
100 defaultTemplates={}):
101 ccdExposure = cT.Input(
102 name="raw",
103 doc="Input exposure to process.",
104 storageClass="Exposure",
105 dimensions=["instrument", "exposure", "detector"],
106 )
107 camera = cT.PrerequisiteInput(
108 name="camera",
109 storageClass="Camera",
110 doc="Input camera to construct complete exposures.",
111 dimensions=["instrument"],
112 isCalibration=True,
113 )
115 crosstalk = cT.PrerequisiteInput(
116 name="crosstalk",
117 doc="Input crosstalk object",
118 storageClass="CrosstalkCalib",
119 dimensions=["instrument", "detector"],
120 isCalibration=True,
121 minimum=0, # can fall back to cameraGeom
122 )
123 crosstalkSources = cT.PrerequisiteInput(
124 name="isrOverscanCorrected",
125 doc="Overscan corrected input images.",
126 storageClass="Exposure",
127 dimensions=["instrument", "exposure", "detector"],
128 deferLoad=True,
129 multiple=True,
130 lookupFunction=crosstalkSourceLookup,
131 minimum=0, # not needed for all instruments, no config to control this
132 )
133 bias = cT.PrerequisiteInput(
134 name="bias",
135 doc="Input bias calibration.",
136 storageClass="ExposureF",
137 dimensions=["instrument", "detector"],
138 isCalibration=True,
139 )
140 dark = cT.PrerequisiteInput(
141 name='dark',
142 doc="Input dark calibration.",
143 storageClass="ExposureF",
144 dimensions=["instrument", "detector"],
145 isCalibration=True,
146 )
147 flat = cT.PrerequisiteInput(
148 name="flat",
149 doc="Input flat calibration.",
150 storageClass="ExposureF",
151 dimensions=["instrument", "physical_filter", "detector"],
152 isCalibration=True,
153 )
154 ptc = cT.PrerequisiteInput(
155 name="ptc",
156 doc="Input Photon Transfer Curve dataset",
157 storageClass="PhotonTransferCurveDataset",
158 dimensions=["instrument", "detector"],
159 isCalibration=True,
160 )
161 fringes = cT.PrerequisiteInput(
162 name="fringe",
163 doc="Input fringe calibration.",
164 storageClass="ExposureF",
165 dimensions=["instrument", "physical_filter", "detector"],
166 isCalibration=True,
167 minimum=0, # only needed for some bands, even when enabled
168 )
169 strayLightData = cT.PrerequisiteInput(
170 name='yBackground',
171 doc="Input stray light calibration.",
172 storageClass="StrayLightData",
173 dimensions=["instrument", "physical_filter", "detector"],
174 deferLoad=True,
175 isCalibration=True,
176 minimum=0, # only needed for some bands, even when enabled
177 )
178 bfKernel = cT.PrerequisiteInput(
179 name='bfKernel',
180 doc="Input brighter-fatter kernel.",
181 storageClass="NumpyArray",
182 dimensions=["instrument"],
183 isCalibration=True,
184 minimum=0, # can use either bfKernel or newBFKernel
185 )
186 newBFKernel = cT.PrerequisiteInput(
187 name='brighterFatterKernel',
188 doc="Newer complete kernel + gain solutions.",
189 storageClass="BrighterFatterKernel",
190 dimensions=["instrument", "detector"],
191 isCalibration=True,
192 minimum=0, # can use either bfKernel or newBFKernel
193 )
194 defects = cT.PrerequisiteInput(
195 name='defects',
196 doc="Input defect tables.",
197 storageClass="Defects",
198 dimensions=["instrument", "detector"],
199 isCalibration=True,
200 )
201 linearizer = cT.PrerequisiteInput(
202 name='linearizer',
203 storageClass="Linearizer",
204 doc="Linearity correction calibration.",
205 dimensions=["instrument", "detector"],
206 isCalibration=True,
207 minimum=0, # can fall back to cameraGeom
208 )
209 opticsTransmission = cT.PrerequisiteInput(
210 name="transmission_optics",
211 storageClass="TransmissionCurve",
212 doc="Transmission curve due to the optics.",
213 dimensions=["instrument"],
214 isCalibration=True,
215 )
216 filterTransmission = cT.PrerequisiteInput(
217 name="transmission_filter",
218 storageClass="TransmissionCurve",
219 doc="Transmission curve due to the filter.",
220 dimensions=["instrument", "physical_filter"],
221 isCalibration=True,
222 )
223 sensorTransmission = cT.PrerequisiteInput(
224 name="transmission_sensor",
225 storageClass="TransmissionCurve",
226 doc="Transmission curve due to the sensor.",
227 dimensions=["instrument", "detector"],
228 isCalibration=True,
229 )
230 atmosphereTransmission = cT.PrerequisiteInput(
231 name="transmission_atmosphere",
232 storageClass="TransmissionCurve",
233 doc="Transmission curve due to the atmosphere.",
234 dimensions=["instrument"],
235 isCalibration=True,
236 )
237 illumMaskedImage = cT.PrerequisiteInput(
238 name="illum",
239 doc="Input illumination correction.",
240 storageClass="MaskedImageF",
241 dimensions=["instrument", "physical_filter", "detector"],
242 isCalibration=True,
243 )
244 deferredChargeCalib = cT.PrerequisiteInput(
245 name="cpCtiCalib",
246 doc="Deferred charge/CTI correction dataset.",
247 storageClass="IsrCalib",
248 dimensions=["instrument", "detector"],
249 isCalibration=True,
250 )
252 outputExposure = cT.Output(
253 name='postISRCCD',
254 doc="Output ISR processed exposure.",
255 storageClass="Exposure",
256 dimensions=["instrument", "exposure", "detector"],
257 )
258 preInterpExposure = cT.Output(
259 name='preInterpISRCCD',
260 doc="Output ISR processed exposure, with pixels left uninterpolated.",
261 storageClass="ExposureF",
262 dimensions=["instrument", "exposure", "detector"],
263 )
264 outputBin1Exposure = cT.Output(
265 name="postIsrBin1",
266 doc="First binned image.",
267 storageClass="ExposureF",
268 dimensions=["instrument", "exposure", "detector"],
269 )
270 outputBin2Exposure = cT.Output(
271 name="postIsrBin2",
272 doc="Second binned image.",
273 storageClass="ExposureF",
274 dimensions=["instrument", "exposure", "detector"],
275 )
277 outputOssThumbnail = cT.Output(
278 name="OssThumb",
279 doc="Output Overscan-subtracted thumbnail image.",
280 storageClass="Thumbnail",
281 dimensions=["instrument", "exposure", "detector"],
282 )
283 outputFlattenedThumbnail = cT.Output(
284 name="FlattenedThumb",
285 doc="Output flat-corrected thumbnail image.",
286 storageClass="Thumbnail",
287 dimensions=["instrument", "exposure", "detector"],
288 )
289 outputStatistics = cT.Output(
290 name="isrStatistics",
291 doc="Output of additional statistics table.",
292 storageClass="StructuredDataDict",
293 dimensions=["instrument", "exposure", "detector"],
294 )
296 def __init__(self, *, config=None):
297 super().__init__(config=config)
299 if config.doBias is not True:
300 self.prerequisiteInputs.remove("bias")
301 if config.doLinearize is not True:
302 self.prerequisiteInputs.remove("linearizer")
303 if config.doCrosstalk is not True:
304 self.prerequisiteInputs.remove("crosstalkSources")
305 self.prerequisiteInputs.remove("crosstalk")
306 if config.doBrighterFatter is not True:
307 self.prerequisiteInputs.remove("bfKernel")
308 self.prerequisiteInputs.remove("newBFKernel")
309 if config.doDefect is not True:
310 self.prerequisiteInputs.remove("defects")
311 if config.doDark is not True:
312 self.prerequisiteInputs.remove("dark")
313 if config.doFlat is not True:
314 self.prerequisiteInputs.remove("flat")
315 if config.doFringe is not True:
316 self.prerequisiteInputs.remove("fringes")
317 if config.doStrayLight is not True:
318 self.prerequisiteInputs.remove("strayLightData")
319 if config.usePtcGains is not True and config.usePtcReadNoise is not True:
320 self.prerequisiteInputs.remove("ptc")
321 if config.doAttachTransmissionCurve is not True:
322 self.prerequisiteInputs.remove("opticsTransmission")
323 self.prerequisiteInputs.remove("filterTransmission")
324 self.prerequisiteInputs.remove("sensorTransmission")
325 self.prerequisiteInputs.remove("atmosphereTransmission")
326 else:
327 if config.doUseOpticsTransmission is not True:
328 self.prerequisiteInputs.remove("opticsTransmission")
329 if config.doUseFilterTransmission is not True:
330 self.prerequisiteInputs.remove("filterTransmission")
331 if config.doUseSensorTransmission is not True:
332 self.prerequisiteInputs.remove("sensorTransmission")
333 if config.doUseAtmosphereTransmission is not True:
334 self.prerequisiteInputs.remove("atmosphereTransmission")
335 if config.doIlluminationCorrection is not True:
336 self.prerequisiteInputs.remove("illumMaskedImage")
337 if config.doDeferredCharge is not True:
338 self.prerequisiteInputs.remove("deferredChargeCalib")
340 if config.doWrite is not True:
341 self.outputs.remove("outputExposure")
342 self.outputs.remove("preInterpExposure")
343 self.outputs.remove("outputFlattenedThumbnail")
344 self.outputs.remove("outputOssThumbnail")
345 self.outputs.remove("outputStatistics")
346 self.outputs.remove("outputBin1Exposure")
347 self.outputs.remove("outputBin2Exposure")
349 if config.doBinnedExposures is not True:
350 self.outputs.remove("outputBin1Exposure")
351 self.outputs.remove("outputBin2Exposure")
352 if config.doSaveInterpPixels is not True:
353 self.outputs.remove("preInterpExposure")
354 if config.qa.doThumbnailOss is not True:
355 self.outputs.remove("outputOssThumbnail")
356 if config.qa.doThumbnailFlattened is not True:
357 self.outputs.remove("outputFlattenedThumbnail")
358 if config.doCalculateStatistics is not True:
359 self.outputs.remove("outputStatistics")
362class IsrTaskConfig(pipeBase.PipelineTaskConfig,
363 pipelineConnections=IsrTaskConnections):
364 """Configuration parameters for IsrTask.
366 Items are grouped in the order in which they are executed by the task.
367 """
368 datasetType = pexConfig.Field(
369 dtype=str,
370 doc="Dataset type for input data; users will typically leave this alone, "
371 "but camera-specific ISR tasks will override it",
372 default="raw",
373 )
375 fallbackFilterName = pexConfig.Field(
376 dtype=str,
377 doc="Fallback default filter name for calibrations.",
378 optional=True
379 )
380 useFallbackDate = pexConfig.Field(
381 dtype=bool,
382 doc="Pass observation date when using fallback filter.",
383 default=False,
384 )
385 expectWcs = pexConfig.Field(
386 dtype=bool,
387 default=True,
388 doc="Expect input science images to have a WCS (set False for e.g. spectrographs)."
389 )
390 fwhm = pexConfig.Field(
391 dtype=float,
392 doc="FWHM of PSF in arcseconds (currently unused).",
393 default=1.0,
394 )
395 qa = pexConfig.ConfigField(
396 dtype=isrQa.IsrQaConfig,
397 doc="QA related configuration options.",
398 )
399 doHeaderProvenance = pexConfig.Field(
400 dtype=bool,
401 default=True,
402 doc="Write calibration identifiers into output exposure header?",
403 )
405 # Calib checking configuration:
406 doRaiseOnCalibMismatch = pexConfig.Field(
407 dtype=bool,
408 default=False,
409 doc="Should IsrTask halt if exposure and calibration header values do not match?",
410 )
411 cameraKeywordsToCompare = pexConfig.ListField(
412 dtype=str,
413 doc="List of header keywords to compare between exposure and calibrations.",
414 default=[],
415 )
417 # Image conversion configuration
418 doConvertIntToFloat = pexConfig.Field(
419 dtype=bool,
420 doc="Convert integer raw images to floating point values?",
421 default=True,
422 )
424 # Saturated pixel handling.
425 doSaturation = pexConfig.Field(
426 dtype=bool,
427 doc="Mask saturated pixels? NB: this is totally independent of the"
428 " interpolation option - this is ONLY setting the bits in the mask."
429 " To have them interpolated make sure doSaturationInterpolation=True",
430 default=True,
431 )
432 saturatedMaskName = pexConfig.Field(
433 dtype=str,
434 doc="Name of mask plane to use in saturation detection and interpolation",
435 default="SAT",
436 )
437 saturation = pexConfig.Field(
438 dtype=float,
439 doc="The saturation level to use if no Detector is present in the Exposure (ignored if NaN)",
440 default=float("NaN"),
441 )
442 growSaturationFootprintSize = pexConfig.Field(
443 dtype=int,
444 doc="Number of pixels by which to grow the saturation footprints",
445 default=1,
446 )
448 # Suspect pixel handling.
449 doSuspect = pexConfig.Field(
450 dtype=bool,
451 doc="Mask suspect pixels?",
452 default=False,
453 )
454 suspectMaskName = pexConfig.Field(
455 dtype=str,
456 doc="Name of mask plane to use for suspect pixels",
457 default="SUSPECT",
458 )
459 numEdgeSuspect = pexConfig.Field(
460 dtype=int,
461 doc="Number of edge pixels to be flagged as untrustworthy.",
462 default=0,
463 )
464 edgeMaskLevel = pexConfig.ChoiceField(
465 dtype=str,
466 doc="Mask edge pixels in which coordinate frame: DETECTOR or AMP?",
467 default="DETECTOR",
468 allowed={
469 'DETECTOR': 'Mask only the edges of the full detector.',
470 'AMP': 'Mask edges of each amplifier.',
471 },
472 )
474 # Initial masking options.
475 doSetBadRegions = pexConfig.Field(
476 dtype=bool,
477 doc="Should we set the level of all BAD patches of the chip to the chip's average value?",
478 default=True,
479 )
480 badStatistic = pexConfig.ChoiceField(
481 dtype=str,
482 doc="How to estimate the average value for BAD regions.",
483 default='MEANCLIP',
484 allowed={
485 "MEANCLIP": "Correct using the (clipped) mean of good data",
486 "MEDIAN": "Correct using the median of the good data",
487 },
488 )
490 # Overscan subtraction configuration.
491 doOverscan = pexConfig.Field(
492 dtype=bool,
493 doc="Do overscan subtraction?",
494 default=True,
495 )
496 overscan = pexConfig.ConfigurableField(
497 target=OverscanCorrectionTask,
498 doc="Overscan subtraction task for image segments.",
499 )
501 # Amplifier to CCD assembly configuration
502 doAssembleCcd = pexConfig.Field(
503 dtype=bool,
504 default=True,
505 doc="Assemble amp-level exposures into a ccd-level exposure?"
506 )
507 assembleCcd = pexConfig.ConfigurableField(
508 target=AssembleCcdTask,
509 doc="CCD assembly task",
510 )
512 # General calibration configuration.
513 doAssembleIsrExposures = pexConfig.Field(
514 dtype=bool,
515 default=False,
516 doc="Assemble amp-level calibration exposures into ccd-level exposure?"
517 )
518 doTrimToMatchCalib = pexConfig.Field(
519 dtype=bool,
520 default=False,
521 doc="Trim raw data to match calibration bounding boxes?"
522 )
524 # Bias subtraction.
525 doBias = pexConfig.Field(
526 dtype=bool,
527 doc="Apply bias frame correction?",
528 default=True,
529 )
530 biasDataProductName = pexConfig.Field(
531 dtype=str,
532 doc="Name of the bias data product",
533 default="bias",
534 )
535 doBiasBeforeOverscan = pexConfig.Field(
536 dtype=bool,
537 doc="Reverse order of overscan and bias correction.",
538 default=False
539 )
541 # Deferred charge correction.
542 doDeferredCharge = pexConfig.Field(
543 dtype=bool,
544 doc="Apply deferred charge correction?",
545 default=False,
546 )
547 deferredChargeCorrection = pexConfig.ConfigurableField(
548 target=DeferredChargeTask,
549 doc="Deferred charge correction task.",
550 )
552 # Variance construction
553 doVariance = pexConfig.Field(
554 dtype=bool,
555 doc="Calculate variance?",
556 default=True
557 )
558 gain = pexConfig.Field(
559 dtype=float,
560 doc="The gain to use if no Detector is present in the Exposure (ignored if NaN)",
561 default=float("NaN"),
562 )
563 readNoise = pexConfig.Field(
564 dtype=float,
565 doc="The read noise to use if no Detector is present in the Exposure",
566 default=0.0,
567 )
568 doEmpiricalReadNoise = pexConfig.Field(
569 dtype=bool,
570 default=False,
571 doc="Calculate empirical read noise instead of value from AmpInfo data?"
572 )
573 usePtcReadNoise = pexConfig.Field(
574 dtype=bool,
575 default=False,
576 doc="Use readnoise values from the Photon Transfer Curve?"
577 )
578 maskNegativeVariance = pexConfig.Field(
579 dtype=bool,
580 default=True,
581 doc="Mask pixels that claim a negative variance? This likely indicates a failure "
582 "in the measurement of the overscan at an edge due to the data falling off faster "
583 "than the overscan model can account for it."
584 )
585 negativeVarianceMaskName = pexConfig.Field(
586 dtype=str,
587 default="BAD",
588 doc="Mask plane to use to mark pixels with negative variance, if `maskNegativeVariance` is True.",
589 )
590 # Linearization.
591 doLinearize = pexConfig.Field(
592 dtype=bool,
593 doc="Correct for nonlinearity of the detector's response?",
594 default=True,
595 )
597 # Crosstalk.
598 doCrosstalk = pexConfig.Field(
599 dtype=bool,
600 doc="Apply intra-CCD crosstalk correction?",
601 default=False,
602 )
603 doCrosstalkBeforeAssemble = pexConfig.Field(
604 dtype=bool,
605 doc="Apply crosstalk correction before CCD assembly, and before trimming?",
606 default=False,
607 )
608 crosstalk = pexConfig.ConfigurableField(
609 target=CrosstalkTask,
610 doc="Intra-CCD crosstalk correction",
611 )
613 # Masking options.
614 doDefect = pexConfig.Field(
615 dtype=bool,
616 doc="Apply correction for CCD defects, e.g. hot pixels?",
617 default=True,
618 )
619 doNanMasking = pexConfig.Field(
620 dtype=bool,
621 doc="Mask non-finite (NAN, inf) pixels?",
622 default=True,
623 )
624 doWidenSaturationTrails = pexConfig.Field(
625 dtype=bool,
626 doc="Widen bleed trails based on their width?",
627 default=True
628 )
630 # Brighter-Fatter correction.
631 doBrighterFatter = pexConfig.Field(
632 dtype=bool,
633 default=False,
634 doc="Apply the brighter-fatter correction?"
635 )
636 doFluxConservingBrighterFatterCorrection = pexConfig.Field(
637 dtype=bool,
638 default=False,
639 doc="Apply the flux-conserving BFE correction by Miller et al.?"
640 )
641 brighterFatterLevel = pexConfig.ChoiceField(
642 dtype=str,
643 default="DETECTOR",
644 doc="The level at which to correct for brighter-fatter.",
645 allowed={
646 "AMP": "Every amplifier treated separately.",
647 "DETECTOR": "One kernel per detector",
648 }
649 )
650 brighterFatterMaxIter = pexConfig.Field(
651 dtype=int,
652 default=10,
653 doc="Maximum number of iterations for the brighter-fatter correction"
654 )
655 brighterFatterThreshold = pexConfig.Field(
656 dtype=float,
657 default=1000,
658 doc="Threshold used to stop iterating the brighter-fatter correction. It is the "
659 "absolute value of the difference between the current corrected image and the one "
660 "from the previous iteration summed over all the pixels."
661 )
662 brighterFatterApplyGain = pexConfig.Field(
663 dtype=bool,
664 default=True,
665 doc="Should the gain be applied when applying the brighter-fatter correction?"
666 )
667 brighterFatterMaskListToInterpolate = pexConfig.ListField(
668 dtype=str,
669 doc="List of mask planes that should be interpolated over when applying the brighter-fatter "
670 "correction.",
671 default=["SAT", "BAD", "NO_DATA", "UNMASKEDNAN"],
672 )
673 brighterFatterMaskGrowSize = pexConfig.Field(
674 dtype=int,
675 default=0,
676 doc="Number of pixels to grow the masks listed in config.brighterFatterMaskListToInterpolate "
677 "when brighter-fatter correction is applied."
678 )
680 # Dark subtraction.
681 doDark = pexConfig.Field(
682 dtype=bool,
683 doc="Apply dark frame correction?",
684 default=True,
685 )
686 darkDataProductName = pexConfig.Field(
687 dtype=str,
688 doc="Name of the dark data product",
689 default="dark",
690 )
692 # Camera-specific stray light removal.
693 doStrayLight = pexConfig.Field(
694 dtype=bool,
695 doc="Subtract stray light in the y-band (due to encoder LEDs)?",
696 default=False,
697 )
698 strayLight = pexConfig.ConfigurableField(
699 target=StrayLightTask,
700 doc="y-band stray light correction"
701 )
703 # Flat correction.
704 doFlat = pexConfig.Field(
705 dtype=bool,
706 doc="Apply flat field correction?",
707 default=True,
708 )
709 flatDataProductName = pexConfig.Field(
710 dtype=str,
711 doc="Name of the flat data product",
712 default="flat",
713 )
714 flatScalingType = pexConfig.ChoiceField(
715 dtype=str,
716 doc="The method for scaling the flat on the fly.",
717 default='USER',
718 allowed={
719 "USER": "Scale by flatUserScale",
720 "MEAN": "Scale by the inverse of the mean",
721 "MEDIAN": "Scale by the inverse of the median",
722 },
723 )
724 flatUserScale = pexConfig.Field(
725 dtype=float,
726 doc="If flatScalingType is 'USER' then scale flat by this amount; ignored otherwise",
727 default=1.0,
728 )
729 doTweakFlat = pexConfig.Field(
730 dtype=bool,
731 doc="Tweak flats to match observed amplifier ratios?",
732 default=False
733 )
735 # Amplifier normalization based on gains instead of using flats
736 # configuration.
737 doApplyGains = pexConfig.Field(
738 dtype=bool,
739 doc="Correct the amplifiers for their gains instead of applying flat correction",
740 default=False,
741 )
742 usePtcGains = pexConfig.Field(
743 dtype=bool,
744 doc="Use the gain values from the input Photon Transfer Curve?",
745 default=False,
746 )
747 normalizeGains = pexConfig.Field(
748 dtype=bool,
749 doc="Normalize all the amplifiers in each CCD to have the same median value.",
750 default=False,
751 )
753 # Fringe correction.
754 doFringe = pexConfig.Field(
755 dtype=bool,
756 doc="Apply fringe correction?",
757 default=True,
758 )
759 fringe = pexConfig.ConfigurableField(
760 target=FringeTask,
761 doc="Fringe subtraction task",
762 )
763 fringeAfterFlat = pexConfig.Field(
764 dtype=bool,
765 doc="Do fringe subtraction after flat-fielding?",
766 default=True,
767 )
769 # Amp offset correction.
770 doAmpOffset = pexConfig.Field(
771 doc="Calculate and apply amp offset corrections?",
772 dtype=bool,
773 default=False,
774 )
775 ampOffset = pexConfig.ConfigurableField(
776 doc="Amp offset correction task.",
777 target=AmpOffsetTask,
778 )
780 # Initial CCD-level background statistics options.
781 doMeasureBackground = pexConfig.Field(
782 dtype=bool,
783 doc="Measure the background level on the reduced image?",
784 default=False,
785 )
787 # Camera-specific masking configuration.
788 doCameraSpecificMasking = pexConfig.Field(
789 dtype=bool,
790 doc="Mask camera-specific bad regions?",
791 default=False,
792 )
793 masking = pexConfig.ConfigurableField(
794 target=MaskingTask,
795 doc="Masking task."
796 )
798 # Interpolation options.
799 doInterpolate = pexConfig.Field(
800 dtype=bool,
801 doc="Interpolate masked pixels?",
802 default=True,
803 )
804 doSaturationInterpolation = pexConfig.Field(
805 dtype=bool,
806 doc="Perform interpolation over pixels masked as saturated?"
807 " NB: This is independent of doSaturation; if that is False this plane"
808 " will likely be blank, resulting in a no-op here.",
809 default=True,
810 )
811 doNanInterpolation = pexConfig.Field(
812 dtype=bool,
813 doc="Perform interpolation over pixels masked as NaN?"
814 " NB: This is independent of doNanMasking; if that is False this plane"
815 " will likely be blank, resulting in a no-op here.",
816 default=True,
817 )
818 doNanInterpAfterFlat = pexConfig.Field(
819 dtype=bool,
820 doc=("If True, ensure we interpolate NaNs after flat-fielding, even if we "
821 "also have to interpolate them before flat-fielding."),
822 default=False,
823 )
824 maskListToInterpolate = pexConfig.ListField(
825 dtype=str,
826 doc="List of mask planes that should be interpolated.",
827 default=['SAT', 'BAD'],
828 )
829 doSaveInterpPixels = pexConfig.Field(
830 dtype=bool,
831 doc="Save a copy of the pre-interpolated pixel values?",
832 default=False,
833 )
835 # Default photometric calibration options.
836 fluxMag0T1 = pexConfig.DictField(
837 keytype=str,
838 itemtype=float,
839 doc="The approximate flux of a zero-magnitude object in a one-second exposure, per filter.",
840 default=dict((f, pow(10.0, 0.4*m)) for f, m in (("Unknown", 28.0),
841 ))
842 )
843 defaultFluxMag0T1 = pexConfig.Field(
844 dtype=float,
845 doc="Default value for fluxMag0T1 (for an unrecognized filter).",
846 default=pow(10.0, 0.4*28.0)
847 )
849 # Vignette correction configuration.
850 doVignette = pexConfig.Field(
851 dtype=bool,
852 doc=("Compute and attach the validPolygon defining the unvignetted region to the exposure "
853 "according to vignetting parameters?"),
854 default=False,
855 )
856 doMaskVignettePolygon = pexConfig.Field(
857 dtype=bool,
858 doc=("Add a mask bit for pixels within the vignetted region. Ignored if doVignette "
859 "is False"),
860 default=True,
861 )
862 vignetteValue = pexConfig.Field(
863 dtype=float,
864 doc="Value to replace image array pixels with in the vignetted region? Ignored if None.",
865 optional=True,
866 default=None,
867 )
868 vignette = pexConfig.ConfigurableField(
869 target=VignetteTask,
870 doc="Vignetting task.",
871 )
873 # Transmission curve configuration.
874 doAttachTransmissionCurve = pexConfig.Field(
875 dtype=bool,
876 default=False,
877 doc="Construct and attach a wavelength-dependent throughput curve for this CCD image?"
878 )
879 doUseOpticsTransmission = pexConfig.Field(
880 dtype=bool,
881 default=True,
882 doc="Load and use transmission_optics (if doAttachTransmissionCurve is True)?"
883 )
884 doUseFilterTransmission = pexConfig.Field(
885 dtype=bool,
886 default=True,
887 doc="Load and use transmission_filter (if doAttachTransmissionCurve is True)?"
888 )
889 doUseSensorTransmission = pexConfig.Field(
890 dtype=bool,
891 default=True,
892 doc="Load and use transmission_sensor (if doAttachTransmissionCurve is True)?"
893 )
894 doUseAtmosphereTransmission = pexConfig.Field(
895 dtype=bool,
896 default=True,
897 doc="Load and use transmission_atmosphere (if doAttachTransmissionCurve is True)?"
898 )
900 # Illumination correction.
901 doIlluminationCorrection = pexConfig.Field(
902 dtype=bool,
903 default=False,
904 doc="Perform illumination correction?"
905 )
906 illuminationCorrectionDataProductName = pexConfig.Field(
907 dtype=str,
908 doc="Name of the illumination correction data product.",
909 default="illumcor",
910 )
911 illumScale = pexConfig.Field(
912 dtype=float,
913 doc="Scale factor for the illumination correction.",
914 default=1.0,
915 )
916 illumFilters = pexConfig.ListField(
917 dtype=str,
918 default=[],
919 doc="Only perform illumination correction for these filters."
920 )
922 # Calculate image quality statistics?
923 doStandardStatistics = pexConfig.Field(
924 dtype=bool,
925 doc="Should standard image quality statistics be calculated?",
926 default=True,
927 )
928 # Calculate additional statistics?
929 doCalculateStatistics = pexConfig.Field(
930 dtype=bool,
931 doc="Should additional ISR statistics be calculated?",
932 default=False,
933 )
934 isrStats = pexConfig.ConfigurableField(
935 target=IsrStatisticsTask,
936 doc="Task to calculate additional statistics.",
937 )
939 # Make binned images?
940 doBinnedExposures = pexConfig.Field(
941 dtype=bool,
942 doc="Should binned exposures be calculated?",
943 default=False,
944 )
945 binFactor1 = pexConfig.Field( 945 ↛ exitline 945 didn't jump to the function exit
946 dtype=int,
947 doc="Binning factor for first binned exposure. This is intended for a finely binned output.",
948 default=8,
949 check=lambda x: x > 1,
950 )
951 binFactor2 = pexConfig.Field( 951 ↛ exitline 951 didn't jump to the function exit
952 dtype=int,
953 doc="Binning factor for second binned exposure. This is intended for a coarsely binned output.",
954 default=64,
955 check=lambda x: x > 1,
956 )
958 # Write the outputs to disk. If ISR is run as a subtask, this may not
959 # be needed.
960 doWrite = pexConfig.Field(
961 dtype=bool,
962 doc="Persist postISRCCD?",
963 default=True,
964 )
966 def validate(self):
967 super().validate()
968 if self.doFlat and self.doApplyGains:
969 raise ValueError("You may not specify both doFlat and doApplyGains")
970 if self.doBiasBeforeOverscan and self.doTrimToMatchCalib:
971 raise ValueError("You may not specify both doBiasBeforeOverscan and doTrimToMatchCalib")
972 if self.doSaturationInterpolation and self.saturatedMaskName not in self.maskListToInterpolate:
973 self.maskListToInterpolate.append(self.saturatedMaskName)
974 if not self.doSaturationInterpolation and self.saturatedMaskName in self.maskListToInterpolate:
975 self.maskListToInterpolate.remove(self.saturatedMaskName)
976 if self.doNanInterpolation and "UNMASKEDNAN" not in self.maskListToInterpolate:
977 self.maskListToInterpolate.append("UNMASKEDNAN")
980class IsrTask(pipeBase.PipelineTask):
981 """Apply common instrument signature correction algorithms to a raw frame.
983 The process for correcting imaging data is very similar from
984 camera to camera. This task provides a vanilla implementation of
985 doing these corrections, including the ability to turn certain
986 corrections off if they are not needed. The inputs to the primary
987 method, `run()`, are a raw exposure to be corrected and the
988 calibration data products. The raw input is a single chip sized
989 mosaic of all amps including overscans and other non-science
990 pixels.
992 The __init__ method sets up the subtasks for ISR processing, using
993 the defaults from `lsst.ip.isr`.
995 Parameters
996 ----------
997 args : `list`
998 Positional arguments passed to the Task constructor.
999 None used at this time.
1000 kwargs : `dict`, optional
1001 Keyword arguments passed on to the Task constructor.
1002 None used at this time.
1003 """
1004 ConfigClass = IsrTaskConfig
1005 _DefaultName = "isr"
1007 def __init__(self, **kwargs):
1008 super().__init__(**kwargs)
1009 self.makeSubtask("assembleCcd")
1010 self.makeSubtask("crosstalk")
1011 self.makeSubtask("strayLight")
1012 self.makeSubtask("fringe")
1013 self.makeSubtask("masking")
1014 self.makeSubtask("overscan")
1015 self.makeSubtask("vignette")
1016 self.makeSubtask("ampOffset")
1017 self.makeSubtask("deferredChargeCorrection")
1018 self.makeSubtask("isrStats")
1020 def runQuantum(self, butlerQC, inputRefs, outputRefs):
1021 inputs = butlerQC.get(inputRefs)
1023 try:
1024 inputs['detectorNum'] = inputRefs.ccdExposure.dataId['detector']
1025 except Exception as e:
1026 raise ValueError("Failure to find valid detectorNum value for Dataset %s: %s." %
1027 (inputRefs, e))
1029 detector = inputs['ccdExposure'].getDetector()
1031 # This is use for header provenance.
1032 additionalInputDates = {}
1034 if self.config.doCrosstalk is True:
1035 # Crosstalk sources need to be defined by the pipeline
1036 # yaml if they exist.
1037 if 'crosstalk' in inputs and inputs['crosstalk'] is not None:
1038 if not isinstance(inputs['crosstalk'], CrosstalkCalib):
1039 inputs['crosstalk'] = CrosstalkCalib.fromTable(inputs['crosstalk'])
1040 else:
1041 coeffVector = (self.config.crosstalk.crosstalkValues
1042 if self.config.crosstalk.useConfigCoefficients else None)
1043 crosstalkCalib = CrosstalkCalib().fromDetector(detector, coeffVector=coeffVector)
1044 inputs['crosstalk'] = crosstalkCalib
1045 if inputs['crosstalk'].interChip and len(inputs['crosstalk'].interChip) > 0:
1046 if 'crosstalkSources' not in inputs:
1047 self.log.warning("No crosstalkSources found for chip with interChip terms!")
1049 if self.doLinearize(detector) is True:
1050 if 'linearizer' in inputs:
1051 if isinstance(inputs['linearizer'], dict):
1052 linearizer = linearize.Linearizer(detector=detector, log=self.log)
1053 linearizer.fromYaml(inputs['linearizer'])
1054 self.log.warning("Dictionary linearizers will be deprecated in DM-28741.")
1055 elif isinstance(inputs['linearizer'], numpy.ndarray):
1056 linearizer = linearize.Linearizer(table=inputs.get('linearizer', None),
1057 detector=detector,
1058 log=self.log)
1059 self.log.warning("Bare lookup table linearizers will be deprecated in DM-28741.")
1060 else:
1061 linearizer = inputs['linearizer']
1062 linearizer.log = self.log
1063 inputs['linearizer'] = linearizer
1064 else:
1065 inputs['linearizer'] = linearize.Linearizer(detector=detector, log=self.log)
1066 self.log.warning("Constructing linearizer from cameraGeom information.")
1068 if self.config.doDefect is True:
1069 if "defects" in inputs and inputs['defects'] is not None:
1070 # defects is loaded as a BaseCatalog with columns
1071 # x0, y0, width, height. Masking expects a list of defects
1072 # defined by their bounding box
1073 if not isinstance(inputs["defects"], Defects):
1074 inputs["defects"] = Defects.fromTable(inputs["defects"])
1076 # Load the correct style of brighter-fatter kernel, and repack
1077 # the information as a numpy array.
1078 brighterFatterSource = None
1079 if self.config.doBrighterFatter:
1080 brighterFatterKernel = inputs.pop('newBFKernel', None)
1081 if brighterFatterKernel is None:
1082 # This type of kernel must be in (y, x) index
1083 # ordering, as it used directly as the .array
1084 # component of the afwImage kernel.
1085 brighterFatterKernel = inputs.get('bfKernel', None)
1086 brighterFatterSource = 'bfKernel'
1087 additionalInputDates[brighterFatterSource] = self.extractCalibDate(brighterFatterKernel)
1089 if brighterFatterKernel is None:
1090 # This was requested by the config, but none were found.
1091 raise RuntimeError("No brighter-fatter kernel was supplied.")
1092 elif not isinstance(brighterFatterKernel, numpy.ndarray):
1093 # This is a ISR calib kernel. These kernels are
1094 # generated in (x, y) index ordering, and need to be
1095 # transposed to be used directly as the .array
1096 # component of the afwImage kernel. This is done
1097 # explicitly below when setting the ``bfKernel``
1098 # input.
1099 brighterFatterSource = 'newBFKernel'
1100 additionalInputDates[brighterFatterSource] = self.extractCalibDate(brighterFatterKernel)
1102 detName = detector.getName()
1103 level = brighterFatterKernel.level
1105 # This is expected to be a dictionary of amp-wise gains.
1106 inputs['bfGains'] = brighterFatterKernel.gain
1107 if self.config.brighterFatterLevel == 'DETECTOR':
1108 kernel = None
1109 if level == 'DETECTOR':
1110 if detName in brighterFatterKernel.detKernels:
1111 kernel = brighterFatterKernel.detKernels[detName]
1112 else:
1113 raise RuntimeError("Failed to extract kernel from new-style BF kernel.")
1114 elif level == 'AMP':
1115 self.log.warning("Making DETECTOR level kernel from AMP based brighter "
1116 "fatter kernels.")
1117 brighterFatterKernel.makeDetectorKernelFromAmpwiseKernels(detName)
1118 kernel = brighterFatterKernel.detKernels[detName]
1119 if kernel is None:
1120 raise RuntimeError("Could not identify brighter-fatter kernel!")
1121 # Do the one single transpose here so the kernel
1122 # can be directly loaded into the afwImage .array
1123 # component.
1124 inputs['bfKernel'] = numpy.transpose(kernel)
1125 elif self.config.brighterFatterLevel == 'AMP':
1126 raise NotImplementedError("Per-amplifier brighter-fatter correction not implemented")
1128 if self.config.doFringe is True and self.fringe.checkFilter(inputs['ccdExposure']):
1129 expId = inputs['ccdExposure'].info.id
1130 inputs['fringes'] = self.fringe.loadFringes(inputs['fringes'],
1131 expId=expId,
1132 assembler=self.assembleCcd
1133 if self.config.doAssembleIsrExposures else None)
1134 else:
1135 inputs['fringes'] = pipeBase.Struct(fringes=None)
1137 if self.config.doStrayLight is True and self.strayLight.checkFilter(inputs['ccdExposure']):
1138 if 'strayLightData' not in inputs:
1139 inputs['strayLightData'] = None
1141 if self.config.doHeaderProvenance:
1142 # Add calibration provenanace info to header.
1143 exposureMetadata = inputs['ccdExposure'].getMetadata()
1145 # These inputs change name during this step. These should
1146 # have matching entries in the additionalInputDates dict.
1147 additionalInputs = []
1148 if self.config.doBrighterFatter:
1149 additionalInputs.append(brighterFatterSource)
1151 for inputName in sorted(list(inputs.keys()) + additionalInputs):
1152 reference = getattr(inputRefs, inputName, None)
1153 if reference is not None and hasattr(reference, "run"):
1154 runKey = f"LSST CALIB RUN {inputName.upper()}"
1155 runValue = reference.run
1156 idKey = f"LSST CALIB UUID {inputName.upper()}"
1157 idValue = str(reference.id)
1158 dateKey = f"LSST CALIB DATE {inputName.upper()}"
1160 if inputName in additionalInputDates:
1161 dateValue = additionalInputDates[inputName]
1162 else:
1163 dateValue = self.extractCalibDate(inputs[inputName])
1165 exposureMetadata[runKey] = runValue
1166 exposureMetadata[idKey] = idValue
1167 exposureMetadata[dateKey] = dateValue
1169 outputs = self.run(**inputs)
1170 butlerQC.put(outputs, outputRefs)
1172 @timeMethod
1173 def run(self, ccdExposure, *, camera=None, bias=None, linearizer=None,
1174 crosstalk=None, crosstalkSources=None,
1175 dark=None, flat=None, ptc=None, bfKernel=None, bfGains=None, defects=None,
1176 fringes=pipeBase.Struct(fringes=None), opticsTransmission=None, filterTransmission=None,
1177 sensorTransmission=None, atmosphereTransmission=None,
1178 detectorNum=None, strayLightData=None, illumMaskedImage=None,
1179 deferredChargeCalib=None,
1180 ):
1181 """Perform instrument signature removal on an exposure.
1183 Steps included in the ISR processing, in order performed, are:
1185 - saturation and suspect pixel masking
1186 - overscan subtraction
1187 - CCD assembly of individual amplifiers
1188 - bias subtraction
1189 - variance image construction
1190 - linearization of non-linear response
1191 - crosstalk masking
1192 - brighter-fatter correction
1193 - dark subtraction
1194 - fringe correction
1195 - stray light subtraction
1196 - flat correction
1197 - masking of known defects and camera specific features
1198 - vignette calculation
1199 - appending transmission curve and distortion model
1201 Parameters
1202 ----------
1203 ccdExposure : `lsst.afw.image.Exposure`
1204 The raw exposure that is to be run through ISR. The
1205 exposure is modified by this method.
1206 camera : `lsst.afw.cameraGeom.Camera`, optional
1207 The camera geometry for this exposure. Required if
1208 one or more of ``ccdExposure``, ``bias``, ``dark``, or
1209 ``flat`` does not have an associated detector.
1210 bias : `lsst.afw.image.Exposure`, optional
1211 Bias calibration frame.
1212 linearizer : `lsst.ip.isr.linearize.LinearizeBase`, optional
1213 Functor for linearization.
1214 crosstalk : `lsst.ip.isr.crosstalk.CrosstalkCalib`, optional
1215 Calibration for crosstalk.
1216 crosstalkSources : `list`, optional
1217 List of possible crosstalk sources.
1218 dark : `lsst.afw.image.Exposure`, optional
1219 Dark calibration frame.
1220 flat : `lsst.afw.image.Exposure`, optional
1221 Flat calibration frame.
1222 ptc : `lsst.ip.isr.PhotonTransferCurveDataset`, optional
1223 Photon transfer curve dataset, with, e.g., gains
1224 and read noise.
1225 bfKernel : `numpy.ndarray`, optional
1226 Brighter-fatter kernel.
1227 bfGains : `dict` of `float`, optional
1228 Gains used to override the detector's nominal gains for the
1229 brighter-fatter correction. A dict keyed by amplifier name for
1230 the detector in question.
1231 defects : `lsst.ip.isr.Defects`, optional
1232 List of defects.
1233 fringes : `lsst.pipe.base.Struct`, optional
1234 Struct containing the fringe correction data, with
1235 elements:
1237 ``fringes``
1238 fringe calibration frame (`lsst.afw.image.Exposure`)
1239 ``seed``
1240 random seed derived from the ``ccdExposureId`` for random
1241 number generator (`numpy.uint32`)
1242 opticsTransmission: `lsst.afw.image.TransmissionCurve`, optional
1243 A ``TransmissionCurve`` that represents the throughput of the,
1244 optics, to be evaluated in focal-plane coordinates.
1245 filterTransmission : `lsst.afw.image.TransmissionCurve`
1246 A ``TransmissionCurve`` that represents the throughput of the
1247 filter itself, to be evaluated in focal-plane coordinates.
1248 sensorTransmission : `lsst.afw.image.TransmissionCurve`
1249 A ``TransmissionCurve`` that represents the throughput of the
1250 sensor itself, to be evaluated in post-assembly trimmed detector
1251 coordinates.
1252 atmosphereTransmission : `lsst.afw.image.TransmissionCurve`
1253 A ``TransmissionCurve`` that represents the throughput of the
1254 atmosphere, assumed to be spatially constant.
1255 detectorNum : `int`, optional
1256 The integer number for the detector to process.
1257 strayLightData : `object`, optional
1258 Opaque object containing calibration information for stray-light
1259 correction. If `None`, no correction will be performed.
1260 illumMaskedImage : `lsst.afw.image.MaskedImage`, optional
1261 Illumination correction image.
1263 Returns
1264 -------
1265 result : `lsst.pipe.base.Struct`
1266 Result struct with component:
1268 ``exposure``
1269 The fully ISR corrected exposure.
1270 (`lsst.afw.image.Exposure`)
1271 ``outputExposure``
1272 An alias for ``exposure``. (`lsst.afw.image.Exposure`)
1273 ``ossThumb``
1274 Thumbnail image of the exposure after overscan subtraction.
1275 (`numpy.ndarray`)
1276 ``flattenedThumb``
1277 Thumbnail image of the exposure after flat-field correction.
1278 (`numpy.ndarray`)
1279 ``outputStatistics``
1280 Values of the additional statistics calculated.
1282 Raises
1283 ------
1284 RuntimeError
1285 Raised if a configuration option is set to `True`, but the
1286 required calibration data has not been specified.
1288 Notes
1289 -----
1290 The current processed exposure can be viewed by setting the
1291 appropriate `lsstDebug` entries in the ``debug.display``
1292 dictionary. The names of these entries correspond to some of
1293 the `IsrTaskConfig` Boolean options, with the value denoting the
1294 frame to use. The exposure is shown inside the matching
1295 option check and after the processing of that step has
1296 finished. The steps with debug points are:
1298 * doAssembleCcd
1299 * doBias
1300 * doCrosstalk
1301 * doBrighterFatter
1302 * doDark
1303 * doFringe
1304 * doStrayLight
1305 * doFlat
1307 In addition, setting the ``postISRCCD`` entry displays the
1308 exposure after all ISR processing has finished.
1309 """
1311 ccdExposure = self.ensureExposure(ccdExposure, camera, detectorNum)
1312 bias = self.ensureExposure(bias, camera, detectorNum)
1313 dark = self.ensureExposure(dark, camera, detectorNum)
1314 flat = self.ensureExposure(flat, camera, detectorNum)
1316 ccd = ccdExposure.getDetector()
1317 filterLabel = ccdExposure.getFilter()
1318 physicalFilter = isrFunctions.getPhysicalFilter(filterLabel, self.log)
1320 if not ccd:
1321 assert not self.config.doAssembleCcd, "You need a Detector to run assembleCcd."
1322 ccd = [FakeAmp(ccdExposure, self.config)]
1324 # Validate Input
1325 if self.config.doBias and bias is None:
1326 raise RuntimeError("Must supply a bias exposure if config.doBias=True.")
1327 if self.doLinearize(ccd) and linearizer is None:
1328 raise RuntimeError("Must supply a linearizer if config.doLinearize=True for this detector.")
1329 if self.config.doBrighterFatter and bfKernel is None:
1330 raise RuntimeError("Must supply a kernel if config.doBrighterFatter=True.")
1331 if self.config.doDark and dark is None:
1332 raise RuntimeError("Must supply a dark exposure if config.doDark=True.")
1333 if self.config.doFlat and flat is None:
1334 raise RuntimeError("Must supply a flat exposure if config.doFlat=True.")
1335 if self.config.doDefect and defects is None:
1336 raise RuntimeError("Must supply defects if config.doDefect=True.")
1337 if (self.config.doFringe and physicalFilter in self.fringe.config.filters
1338 and fringes.fringes is None):
1339 # The `fringes` object needs to be a pipeBase.Struct, as
1340 # we use it as a `dict` for the parameters of
1341 # `FringeTask.run()`. The `fringes.fringes` `list` may
1342 # not be `None` if `doFringe=True`. Otherwise, raise.
1343 raise RuntimeError("Must supply fringe exposure as a pipeBase.Struct.")
1344 if (self.config.doIlluminationCorrection and physicalFilter in self.config.illumFilters
1345 and illumMaskedImage is None):
1346 raise RuntimeError("Must supply an illumcor if config.doIlluminationCorrection=True.")
1347 if (self.config.doDeferredCharge and deferredChargeCalib is None):
1348 raise RuntimeError("Must supply a deferred charge calibration if config.doDeferredCharge=True.")
1349 if (self.config.usePtcGains and ptc is None):
1350 raise RuntimeError("No ptcDataset provided to use PTC gains.")
1351 if (self.config.usePtcReadNoise and ptc is None):
1352 raise RuntimeError("No ptcDataset provided to use PTC read noise.")
1354 # Validate that the inputs match the exposure configuration.
1355 exposureMetadata = ccdExposure.getMetadata()
1356 if self.config.doBias:
1357 self.compareCameraKeywords(exposureMetadata, bias, "bias")
1358 if self.config.doBrighterFatter:
1359 self.compareCameraKeywords(exposureMetadata, bfKernel, "brighter-fatter")
1360 if self.config.doCrosstalk:
1361 self.compareCameraKeywords(exposureMetadata, crosstalk, "crosstalk")
1362 if self.config.doDark:
1363 self.compareCameraKeywords(exposureMetadata, dark, "dark")
1364 if self.config.doDefect:
1365 self.compareCameraKeywords(exposureMetadata, defects, "defects")
1366 if self.config.doDeferredCharge:
1367 self.compareCameraKeywords(exposureMetadata, deferredChargeCalib, "CTI")
1368 if self.config.doFlat:
1369 self.compareCameraKeywords(exposureMetadata, flat, "flat")
1370 if (self.config.doFringe and physicalFilter in self.fringe.config.filters):
1371 self.compareCameraKeywords(exposureMetadata, fringes.fringes, "fringe")
1372 if (self.config.doIlluminationCorrection and physicalFilter in self.config.illumFilters):
1373 self.compareCameraKeywords(exposureMetadata, illumMaskedImage, "illumination")
1374 if self.doLinearize(ccd):
1375 self.compareCameraKeywords(exposureMetadata, linearizer, "linearizer")
1376 if self.config.usePtcGains or self.config.usePtcReadNoise:
1377 self.compareCameraKeywords(exposureMetadata, ptc, "PTC")
1378 if self.config.doStrayLight:
1379 self.compareCameraKeywords(exposureMetadata, strayLightData, "straylight")
1381 # Start in ADU. Update units to electrons when gain is applied:
1382 # updateVariance, applyGains
1383 # Check if needed during/after BFE correction, CTI correction.
1384 exposureMetadata["LSST ISR UNITS"] = "ADU"
1386 # Begin ISR processing.
1387 if self.config.doConvertIntToFloat:
1388 self.log.info("Converting exposure to floating point values.")
1389 ccdExposure = self.convertIntToFloat(ccdExposure)
1391 if self.config.doBias and self.config.doBiasBeforeOverscan:
1392 self.log.info("Applying bias correction.")
1393 isrFunctions.biasCorrection(ccdExposure.getMaskedImage(), bias.getMaskedImage(),
1394 trimToFit=self.config.doTrimToMatchCalib)
1395 self.debugView(ccdExposure, "doBias")
1397 # Amplifier level processing.
1398 overscans = []
1400 if self.config.doOverscan and self.config.overscan.doParallelOverscan:
1401 # This will attempt to mask bleed pixels across all amplifiers.
1402 self.overscan.maskParallelOverscan(ccdExposure, ccd)
1404 for amp in ccd:
1405 # if ccdExposure is one amp,
1406 # check for coverage to prevent performing ops multiple times
1407 if ccdExposure.getBBox().contains(amp.getBBox()):
1408 # Check for fully masked bad amplifiers,
1409 # and generate masks for SUSPECT and SATURATED values.
1410 badAmp = self.maskAmplifier(ccdExposure, amp, defects)
1412 if self.config.doOverscan and not badAmp:
1413 # Overscan correction on amp-by-amp basis.
1414 overscanResults = self.overscanCorrection(ccdExposure, amp)
1415 self.log.debug("Corrected overscan for amplifier %s.", amp.getName())
1416 if overscanResults is not None and \
1417 self.config.qa is not None and self.config.qa.saveStats is True:
1418 if isinstance(overscanResults.overscanMean, float):
1419 # Only serial overscan was run
1420 mean = overscanResults.overscanMean
1421 sigma = overscanResults.overscanSigma
1422 residMean = overscanResults.residualMean
1423 residSigma = overscanResults.residualSigma
1424 else:
1425 # Both serial and parallel overscan were
1426 # run. Only report serial here.
1427 mean = overscanResults.overscanMean[0]
1428 sigma = overscanResults.overscanSigma[0]
1429 residMean = overscanResults.residualMean[0]
1430 residSigma = overscanResults.residualSigma[0]
1432 self.metadata[f"FIT MEDIAN {amp.getName()}"] = mean
1433 self.metadata[f"FIT STDEV {amp.getName()}"] = sigma
1434 self.log.debug(" Overscan stats for amplifer %s: %f +/- %f",
1435 amp.getName(), mean, sigma)
1437 self.metadata[f"RESIDUAL MEDIAN {amp.getName()}"] = residMean
1438 self.metadata[f"RESIDUAL STDEV {amp.getName()}"] = residSigma
1439 self.log.debug(" Overscan stats for amplifer %s after correction: %f +/- %f",
1440 amp.getName(), residMean, residSigma)
1442 ccdExposure.getMetadata().set('OVERSCAN', "Overscan corrected")
1443 else:
1444 if badAmp:
1445 self.log.warning("Amplifier %s is bad.", amp.getName())
1446 overscanResults = None
1448 overscans.append(overscanResults if overscanResults is not None else None)
1449 else:
1450 self.log.info("Skipped OSCAN for %s.", amp.getName())
1452 # Define an effective PTC that will contain the gain and readout
1453 # noise to be used throughout the ISR task.
1454 ptc = self.defineEffectivePtc(ptc, ccd, bfGains, overscans, exposureMetadata)
1456 if self.config.doDeferredCharge:
1457 self.log.info("Applying deferred charge/CTI correction.")
1458 self.deferredChargeCorrection.run(ccdExposure, deferredChargeCalib)
1459 self.debugView(ccdExposure, "doDeferredCharge")
1461 if self.config.doCrosstalk and self.config.doCrosstalkBeforeAssemble:
1462 self.log.info("Applying crosstalk correction.")
1463 self.crosstalk.run(ccdExposure, crosstalk=crosstalk,
1464 crosstalkSources=crosstalkSources, camera=camera)
1465 self.debugView(ccdExposure, "doCrosstalk")
1467 if self.config.doAssembleCcd:
1468 self.log.info("Assembling CCD from amplifiers.")
1469 ccdExposure = self.assembleCcd.assembleCcd(ccdExposure)
1471 if self.config.expectWcs and not ccdExposure.getWcs():
1472 self.log.warning("No WCS found in input exposure.")
1473 self.debugView(ccdExposure, "doAssembleCcd")
1475 ossThumb = None
1476 if self.config.qa.doThumbnailOss:
1477 ossThumb = isrQa.makeThumbnail(ccdExposure, isrQaConfig=self.config.qa)
1479 if self.config.doBias and not self.config.doBiasBeforeOverscan:
1480 self.log.info("Applying bias correction.")
1481 isrFunctions.biasCorrection(ccdExposure.getMaskedImage(), bias.getMaskedImage(),
1482 trimToFit=self.config.doTrimToMatchCalib)
1483 self.debugView(ccdExposure, "doBias")
1485 if self.config.doVariance:
1486 for amp, overscanResults in zip(ccd, overscans):
1487 if ccdExposure.getBBox().contains(amp.getBBox()):
1488 self.log.debug("Constructing variance map for amplifer %s.", amp.getName())
1489 ampExposure = ccdExposure.Factory(ccdExposure, amp.getBBox())
1490 self.updateVariance(ampExposure, amp, ptc)
1492 if self.config.qa is not None and self.config.qa.saveStats is True:
1493 qaStats = afwMath.makeStatistics(ampExposure.getVariance(),
1494 afwMath.MEDIAN | afwMath.STDEVCLIP)
1495 self.metadata[f"ISR VARIANCE {amp.getName()} MEDIAN"] = \
1496 qaStats.getValue(afwMath.MEDIAN)
1497 self.metadata[f"ISR VARIANCE {amp.getName()} STDEV"] = \
1498 qaStats.getValue(afwMath.STDEVCLIP)
1499 self.log.debug(" Variance stats for amplifer %s: %f +/- %f.",
1500 amp.getName(), qaStats.getValue(afwMath.MEDIAN),
1501 qaStats.getValue(afwMath.STDEVCLIP))
1502 if self.config.maskNegativeVariance:
1503 self.maskNegativeVariance(ccdExposure)
1505 if self.doLinearize(ccd):
1506 self.log.info("Applying linearizer.")
1507 linearizer.applyLinearity(image=ccdExposure.getMaskedImage().getImage(),
1508 detector=ccd, log=self.log)
1510 if self.config.doCrosstalk and not self.config.doCrosstalkBeforeAssemble:
1511 self.log.info("Applying crosstalk correction.")
1512 self.crosstalk.run(ccdExposure, crosstalk=crosstalk,
1513 crosstalkSources=crosstalkSources, isTrimmed=True)
1514 self.debugView(ccdExposure, "doCrosstalk")
1516 # Masking block. Optionally mask known defects, NAN/inf pixels,
1517 # widen trails, and do anything else the camera needs. Saturated and
1518 # suspect pixels have already been masked.
1519 if self.config.doDefect:
1520 self.log.info("Masking defects.")
1521 self.maskDefect(ccdExposure, defects)
1523 if self.config.numEdgeSuspect > 0:
1524 self.log.info("Masking edges as SUSPECT.")
1525 self.maskEdges(ccdExposure, numEdgePixels=self.config.numEdgeSuspect,
1526 maskPlane="SUSPECT", level=self.config.edgeMaskLevel)
1528 if self.config.doNanMasking:
1529 self.log.info("Masking non-finite (NAN, inf) value pixels.")
1530 self.maskNan(ccdExposure)
1532 if self.config.doWidenSaturationTrails:
1533 self.log.info("Widening saturation trails.")
1534 isrFunctions.widenSaturationTrails(ccdExposure.getMaskedImage().getMask())
1536 if self.config.doCameraSpecificMasking:
1537 self.log.info("Masking regions for camera specific reasons.")
1538 self.masking.run(ccdExposure)
1540 if self.config.doBrighterFatter:
1541 # We need to apply flats and darks before we can interpolate, and
1542 # we need to interpolate before we do B-F, but we do B-F without
1543 # the flats and darks applied so we can work in units of electrons
1544 # or holes. This context manager applies and then removes the darks
1545 # and flats.
1546 #
1547 # We also do not want to interpolate values here, so operate on
1548 # temporary images so we can apply only the BF-correction and roll
1549 # back the interpolation.
1550 interpExp = ccdExposure.clone()
1551 with self.flatContext(interpExp, flat, dark):
1552 isrFunctions.interpolateFromMask(
1553 maskedImage=interpExp.getMaskedImage(),
1554 fwhm=self.config.fwhm,
1555 growSaturatedFootprints=self.config.growSaturationFootprintSize,
1556 maskNameList=list(self.config.brighterFatterMaskListToInterpolate)
1557 )
1558 bfExp = interpExp.clone()
1560 self.log.info("Applying brighter-fatter correction using kernel type %s / gains %s.",
1561 type(bfKernel), type(bfGains))
1562 if self.config.doFluxConservingBrighterFatterCorrection:
1563 bfResults = isrFunctions.fluxConservingBrighterFatterCorrection(
1564 bfExp,
1565 bfKernel,
1566 self.config.brighterFatterMaxIter,
1567 self.config.brighterFatterThreshold,
1568 self.config.brighterFatterApplyGain,
1569 bfGains
1570 )
1571 else:
1572 bfResults = isrFunctions.brighterFatterCorrection(
1573 bfExp,
1574 bfKernel,
1575 self.config.brighterFatterMaxIter,
1576 self.config.brighterFatterThreshold,
1577 self.config.brighterFatterApplyGain,
1578 bfGains
1579 )
1580 if bfResults[1] == self.config.brighterFatterMaxIter - 1:
1581 self.log.warning("Brighter-fatter correction did not converge, final difference %f.",
1582 bfResults[0])
1583 else:
1584 self.log.info("Finished brighter-fatter correction in %d iterations.",
1585 bfResults[1])
1586 image = ccdExposure.getMaskedImage().getImage()
1587 bfCorr = bfExp.getMaskedImage().getImage()
1588 bfCorr -= interpExp.getMaskedImage().getImage()
1589 image += bfCorr
1591 # Applying the brighter-fatter correction applies a
1592 # convolution to the science image. At the edges this
1593 # convolution may not have sufficient valid pixels to
1594 # produce a valid correction. Mark pixels within the size
1595 # of the brighter-fatter kernel as EDGE to warn of this
1596 # fact.
1597 self.log.info("Ensuring image edges are masked as EDGE to the brighter-fatter kernel size.")
1598 self.maskEdges(ccdExposure, numEdgePixels=numpy.max(bfKernel.shape) // 2,
1599 maskPlane="EDGE")
1601 if self.config.brighterFatterMaskGrowSize > 0:
1602 self.log.info("Growing masks to account for brighter-fatter kernel convolution.")
1603 for maskPlane in self.config.brighterFatterMaskListToInterpolate:
1604 isrFunctions.growMasks(ccdExposure.getMask(),
1605 radius=self.config.brighterFatterMaskGrowSize,
1606 maskNameList=maskPlane,
1607 maskValue=maskPlane)
1609 self.debugView(ccdExposure, "doBrighterFatter")
1611 if self.config.doDark:
1612 self.log.info("Applying dark correction.")
1613 self.darkCorrection(ccdExposure, dark)
1614 self.debugView(ccdExposure, "doDark")
1616 if self.config.doFringe and not self.config.fringeAfterFlat:
1617 self.log.info("Applying fringe correction before flat.")
1618 self.fringe.run(ccdExposure, **fringes.getDict())
1619 self.debugView(ccdExposure, "doFringe")
1621 if self.config.doStrayLight and self.strayLight.check(ccdExposure):
1622 self.log.info("Checking strayLight correction.")
1623 self.strayLight.run(ccdExposure, strayLightData)
1624 self.debugView(ccdExposure, "doStrayLight")
1626 if self.config.doFlat:
1627 self.log.info("Applying flat correction.")
1628 self.flatCorrection(ccdExposure, flat)
1629 self.debugView(ccdExposure, "doFlat")
1631 if self.config.doApplyGains:
1632 self.log.info("Applying gain correction instead of flat.")
1633 isrFunctions.applyGains(ccdExposure, self.config.normalizeGains,
1634 ptcGains=ptc.gain)
1635 exposureMetadata["LSST ISR UNITS"] = "electrons"
1637 if self.config.doFringe and self.config.fringeAfterFlat:
1638 self.log.info("Applying fringe correction after flat.")
1639 self.fringe.run(ccdExposure, **fringes.getDict())
1641 if self.config.doVignette:
1642 if self.config.doMaskVignettePolygon:
1643 self.log.info("Constructing, attaching, and masking vignette polygon.")
1644 else:
1645 self.log.info("Constructing and attaching vignette polygon.")
1646 self.vignettePolygon = self.vignette.run(
1647 exposure=ccdExposure, doUpdateMask=self.config.doMaskVignettePolygon,
1648 vignetteValue=self.config.vignetteValue, log=self.log)
1650 if self.config.doAttachTransmissionCurve:
1651 self.log.info("Adding transmission curves.")
1652 isrFunctions.attachTransmissionCurve(ccdExposure, opticsTransmission=opticsTransmission,
1653 filterTransmission=filterTransmission,
1654 sensorTransmission=sensorTransmission,
1655 atmosphereTransmission=atmosphereTransmission)
1657 flattenedThumb = None
1658 if self.config.qa.doThumbnailFlattened:
1659 flattenedThumb = isrQa.makeThumbnail(ccdExposure, isrQaConfig=self.config.qa)
1661 if self.config.doIlluminationCorrection and physicalFilter in self.config.illumFilters:
1662 self.log.info("Performing illumination correction.")
1663 isrFunctions.illuminationCorrection(ccdExposure.getMaskedImage(),
1664 illumMaskedImage, illumScale=self.config.illumScale,
1665 trimToFit=self.config.doTrimToMatchCalib)
1667 preInterpExp = None
1668 if self.config.doSaveInterpPixels:
1669 preInterpExp = ccdExposure.clone()
1671 # Reset and interpolate bad pixels.
1672 #
1673 # Large contiguous bad regions (which should have the BAD mask
1674 # bit set) should have their values set to the image median.
1675 # This group should include defects and bad amplifiers. As the
1676 # area covered by these defects are large, there's little
1677 # reason to expect that interpolation would provide a more
1678 # useful value.
1679 #
1680 # Smaller defects can be safely interpolated after the larger
1681 # regions have had their pixel values reset. This ensures
1682 # that the remaining defects adjacent to bad amplifiers (as an
1683 # example) do not attempt to interpolate extreme values.
1684 if self.config.doSetBadRegions:
1685 badPixelCount, badPixelValue = isrFunctions.setBadRegions(ccdExposure)
1686 if badPixelCount > 0:
1687 self.log.info("Set %d BAD pixels to %f.", badPixelCount, badPixelValue)
1689 if self.config.doInterpolate:
1690 self.log.info("Interpolating masked pixels.")
1691 isrFunctions.interpolateFromMask(
1692 maskedImage=ccdExposure.getMaskedImage(),
1693 fwhm=self.config.fwhm,
1694 growSaturatedFootprints=self.config.growSaturationFootprintSize,
1695 maskNameList=list(self.config.maskListToInterpolate)
1696 )
1698 self.roughZeroPoint(ccdExposure)
1700 # correct for amp offsets within the CCD
1701 if self.config.doAmpOffset:
1702 self.log.info("Correcting amp offsets.")
1703 self.ampOffset.run(ccdExposure)
1705 if self.config.doMeasureBackground:
1706 self.log.info("Measuring background level.")
1707 self.measureBackground(ccdExposure, self.config.qa)
1709 if self.config.qa is not None and self.config.qa.saveStats is True:
1710 for amp in ccd:
1711 ampExposure = ccdExposure.Factory(ccdExposure, amp.getBBox())
1712 qaStats = afwMath.makeStatistics(ampExposure.getImage(),
1713 afwMath.MEDIAN | afwMath.STDEVCLIP)
1714 self.metadata[f"ISR BACKGROUND {amp.getName()} MEDIAN"] = qaStats.getValue(afwMath.MEDIAN)
1715 self.metadata[f"ISR BACKGROUND {amp.getName()} STDEV"] = \
1716 qaStats.getValue(afwMath.STDEVCLIP)
1717 self.log.debug(" Background stats for amplifer %s: %f +/- %f",
1718 amp.getName(), qaStats.getValue(afwMath.MEDIAN),
1719 qaStats.getValue(afwMath.STDEVCLIP))
1721 # Calculate standard image quality statistics
1722 if self.config.doStandardStatistics:
1723 metadata = ccdExposure.getMetadata()
1724 for amp in ccd:
1725 ampExposure = ccdExposure.Factory(ccdExposure, amp.getBBox())
1726 ampName = amp.getName()
1727 metadata[f"LSST ISR MASK SAT {ampName}"] = isrFunctions.countMaskedPixels(
1728 ampExposure.getMaskedImage(),
1729 [self.config.saturatedMaskName]
1730 )
1731 metadata[f"LSST ISR MASK BAD {ampName}"] = isrFunctions.countMaskedPixels(
1732 ampExposure.getMaskedImage(),
1733 ["BAD"]
1734 )
1735 qaStats = afwMath.makeStatistics(ampExposure.getImage(),
1736 afwMath.MEAN | afwMath.MEDIAN | afwMath.STDEVCLIP)
1738 metadata[f"LSST ISR FINAL MEAN {ampName}"] = qaStats.getValue(afwMath.MEAN)
1739 metadata[f"LSST ISR FINAL MEDIAN {ampName}"] = qaStats.getValue(afwMath.MEDIAN)
1740 metadata[f"LSST ISR FINAL STDEV {ampName}"] = qaStats.getValue(afwMath.STDEVCLIP)
1742 k1 = f"LSST ISR FINAL MEDIAN {ampName}"
1743 k2 = f"LSST ISR OVERSCAN SERIAL MEDIAN {ampName}"
1744 if self.config.doOverscan and k1 in metadata and k2 in metadata:
1745 metadata[f"LSST ISR LEVEL {ampName}"] = metadata[k1] - metadata[k2]
1746 else:
1747 metadata[f"LSST ISR LEVEL {ampName}"] = numpy.nan
1749 # calculate additional statistics.
1750 outputStatistics = None
1751 if self.config.doCalculateStatistics:
1752 outputStatistics = self.isrStats.run(ccdExposure, overscanResults=overscans,
1753 ptc=ptc).results
1755 # do any binning.
1756 outputBin1Exposure = None
1757 outputBin2Exposure = None
1758 if self.config.doBinnedExposures:
1759 outputBin1Exposure, outputBin2Exposure = self.makeBinnedImages(ccdExposure)
1761 self.debugView(ccdExposure, "postISRCCD")
1763 return pipeBase.Struct(
1764 exposure=ccdExposure,
1765 ossThumb=ossThumb,
1766 flattenedThumb=flattenedThumb,
1768 outputBin1Exposure=outputBin1Exposure,
1769 outputBin2Exposure=outputBin2Exposure,
1771 preInterpExposure=preInterpExp,
1772 outputExposure=ccdExposure,
1773 outputOssThumbnail=ossThumb,
1774 outputFlattenedThumbnail=flattenedThumb,
1775 outputStatistics=outputStatistics,
1776 )
1778 def defineEffectivePtc(self, ptcDataset, detector, bfGains, overScans, metadata):
1779 """Define an effective Photon Transfer Curve dataset
1780 with nominal gains and noise.
1782 Parameters
1783 ------
1784 ptcDataset : `lsst.ip.isr.PhotonTransferCurveDataset`
1785 Input Photon Transfer Curve dataset.
1786 detector : `lsst.afw.cameraGeom.Detector`
1787 Detector object.
1788 bfGains : `dict`
1789 Gains from running the brighter-fatter code.
1790 A dict keyed by amplifier name for the detector
1791 in question.
1792 ovserScans : `list` [`lsst.pipe.base.Struct`]
1793 List of overscanResults structures
1794 metadata : `lsst.daf.base.PropertyList`
1795 Exposure metadata to update gain and noise provenance.
1797 Returns
1798 -------
1799 effectivePtc : `lsst.ip.isr.PhotonTransferCurveDataset`
1800 PTC dataset containing gains and readout noise
1801 values to be used throughout
1802 Instrument Signature Removal.
1803 """
1804 amps = detector.getAmplifiers()
1805 ampNames = [amp.getName() for amp in amps]
1806 detName = detector.getName()
1807 effectivePtc = PhotonTransferCurveDataset(ampNames, 'EFFECTIVE_PTC', 1)
1808 boolGainMismatch = False
1810 for amp, overscanResults in zip(amps, overScans):
1811 ampName = amp.getName()
1812 # Gain:
1813 # Try first with the PTC gains.
1814 gainProvenanceString = "amp"
1815 if self.config.usePtcGains:
1816 gain = ptcDataset.gain[ampName]
1817 gainProvenanceString = "ptc"
1818 self.log.debug("Using gain from Photon Transfer Curve.")
1819 else:
1820 # Try then with the amplifier gain.
1821 # We already have a detector at this point. If there was no
1822 # detector to begin with, one would have been created with
1823 # self.config.gain and self.config.noise. Same comment
1824 # applies for the noise block below.
1825 gain = amp.getGain()
1827 # Check if the gain up to this point differs from the
1828 # gain in bfGains. If so, raise or warn, accordingly.
1829 if not boolGainMismatch and bfGains is not None and ampName in bfGains:
1830 bfGain = bfGains[ampName]
1831 if not math.isclose(gain, bfGain, rel_tol=1e-4):
1832 if self.config.doRaiseOnCalibMismatch:
1833 raise RuntimeError("Gain mismatch for det %s amp %s: "
1834 "(gain (%s): %s, bfGain: %s)",
1835 detName, ampName, gainProvenanceString,
1836 gain, bfGain)
1837 else:
1838 self.log.warning("Gain mismatch for det %s amp %s: "
1839 "(gain (%s): %s, bfGain: %s)",
1840 detName, ampName, gainProvenanceString,
1841 gain, bfGain)
1842 boolGainMismatch = True
1844 # Noise:
1845 # Try first with the empirical noise from the overscan.
1846 noiseProvenanceString = "amp"
1847 if self.config.doEmpiricalReadNoise and overscanResults is not None:
1848 noiseProvenanceString = "serial overscan"
1849 if isinstance(overscanResults.residualSigma, float):
1850 # Only serial overscan was run
1851 noise = overscanResults.residualSigma
1852 else:
1853 # Both serial and parallel overscan were
1854 # run. Only report noise from serial here.
1855 noise = overscanResults.residualSigma[0]
1856 elif self.config.usePtcReadNoise:
1857 # Try then with the PTC noise.
1858 noise = ptcDataset.noise[amp.getName()]
1859 noiseProvenanceString = "ptc"
1860 self.log.debug("Using noise from Photon Transfer Curve.")
1861 else:
1862 # Finally, try with the amplifier noise.
1863 # We already have a detector at this point. If there
1864 # was no detector to begin with, one would have
1865 # been created with self.config.gain and
1866 # self.config.noise.
1867 noise = amp.getReadNoise()
1869 if math.isnan(gain):
1870 gain = 1.0
1871 self.log.warning("Gain for amp %s set to NAN! Updating to"
1872 " 1.0 to generate Poisson variance.", ampName)
1873 elif gain <= 0:
1874 patchedGain = 1.0
1875 self.log.warning("Gain for amp %s == %g <= 0; setting to %f.",
1876 ampName, gain, patchedGain)
1877 gain = patchedGain
1879 effectivePtc.gain[ampName] = gain
1880 effectivePtc.noise[ampName] = noise
1881 # Make sure noise,turnoff, and gain make sense
1882 effectivePtc.validateGainNoiseTurnoffValues(ampName)
1884 metadata[f"LSST GAIN {amp.getName()}"] = effectivePtc.gain[ampName]
1885 metadata[f"LSST READNOISE {amp.getName()}"] = effectivePtc.noise[ampName]
1887 self.log.info("Det: %s - Noise provenance: %s, Gain provenance: %s",
1888 detName,
1889 noiseProvenanceString,
1890 gainProvenanceString)
1891 metadata["LSST ISR GAIN SOURCE"] = gainProvenanceString
1892 metadata["LSST ISR NOISE SOURCE"] = noiseProvenanceString
1894 return effectivePtc
1896 def ensureExposure(self, inputExp, camera=None, detectorNum=None):
1897 """Ensure that the data returned by Butler is a fully constructed exp.
1899 ISR requires exposure-level image data for historical reasons, so if we
1900 did not recieve that from Butler, construct it from what we have,
1901 modifying the input in place.
1903 Parameters
1904 ----------
1905 inputExp : `lsst.afw.image` image-type.
1906 The input data structure obtained from Butler.
1907 Can be `lsst.afw.image.Exposure`,
1908 `lsst.afw.image.DecoratedImageU`,
1909 or `lsst.afw.image.ImageF`
1910 camera : `lsst.afw.cameraGeom.camera`, optional
1911 The camera associated with the image. Used to find the appropriate
1912 detector if detector is not already set.
1913 detectorNum : `int`, optional
1914 The detector in the camera to attach, if the detector is not
1915 already set.
1917 Returns
1918 -------
1919 inputExp : `lsst.afw.image.Exposure`
1920 The re-constructed exposure, with appropriate detector parameters.
1922 Raises
1923 ------
1924 TypeError
1925 Raised if the input data cannot be used to construct an exposure.
1926 """
1927 if isinstance(inputExp, afwImage.DecoratedImageU):
1928 inputExp = afwImage.makeExposure(afwImage.makeMaskedImage(inputExp))
1929 elif isinstance(inputExp, afwImage.ImageF):
1930 inputExp = afwImage.makeExposure(afwImage.makeMaskedImage(inputExp))
1931 elif isinstance(inputExp, afwImage.MaskedImageF):
1932 inputExp = afwImage.makeExposure(inputExp)
1933 elif isinstance(inputExp, afwImage.Exposure):
1934 pass
1935 elif inputExp is None:
1936 # Assume this will be caught by the setup if it is a problem.
1937 return inputExp
1938 else:
1939 raise TypeError("Input Exposure is not known type in isrTask.ensureExposure: %s." %
1940 (type(inputExp), ))
1942 if inputExp.getDetector() is None:
1943 if camera is None or detectorNum is None:
1944 raise RuntimeError('Must supply both a camera and detector number when using exposures '
1945 'without a detector set.')
1946 inputExp.setDetector(camera[detectorNum])
1948 return inputExp
1950 @staticmethod
1951 def extractCalibDate(calib):
1952 """Extract common calibration metadata values that will be written to
1953 output header.
1955 Parameters
1956 ----------
1957 calib : `lsst.afw.image.Exposure` or `lsst.ip.isr.IsrCalib`
1958 Calibration to pull date information from.
1960 Returns
1961 -------
1962 dateString : `str`
1963 Calibration creation date string to add to header.
1964 """
1965 if hasattr(calib, "getMetadata"):
1966 if 'CALIB_CREATION_DATE' in calib.getMetadata():
1967 return " ".join((calib.getMetadata().get("CALIB_CREATION_DATE", "Unknown"),
1968 calib.getMetadata().get("CALIB_CREATION_TIME", "Unknown")))
1969 else:
1970 return " ".join((calib.getMetadata().get("CALIB_CREATE_DATE", "Unknown"),
1971 calib.getMetadata().get("CALIB_CREATE_TIME", "Unknown")))
1972 else:
1973 return "Unknown Unknown"
1975 def compareCameraKeywords(self, exposureMetadata, calib, calibName):
1976 """Compare header keywords to confirm camera states match.
1978 Parameters
1979 ----------
1980 exposureMetadata : `lsst.daf.base.PropertySet`
1981 Header for the exposure being processed.
1982 calib : `lsst.afw.image.Exposure` or `lsst.ip.isr.IsrCalib`
1983 Calibration to be applied.
1984 calibName : `str`
1985 Calib type for log message.
1986 """
1987 try:
1988 calibMetadata = calib.getMetadata()
1989 except AttributeError:
1990 return
1991 for keyword in self.config.cameraKeywordsToCompare:
1992 if keyword in exposureMetadata and keyword in calibMetadata:
1993 if exposureMetadata[keyword] != calibMetadata[keyword]:
1994 if self.config.doRaiseOnCalibMismatch:
1995 raise RuntimeError("Sequencer mismatch for %s [%s]: exposure: %s calib: %s",
1996 calibName, keyword,
1997 exposureMetadata[keyword], calibMetadata[keyword])
1998 else:
1999 self.log.warning("Sequencer mismatch for %s [%s]: exposure: %s calib: %s",
2000 calibName, keyword,
2001 exposureMetadata[keyword], calibMetadata[keyword])
2002 else:
2003 self.log.debug("Sequencer keyword %s not found.", keyword)
2005 def convertIntToFloat(self, exposure):
2006 """Convert exposure image from uint16 to float.
2008 If the exposure does not need to be converted, the input is
2009 immediately returned. For exposures that are converted to use
2010 floating point pixels, the variance is set to unity and the
2011 mask to zero.
2013 Parameters
2014 ----------
2015 exposure : `lsst.afw.image.Exposure`
2016 The raw exposure to be converted.
2018 Returns
2019 -------
2020 newexposure : `lsst.afw.image.Exposure`
2021 The input ``exposure``, converted to floating point pixels.
2023 Raises
2024 ------
2025 RuntimeError
2026 Raised if the exposure type cannot be converted to float.
2028 """
2029 if isinstance(exposure, afwImage.ExposureF):
2030 # Nothing to be done
2031 self.log.debug("Exposure already of type float.")
2032 return exposure
2033 if not hasattr(exposure, "convertF"):
2034 raise RuntimeError("Unable to convert exposure (%s) to float." % type(exposure))
2036 newexposure = exposure.convertF()
2037 newexposure.variance[:] = 1
2038 newexposure.mask[:] = 0x0
2040 return newexposure
2042 def maskAmplifier(self, ccdExposure, amp, defects):
2043 """Identify bad amplifiers, saturated and suspect pixels.
2045 Parameters
2046 ----------
2047 ccdExposure : `lsst.afw.image.Exposure`
2048 Input exposure to be masked.
2049 amp : `lsst.afw.cameraGeom.Amplifier`
2050 Catalog of parameters defining the amplifier on this
2051 exposure to mask.
2052 defects : `lsst.ip.isr.Defects`
2053 List of defects. Used to determine if the entire
2054 amplifier is bad.
2056 Returns
2057 -------
2058 badAmp : `Bool`
2059 If this is true, the entire amplifier area is covered by
2060 defects and unusable.
2062 """
2063 maskedImage = ccdExposure.getMaskedImage()
2065 badAmp = False
2067 # Check if entire amp region is defined as a defect
2068 # NB: need to use amp.getBBox() for correct comparison with current
2069 # defects definition.
2070 if defects is not None:
2071 badAmp = bool(sum([v.getBBox().contains(amp.getBBox()) for v in defects]))
2073 # In the case of a bad amp, we will set mask to "BAD"
2074 # (here use amp.getRawBBox() for correct association with pixels in
2075 # current ccdExposure).
2076 if badAmp:
2077 dataView = afwImage.MaskedImageF(maskedImage, amp.getRawBBox(),
2078 afwImage.PARENT)
2079 maskView = dataView.getMask()
2080 maskView |= maskView.getPlaneBitMask("BAD")
2081 del maskView
2082 return badAmp
2084 # Mask remaining defects after assembleCcd() to allow for defects that
2085 # cross amplifier boundaries. Saturation and suspect pixels can be
2086 # masked now, though.
2087 limits = dict()
2088 if self.config.doSaturation and not badAmp:
2089 limits.update({self.config.saturatedMaskName: amp.getSaturation()})
2090 if self.config.doSuspect and not badAmp:
2091 limits.update({self.config.suspectMaskName: amp.getSuspectLevel()})
2092 if math.isfinite(self.config.saturation):
2093 limits.update({self.config.saturatedMaskName: self.config.saturation})
2095 for maskName, maskThreshold in limits.items():
2096 if not math.isnan(maskThreshold):
2097 dataView = maskedImage.Factory(maskedImage, amp.getRawBBox())
2098 isrFunctions.makeThresholdMask(
2099 maskedImage=dataView,
2100 threshold=maskThreshold,
2101 growFootprints=0,
2102 maskName=maskName
2103 )
2105 # Determine if we've fully masked this amplifier with SUSPECT and
2106 # SAT pixels.
2107 maskView = afwImage.Mask(maskedImage.getMask(), amp.getRawDataBBox(),
2108 afwImage.PARENT)
2109 maskVal = maskView.getPlaneBitMask([self.config.saturatedMaskName,
2110 self.config.suspectMaskName])
2111 if numpy.all(maskView.getArray() & maskVal > 0):
2112 badAmp = True
2113 maskView |= maskView.getPlaneBitMask("BAD")
2115 return badAmp
2117 def overscanCorrection(self, ccdExposure, amp):
2118 """Apply overscan correction in place.
2120 This method does initial pixel rejection of the overscan
2121 region. The overscan can also be optionally segmented to
2122 allow for discontinuous overscan responses to be fit
2123 separately. The actual overscan subtraction is performed by
2124 the `lsst.ip.isr.overscan.OverscanTask`, which is called here
2125 after the amplifier is preprocessed.
2127 Parameters
2128 ----------
2129 ccdExposure : `lsst.afw.image.Exposure`
2130 Exposure to have overscan correction performed.
2131 amp : `lsst.afw.cameraGeom.Amplifer`
2132 The amplifier to consider while correcting the overscan.
2134 Returns
2135 -------
2136 overscanResults : `lsst.pipe.base.Struct`
2137 Result struct with components:
2139 ``imageFit``
2140 Value or fit subtracted from the amplifier image data.
2141 (scalar or `lsst.afw.image.Image`)
2142 ``overscanFit``
2143 Value or fit subtracted from the overscan image data.
2144 (scalar or `lsst.afw.image.Image`)
2145 ``overscanImage``
2146 Image of the overscan region with the overscan
2147 correction applied. This quantity is used to estimate
2148 the amplifier read noise empirically.
2149 (`lsst.afw.image.Image`)
2150 ``edgeMask``
2151 Mask of the suspect pixels. (`lsst.afw.image.Mask`)
2152 ``overscanMean``
2153 Median overscan fit value. (`float`)
2154 ``overscanSigma``
2155 Clipped standard deviation of the overscan after
2156 correction. (`float`)
2158 Raises
2159 ------
2160 RuntimeError
2161 Raised if the ``amp`` does not contain raw pixel information.
2163 See Also
2164 --------
2165 lsst.ip.isr.overscan.OverscanTask
2166 """
2167 if amp.getRawHorizontalOverscanBBox().isEmpty():
2168 self.log.info("ISR_OSCAN: No overscan region. Not performing overscan correction.")
2169 return None
2171 # Perform overscan correction on subregions.
2172 overscanResults = self.overscan.run(ccdExposure, amp)
2174 metadata = ccdExposure.getMetadata()
2175 ampName = amp.getName()
2177 keyBase = "LSST ISR OVERSCAN"
2178 # Updated quantities
2179 if isinstance(overscanResults.overscanMean, float):
2180 # Serial overscan correction only:
2181 metadata[f"{keyBase} SERIAL MEAN {ampName}"] = overscanResults.overscanMean
2182 metadata[f"{keyBase} SERIAL MEDIAN {ampName}"] = overscanResults.overscanMedian
2183 metadata[f"{keyBase} SERIAL STDEV {ampName}"] = overscanResults.overscanSigma
2185 metadata[f"{keyBase} RESIDUAL SERIAL MEAN {ampName}"] = overscanResults.residualMean
2186 metadata[f"{keyBase} RESIDUAL SERIAL MEDIAN {ampName}"] = overscanResults.residualMedian
2187 metadata[f"{keyBase} RESIDUAL SERIAL STDEV {ampName}"] = overscanResults.residualSigma
2188 elif isinstance(overscanResults.overscanMean, tuple):
2189 # Both serial and parallel overscan have run:
2190 metadata[f"{keyBase} SERIAL MEAN {ampName}"] = overscanResults.overscanMean[0]
2191 metadata[f"{keyBase} SERIAL MEDIAN {ampName}"] = overscanResults.overscanMedian[0]
2192 metadata[f"{keyBase} SERIAL STDEV {ampName}"] = overscanResults.overscanSigma[0]
2194 metadata[f"{keyBase} PARALLEL MEAN {ampName}"] = overscanResults.overscanMean[1]
2195 metadata[f"{keyBase} PARALLEL MEDIAN {ampName}"] = overscanResults.overscanMedian[1]
2196 metadata[f"{keyBase} PARALLEL STDEV {ampName}"] = overscanResults.overscanSigma[1]
2198 metadata[f"{keyBase} RESIDUAL SERIAL MEAN {ampName}"] = overscanResults.residualMean[0]
2199 metadata[f"{keyBase} RESIDUAL SERIAL MEDIAN {ampName}"] = overscanResults.residualMedian[0]
2200 metadata[f"{keyBase} RESIDUAL SERIAL STDEV {ampName}"] = overscanResults.residualSigma[0]
2202 metadata[f"{keyBase} RESIDUAL PARALLEL MEAN {ampName}"] = overscanResults.residualMean[1]
2203 metadata[f"{keyBase} RESIDUAL PARALLEL MEDIAN {ampName}"] = overscanResults.residualMedian[1]
2204 metadata[f"{keyBase} RESIDUAL PARALLEL STDEV {ampName}"] = overscanResults.residualSigma[1]
2205 else:
2206 self.log.warning("Unexpected type for overscan values; none added to header.")
2208 return overscanResults
2210 def updateVariance(self, ampExposure, amp, ptcDataset):
2211 """Set the variance plane using the gain and read noise
2213 The read noise is calculated from the ``overscanImage`` if the
2214 ``doEmpiricalReadNoise`` option is set in the configuration; otherwise
2215 the value from the amplifier data is used.
2217 Parameters
2218 ----------
2219 ampExposure : `lsst.afw.image.Exposure`
2220 Exposure to process.
2221 amp : `lsst.afw.cameraGeom.Amplifier` or `FakeAmp`
2222 Amplifier detector data.
2223 ptcDataset : `lsst.ip.isr.PhotonTransferCurveDataset`
2224 Effective PTC dataset containing the gains and read noise.
2226 See also
2227 --------
2228 lsst.ip.isr.isrFunctions.updateVariance
2229 """
2230 ampName = amp.getName()
2231 # At this point, the effective PTC should have
2232 # gain and noise values.
2233 gain = ptcDataset.gain[ampName]
2234 readNoise = ptcDataset.noise[ampName]
2236 isrFunctions.updateVariance(
2237 maskedImage=ampExposure.getMaskedImage(),
2238 gain=gain,
2239 readNoise=readNoise,
2240 )
2242 def maskNegativeVariance(self, exposure):
2243 """Identify and mask pixels with negative variance values.
2245 Parameters
2246 ----------
2247 exposure : `lsst.afw.image.Exposure`
2248 Exposure to process.
2250 See Also
2251 --------
2252 lsst.ip.isr.isrFunctions.updateVariance
2253 """
2254 maskPlane = exposure.getMask().getPlaneBitMask(self.config.negativeVarianceMaskName)
2255 bad = numpy.where(exposure.getVariance().getArray() <= 0.0)
2256 exposure.mask.array[bad] |= maskPlane
2258 def darkCorrection(self, exposure, darkExposure, invert=False):
2259 """Apply dark correction in place.
2261 Parameters
2262 ----------
2263 exposure : `lsst.afw.image.Exposure`
2264 Exposure to process.
2265 darkExposure : `lsst.afw.image.Exposure`
2266 Dark exposure of the same size as ``exposure``.
2267 invert : `Bool`, optional
2268 If True, re-add the dark to an already corrected image.
2270 Raises
2271 ------
2272 RuntimeError
2273 Raised if either ``exposure`` or ``darkExposure`` do not
2274 have their dark time defined.
2276 See Also
2277 --------
2278 lsst.ip.isr.isrFunctions.darkCorrection
2279 """
2280 expScale = exposure.getInfo().getVisitInfo().getDarkTime()
2281 if math.isnan(expScale):
2282 raise RuntimeError("Exposure darktime is NAN.")
2283 if darkExposure.getInfo().getVisitInfo() is not None \
2284 and not math.isnan(darkExposure.getInfo().getVisitInfo().getDarkTime()):
2285 darkScale = darkExposure.getInfo().getVisitInfo().getDarkTime()
2286 else:
2287 # DM-17444: darkExposure.getInfo.getVisitInfo() is None
2288 # so getDarkTime() does not exist.
2289 self.log.warning("darkExposure.getInfo().getVisitInfo() does not exist. Using darkScale = 1.0.")
2290 darkScale = 1.0
2292 isrFunctions.darkCorrection(
2293 maskedImage=exposure.getMaskedImage(),
2294 darkMaskedImage=darkExposure.getMaskedImage(),
2295 expScale=expScale,
2296 darkScale=darkScale,
2297 invert=invert,
2298 trimToFit=self.config.doTrimToMatchCalib
2299 )
2301 def doLinearize(self, detector):
2302 """Check if linearization is needed for the detector cameraGeom.
2304 Checks config.doLinearize and the linearity type of the first
2305 amplifier.
2307 Parameters
2308 ----------
2309 detector : `lsst.afw.cameraGeom.Detector`
2310 Detector to get linearity type from.
2312 Returns
2313 -------
2314 doLinearize : `Bool`
2315 If True, linearization should be performed.
2316 """
2317 return self.config.doLinearize and \
2318 detector.getAmplifiers()[0].getLinearityType() != NullLinearityType
2320 def flatCorrection(self, exposure, flatExposure, invert=False):
2321 """Apply flat correction in place.
2323 Parameters
2324 ----------
2325 exposure : `lsst.afw.image.Exposure`
2326 Exposure to process.
2327 flatExposure : `lsst.afw.image.Exposure`
2328 Flat exposure of the same size as ``exposure``.
2329 invert : `Bool`, optional
2330 If True, unflatten an already flattened image.
2332 See Also
2333 --------
2334 lsst.ip.isr.isrFunctions.flatCorrection
2335 """
2336 isrFunctions.flatCorrection(
2337 maskedImage=exposure.getMaskedImage(),
2338 flatMaskedImage=flatExposure.getMaskedImage(),
2339 scalingType=self.config.flatScalingType,
2340 userScale=self.config.flatUserScale,
2341 invert=invert,
2342 trimToFit=self.config.doTrimToMatchCalib
2343 )
2345 def saturationDetection(self, exposure, amp):
2346 """Detect and mask saturated pixels in config.saturatedMaskName.
2348 Parameters
2349 ----------
2350 exposure : `lsst.afw.image.Exposure`
2351 Exposure to process. Only the amplifier DataSec is processed.
2352 amp : `lsst.afw.cameraGeom.Amplifier`
2353 Amplifier detector data.
2355 See Also
2356 --------
2357 lsst.ip.isr.isrFunctions.makeThresholdMask
2358 """
2359 if not math.isnan(amp.getSaturation()):
2360 maskedImage = exposure.getMaskedImage()
2361 dataView = maskedImage.Factory(maskedImage, amp.getRawBBox())
2362 isrFunctions.makeThresholdMask(
2363 maskedImage=dataView,
2364 threshold=amp.getSaturation(),
2365 growFootprints=0,
2366 maskName=self.config.saturatedMaskName,
2367 )
2369 def saturationInterpolation(self, exposure):
2370 """Interpolate over saturated pixels, in place.
2372 This method should be called after `saturationDetection`, to
2373 ensure that the saturated pixels have been identified in the
2374 SAT mask. It should also be called after `assembleCcd`, since
2375 saturated regions may cross amplifier boundaries.
2377 Parameters
2378 ----------
2379 exposure : `lsst.afw.image.Exposure`
2380 Exposure to process.
2382 See Also
2383 --------
2384 lsst.ip.isr.isrTask.saturationDetection
2385 lsst.ip.isr.isrFunctions.interpolateFromMask
2386 """
2387 isrFunctions.interpolateFromMask(
2388 maskedImage=exposure.getMaskedImage(),
2389 fwhm=self.config.fwhm,
2390 growSaturatedFootprints=self.config.growSaturationFootprintSize,
2391 maskNameList=list(self.config.saturatedMaskName),
2392 )
2394 def suspectDetection(self, exposure, amp):
2395 """Detect and mask suspect pixels in config.suspectMaskName.
2397 Parameters
2398 ----------
2399 exposure : `lsst.afw.image.Exposure`
2400 Exposure to process. Only the amplifier DataSec is processed.
2401 amp : `lsst.afw.cameraGeom.Amplifier`
2402 Amplifier detector data.
2404 See Also
2405 --------
2406 lsst.ip.isr.isrFunctions.makeThresholdMask
2408 Notes
2409 -----
2410 Suspect pixels are pixels whose value is greater than
2411 amp.getSuspectLevel(). This is intended to indicate pixels that may be
2412 affected by unknown systematics; for example if non-linearity
2413 corrections above a certain level are unstable then that would be a
2414 useful value for suspectLevel. A value of `nan` indicates that no such
2415 level exists and no pixels are to be masked as suspicious.
2416 """
2417 suspectLevel = amp.getSuspectLevel()
2418 if math.isnan(suspectLevel):
2419 return
2421 maskedImage = exposure.getMaskedImage()
2422 dataView = maskedImage.Factory(maskedImage, amp.getRawBBox())
2423 isrFunctions.makeThresholdMask(
2424 maskedImage=dataView,
2425 threshold=suspectLevel,
2426 growFootprints=0,
2427 maskName=self.config.suspectMaskName,
2428 )
2430 def maskDefect(self, exposure, defectBaseList):
2431 """Mask defects using mask plane "BAD", in place.
2433 Parameters
2434 ----------
2435 exposure : `lsst.afw.image.Exposure`
2436 Exposure to process.
2437 defectBaseList : defect-type
2438 List of defects to mask. Can be of type `lsst.ip.isr.Defects`
2439 or `list` of `lsst.afw.image.DefectBase`.
2441 Notes
2442 -----
2443 Call this after CCD assembly, since defects may cross amplifier
2444 boundaries.
2445 """
2446 maskedImage = exposure.getMaskedImage()
2447 if not isinstance(defectBaseList, Defects):
2448 # Promotes DefectBase to Defect
2449 defectList = Defects(defectBaseList)
2450 else:
2451 defectList = defectBaseList
2452 defectList.maskPixels(maskedImage, maskName="BAD")
2454 def maskEdges(self, exposure, numEdgePixels=0, maskPlane="SUSPECT", level='DETECTOR'):
2455 """Mask edge pixels with applicable mask plane.
2457 Parameters
2458 ----------
2459 exposure : `lsst.afw.image.Exposure`
2460 Exposure to process.
2461 numEdgePixels : `int`, optional
2462 Number of edge pixels to mask.
2463 maskPlane : `str`, optional
2464 Mask plane name to use.
2465 level : `str`, optional
2466 Level at which to mask edges.
2467 """
2468 maskedImage = exposure.getMaskedImage()
2469 maskBitMask = maskedImage.getMask().getPlaneBitMask(maskPlane)
2471 if numEdgePixels > 0:
2472 if level == 'DETECTOR':
2473 boxes = [maskedImage.getBBox()]
2474 elif level == 'AMP':
2475 boxes = [amp.getBBox() for amp in exposure.getDetector()]
2477 for box in boxes:
2478 # This makes a bbox numEdgeSuspect pixels smaller than the
2479 # image on each side
2480 subImage = maskedImage[box]
2481 box.grow(-numEdgePixels)
2482 # Mask pixels outside box
2483 SourceDetectionTask.setEdgeBits(
2484 subImage,
2485 box,
2486 maskBitMask)
2488 def maskAndInterpolateDefects(self, exposure, defectBaseList):
2489 """Mask and interpolate defects using mask plane "BAD", in place.
2491 Parameters
2492 ----------
2493 exposure : `lsst.afw.image.Exposure`
2494 Exposure to process.
2495 defectBaseList : defects-like
2496 List of defects to mask and interpolate. Can be
2497 `lsst.ip.isr.Defects` or `list` of `lsst.afw.image.DefectBase`.
2499 See Also
2500 --------
2501 lsst.ip.isr.isrTask.maskDefect
2502 """
2503 self.maskDefect(exposure, defectBaseList)
2504 self.maskEdges(exposure, numEdgePixels=self.config.numEdgeSuspect,
2505 maskPlane="SUSPECT", level=self.config.edgeMaskLevel)
2506 isrFunctions.interpolateFromMask(
2507 maskedImage=exposure.getMaskedImage(),
2508 fwhm=self.config.fwhm,
2509 growSaturatedFootprints=0,
2510 maskNameList=["BAD"],
2511 )
2513 def maskNan(self, exposure):
2514 """Mask NaNs using mask plane "UNMASKEDNAN", in place.
2516 Parameters
2517 ----------
2518 exposure : `lsst.afw.image.Exposure`
2519 Exposure to process.
2521 Notes
2522 -----
2523 We mask over all non-finite values (NaN, inf), including those
2524 that are masked with other bits (because those may or may not be
2525 interpolated over later, and we want to remove all NaN/infs).
2526 Despite this behaviour, the "UNMASKEDNAN" mask plane is used to
2527 preserve the historical name.
2528 """
2529 maskedImage = exposure.getMaskedImage()
2531 # Find and mask NaNs
2532 maskedImage.getMask().addMaskPlane("UNMASKEDNAN")
2533 maskVal = maskedImage.getMask().getPlaneBitMask("UNMASKEDNAN")
2534 numNans = maskNans(maskedImage, maskVal)
2535 self.metadata["NUMNANS"] = numNans
2536 if numNans > 0:
2537 self.log.warning("There were %d unmasked NaNs.", numNans)
2539 def maskAndInterpolateNan(self, exposure):
2540 """"Mask and interpolate NaN/infs using mask plane "UNMASKEDNAN",
2541 in place.
2543 Parameters
2544 ----------
2545 exposure : `lsst.afw.image.Exposure`
2546 Exposure to process.
2548 See Also
2549 --------
2550 lsst.ip.isr.isrTask.maskNan
2551 """
2552 self.maskNan(exposure)
2553 isrFunctions.interpolateFromMask(
2554 maskedImage=exposure.getMaskedImage(),
2555 fwhm=self.config.fwhm,
2556 growSaturatedFootprints=0,
2557 maskNameList=["UNMASKEDNAN"],
2558 )
2560 def measureBackground(self, exposure, IsrQaConfig=None):
2561 """Measure the image background in subgrids, for quality control.
2563 Parameters
2564 ----------
2565 exposure : `lsst.afw.image.Exposure`
2566 Exposure to process.
2567 IsrQaConfig : `lsst.ip.isr.isrQa.IsrQaConfig`
2568 Configuration object containing parameters on which background
2569 statistics and subgrids to use.
2570 """
2571 if IsrQaConfig is not None:
2572 statsControl = afwMath.StatisticsControl(IsrQaConfig.flatness.clipSigma,
2573 IsrQaConfig.flatness.nIter)
2574 maskVal = exposure.getMaskedImage().getMask().getPlaneBitMask(["BAD", "SAT", "DETECTED"])
2575 statsControl.setAndMask(maskVal)
2576 maskedImage = exposure.getMaskedImage()
2577 stats = afwMath.makeStatistics(maskedImage, afwMath.MEDIAN | afwMath.STDEVCLIP, statsControl)
2578 skyLevel = stats.getValue(afwMath.MEDIAN)
2579 skySigma = stats.getValue(afwMath.STDEVCLIP)
2580 self.log.info("Flattened sky level: %f +/- %f.", skyLevel, skySigma)
2581 metadata = exposure.getMetadata()
2582 metadata["SKYLEVEL"] = skyLevel
2583 metadata["SKYSIGMA"] = skySigma
2585 # calcluating flatlevel over the subgrids
2586 stat = afwMath.MEANCLIP if IsrQaConfig.flatness.doClip else afwMath.MEAN
2587 meshXHalf = int(IsrQaConfig.flatness.meshX/2.)
2588 meshYHalf = int(IsrQaConfig.flatness.meshY/2.)
2589 nX = int((exposure.getWidth() + meshXHalf) / IsrQaConfig.flatness.meshX)
2590 nY = int((exposure.getHeight() + meshYHalf) / IsrQaConfig.flatness.meshY)
2591 skyLevels = numpy.zeros((nX, nY))
2593 for j in range(nY):
2594 yc = meshYHalf + j * IsrQaConfig.flatness.meshY
2595 for i in range(nX):
2596 xc = meshXHalf + i * IsrQaConfig.flatness.meshX
2598 xLLC = xc - meshXHalf
2599 yLLC = yc - meshYHalf
2600 xURC = xc + meshXHalf - 1
2601 yURC = yc + meshYHalf - 1
2603 bbox = lsst.geom.Box2I(lsst.geom.Point2I(xLLC, yLLC), lsst.geom.Point2I(xURC, yURC))
2604 miMesh = maskedImage.Factory(exposure.getMaskedImage(), bbox, afwImage.LOCAL)
2606 skyLevels[i, j] = afwMath.makeStatistics(miMesh, stat, statsControl).getValue()
2608 good = numpy.where(numpy.isfinite(skyLevels))
2609 skyMedian = numpy.median(skyLevels[good])
2610 flatness = (skyLevels[good] - skyMedian) / skyMedian
2611 flatness_rms = numpy.std(flatness)
2612 flatness_pp = flatness.max() - flatness.min() if len(flatness) > 0 else numpy.nan
2614 self.log.info("Measuring sky levels in %dx%d grids: %f.", nX, nY, skyMedian)
2615 self.log.info("Sky flatness in %dx%d grids - pp: %f rms: %f.",
2616 nX, nY, flatness_pp, flatness_rms)
2618 metadata["FLATNESS_PP"] = float(flatness_pp)
2619 metadata["FLATNESS_RMS"] = float(flatness_rms)
2620 metadata["FLATNESS_NGRIDS"] = '%dx%d' % (nX, nY)
2621 metadata["FLATNESS_MESHX"] = IsrQaConfig.flatness.meshX
2622 metadata["FLATNESS_MESHY"] = IsrQaConfig.flatness.meshY
2624 def roughZeroPoint(self, exposure):
2625 """Set an approximate magnitude zero point for the exposure.
2627 Parameters
2628 ----------
2629 exposure : `lsst.afw.image.Exposure`
2630 Exposure to process.
2631 """
2632 filterLabel = exposure.getFilter()
2633 physicalFilter = isrFunctions.getPhysicalFilter(filterLabel, self.log)
2635 if physicalFilter in self.config.fluxMag0T1:
2636 fluxMag0 = self.config.fluxMag0T1[physicalFilter]
2637 else:
2638 self.log.warning("No rough magnitude zero point defined for filter %s.", physicalFilter)
2639 fluxMag0 = self.config.defaultFluxMag0T1
2641 expTime = exposure.getInfo().getVisitInfo().getExposureTime()
2642 if not expTime > 0: # handle NaN as well as <= 0
2643 self.log.warning("Non-positive exposure time; skipping rough zero point.")
2644 return
2646 self.log.info("Setting rough magnitude zero point for filter %s: %f",
2647 physicalFilter, 2.5*math.log10(fluxMag0*expTime))
2648 exposure.setPhotoCalib(afwImage.makePhotoCalibFromCalibZeroPoint(fluxMag0*expTime, 0.0))
2650 @contextmanager
2651 def flatContext(self, exp, flat, dark=None):
2652 """Context manager that applies and removes flats and darks,
2653 if the task is configured to apply them.
2655 Parameters
2656 ----------
2657 exp : `lsst.afw.image.Exposure`
2658 Exposure to process.
2659 flat : `lsst.afw.image.Exposure`
2660 Flat exposure the same size as ``exp``.
2661 dark : `lsst.afw.image.Exposure`, optional
2662 Dark exposure the same size as ``exp``.
2664 Yields
2665 ------
2666 exp : `lsst.afw.image.Exposure`
2667 The flat and dark corrected exposure.
2668 """
2669 if self.config.doDark and dark is not None:
2670 self.darkCorrection(exp, dark)
2671 if self.config.doFlat:
2672 self.flatCorrection(exp, flat)
2673 try:
2674 yield exp
2675 finally:
2676 if self.config.doFlat:
2677 self.flatCorrection(exp, flat, invert=True)
2678 if self.config.doDark and dark is not None:
2679 self.darkCorrection(exp, dark, invert=True)
2681 def makeBinnedImages(self, exposure):
2682 """Make visualizeVisit style binned exposures.
2684 Parameters
2685 ----------
2686 exposure : `lsst.afw.image.Exposure`
2687 Exposure to bin.
2689 Returns
2690 -------
2691 bin1 : `lsst.afw.image.Exposure`
2692 Binned exposure using binFactor1.
2693 bin2 : `lsst.afw.image.Exposure`
2694 Binned exposure using binFactor2.
2695 """
2696 mi = exposure.getMaskedImage()
2698 bin1 = afwMath.binImage(mi, self.config.binFactor1)
2699 bin2 = afwMath.binImage(mi, self.config.binFactor2)
2701 return bin1, bin2
2703 def debugView(self, exposure, stepname):
2704 """Utility function to examine ISR exposure at different stages.
2706 Parameters
2707 ----------
2708 exposure : `lsst.afw.image.Exposure`
2709 Exposure to view.
2710 stepname : `str`
2711 State of processing to view.
2712 """
2713 frame = getDebugFrame(self._display, stepname)
2714 if frame:
2715 display = getDisplay(frame)
2716 display.scale('asinh', 'zscale')
2717 display.mtv(exposure)
2718 prompt = "Press Enter to continue [c]... "
2719 while True:
2720 ans = input(prompt).lower()
2721 if ans in ("", "c",):
2722 break
2725class FakeAmp(object):
2726 """A Detector-like object that supports returning gain and saturation level
2728 This is used when the input exposure does not have a detector.
2730 Parameters
2731 ----------
2732 exposure : `lsst.afw.image.Exposure`
2733 Exposure to generate a fake amplifier for.
2734 config : `lsst.ip.isr.isrTaskConfig`
2735 Configuration to apply to the fake amplifier.
2736 """
2738 def __init__(self, exposure, config):
2739 self._bbox = exposure.getBBox(afwImage.LOCAL)
2740 self._RawHorizontalOverscanBBox = lsst.geom.Box2I()
2741 self._gain = config.gain
2742 self._readNoise = config.readNoise
2743 self._saturation = config.saturation
2745 def getBBox(self):
2746 return self._bbox
2748 def getRawBBox(self):
2749 return self._bbox
2751 def getRawHorizontalOverscanBBox(self):
2752 return self._RawHorizontalOverscanBBox
2754 def getGain(self):
2755 return self._gain
2757 def getReadNoise(self):
2758 return self._readNoise
2760 def getSaturation(self):
2761 return self._saturation
2763 def getSuspectLevel(self):
2764 return float("NaN")