lsst.ip.isr ga92a4e6fc1+12d102fd6a
Loading...
Searching...
No Matches
isrTaskLSST.py
Go to the documentation of this file.
1__all__ = ["IsrTaskLSST", "IsrTaskLSSTConfig"]
2
3import numpy
4import math
5import copy
6
7from . import isrFunctions
8from . import isrQa
9from .defects import Defects
10
11from contextlib import contextmanager
12from deprecated.sphinx import deprecated
13import lsst.pex.config as pexConfig
14import lsst.afw.math as afwMath
15import lsst.pipe.base as pipeBase
16import lsst.afw.image as afwImage
17import lsst.pipe.base.connectionTypes as cT
18from lsst.pipe.base import UnprocessableDataError
19from lsst.meas.algorithms.detection import SourceDetectionTask
20import lsst.afw.detection as afwDetection
21
22from .ampOffset import AmpOffsetTask
23from .binImageDataTask import BinImageDataTask
24from .overscan import SerialOverscanCorrectionTask, ParallelOverscanCorrectionTask
25from .overscanAmpConfig import OverscanCameraConfig
26from .assembleCcdTask import AssembleCcdTask
27from .deferredCharge import DeferredChargeTask
28from .crosstalk import CrosstalkTask
29from .masking import MaskingTask
30from .isrStatistics import IsrStatisticsTask
31from .isr import maskNans
32from .ptcDataset import PhotonTransferCurveDataset
33from .isrFunctions import isTrimmedExposure, compareCameraKeywords
34from .brighterFatterKernel import (brighterFatterCorrection,
35 fluxConservingBrighterFatterCorrection)
36from .electrostaticBrighterFatter import electrostaticBrighterFatterCorrection
37
38
39class IsrTaskLSSTConnections(pipeBase.PipelineTaskConnections,
40 dimensions={"instrument", "exposure", "detector"},
41 defaultTemplates={}):
42 ccdExposure = cT.Input(
43 name="raw",
44 doc="Input exposure to process.",
45 storageClass="Exposure",
46 dimensions=["instrument", "exposure", "detector"],
47 )
48 camera = cT.PrerequisiteInput(
49 name="camera",
50 storageClass="Camera",
51 doc="Input camera to construct complete exposures.",
52 dimensions=["instrument"],
53 isCalibration=True,
54 )
55 dnlLUT = cT.PrerequisiteInput(
56 name="dnlLUT",
57 doc="Look-up table for differential non-linearity.",
58 storageClass="IsrCalib",
59 dimensions=["instrument", "exposure", "detector"],
60 isCalibration=True,
61 # TODO DM 36636
62 )
63 bias = cT.PrerequisiteInput(
64 name="bias",
65 doc="Input bias calibration.",
66 storageClass="ExposureF",
67 dimensions=["instrument", "detector"],
68 isCalibration=True,
69 )
70 deferredChargeCalib = cT.PrerequisiteInput(
71 name="cti",
72 doc="Deferred charge/CTI correction dataset.",
73 storageClass="IsrCalib",
74 dimensions=["instrument", "detector"],
75 isCalibration=True,
76 )
77 linearizer = cT.PrerequisiteInput(
78 name='linearizer',
79 storageClass="Linearizer",
80 doc="Linearity correction calibration.",
81 dimensions=["instrument", "detector"],
82 isCalibration=True,
83 )
84 ptc = cT.PrerequisiteInput(
85 name="ptc",
86 doc="Input Photon Transfer Curve dataset",
87 storageClass="PhotonTransferCurveDataset",
88 dimensions=["instrument", "detector"],
89 isCalibration=True,
90 )
91 gainCorrection = cT.PrerequisiteInput(
92 name="gain_correction",
93 doc="Gain correction dataset",
94 storageClass="IsrCalib",
95 dimensions=["instrument", "detector"],
96 isCalibration=True,
97 minimum=0,
98 )
99 crosstalk = cT.PrerequisiteInput(
100 name="crosstalk",
101 doc="Input crosstalk object",
102 storageClass="CrosstalkCalib",
103 dimensions=["instrument", "detector"],
104 isCalibration=True,
105 )
106 defects = cT.PrerequisiteInput(
107 name='defects',
108 doc="Input defect tables.",
109 storageClass="Defects",
110 dimensions=["instrument", "detector"],
111 isCalibration=True,
112 )
113 bfKernel = cT.PrerequisiteInput(
114 name="bfk",
115 doc="Complete kernel + gain solutions.",
116 storageClass="BrighterFatterKernel",
117 dimensions=["instrument", "detector"],
118 isCalibration=True,
119 )
120 electroBfDistortionMatrix = cT.PrerequisiteInput(
121 name="electroBfDistortionMatrix",
122 doc="Electrostatic BF solution",
123 storageClass="IsrCalib",
124 dimensions=["instrument", "detector"],
125 isCalibration=True,
126 )
127 dark = cT.PrerequisiteInput(
128 name='dark',
129 doc="Input dark calibration.",
130 storageClass="ExposureF",
131 dimensions=["instrument", "detector"],
132 isCalibration=True,
133 )
134 flat = cT.PrerequisiteInput(
135 name="flat",
136 doc="Input flat calibration.",
137 storageClass="ExposureF",
138 dimensions=["instrument", "detector", "physical_filter"],
139 isCalibration=True,
140 )
141 outputExposure = cT.Output(
142 name='postISRCCD',
143 doc="Output ISR processed exposure.",
144 storageClass="Exposure",
145 dimensions=["instrument", "exposure", "detector"],
146 )
147 preInterpExposure = cT.Output(
148 name='preInterpISRCCD',
149 doc="Output ISR processed exposure, with pixels left uninterpolated.",
150 storageClass="ExposureF",
151 dimensions=["instrument", "exposure", "detector"],
152 )
153 outputBin1Exposure = cT.Output(
154 name="postIsrBin1",
155 doc="First binned image.",
156 storageClass="ExposureF",
157 dimensions=["instrument", "exposure", "detector"],
158 )
159 outputBin2Exposure = cT.Output(
160 name="postIsrBin2",
161 doc="Second binned image.",
162 storageClass="ExposureF",
163 dimensions=["instrument", "exposure", "detector"],
164 )
165
166 outputStatistics = cT.Output(
167 name="isrStatistics",
168 doc="Output of additional statistics table.",
169 storageClass="StructuredDataDict",
170 dimensions=["instrument", "exposure", "detector"],
171 )
172
173 def __init__(self, *, config=None):
174 super().__init__(config=config)
175
176 doApplyGains = config.doApplyGains
177 useLinearizerGains = config.useGainsFrom == "LINEARIZER"
178
179 if config.doBootstrap or (doApplyGains and useLinearizerGains):
180 del self.ptc
181 if not config.doCorrectGains:
182 del self.gainCorrection
183 if config.doDiffNonLinearCorrection is not True:
184 del self.dnlLUT
185 if config.doBias is not True:
186 del self.bias
187 if config.doDeferredCharge is not True:
188 del self.deferredChargeCalib
189 if (config.doLinearize or (doApplyGains and useLinearizerGains)) is not True:
190 del self.linearizer
191
192 if not config.doCrosstalk:
193 del self.crosstalk
194 if config.doDefect is not True:
195 del self.defects
196 if config.doBrighterFatter is not True:
197 del self.bfKernel
199 else:
200 if config.brighterFatterCorrectionMethod.startswith("COULTON"):
202 else:
203 del self.bfKernel
204 if config.doDark is not True:
205 del self.dark
206 if config.doFlat is not True:
207 del self.flat
208
209 if config.doBinnedExposures is not True:
210 del self.outputBin1Exposure
211 del self.outputBin2Exposure
212 if config.doSaveInterpPixels is not True:
213 del self.preInterpExposure
214
215 if config.doCalculateStatistics is not True:
216 del self.outputStatistics
217
218
219class IsrTaskLSSTConfig(pipeBase.PipelineTaskConfig,
220 pipelineConnections=IsrTaskLSSTConnections):
221 """Configuration parameters for IsrTaskLSST.
222
223 Items are grouped in the order in which they are executed by the task.
224 """
225 expectWcs = pexConfig.Field(
226 dtype=bool,
227 default=True,
228 doc="Expect input science images to have a WCS (set False for e.g. spectrographs)."
229 )
230 qa = pexConfig.ConfigField(
231 dtype=isrQa.IsrQaConfig,
232 doc="QA related configuration options.",
233 )
234 doHeaderProvenance = pexConfig.Field(
235 dtype=bool,
236 default=True,
237 doc="Write calibration identifiers into output exposure header.",
238 )
239
240 # Calib checking configuration:
241 doRaiseOnCalibMismatch = pexConfig.Field(
242 dtype=bool,
243 default=False,
244 doc="Should IsrTaskLSST halt if exposure and calibration header values do not match?",
245 )
246 cameraKeywordsToCompare = pexConfig.ListField(
247 dtype=str,
248 doc="List of header keywords to compare between exposure and calibrations.",
249 default=[],
250 )
251
252 # Differential non-linearity correction.
253 doDiffNonLinearCorrection = pexConfig.Field(
254 dtype=bool,
255 doc="Do differential non-linearity correction?",
256 default=False,
257 )
258
259 doBootstrap = pexConfig.Field(
260 dtype=bool,
261 default=False,
262 doc="Is this task to be run in a ``bootstrap`` fashion that does not require "
263 "a PTC or full calibrations?",
264 )
265
266 doCheckUnprocessableData = pexConfig.Field(
267 dtype=bool,
268 default=True,
269 doc="Check if this image is completely unprocessable due to all bad amps.",
270 )
271
272 overscanCamera = pexConfig.ConfigField(
273 dtype=OverscanCameraConfig,
274 doc="Per-detector and per-amplifier overscan configurations.",
275 )
276
277 serialOverscanMedianShiftSigmaThreshold = pexConfig.Field(
278 dtype=float,
279 default=numpy.inf,
280 doc="Number of sigma difference from per-amp overscan median (as compared to PTC) to "
281 "check if an amp is in a different state than the baseline PTC calib and should "
282 "be marked BAD. Set to np.inf/np.nan to turn off overscan median checking.",
283 )
284
285 ampNoiseThreshold = pexConfig.Field(
286 dtype=float,
287 default=25.0,
288 doc="Maximum amplifier noise (e-) that is allowed before an amp is masked as bad. "
289 "Set to np.inf/np.nan to turn off noise checking.",
290 )
291
292 bssVoltageMinimum = pexConfig.Field(
293 dtype=float,
294 default=5.0,
295 doc="Minimum back-side bias voltage. Below this the detector is ``off`` and an "
296 "UnprocessableDataError will be logged. Check will be skipped if doCheckUnprocessableData "
297 "is False or if value is less than or equal to 0.",
298 )
299 bssVoltageKeyword = pexConfig.Field(
300 dtype=str,
301 default="BSSVBS",
302 doc="Back-side bias voltage header keyword. Only checked if doCheckUnprocessableData is True "
303 "and bssVoltageMinimum is greater than 0.",
304 )
305 hvBiasKeyword = pexConfig.Field(
306 dtype=str,
307 default="HVBIAS",
308 doc="Back-side bias voltage on/off header keyword. Only checked if doCheckUnprocessableData is True "
309 "and bssVoltageMinimum is greater than 0.",
310 )
311
312 # Amplifier to CCD assembly configuration.
313 doAssembleCcd = pexConfig.Field(
314 dtype=bool,
315 default=True,
316 doc="Assemble amp-level exposures into a ccd-level exposure?"
317 )
318 assembleCcd = pexConfig.ConfigurableField(
319 target=AssembleCcdTask,
320 doc="CCD assembly task.",
321 )
322
323 # Bias subtraction.
324 doBias = pexConfig.Field(
325 dtype=bool,
326 doc="Apply bias frame correction?",
327 default=True,
328 )
329
330 # Deferred charge correction.
331 doDeferredCharge = pexConfig.Field(
332 dtype=bool,
333 doc="Apply deferred charge correction?",
334 default=True,
335 )
336 deferredChargeCorrection = pexConfig.ConfigurableField(
337 target=DeferredChargeTask,
338 doc="Deferred charge correction task.",
339 )
340
341 # Linearization.
342 doLinearize = pexConfig.Field(
343 dtype=bool,
344 doc="Correct for nonlinearity of the detector's response?",
345 default=True,
346 )
347
348 # Gains.
349 doCorrectGains = pexConfig.Field(
350 dtype=bool,
351 doc="Apply gain corrections from detector restarts?",
352 default=True,
353 )
354 doApplyGains = pexConfig.Field(
355 dtype=bool,
356 doc="Apply gains to the image?",
357 default=True,
358 )
359 useGainsFrom = pexConfig.ChoiceField(
360 dtype=str,
361 doc="Where to retrieve the gains. Unused if doBootstrap is True.",
362 allowed={
363 "PTC": "Use the gains from the inputPtc calibration.",
364 "LINEARIZER": "Use the gains from the linearizer calibration.",
365 },
366 default="PTC",
367 )
368
369 # Variance construction.
370 doVariance = pexConfig.Field(
371 dtype=bool,
372 doc="Calculate variance?",
373 default=True
374 )
375 maskNegativeVariance = pexConfig.Field(
376 dtype=bool,
377 doc="Mask pixels that claim a negative variance. This likely indicates a failure "
378 "in the measurement of the overscan at an edge due to the data falling off faster "
379 "than the overscan model can account for it.",
380 default=True,
381 )
382 negativeVarianceMaskName = pexConfig.Field(
383 dtype=str,
384 doc="Mask plane to use to mark pixels with negative variance, if `maskNegativeVariance` is True.",
385 default="BAD",
386 )
387 doSaturation = pexConfig.Field(
388 dtype=bool,
389 doc="Mask saturated pixels? NB: this is totally independent of the"
390 " interpolation option - this is ONLY setting the bits in the mask."
391 " To have them interpolated make sure doInterpolate=True and"
392 " maskListToInterpolate includes SAT.",
393 default=True,
394 )
395 saturatedMaskName = pexConfig.Field(
396 dtype=str,
397 doc="Name of mask plane to use in saturation detection and interpolation.",
398 default="SAT",
399 )
400 defaultSaturationSource = pexConfig.ChoiceField(
401 dtype=str,
402 doc="Source to retrieve default amp-level saturation values.",
403 allowed={
404 "NONE": "No default saturation values; only config overrides will be used.",
405 "CAMERAMODEL": "Use the default from the camera model (old defaults).",
406 "PTCTURNOFF": "Use the ptcTurnoff value as the saturation level.",
407 },
408 default="PTCTURNOFF",
409 )
410 doSuspect = pexConfig.Field(
411 dtype=bool,
412 doc="Mask suspect pixels?",
413 default=True,
414 )
415 suspectMaskName = pexConfig.Field(
416 dtype=str,
417 doc="Name of mask plane to use for suspect pixels.",
418 default="SUSPECT",
419 )
420 defaultSuspectSource = pexConfig.ChoiceField(
421 dtype=str,
422 doc="Source to retrieve default amp-level suspect values.",
423 allowed={
424 "NONE": "No default suspect values; only config overrides will be used.",
425 "CAMERAMODEL": "Use the default from the camera model (old defaults).",
426 "PTCTURNOFF": "Use the ptcTurnoff value as the suspect level.",
427 },
428 default="PTCTURNOFF",
429 )
430
431 # Crosstalk.
432 doCrosstalk = pexConfig.Field(
433 dtype=bool,
434 doc="Apply intra-CCD crosstalk correction?",
435 default=True,
436 )
437 crosstalk = pexConfig.ConfigurableField(
438 target=CrosstalkTask,
439 doc="Intra-CCD crosstalk correction.",
440 )
441
442 # Masking options.
443 doITLDipMask = pexConfig.Field(
444 dtype=bool,
445 doc="Apply ``ITL dip`` masking. The ``itlDipMaskPlane`` mask plane "
446 "will be added even if this configuration is False.",
447 default=True,
448 )
449 itlDipMaskPlanes = pexConfig.ListField(
450 dtype=str,
451 doc="Mask plane to use for ITL dip pixels.",
452 default=["SUSPECT", "ITL_DIP"],
453 )
454 doDefect = pexConfig.Field(
455 dtype=bool,
456 doc="Apply correction for CCD defects, e.g. hot pixels?",
457 default=True,
458 )
459 badAmps = pexConfig.ListField(
460 dtype=str,
461 doc="List of bad amps that should be masked as BAD in the defect code. "
462 "Value should be of form {detector_name}_{amp_name}, e.g. ``R42_S21_C07``. "
463 "Only used if doDefect is True.",
464 default=[],
465 )
466 doNanMasking = pexConfig.Field(
467 dtype=bool,
468 doc="Mask non-finite (NAN, inf) pixels. The UNMASKEDNAN mask plane "
469 "will be added even if this configuration is False.",
470 default=True,
471 )
472 doWidenSaturationTrails = pexConfig.Field(
473 dtype=bool,
474 doc="Widen bleed trails based on their width.",
475 default=False,
476 )
477 masking = pexConfig.ConfigurableField(
478 target=MaskingTask,
479 doc="Masking task."
480 )
481 doE2VEdgeBleedMask = pexConfig.Field(
482 dtype=bool,
483 doc="Mask flag-like edge bleeds from saturated columns "
484 "in E2V amplifiers.",
485 default=True,
486 )
487 e2vEdgeBleedSatMinArea = pexConfig.Field(
488 dtype=int,
489 doc="Minimum limit of saturated cores footprint area to apply edge"
490 "bleed masking in E2V amplifiers.",
491 default=10000,
492 )
493 e2vEdgeBleedSatMaxArea = pexConfig.Field(
494 dtype=int,
495 doc="Maximum limit of saturated cores footprint area to apply edge"
496 "bleed masking in E2V amplifiers.",
497 default=100000,
498 )
499 e2vEdgeBleedYMax = pexConfig.Field(
500 dtype=int,
501 doc="Height in pixels of edge bleed masking in E2V amplifiers (width"
502 "is the width of the amplifier).",
503 default=350,
504 )
505 doITLEdgeBleedMask = pexConfig.Field(
506 dtype=bool,
507 doc="Mask edge bleeds from saturated columns in ITL amplifiers.",
508 default=True,
509 )
510 doITLSatSagMask = pexConfig.Field(
511 dtype=bool,
512 doc="Mask columns presenting saturation sag.",
513 default=True,
514 )
515 itlEdgeBleedSatMinArea = pexConfig.Field(
516 dtype=int,
517 doc="Minimum limit for saturated cores footprint area.",
518 default=10000,
519 )
520 itlEdgeBleedSatMaxArea = pexConfig.Field(
521 dtype=int,
522 doc="Maximum limit for saturated cores footprint area.",
523 default=100000,
524 )
525 itlEdgeBleedThreshold = pexConfig.Field(
526 dtype=float,
527 doc="Sky background threshold for edge bleed detection.",
528 default=5000.,
529 )
530 itlEdgeBleedModelConstant = pexConfig.Field(
531 dtype=float,
532 doc="Constant in the edge bleed exponential decay model.",
533 default=0.02,
534 )
535
536 # Interpolation options.
537 doInterpolate = pexConfig.Field(
538 dtype=bool,
539 doc="Interpolate masked pixels?",
540 default=True,
541 )
542 maskListToInterpolate = pexConfig.ListField(
543 dtype=str,
544 doc="List of mask planes that should be interpolated.",
545 default=["SAT", "BAD", "UNMASKEDNAN"],
546 )
547 doSaveInterpPixels = pexConfig.Field(
548 dtype=bool,
549 doc="Save a copy of the pre-interpolated pixel values?",
550 default=False,
551 )
552 useLegacyInterp = pexConfig.Field(
553 dtype=bool,
554 doc="Use the legacy interpolation algorithm. If False use Gaussian Process.",
555 default=True,
556 )
557
558 # Amp offset correction.
559 doAmpOffset = pexConfig.Field(
560 doc="Calculate amp offset corrections?",
561 dtype=bool,
562 default=False,
563 )
564 ampOffset = pexConfig.ConfigurableField(
565 doc="Amp offset correction task.",
566 target=AmpOffsetTask,
567 )
568
569 # Initial masking options.
570 doSetBadRegions = pexConfig.Field(
571 dtype=bool,
572 doc="Should we set the level of all BAD patches of the chip to the chip's average value?",
573 default=True,
574 )
575
576 # Brighter-Fatter correction.
577 doBrighterFatter = pexConfig.Field(
578 dtype=bool,
579 doc="Apply the brighter-fatter correction?",
580 default=True,
581 )
582 brighterFatterCorrectionMethod = pexConfig.ChoiceField(
583 dtype=str,
584 doc="The method for brighter-fatter correction.",
585 default="COULTON18",
586 allowed={
587 "COULTON18": "Coulton et al. 2018 BF correction with kernel",
588 "COULTON18_FLUX_CONSERVING": "Coulton et al. 2018 BF correction "
589 "with kernel + Flux conserving corrections",
590 "ASTIER23": "Astier & Regenault 2023 electrostatic BF correction",
591 "ASTIER23+FILTERCORRECTION": "Astier & Regenault 2023 electrostatic BF "
592 "correction + color correction",
593 },
594 )
595 brighterFatterLevel = pexConfig.ChoiceField(
596 dtype=str,
597 doc="The level at which to correct for brighter-fatter.",
598 allowed={
599 "AMP": "Every amplifier treated separately.",
600 "DETECTOR": "One kernel per detector.",
601 },
602 default="DETECTOR",
603 )
604 brighterFatterMaxIter = pexConfig.Field(
605 dtype=int,
606 doc="Maximum number of iterations for the brighter-fatter correction for "
607 "the COULTON18* correction types",
608 default=10,
609 )
610 brighterFatterThreshold = pexConfig.Field(
611 dtype=float,
612 doc="Threshold used to stop iterating the brighter-fatter correction for "
613 "the COULTON18* correction types. It is the absolute value of the difference "
614 "between the current corrected image and the one from the previous iteration "
615 "summed over all the pixels.",
616 default=1000,
617 )
618 brighterFatterMaskListToInterpolate = pexConfig.ListField(
619 dtype=str,
620 doc="List of mask planes that should be interpolated over when applying the brighter-fatter "
621 "correction.",
622 default=["SAT", "BAD", "NO_DATA", "UNMASKEDNAN"],
623 )
624 brighterFatterMaskGrowSize = pexConfig.Field(
625 dtype=int,
626 doc="Number of pixels to grow the masks listed in config.brighterFatterMaskListToInterpolate "
627 "when brighter-fatter correction is applied.",
628 default=2,
629 )
630 brighterFatterFwhmForInterpolation = pexConfig.Field(
631 dtype=float,
632 doc="FWHM of PSF in arcseconds used for interpolation in brighter-fatter correction "
633 "(currently unused).",
634 default=1.0,
635 )
636 growSaturationFootprintSize = pexConfig.Field(
637 dtype=int,
638 doc="Number of pixels by which to grow the saturation footprints.",
639 default=1,
640 )
641
642 # Dark subtraction.
643 doDark = pexConfig.Field(
644 dtype=bool,
645 doc="Apply dark frame correction.",
646 default=True,
647 )
648
649 # Flat correction.
650 doFlat = pexConfig.Field(
651 dtype=bool,
652 doc="Apply flat field correction.",
653 default=True,
654 )
655 flatScalingType = pexConfig.ChoiceField(
656 dtype=str,
657 doc="The method for scaling the flat on the fly.",
658 default='USER',
659 allowed={
660 "USER": "Scale by flatUserScale",
661 "MEAN": "Scale by the inverse of the mean",
662 "MEDIAN": "Scale by the inverse of the median",
663 },
664 )
665 flatUserScale = pexConfig.Field(
666 dtype=float,
667 doc="If flatScalingType is 'USER' then scale flat by this amount; ignored otherwise.",
668 default=1.0,
669 )
670 noDataVariance = pexConfig.Field(
671 dtype=float,
672 doc="Value to fill for variance plane in NO_DATA regions (which are generally "
673 "inherited from the flat in fully vignetted regions.)",
674 default=1e10,
675 )
676
677 # Calculate image quality statistics?
678 doStandardStatistics = pexConfig.Field(
679 dtype=bool,
680 doc="Should standard image quality statistics be calculated?",
681 default=True,
682 )
683 # Calculate additional statistics?
684 doCalculateStatistics = pexConfig.Field(
685 dtype=bool,
686 doc="Should additional ISR statistics be calculated?",
687 default=True,
688 )
689 isrStats = pexConfig.ConfigurableField(
690 target=IsrStatisticsTask,
691 doc="Task to calculate additional statistics.",
692 )
693
694 # Make binned images?
695 doBinnedExposures = pexConfig.Field(
696 dtype=bool,
697 doc="Should binned exposures be calculated?",
698 default=False,
699 )
700 binning = pexConfig.ConfigurableField(
701 target=BinImageDataTask,
702 doc="Task to bin the exposure.",
703 )
704 binFactor1 = pexConfig.Field(
705 dtype=int,
706 doc="Binning factor for first binned exposure. This is intended for a finely binned output.",
707 default=8,
708 check=lambda x: x > 1,
709 )
710 binFactor2 = pexConfig.Field(
711 dtype=int,
712 doc="Binning factor for second binned exposure. This is intended for a coarsely binned output.",
713 default=64,
714 check=lambda x: x > 1,
715 )
716
717 def validate(self):
718 super().validate()
719
720 if self.doBootstrap:
721 # Additional checks in bootstrap (no gains) mode.
722 if self.doApplyGains:
723 raise ValueError("Cannot run task with doBootstrap=True and doApplyGains=True.")
724 if self.doCorrectGains:
725 raise ValueError("Cannot run task with doBootstrap=True and doCorrectGains=True.")
726 if self.doCrosstalk and self.crosstalk.doQuadraticCrosstalkCorrection:
727 raise ValueError("Cannot apply quadratic crosstalk correction with doBootstrap=True.")
728 if numpy.isfinite(self.serialOverscanMedianShiftSigmaThreshold):
729 raise ValueError("Cannot do amp overscan level checks with doBootstrap=True.")
730 if numpy.isfinite(self.ampNoiseThreshold):
731 raise ValueError("Cannot do amp noise thresholds with doBootstrap=True.")
732
733 if self.doITLEdgeBleedMask and not self.doSaturation:
734 raise ValueError("Cannot do ITL edge bleed masking when doSaturation=False.")
735 if self.doE2VEdgeBleedMask and not self.doSaturation:
736 raise ValueError("Cannot do e2v edge bleed masking when doSaturation=False.")
737
738 def setDefaults(self):
739 super().setDefaults()
740
741
742class IsrTaskLSST(pipeBase.PipelineTask):
743 ConfigClass = IsrTaskLSSTConfig
744 _DefaultName = "isrLSST"
745
746 def __init__(self, **kwargs):
747 super().__init__(**kwargs)
748 self.makeSubtask("assembleCcd")
749 self.makeSubtask("deferredChargeCorrection")
750 self.makeSubtask("crosstalk")
751 self.makeSubtask("masking")
752 self.makeSubtask("isrStats")
753 self.makeSubtask("ampOffset")
754 self.makeSubtask("binning")
755
756 def runQuantum(self, butlerQC, inputRefs, outputRefs):
757
758 inputs = butlerQC.get(inputRefs)
759 self.validateInput(inputs)
760
761 if self.config.doHeaderProvenance:
762 # Add calibration provenanace info to header.
763 exposureMetadata = inputs['ccdExposure'].metadata
764 for inputName in sorted(list(inputs.keys())):
765 reference = getattr(inputRefs, inputName, None)
766 if reference is not None and hasattr(reference, "run"):
767 runKey = f"LSST CALIB RUN {inputName.upper()}"
768 runValue = reference.run
769 idKey = f"LSST CALIB UUID {inputName.upper()}"
770 idValue = str(reference.id)
771 dateKey = f"LSST CALIB DATE {inputName.upper()}"
772 dateValue = self.extractCalibDate(inputs[inputName])
773 if dateValue != "Unknown Unknown":
774 butlerQC.add_additional_provenance(reference, {"calib date": dateValue})
775
776 exposureMetadata[runKey] = runValue
777 exposureMetadata[idKey] = idValue
778 exposureMetadata[dateKey] = dateValue
779
780 outputs = self.run(**inputs)
781 butlerQC.put(outputs, outputRefs)
782
783 def validateInput(self, inputs):
784 """
785 This is a check that all the inputs required by the config
786 are available.
787 """
788
789 # Inputs depend on where the gains are coming from
790 doApplyGains = self.config.doApplyGains
791 useLinearizerGains = self.config.useGainsFrom == "LINEARIZER"
792 usePtcGains = not useLinearizerGains
793
794 # Inputs depend on the BF method
795 method = self.config.brighterFatterCorrectionMethod
796
797 inputMap = {
798 'dnlLUT': self.config.doDiffNonLinearCorrection,
799 'bias': self.config.doBias,
800 'deferredChargeCalib': self.config.doDeferredCharge,
801 # Some tasks require gains in order to be
802 # supplied regardless of whether
803 # self.config.doApplyGains is True or False.
804 'linearizer': (self.config.doLinearize or (doApplyGains and useLinearizerGains)),
805 'ptc': self.config.doApplyGains and usePtcGains,
806 'crosstalk': self.config.doCrosstalk,
807 'defects': self.config.doDefect,
808 'bfKernel': self.config.doBrighterFatter & method.startswith("COULTON18"),
809 'electroBfDistortionMatrix': self.config.doBrighterFatter & (method == "ASTIER23"),
810 'dark': self.config.doDark,
811 }
812
813 for calibrationFile, configValue in inputMap.items():
814 if configValue and inputs[calibrationFile] is None:
815 raise RuntimeError("Must supply ", calibrationFile)
816
817 def diffNonLinearCorrection(self, ccdExposure, dnlLUT, **kwargs):
818 # TODO DM 36636
819 # isrFunctions.diffNonLinearCorrection
820 pass
821
822 def maskFullAmplifiers(self, ccdExposure, detector, defects, gains=None):
823 """
824 Check for fully masked bad amplifiers and mask them.
825
826 This includes defects which cover full amplifiers, as well
827 as amplifiers with nan gain values which should be used
828 if self.config.doApplyGains=True.
829
830 Full defect masking happens later to allow for defects which
831 cross amplifier boundaries.
832
833 Parameters
834 ----------
835 ccdExposure : `lsst.afw.image.Exposure`
836 Input exposure to be masked.
837 detector : `lsst.afw.cameraGeom.Detector`
838 Detector object.
839 defects : `lsst.ip.isr.Defects`
840 List of defects. Used to determine if an entire
841 amplifier is bad.
842 gains : `dict` [`str`, `float`], optional
843 Dictionary of gains to check if
844 self.config.doApplyGains=True.
845
846 Returns
847 -------
848 badAmpDict : `str`[`bool`]
849 Dictionary of amplifiers, keyed by name, value is True if
850 amplifier is fully masked.
851 """
852 badAmpDict = {}
853
854 maskedImage = ccdExposure.getMaskedImage()
855
856 for amp in detector:
857 ampName = amp.getName()
858 badAmpDict[ampName] = False
859
860 # Check if entire amp region is defined as a defect
861 # NB: need to use amp.getBBox() for correct comparison with current
862 # defects definition.
863 if defects is not None:
864 badAmpDict[ampName] = bool(sum([v.getBBox().contains(amp.getBBox()) for v in defects]))
865
866 if badAmpDict[ampName]:
867 self.log.warning("Amplifier %s is bad (completely covered with defects)", ampName)
868
869 if gains is not None and self.config.doApplyGains:
870 if not math.isfinite(gains[ampName]):
871 badAmpDict[ampName] = True
872
873 self.log.warning("Amplifier %s is bad (non-finite gain)", ampName)
874
875 # In the case of a bad amp, we will set mask to "BAD"
876 # (here use amp.getRawBBox() for correct association with pixels in
877 # current ccdExposure).
878 if badAmpDict[ampName]:
879 dataView = afwImage.MaskedImageF(maskedImage, amp.getRawBBox(),
880 afwImage.PARENT)
881 maskView = dataView.getMask()
882 maskView |= maskView.getPlaneBitMask("BAD")
883 del maskView
884
885 return badAmpDict
886
887 def checkAllBadAmps(self, badAmpDict, detector):
888 """Check if all amps are marked as bad.
889
890 Parameters
891 ----------
892 badAmpDict : `str`[`bool`]
893 Dictionary of amplifiers, keyed by name, value is True if
894 amplifier is fully masked.
895 detector : `lsst.afw.cameraGeom.Detector`
896 Detector object.
897
898 Raises
899 ------
900 UnprocessableDataError if all amps are bad and doCheckUnprocessableData
901 configuration is True.
902 """
903 if not self.config.doCheckUnprocessableData:
904 return
905
906 for amp in detector:
907 if not badAmpDict.get(amp.getName(), False):
908 return
909
910 raise UnprocessableDataError(f"All amps in the exposure {detector.getName()} are bad; skipping ISR.")
911
912 def checkAmpOverscanLevel(self, badAmpDict, exposure, ptc):
913 """Check if the amplifier overscan levels have changed.
914
915 Any amplifier that has an overscan median level that has changed
916 significantly will be masked as BAD and added to toe badAmpDict.
917
918 Parameters
919 ----------
920 badAmpDict : `str` [`bool`]
921 Dictionary of amplifiers, keyed by name, value is True if
922 amplifier is fully masked.
923 exposure : `lsst.afw.image.Exposure`
924 Input exposure to be masked (untrimmed).
925 ptc : `lsst.ip.isr.PhotonTransferCurveDataset`
926 PTC dataset with gains/read noises.
927
928 Returns
929 -------
930 badAmpDict : `str`[`bool`]
931 Dictionary of amplifiers, keyed by name.
932
933 """
934 if isTrimmedExposure(exposure):
935 raise RuntimeError("checkAmpOverscanLevel must be run on an untrimmed exposure.")
936
937 # We want to consolidate all the amps into one warning if necessary.
938 # This config should not be set to a finite threshold if the necessary
939 # data is not in the PTC.
940 missingWarnString = "No PTC overscan information for amplifier "
941 missingWarnFlag = False
942 for amp in exposure.getDetector():
943 ampName = amp.getName()
944
945 if not numpy.isfinite(ptc.overscanMedian[ampName]) or \
946 not numpy.isfinite(ptc.overscanMedianSigma[ampName]):
947 missingWarnString += f"{ampName},"
948 missingWarnFlag = True
949 else:
950 key = f"LSST ISR OVERSCAN SERIAL MEDIAN {ampName}"
951 # If it is missing, just return the PTC value and it
952 # will be skipped.
953 overscanLevel = exposure.metadata.get(key, ptc.overscanMedian[ampName])
954 pull = (overscanLevel - ptc.overscanMedian[ampName])/ptc.overscanMedianSigma[ampName]
955 if numpy.abs(pull) > self.config.serialOverscanMedianShiftSigmaThreshold:
956 self.log.warning(
957 "Amplifier %s has an overscan level that is %.2f sigma from the expected level; "
958 "masking it as BAD.",
959 ampName,
960 pull,
961 )
962
963 badAmpDict[ampName] = True
964 exposure.mask[amp.getRawBBox()] |= exposure.mask.getPlaneBitMask("BAD")
965
966 if missingWarnFlag:
967 self.log.warning(missingWarnString)
968
969 return badAmpDict
970
971 def checkAmpNoise(self, badAmpDict, exposure, ptc):
972 """Check if amplifier noise levels are above threshold.
973
974 Any amplifier that is above the noise level will be masked as BAD
975 and added to the badAmpDict.
976
977 Parameters
978 ----------
979 badAmpDict : `str` [`bool`]
980 Dictionary of amplifiers, keyed by name, value is True if
981 amplifier is fully masked.
982 exposure : `lsst.afw.image.Exposure`
983 Input exposure to be masked (untrimmed).
984 ptc : `lsst.ip.isr.PhotonTransferCurveDataset`
985 PTC dataset with gains/read noises.
986
987 Returns
988 -------
989 badAmpDict : `str`[`bool`]
990 Dictionary of amplifiers, keyed by name.
991 """
992
993 if isTrimmedExposure(exposure):
994 raise RuntimeError("checkAmpNoise must be run on an untrimmed exposure.")
995
996 for amp in exposure.getDetector():
997 ampName = amp.getName()
998
999 doMask = False
1000 if ptc.noise[ampName] > self.config.ampNoiseThreshold:
1001 self.log.info(
1002 "Amplifier %s has a PTC noise level of %.2f e-, above threshold.",
1003 ampName,
1004 ptc.noise[ampName],
1005 )
1006 doMask = True
1007 else:
1008 key = f"LSST ISR OVERSCAN RESIDUAL SERIAL STDEV {ampName}"
1009 overscanNoise = exposure.metadata.get(key, numpy.nan)
1010 if overscanNoise * ptc.gain[ampName] > self.config.ampNoiseThreshold:
1011 self.log.warning(
1012 "Amplifier %s has an overscan read noise level of %.2f e-, above threshold.",
1013 ampName,
1014 overscanNoise * ptc.gain[ampName],
1015 )
1016 doMask = True
1017
1018 if doMask:
1019 badAmpDict[ampName] = True
1020
1021 exposure.mask[amp.getRawBBox()] |= exposure.mask.getPlaneBitMask("BAD")
1022
1023 return badAmpDict
1024
1025 def maskSaturatedPixels(self, badAmpDict, ccdExposure, detector, detectorConfig, ptc=None):
1026 """
1027 Mask SATURATED and SUSPECT pixels and check if any amplifiers
1028 are fully masked.
1029
1030 Parameters
1031 ----------
1032 badAmpDict : `str` [`bool`]
1033 Dictionary of amplifiers, keyed by name, value is True if
1034 amplifier is fully masked.
1035 ccdExposure : `lsst.afw.image.Exposure`
1036 Input exposure to be masked.
1037 detector : `lsst.afw.cameraGeom.Detector`
1038 Detector object.
1039 defects : `lsst.ip.isr.Defects`
1040 List of defects. Used to determine if an entire
1041 amplifier is bad.
1042 detectorConfig : `lsst.ip.isr.OverscanDetectorConfig`
1043 Per-amplifier configurations.
1044 ptc : `lsst.ip.isr.PhotonTransferCurveDataset`, optional
1045 PTC dataset (used if configured to use PTCTURNOFF).
1046
1047 Returns
1048 -------
1049 badAmpDict : `str`[`bool`]
1050 Dictionary of amplifiers, keyed by name.
1051 """
1052 maskedImage = ccdExposure.getMaskedImage()
1053
1054 metadata = ccdExposure.metadata
1055
1056 if self.config.doSaturation and self.config.defaultSaturationSource == "PTCTURNOFF" and ptc is None:
1057 raise RuntimeError("Must provide ptc if using PTCTURNOFF as saturation source.")
1058 if self.config.doSuspect and self.config.defaultSuspectSource == "PTCTURNOFF" and ptc is None:
1059 raise RuntimeError("Must provide ptc if using PTCTURNOFF as suspect source.")
1060
1061 for amp in detector:
1062 ampName = amp.getName()
1063
1064 ampConfig = detectorConfig.getOverscanAmpConfig(amp)
1065
1066 if badAmpDict[ampName]:
1067 # No need to check fully bad amplifiers.
1068 continue
1069
1070 # Mask saturated and suspect pixels.
1071 limits = {}
1072 if self.config.doSaturation:
1073 if self.config.defaultSaturationSource == "PTCTURNOFF":
1074 limits.update({self.config.saturatedMaskName: ptc.ptcTurnoff[amp.getName()]})
1075 elif self.config.defaultSaturationSource == "CAMERAMODEL":
1076 # Set to the default from the camera model.
1077 limits.update({self.config.saturatedMaskName: amp.getSaturation()})
1078 elif self.config.defaultSaturationSource == "NONE":
1079 limits.update({self.config.saturatedMaskName: numpy.inf})
1080
1081 # And update if it is set in the config.
1082 if math.isfinite(ampConfig.saturation):
1083 limits.update({self.config.saturatedMaskName: ampConfig.saturation})
1084 metadata[f"LSST ISR SATURATION LEVEL {ampName}"] = limits[self.config.saturatedMaskName]
1085
1086 if self.config.doSuspect:
1087 if self.config.defaultSuspectSource == "PTCTURNOFF":
1088 limits.update({self.config.suspectMaskName: ptc.ptcTurnoff[amp.getName()]})
1089 elif self.config.defaultSuspectSource == "CAMERAMODEL":
1090 # Set to the default from the camera model.
1091 limits.update({self.config.suspectMaskName: amp.getSuspectLevel()})
1092 elif self.config.defaultSuspectSource == "NONE":
1093 limits.update({self.config.suspectMaskName: numpy.inf})
1094
1095 # And update if it set in the config.
1096 if math.isfinite(ampConfig.suspectLevel):
1097 limits.update({self.config.suspectMaskName: ampConfig.suspectLevel})
1098 metadata[f"LSST ISR SUSPECT LEVEL {ampName}"] = limits[self.config.suspectMaskName]
1099
1100 for maskName, maskThreshold in limits.items():
1101 if not math.isnan(maskThreshold):
1102 dataView = maskedImage.Factory(maskedImage, amp.getRawBBox())
1103 toMask = (dataView.image.array >= maskThreshold)
1104 dataView.mask.array[toMask] |= dataView.mask.getPlaneBitMask(maskName)
1105
1106 # Determine if we've fully masked this amplifier with SUSPECT and
1107 # SAT pixels.
1108 maskView = afwImage.Mask(maskedImage.getMask(), amp.getRawDataBBox(),
1109 afwImage.PARENT)
1110 maskVal = maskView.getPlaneBitMask([self.config.saturatedMaskName,
1111 self.config.suspectMaskName])
1112 if numpy.all(maskView.getArray() & maskVal > 0):
1113 self.log.warning("Amplifier %s is bad (completely SATURATED or SUSPECT)", ampName)
1114 badAmpDict[ampName] = True
1115 maskView |= maskView.getPlaneBitMask("BAD")
1116
1117 return badAmpDict
1118
1119 def maskITLSatEdgesAndColumns(self, exposure, badAmpDict):
1120
1121 # The following steps will rely on the footprint of saturated
1122 # cores with large areas.
1123 thresh = afwDetection.Threshold(exposure.mask.getPlaneBitMask("SAT"),
1124 afwDetection.Threshold.BITMASK
1125 )
1126 fpList = afwDetection.FootprintSet(exposure.mask, thresh).getFootprints()
1127
1128 satAreas = numpy.asarray([fp.getArea() for fp in fpList])
1129 largeAreas, = numpy.where((satAreas >= self.config.itlEdgeBleedSatMinArea)
1130 & (satAreas < self.config.itlEdgeBleedSatMaxArea))
1131
1132 for largeAreasIndex in largeAreas:
1133
1134 fpCore = fpList[largeAreasIndex]
1135
1136 # Edge bleed masking
1137 if self.config.doITLEdgeBleedMask:
1138 isrFunctions.maskITLEdgeBleed(ccdExposure=exposure,
1139 badAmpDict=badAmpDict,
1140 fpCore=fpCore,
1141 itlEdgeBleedSatMinArea=self.config.itlEdgeBleedSatMinArea,
1142 itlEdgeBleedSatMaxArea=self.config.itlEdgeBleedSatMaxArea,
1143 itlEdgeBleedThreshold=self.config.itlEdgeBleedThreshold,
1144 itlEdgeBleedModelConstant=self.config.itlEdgeBleedModelConstant,
1145 saturatedMaskName=self.config.saturatedMaskName,
1146 log=self.log
1147 )
1148 if self.config.doITLSatSagMask:
1149 isrFunctions.maskITLSatSag(ccdExposure=exposure, fpCore=fpCore,
1150 saturatedMaskName=self.config.saturatedMaskName)
1151
1152 def overscanCorrection(self, mode, detectorConfig, detector, badAmpDict, ccdExposure):
1153 """Apply serial overscan correction in place to all amps.
1154
1155 The actual overscan subtraction is performed by the
1156 `lsst.ip.isr.overscan.OverscanTask`, which is called here.
1157
1158 Parameters
1159 ----------
1160 mode : `str`
1161 Must be `SERIAL` or `PARALLEL`.
1162 detectorConfig : `lsst.ip.isr.OverscanDetectorConfig`
1163 Per-amplifier configurations.
1164 detector : `lsst.afw.cameraGeom.Detector`
1165 Detector object.
1166 badAmpDict : `dict`
1167 Dictionary of amp name to whether it is a bad amp.
1168 ccdExposure : `lsst.afw.image.Exposure`
1169 Exposure to have overscan correction performed.
1170
1171 Returns
1172 -------
1173 overscans : `list` [`lsst.pipe.base.Struct` or None]
1174 Overscan measurements (always in adu).
1175 Each result struct has components:
1176
1177 ``imageFit``
1178 Value or fit subtracted from the amplifier image data.
1179 (scalar or `lsst.afw.image.Image`)
1180 ``overscanFit``
1181 Value or fit subtracted from the overscan image data.
1182 (scalar or `lsst.afw.image.Image`)
1183 ``overscanImage``
1184 Image of the overscan region with the overscan
1185 correction applied. This quantity is used to estimate
1186 the amplifier read noise empirically.
1187 (`lsst.afw.image.Image`)
1188 ``overscanMean``
1189 Mean overscan fit value. (`float`)
1190 ``overscanMedian``
1191 Median overscan fit value. (`float`)
1192 ``overscanSigma``
1193 Clipped standard deviation of the overscan fit. (`float`)
1194 ``residualMean``
1195 Mean of the overscan after fit subtraction. (`float`)
1196 ``residualMedian``
1197 Median of the overscan after fit subtraction. (`float`)
1198 ``residualSigma``
1199 Clipped standard deviation of the overscan after fit
1200 subtraction. (`float`)
1201
1202 See Also
1203 --------
1204 lsst.ip.isr.overscan.OverscanTask
1205 """
1206 if mode not in ["SERIAL", "PARALLEL"]:
1207 raise ValueError("Mode must be SERIAL or PARALLEL")
1208
1209 # This returns a list in amp order, with None for uncorrected amps.
1210 overscans = []
1211
1212 for i, amp in enumerate(detector):
1213 ampName = amp.getName()
1214
1215 ampConfig = detectorConfig.getOverscanAmpConfig(amp)
1216
1217 if mode == "SERIAL" and not ampConfig.doSerialOverscan:
1218 self.log.debug(
1219 "ISR_OSCAN: Amplifier %s/%s configured to skip serial overscan.",
1220 detector.getName(),
1221 ampName,
1222 )
1223 results = None
1224 elif mode == "PARALLEL" and not ampConfig.doParallelOverscan:
1225 self.log.debug(
1226 "ISR_OSCAN: Amplifier %s configured to skip parallel overscan.",
1227 detector.getName(),
1228 ampName,
1229 )
1230 results = None
1231 elif badAmpDict[ampName] or not ccdExposure.getBBox().contains(amp.getBBox()):
1232 results = None
1233 else:
1234 # This check is to confirm that we are not trying to run
1235 # overscan on an already trimmed image.
1236 if isTrimmedExposure(ccdExposure):
1237 self.log.warning(
1238 "ISR_OSCAN: No overscan region for amp %s. Not performing overscan correction.",
1239 ampName,
1240 )
1241 results = None
1242 else:
1243 if mode == "SERIAL":
1244 # We need to set up the subtask here with a custom
1245 # configuration.
1246 serialOverscan = SerialOverscanCorrectionTask(config=ampConfig.serialOverscanConfig)
1247 results = serialOverscan.run(ccdExposure, amp)
1248 else:
1249 config = ampConfig.parallelOverscanConfig
1250 parallelOverscan = ParallelOverscanCorrectionTask(
1251 config=config,
1252 )
1253
1254 metadata = ccdExposure.metadata
1255
1256 # We need to know the saturation level that was used
1257 # for the parallel overscan masking. If it isn't set
1258 # then the configured parallelOverscanSaturationLevel
1259 # will be used instead (assuming
1260 # doParallelOverscanSaturation is True). Note that
1261 # this will have the correct units (adu or electron)
1262 # depending on whether the gain has been applied.
1263 if self.config.doSaturation:
1264 saturationLevel = metadata[f"LSST ISR SATURATION LEVEL {amp.getName()}"]
1265 saturationLevel *= config.parallelOverscanSaturationLevelAdjustmentFactor
1266 else:
1267 saturationLevel = config.parallelOverscanSaturationLevel
1268 if ccdExposure.metadata["LSST ISR UNITS"] == "electron":
1269 # Need to convert to electron from adu.
1270 saturationLevel *= metadata[f"LSST ISR GAIN {amp.getName()}"]
1271
1272 self.log.debug(
1273 "Using saturation level of %.2f for parallel overscan amp %s",
1274 saturationLevel,
1275 amp.getName(),
1276 )
1277
1278 parallelOverscan.maskParallelOverscanAmp(
1279 ccdExposure,
1280 amp,
1281 saturationLevel=saturationLevel,
1282 )
1283
1284 results = parallelOverscan.run(ccdExposure, amp)
1285
1286 metadata = ccdExposure.metadata
1287 keyBase = "LSST ISR OVERSCAN"
1288
1289 # The overscan is always in adu for the serial mode,
1290 # but, it may be electron in the parallel mode if
1291 # doApplyGains==True. If doApplyGains==True, then the
1292 # gains are applied to the untrimmed image, so the
1293 # overscan statistics units here will always match the
1294 # units of the image at this point.
1295 metadata[f"{keyBase} {mode} UNITS"] = ccdExposure.metadata["LSST ISR UNITS"]
1296 metadata[f"{keyBase} {mode} MEAN {ampName}"] = results.overscanMean
1297 metadata[f"{keyBase} {mode} MEDIAN {ampName}"] = results.overscanMedian
1298 metadata[f"{keyBase} {mode} STDEV {ampName}"] = results.overscanSigma
1299
1300 metadata[f"{keyBase} RESIDUAL {mode} MEAN {ampName}"] = results.residualMean
1301 metadata[f"{keyBase} RESIDUAL {mode} MEDIAN {ampName}"] = results.residualMedian
1302 metadata[f"{keyBase} RESIDUAL {mode} STDEV {ampName}"] = results.residualSigma
1303
1304 overscans.append(results)
1305
1306 # Question: should this be finer grained?
1307 ccdExposure.metadata.set("OVERSCAN", "Overscan corrected")
1308
1309 return overscans
1310
1311 def maskNegativeVariance(self, exposure):
1312 """Identify and mask pixels with negative variance values.
1313
1314 Parameters
1315 ----------
1316 exposure : `lsst.afw.image.Exposure`
1317 Exposure to process.
1318
1319 See Also
1320 --------
1321 lsst.ip.isr.isrFunctions.updateVariance
1322 """
1323 maskPlane = exposure.getMask().getPlaneBitMask(self.config.negativeVarianceMaskName)
1324 bad = numpy.where(exposure.getVariance().getArray() <= 0.0)
1325 exposure.mask.array[bad] |= maskPlane
1326
1327 def addVariancePlane(self, exposure, detector):
1328 """Add the variance plane to the image.
1329
1330 The gain and read noise per amp must have been set in the
1331 exposure metadata as ``LSST ISR GAIN ampName`` and
1332 ``LSST ISR READNOISE ampName`` with the units of the image.
1333 Unit conversions for the variance plane will be done as
1334 necessary based on the exposure units.
1335
1336 The units of the variance plane will always be of the same
1337 type as the units of the input image itself
1338 (``LSST ISR UNITS``^2).
1339
1340 Parameters
1341 ----------
1342 exposure : `lsst.afw.image.Exposure`
1343 The exposure to add the variance plane.
1344 detector : `lsst.afw.cameraGeom.Detector`
1345 Detector with geometry info.
1346 """
1347 # NOTE: this will fail if the exposure is not trimmed.
1348 if not isTrimmedExposure(exposure):
1349 raise RuntimeError("Exposure must be trimmed to add variance plane.")
1350
1351 isElectrons = (exposure.metadata["LSST ISR UNITS"] == "electron")
1352
1353 for amp in detector:
1354 if exposure.getBBox().contains(amp.getBBox()):
1355 self.log.debug("Constructing variance map for amplifer %s.", amp.getName())
1356 ampExposure = exposure.Factory(exposure, amp.getBBox())
1357
1358 # The effective gain is 1.0 if we are in electron units.
1359 # The metadata read noise is in the same units as the image.
1360 gain = exposure.metadata[f"LSST ISR GAIN {amp.getName()}"] if not isElectrons else 1.0
1361 readNoise = exposure.metadata[f"LSST ISR READNOISE {amp.getName()}"]
1362
1363 isrFunctions.updateVariance(
1364 maskedImage=ampExposure.maskedImage,
1365 gain=gain,
1366 readNoise=readNoise,
1367 replace=False,
1368 )
1369
1370 if self.config.qa is not None and self.config.qa.saveStats is True:
1371 qaStats = afwMath.makeStatistics(ampExposure.getVariance(),
1372 afwMath.MEDIAN | afwMath.STDEVCLIP)
1373 self.log.debug(" Variance stats for amplifer %s: %f +/- %f.",
1374 amp.getName(), qaStats.getValue(afwMath.MEDIAN),
1375 qaStats.getValue(afwMath.STDEVCLIP))
1376
1377 if self.config.maskNegativeVariance:
1378 self.maskNegativeVariance(exposure)
1379
1380 def maskDefects(self, exposure, defectBaseList):
1381 """Mask defects using mask plane "BAD", in place.
1382
1383 Parameters
1384 ----------
1385 exposure : `lsst.afw.image.Exposure`
1386 Exposure to process.
1387
1388 defectBaseList : defect-type
1389 List of defects to mask. Can be of type `lsst.ip.isr.Defects`
1390 or `list` of `lsst.afw.image.DefectBase`.
1391 """
1392 maskedImage = exposure.getMaskedImage()
1393 if not isinstance(defectBaseList, Defects):
1394 # Promotes DefectBase to Defect
1395 defectList = Defects(defectBaseList)
1396 else:
1397 defectList = defectBaseList
1398 defectList.maskPixels(maskedImage, maskName="BAD")
1399
1400 if len(self.config.badAmps) == 0:
1401 return
1402
1403 detector = exposure.getDetector()
1404 mask = maskedImage.mask
1405 for badAmp in self.config.badAmps:
1406 if badAmp.startswith(detector.getName()):
1407 # Split on the full detector name plus _, which
1408 # gives us an empty string and the amp name.
1409 ampName = badAmp.split(detector.getName() + "_")[-1]
1410 self.log.info("Masking amplifier %s as bad via config.", ampName)
1411 mask[detector[ampName].getBBox()].array[:, :] |= mask.getPlaneBitMask("BAD")
1412
1413 def maskEdges(self, exposure, numEdgePixels=0, maskPlane="SUSPECT", level='DETECTOR'):
1414 """Mask edge pixels with applicable mask plane.
1415
1416 Parameters
1417 ----------
1418 exposure : `lsst.afw.image.Exposure`
1419 Exposure to process.
1420 numEdgePixels : `int`, optional
1421 Number of edge pixels to mask.
1422 maskPlane : `str`, optional
1423 Mask plane name to use.
1424 level : `str`, optional
1425 Level at which to mask edges.
1426 """
1427 maskedImage = exposure.getMaskedImage()
1428 maskBitMask = maskedImage.getMask().getPlaneBitMask(maskPlane)
1429
1430 if numEdgePixels > 0:
1431 if level == 'DETECTOR':
1432 boxes = [maskedImage.getBBox()]
1433 elif level == 'AMP':
1434 boxes = [amp.getBBox() for amp in exposure.getDetector()]
1435
1436 for box in boxes:
1437 # This makes a bbox numEdgeSuspect pixels smaller than the
1438 # image on each side
1439 subImage = maskedImage[box]
1440 box.grow(-numEdgePixels)
1441 # Mask pixels outside box
1442 SourceDetectionTask.setEdgeBits(
1443 subImage,
1444 box,
1445 maskBitMask)
1446
1447 def maskNan(self, exposure):
1448 """Mask NaNs using mask plane "UNMASKEDNAN", in place.
1449
1450 Parameters
1451 ----------
1452 exposure : `lsst.afw.image.Exposure`
1453 Exposure to process.
1454
1455 Notes
1456 -----
1457 We mask over all non-finite values (NaN, inf), including those
1458 that are masked with other bits (because those may or may not be
1459 interpolated over later, and we want to remove all NaN/infs).
1460 Despite this behaviour, the "UNMASKEDNAN" mask plane is used to
1461 preserve the historical name.
1462 """
1463 maskedImage = exposure.getMaskedImage()
1464
1465 # Find and mask NaNs
1466 maskVal = maskedImage.getMask().getPlaneBitMask("UNMASKEDNAN")
1467 numNans = maskNans(maskedImage, maskVal)
1468 self.metadata["NUMNANS"] = numNans
1469 if numNans > 0:
1470 self.log.warning("There were %d unmasked NaNs.", numNans)
1471
1472 def setBadRegions(self, exposure):
1473 """Set bad regions from large contiguous regions.
1474
1475 Parameters
1476 ----------
1477 exposure : `lsst.afw.Exposure`
1478 Exposure to set bad regions.
1479
1480 Notes
1481 -----
1482 Reset and interpolate bad pixels.
1483
1484 Large contiguous bad regions (which should have the BAD mask
1485 bit set) should have their values set to the image median.
1486 This group should include defects and bad amplifiers. As the
1487 area covered by these defects are large, there's little
1488 reason to expect that interpolation would provide a more
1489 useful value.
1490
1491 Smaller defects can be safely interpolated after the larger
1492 regions have had their pixel values reset. This ensures
1493 that the remaining defects adjacent to bad amplifiers (as an
1494 example) do not attempt to interpolate extreme values.
1495 """
1496 badPixelCount, badPixelValue = isrFunctions.setBadRegions(exposure)
1497 if badPixelCount > 0:
1498 self.log.info("Set %d BAD pixels to %f.", badPixelCount, badPixelValue)
1499
1500 @contextmanager
1501 def flatContext(self, exp, flat, dark=None):
1502 """Context manager that applies and removes flats and darks,
1503 if the task is configured to apply them.
1504
1505 Parameters
1506 ----------
1507 exp : `lsst.afw.image.Exposure`
1508 Exposure to process.
1509 flat : `lsst.afw.image.Exposure`
1510 Flat exposure the same size as ``exp``.
1511 dark : `lsst.afw.image.Exposure`, optional
1512 Dark exposure the same size as ``exp``.
1513
1514 Yields
1515 ------
1516 exp : `lsst.afw.image.Exposure`
1517 The flat and dark corrected exposure.
1518 """
1519 imageOnly = not self.config.doVariance
1520 if self.config.doDark and dark is not None:
1521 self.darkCorrection(exp, dark)
1522 if self.config.doFlat and flat is not None:
1523 self.flatCorrection(exp, flat, imageOnly=imageOnly)
1524 try:
1525 yield exp
1526 finally:
1527 if self.config.doFlat and flat is not None:
1528 self.flatCorrection(exp, flat, invert=True, imageOnly=imageOnly)
1529 if self.config.doDark and dark is not None:
1530 self.darkCorrection(exp, dark, invert=True)
1531
1532 def getBrighterFatterKernel(self, detector, bfKernel):
1533 detName = detector.getName()
1534
1535 # This is expected to be a dictionary of amp-wise gains.
1536 bfGains = bfKernel.gain
1537 if bfKernel.level == 'DETECTOR':
1538 if detName in bfKernel.detKernels:
1539 bfKernelOut = bfKernel.detKernels[detName]
1540 return bfKernelOut, bfGains
1541 else:
1542 raise RuntimeError("Failed to extract kernel from new-style BF kernel.")
1543 elif bfKernel.level == 'AMP':
1544 self.log.info("Making DETECTOR level kernel from AMP based brighter "
1545 "fatter kernels.")
1546 bfKernel.makeDetectorKernelFromAmpwiseKernels(detName)
1547 bfKernelOut = bfKernel.detKernels[detName]
1548 return bfKernelOut, bfGains
1549
1550 def applyElectrostaticBrighterFatterCorrection(self, ccdExposure, flat, dark, electroBfDistortionMatrix,
1551 brighterFatterApplyGain, bfGains):
1552 """Apply an electrostatic brighter fatter correction to the image
1553 using the method defined in Astier et al. 2023.
1554
1555 Note that this correction requires that the image is in units
1556 electrons.
1557
1558 Parameters
1559 ----------
1560 ccdExposure : `lsst.afw.image.Exposure`
1561 Exposure to process.
1562 flat : `lsst.afw.image.Exposure`
1563 Flat exposure the same size as ``exp``.
1564 dark : `lsst.afw.image.Exposure`, optional
1565 Dark exposure the same size as ``exp``.
1566 electroBfDistortionMatrix : `lsst.ip.isr.ElectrostaticBrighterFatter`
1567 The brighter-fatter kernel.
1568 brighterFatterApplyGain : `bool`
1569 Apply the gain to convert the image to electrons?
1570 bfGains : `dict`
1571 The gains to use if brighterFatterApplyGain = True.
1572
1573 Yields
1574 ------
1575 exp : `lsst.afw.image.Exposure`
1576 The flat and dark corrected exposure.
1577 """
1578 interpExp = ccdExposure.clone()
1579 method = self.config.brighterFatterCorrectionMethod
1580
1581 # We need to interpolate before we do B-F. Note that
1582 # brighterFatterFwhmForInterpolation is currently unused.
1583 isrFunctions.interpolateFromMask(
1584 maskedImage=interpExp.getMaskedImage(),
1585 fwhm=self.config.brighterFatterFwhmForInterpolation,
1586 growSaturatedFootprints=self.config.growSaturationFootprintSize,
1587 maskNameList=list(self.config.brighterFatterMaskListToInterpolate),
1588 useLegacyInterp=self.config.useLegacyInterp,
1589 )
1590 bfExp = interpExp.clone()
1591
1593 self.log,
1594 bfExp,
1595 electroBfDistortionMatrix,
1596 brighterFatterApplyGain,
1597 bfGains,
1598 applyFilterCorrection=(method == "ASTIER23+FILTERCORRECTION"),
1599 )
1600
1601 # Applying the brighter-fatter correction applies a
1602 # convolution to the science image. At the edges this
1603 # convolution may not have sufficient valid pixels to
1604 # produce a valid correction. Mark pixels within the size
1605 # of the brighter-fatter kernel as EDGE to warn of this
1606 # fact.
1607 self.log.info("Ensuring image edges are masked as EDGE to the brighter-fatter kernel size.")
1608 self.maskEdges(ccdExposure, numEdgePixels=numpy.max(electroBfDistortionMatrix.aMatrix.shape) // 2,
1609 maskPlane="EDGE")
1610
1611 if self.config.brighterFatterMaskGrowSize > 0:
1612 self.log.info("Growing masks to account for brighter-fatter kernel convolution.")
1613 for maskPlane in self.config.brighterFatterMaskListToInterpolate:
1614 isrFunctions.growMasks(ccdExposure.getMask(),
1615 radius=self.config.brighterFatterMaskGrowSize,
1616 maskNameList=maskPlane,
1617 maskValue=maskPlane)
1618
1619 return ccdExposure
1620
1621 def applyFluxConservingBrighterFatterCorrection(self, ccdExposure, flat, dark, bfKernel,
1622 brighterFatterApplyGain, bfGains):
1623 """Apply a brighter fatter correction to the image using the
1624 method defined in Coulton et al. 2019 with flux-conserving
1625 corrections.
1626
1627 Note that this correction requires that the image is in units
1628 electrons.
1629
1630 Parameters
1631 ----------
1632 ccdExposure : `lsst.afw.image.Exposure`
1633 Exposure to process.
1634 flat : `lsst.afw.image.Exposure`
1635 Flat exposure the same size as ``exp``.
1636 dark : `lsst.afw.image.Exposure`, optional
1637 Dark exposure the same size as ``exp``.
1638 bfKernel : `lsst.ip.isr.BrighterFatterKernel`
1639 The brighter-fatter kernel.
1640 brighterFatterApplyGain : `bool`
1641 Apply the gain to convert the image to electrons?
1642 bfGains : `dict`
1643 The gains to use if brighterFatterApplyGain = True.
1644
1645 Yields
1646 ------
1647 exp : `lsst.afw.image.Exposure`
1648 The flat and dark corrected exposure.
1649 """
1650 interpExp = ccdExposure.clone()
1651
1652 # We need to interpolate before we do B-F. Note that
1653 # brighterFatterFwhmForInterpolation is currently unused.
1654 isrFunctions.interpolateFromMask(
1655 maskedImage=interpExp.getMaskedImage(),
1656 fwhm=self.config.brighterFatterFwhmForInterpolation,
1657 growSaturatedFootprints=self.config.growSaturationFootprintSize,
1658 maskNameList=list(self.config.brighterFatterMaskListToInterpolate),
1659 useLegacyInterp=self.config.useLegacyInterp,
1660 )
1661
1662 bfExp = interpExp.clone()
1663
1665 bfExp, bfKernel,
1666 self.config.brighterFatterMaxIter,
1667 self.config.brighterFatterThreshold,
1668 brighterFatterApplyGain,
1669 bfGains,
1670 )
1671
1672 bfCorrIters = bfResults[1]
1673 if bfCorrIters == self.config.brighterFatterMaxIter:
1674 self.log.warning("Brighter-fatter correction did not converge, final difference %f.",
1675 bfResults[0])
1676 else:
1677 self.log.info("Finished brighter-fatter correction in %d iterations.",
1678 bfResults[1])
1679
1680 image = ccdExposure.getMaskedImage().getImage()
1681 bfCorr = bfExp.getMaskedImage().getImage()
1682 bfCorr -= interpExp.getMaskedImage().getImage()
1683 image += bfCorr
1684
1685 # Applying the brighter-fatter correction applies a
1686 # convolution to the science image. At the edges this
1687 # convolution may not have sufficient valid pixels to
1688 # produce a valid correction. Mark pixels within the size
1689 # of the brighter-fatter kernel as EDGE to warn of this
1690 # fact.
1691 self.log.info("Ensuring image edges are masked as EDGE to the brighter-fatter kernel size.")
1692 self.maskEdges(ccdExposure, numEdgePixels=numpy.max(bfKernel.shape) // 2,
1693 maskPlane="EDGE")
1694
1695 if self.config.brighterFatterMaskGrowSize > 0:
1696 self.log.info("Growing masks to account for brighter-fatter kernel convolution.")
1697 for maskPlane in self.config.brighterFatterMaskListToInterpolate:
1698 isrFunctions.growMasks(ccdExposure.getMask(),
1699 radius=self.config.brighterFatterMaskGrowSize,
1700 maskNameList=maskPlane,
1701 maskValue=maskPlane)
1702
1703 # Set the metadata here.
1704 ccdExposure.metadata["LSST ISR BF ITERS"] = bfCorrIters
1705
1706 return ccdExposure
1707
1708 def applyBrighterFatterCorrection(self, ccdExposure, flat, dark, bfKernel, brighterFatterApplyGain,
1709 bfGains):
1710 """Apply a brighter fatter correction to the image using the
1711 method defined in Coulton et al. 2019.
1712
1713 Note that this correction requires that the image is in units
1714 electrons.
1715
1716 Parameters
1717 ----------
1718 ccdExposure : `lsst.afw.image.Exposure`
1719 Exposure to process.
1720 flat : `lsst.afw.image.Exposure`
1721 Flat exposure the same size as ``exp``.
1722 dark : `lsst.afw.image.Exposure`, optional
1723 Dark exposure the same size as ``exp``.
1724 bfKernel : `lsst.ip.isr.BrighterFatterKernel`
1725 The brighter-fatter kernel.
1726 brighterFatterApplyGain : `bool`
1727 Apply the gain to convert the image to electrons?
1728 bfGains : `dict`
1729 The gains to use if brighterFatterApplyGain = True.
1730
1731 Yields
1732 ------
1733 exp : `lsst.afw.image.Exposure`
1734 The flat and dark corrected exposure.
1735 """
1736 interpExp = ccdExposure.clone()
1737
1738 # We need to interpolate before we do B-F. Note that
1739 # brighterFatterFwhmForInterpolation is currently unused.
1740 isrFunctions.interpolateFromMask(
1741 maskedImage=interpExp.getMaskedImage(),
1742 fwhm=self.config.brighterFatterFwhmForInterpolation,
1743 growSaturatedFootprints=self.config.growSaturationFootprintSize,
1744 maskNameList=list(self.config.brighterFatterMaskListToInterpolate),
1745 useLegacyInterp=self.config.useLegacyInterp,
1746 )
1747 bfExp = interpExp.clone()
1748 bfResults = brighterFatterCorrection(bfExp, bfKernel,
1749 self.config.brighterFatterMaxIter,
1750 self.config.brighterFatterThreshold,
1751 brighterFatterApplyGain,
1752 bfGains)
1753 bfCorrIters = bfResults[1]
1754 if bfCorrIters == self.config.brighterFatterMaxIter:
1755 self.log.warning("Brighter-fatter correction did not converge, final difference %f.",
1756 bfResults[0])
1757 else:
1758 self.log.info("Finished brighter-fatter correction in %d iterations.",
1759 bfResults[1])
1760
1761 image = ccdExposure.getMaskedImage().getImage()
1762 bfCorr = bfExp.getMaskedImage().getImage()
1763 bfCorr -= interpExp.getMaskedImage().getImage()
1764 image += bfCorr
1765
1766 # Applying the brighter-fatter correction applies a
1767 # convolution to the science image. At the edges this
1768 # convolution may not have sufficient valid pixels to
1769 # produce a valid correction. Mark pixels within the size
1770 # of the brighter-fatter kernel as EDGE to warn of this
1771 # fact.
1772 self.log.info("Ensuring image edges are masked as EDGE to the brighter-fatter kernel size.")
1773 self.maskEdges(ccdExposure, numEdgePixels=numpy.max(bfKernel.shape) // 2,
1774 maskPlane="EDGE")
1775
1776 if self.config.brighterFatterMaskGrowSize > 0:
1777 self.log.info("Growing masks to account for brighter-fatter kernel convolution.")
1778 for maskPlane in self.config.brighterFatterMaskListToInterpolate:
1779 isrFunctions.growMasks(ccdExposure.getMask(),
1780 radius=self.config.brighterFatterMaskGrowSize,
1781 maskNameList=maskPlane,
1782 maskValue=maskPlane)
1783
1784 # Set the metadata here.
1785 ccdExposure.metadata["LSST ISR BF ITERS"] = bfCorrIters
1786
1787 return ccdExposure
1788
1789 def darkCorrection(self, exposure, darkExposure, invert=False):
1790 """Apply dark correction in place.
1791
1792 Parameters
1793 ----------
1794 exposure : `lsst.afw.image.Exposure`
1795 Exposure to process.
1796 darkExposure : `lsst.afw.image.Exposure`
1797 Dark exposure of the same size as ``exposure``.
1798 invert : `Bool`, optional
1799 If True, re-add the dark to an already corrected image.
1800
1801 Raises
1802 ------
1803 RuntimeError
1804 Raised if either ``exposure`` or ``darkExposure`` do not
1805 have their dark time defined.
1806
1807 See Also
1808 --------
1809 lsst.ip.isr.isrFunctions.darkCorrection
1810 """
1811 expScale = exposure.visitInfo.darkTime
1812 imageOnly = not self.config.doVariance
1813 if math.isnan(expScale):
1814 raise RuntimeError("Exposure darktime is NAN.")
1815 if darkExposure.visitInfo is not None \
1816 and not math.isnan(darkExposure.visitInfo.darkTime):
1817 darkScale = darkExposure.visitInfo.darkTime
1818 else:
1819 # DM-17444: darkExposure.visitInfo is None
1820 # so darkTime does not exist.
1821 self.log.warning("darkExposure.visitInfo does not exist. Using darkScale = 1.0.")
1822 darkScale = 1.0
1823
1824 isrFunctions.darkCorrection(
1825 maskedImage=exposure.maskedImage,
1826 darkMaskedImage=darkExposure.maskedImage,
1827 expScale=expScale,
1828 darkScale=darkScale,
1829 invert=invert,
1830 imageOnly=imageOnly,
1831 )
1832
1833 @staticmethod
1835 """Extract common calibration metadata values that will be written to
1836 output header.
1837
1838 Parameters
1839 ----------
1840 calib : `lsst.afw.image.Exposure` or `lsst.ip.isr.IsrCalib`
1841 Calibration to pull date information from.
1842
1843 Returns
1844 -------
1845 dateString : `str`
1846 Calibration creation date string to add to header.
1847 """
1848 if hasattr(calib, "getMetadata"):
1849 if 'CALIB_CREATION_DATE' in calib.metadata:
1850 return " ".join((calib.metadata.get("CALIB_CREATION_DATE", "Unknown"),
1851 calib.metadata.get("CALIB_CREATION_TIME", "Unknown")))
1852 else:
1853 return " ".join((calib.metadata.get("CALIB_CREATE_DATE", "Unknown"),
1854 calib.metadata.get("CALIB_CREATE_TIME", "Unknown")))
1855 else:
1856 return "Unknown Unknown"
1857
1858 def compareUnits(self, calibMetadata, calibName):
1859 """Compare units from calibration to ISR units.
1860
1861 This compares calibration units (adu or electron) to whether
1862 doApplyGain is set.
1863
1864 Parameters
1865 ----------
1866 calibMetadata : `lsst.daf.base.PropertyList`
1867 Calibration metadata from header.
1868 calibName : `str`
1869 Calibration name for log message.
1870 """
1871 calibUnits = calibMetadata.get("LSST ISR UNITS", "adu")
1872 isrUnits = "electron" if self.config.doApplyGains else "adu"
1873 if calibUnits != isrUnits:
1874 if self.config.doRaiseOnCalibMismatch:
1875 raise RuntimeError(
1876 "Unit mismatch: isr has %s units but %s has %s units",
1877 isrUnits,
1878 calibName,
1879 calibUnits,
1880 )
1881 else:
1882 self.log.warning(
1883 "Unit mismatch: isr has %s units but %s has %s units",
1884 isrUnits,
1885 calibName,
1886 calibUnits,
1887 )
1888
1889 def convertIntToFloat(self, exposure):
1890 """Convert exposure image from uint16 to float.
1891
1892 If the exposure does not need to be converted, the input is
1893 immediately returned. For exposures that are converted to use
1894 floating point pixels, the variance is set to unity and the
1895 mask to zero.
1896
1897 Parameters
1898 ----------
1899 exposure : `lsst.afw.image.Exposure`
1900 The raw exposure to be converted.
1901
1902 Returns
1903 -------
1904 newexposure : `lsst.afw.image.Exposure`
1905 The input ``exposure``, converted to floating point pixels.
1906
1907 Raises
1908 ------
1909 RuntimeError
1910 Raised if the exposure type cannot be converted to float.
1911
1912 """
1913 if isinstance(exposure, afwImage.ExposureF):
1914 # Nothing to be done
1915 self.log.debug("Exposure already of type float.")
1916 return exposure
1917 if not hasattr(exposure, "convertF"):
1918 raise RuntimeError("Unable to convert exposure (%s) to float." % type(exposure))
1919
1920 newexposure = exposure.convertF()
1921 newexposure.variance[:] = 1
1922 newexposure.mask[:] = 0x0
1923
1924 return newexposure
1925
1926 def ditherCounts(self, exposure, detectorConfig, fallbackSeed=12345):
1927 """Dither the counts in the exposure.
1928
1929 Parameters
1930 ----------
1931 exposure : `lsst.afw.image.Exposure`
1932 The raw exposure to be dithered.
1933 detectorConfig : `lsst.ip.isr.OverscanDetectorConfig`
1934 Configuration for overscan/etc for this detector.
1935 fallbackSeed : `int`, optional
1936 Random seed to fall back to if exposure.getInfo().getId() is
1937 not set.
1938 """
1939 if detectorConfig.integerDitherMode == "NONE":
1940 # Nothing to do here.
1941 return
1942
1943 # This ID is a unique combination of {exposure, detector} for a raw
1944 # image as we have here. We additionally need to take the lower
1945 # 32 bits to be used as a random seed.
1946 if exposure.info.id is not None:
1947 seed = exposure.info.id & 0xFFFFFFFF
1948 else:
1949 seed = fallbackSeed
1950 self.log.warning("No exposure ID found; using fallback random seed.")
1951
1952 self.log.info("Seeding dithering random number generator with %d.", seed)
1953 rng = numpy.random.RandomState(seed=seed)
1954
1955 if detectorConfig.integerDitherMode == "POSITIVE":
1956 low = 0.0
1957 high = 1.0
1958 elif detectorConfig.integerDitherMode == "NEGATIVE":
1959 low = -1.0
1960 high = 0.0
1961 elif detectorConfig.integerDitherMode == "SYMMETRIC":
1962 low = -0.5
1963 high = 0.5
1964 else:
1965 raise RuntimeError("Invalid config")
1966
1967 exposure.image.array[:, :] += rng.uniform(low=low, high=high, size=exposure.image.array.shape)
1968
1969 def checkBssVoltage(self, exposure):
1970 """Check the back-side bias voltage to see if the detector is on.
1971
1972 Parameters
1973 ----------
1974 exposure : `lsst.afw.image.ExposureF`
1975 Input exposure.
1976
1977 Raises
1978 ------
1979 `UnprocessableDataError` if voltage is off.
1980 """
1981 voltage = exposure.metadata.get(self.config.bssVoltageKeyword, None)
1982 if voltage is None or not numpy.isfinite(voltage):
1983 self.log.warning(
1984 "Back-side bias voltage %s not found in metadata.",
1985 self.config.bssVoltageKeyword,
1986 )
1987 return
1988
1989 hv = exposure.metadata.get(self.config.hvBiasKeyword, None)
1990 if hv is None:
1991 self.log.warning(
1992 "HV bias on %s not found in metadata.",
1993 self.config.hvBiasKeyword,
1994 )
1995 return
1996
1997 if voltage < self.config.bssVoltageMinimum or hv == "OFF":
1998 detector = exposure.getDetector()
1999 raise UnprocessableDataError(
2000 f"Back-side bias voltage is turned off for {detector.getName()}; skipping ISR.",
2001 )
2002
2003 @deprecated(
2004 reason=(
2005 "makeBinnedImages is no longer used. "
2006 "Please subtask lsst.ip.isr.BinImageDataTask instead."
2007 ),
2008 version="v28", category=FutureWarning
2009 )
2010 def makeBinnedImages(self, exposure):
2011 """Make visualizeVisit style binned exposures.
2012
2013 Parameters
2014 ----------
2015 exposure : `lsst.afw.image.Exposure`
2016 Exposure to bin.
2017
2018 Returns
2019 -------
2020 bin1 : `lsst.afw.image.Exposure`
2021 Binned exposure using binFactor1.
2022 bin2 : `lsst.afw.image.Exposure`
2023 Binned exposure using binFactor2.
2024 """
2025 mi = exposure.getMaskedImage()
2026
2027 bin1 = afwMath.binImage(mi, self.config.binFactor1)
2028 bin2 = afwMath.binImage(mi, self.config.binFactor2)
2029
2030 bin1 = afwImage.makeExposure(bin1)
2031 bin2 = afwImage.makeExposure(bin2)
2032
2033 bin1.setInfo(exposure.getInfo())
2034 bin2.setInfo(exposure.getInfo())
2035
2036 return bin1, bin2
2037
2038 def run(
2039 self,
2040 ccdExposure,
2041 *,
2042 dnlLUT=None,
2043 bias=None,
2044 deferredChargeCalib=None,
2045 linearizer=None,
2046 ptc=None,
2047 gainCorrection=None,
2048 crosstalk=None,
2049 defects=None,
2050 bfKernel=None,
2051 electroBfDistortionMatrix=None,
2052 dark=None,
2053 flat=None,
2054 camera=None,
2055 ):
2056 """Run the IsrTaskLSST task.
2057
2058 Parameters
2059 ----------
2060 ccdExposure : `lsst.afw.image.Exposure`
2061 Exposure to run ISR.
2062 dnlLUT : `None`, optional
2063 DNL lookup table; placeholder, unused.
2064 bias : `lsst.afw.image.Exposure`, optional
2065 Bias frame.
2066 deferredChargeCalib : `lsst.ip.isr.DeferredChargeCalib`, optional
2067 Deferred charge calibration.
2068 linearizer : `lsst.ip.isr.Linearizer`, optional
2069 Linearizer calibration.
2070 ptc : `lsst.ip.isr.PhotonTransferCurveDataset`, optional
2071 PTC dataset.
2072 gainCorrection : `lsst.ip.isr.GainCorrection`, optional
2073 Gain correction dataset.
2074 crosstalk : `lsst.ip.isr.CrosstalkCalib`, optional
2075 Crosstalk calibration dataset.
2076 defects : `lsst.ip.isr.Defects`, optional
2077 Defects dataset.
2078 bfKernel : `lsst.ip.isr.BrighterFatterKernel`, optional
2079 Brighter-fatter kernel dataset.
2080 dark : `lsst.afw.image.Exposure`, optional
2081 Dark frame.
2082 flat : `lsst.afw.image.Exposure`, optional
2083 Flat-field frame.
2084 camera : `lsst.afw.cameraGeom.Camera`, optional
2085 Camera object.
2086
2087 Returns
2088 -------
2089 result : `lsst.pipe.base.Struct`
2090 Struct with fields:
2091 ``exposure``: `lsst.afw.image.Exposure`
2092 Calibrated exposure.
2093 ``outputBin1Exposure``: `lsst.afw.image.Exposure`
2094 Binned exposure (bin1 config).
2095 ``outputBin2Exposure``: `lsst.afw.image.Exposure`
2096 Binned exposure (bin2 config).
2097 ``outputExposure``: `lsst.afw.image.Exposure`
2098 Calibrated exposure (same as ``exposure``).
2099 ``outputStatistics``: `lsst.ip.isr.isrStatistics`
2100 Calibrated exposure statistics.
2101 """
2102 detector = ccdExposure.getDetector()
2103
2104 overscanDetectorConfig = self.config.overscanCamera.getOverscanDetectorConfig(detector)
2105
2106 if self.config.doBootstrap:
2107 if ptc is not None:
2108 self.log.warning("Task configured with doBootstrap=True. Ignoring provided PTC.")
2109 ptc = None
2110 else:
2111 if self.config.useGainsFrom == "LINEARIZER":
2112 if linearizer is None:
2113 raise RuntimeError("doBootstrap==False and useGainsFrom == 'LINEARIZER' but "
2114 "no linearizer provided.")
2115 elif self.config.useGainsFrom == "PTC":
2116 if ptc is None:
2117 raise RuntimeError("doBootstrap==False and useGainsFrom == 'PTC' but no PTC provided.")
2118
2119 # Validation step: check inputs match exposure configuration.
2120 exposureMetadata = ccdExposure.metadata
2121 doRaise = self.config.doRaiseOnCalibMismatch
2122 keywords = self.config.cameraKeywordsToCompare
2123 if not self.config.doBootstrap:
2124 if self.config.useGainsFrom == "LINEARIZER":
2125 compareCameraKeywords(doRaise, keywords, exposureMetadata, linearizer,
2126 "LINEARIZER", log=self.log)
2127 elif self.config.useGainsFrom == "PTC":
2128 compareCameraKeywords(doRaise, keywords, exposureMetadata, ptc, "PTC",
2129 log=self.log)
2130 # Note that doCorrectGains can be True without a gainCorrection.
2131 if self.config.doCorrectGains and gainCorrection is not None:
2133 doRaise,
2134 keywords,
2135 exposureMetadata,
2136 gainCorrection,
2137 "gain_correction",
2138 log=self.log,
2139 )
2140 else:
2141 if self.config.doCorrectGains:
2142 raise RuntimeError("doCorrectGains is True but no ptc provided.")
2143 if self.config.doDiffNonLinearCorrection:
2144 if dnlLUT is None:
2145 raise RuntimeError("doDiffNonLinearCorrection is True but no dnlLUT provided.")
2146 compareCameraKeywords(doRaise, keywords, exposureMetadata, dnlLUT, "dnlLUT", log=self.log)
2147 if self.config.doLinearize:
2148 if linearizer is None:
2149 raise RuntimeError("doLinearize is True but no linearizer provided.")
2150 compareCameraKeywords(doRaise, keywords, exposureMetadata, linearizer, "linearizer", log=self.log)
2151 if self.config.doBias:
2152 if bias is None:
2153 raise RuntimeError("doBias is True but no bias provided.")
2154 compareCameraKeywords(doRaise, keywords, exposureMetadata, bias, "bias", log=self.log)
2155 self.compareUnits(bias.metadata, "bias")
2156 if self.config.doCrosstalk:
2157 if crosstalk is None:
2158 raise RuntimeError("doCrosstalk is True but no crosstalk provided.")
2159 compareCameraKeywords(doRaise, keywords, exposureMetadata, crosstalk, "crosstalk", log=self.log)
2160 if self.config.doDeferredCharge:
2161 if deferredChargeCalib is None:
2162 raise RuntimeError("doDeferredCharge is True but no deferredChargeCalib provided.")
2164 doRaise,
2165 keywords,
2166 exposureMetadata,
2167 deferredChargeCalib,
2168 "CTI",
2169 log=self.log,
2170 )
2171 if self.config.doDefect:
2172 if defects is None:
2173 raise RuntimeError("doDefect is True but no defects provided.")
2174 compareCameraKeywords(doRaise, keywords, exposureMetadata, defects, "defects", log=self.log)
2175 if self.config.doDark:
2176 if dark is None:
2177 raise RuntimeError("doDark is True but no dark frame provided.")
2178 compareCameraKeywords(doRaise, keywords, exposureMetadata, dark, "dark", log=self.log)
2179 self.compareUnits(bias.metadata, "dark")
2180 if self.config.doBrighterFatter:
2181 if self.config.brighterFatterCorrectionMethod in ["ASTIER23", "ASTIER23+FILTERCORRECTION"]:
2182 if electroBfDistortionMatrix is None:
2183 raise RuntimeError("Must supply an electroBfDistortionMatrix if BF "
2184 "correction method is ASTIER23*.")
2185 compareCameraKeywords(doRaise, keywords, exposureMetadata,
2186 electroBfDistortionMatrix, "bf", log=self.log)
2187 elif self.config.brighterFatterCorrectionMethod in ["COULTON18", "COULTON18_FLUX_CONSERVING"]:
2188 if bfKernel is None:
2189 raise RuntimeError("Must supply an kernel if BF correction method is COULTON*.")
2190 compareCameraKeywords(doRaise, keywords, exposureMetadata, bfKernel, "bf", log=self.log)
2191 else:
2192 raise ValueError("%s is not a known brighter-fatter correction "
2193 "method." % self.config.brighterFatterCorrectionMethod)
2194 if self.config.doFlat:
2195 if flat is None:
2196 raise RuntimeError("doFlat is True but no flat provided.")
2197 compareCameraKeywords(doRaise, keywords, exposureMetadata, flat, "flat", log=self.log)
2198
2199 if self.config.doSaturation:
2200 if self.config.defaultSaturationSource in ["PTCTURNOFF",]:
2201 if ptc is None:
2202 raise RuntimeError(
2203 "doSaturation is True and defaultSaturationSource is "
2204 f"{self.config.defaultSaturationSource}, but no ptc provided."
2205 )
2206 if self.config.doSuspect:
2207 if self.config.defaultSuspectSource in ["PTCTURNOFF",]:
2208 if ptc is None:
2209 raise RuntimeError(
2210 "doSuspect is True and defaultSuspectSource is "
2211 f"{self.config.defaultSuspectSource}, but no ptc provided."
2212 )
2213
2214 if self.config.doCheckUnprocessableData and self.config.bssVoltageMinimum > 0.0:
2215 self.checkBssVoltage(ccdExposure)
2216
2217 # FIXME: Make sure that if linearity is done then it is matched
2218 # with the right PTC.
2219
2220 # We keep track of units: start in adu.
2221 exposureMetadata["LSST ISR UNITS"] = "adu"
2222 exposureMetadata["LSST ISR GAINCORRECTION APPLIED"] = False
2223 exposureMetadata["LSST ISR CROSSTALK APPLIED"] = False
2224 exposureMetadata["LSST ISR OVERSCANLEVEL CHECKED"] = False
2225 exposureMetadata["LSST ISR NOISE CHECKED"] = False
2226 exposureMetadata["LSST ISR LINEARIZER APPLIED"] = False
2227 exposureMetadata["LSST ISR CTI APPLIED"] = False
2228 exposureMetadata["LSST ISR BIAS APPLIED"] = False
2229 exposureMetadata["LSST ISR DARK APPLIED"] = False
2230 exposureMetadata["LSST ISR BF APPLIED"] = False
2231 exposureMetadata["LSST ISR FLAT APPLIED"] = False
2232 exposureMetadata["LSST ISR DEFECTS APPLIED"] = False
2233
2234 if self.config.doBootstrap:
2235 self.log.info("Configured using doBootstrap=True; using gain of 1.0 (adu units)")
2236 ptc = PhotonTransferCurveDataset([amp.getName() for amp in detector], "NOMINAL_PTC", 1)
2237 for amp in detector:
2238 ptc.gain[amp.getName()] = 1.0
2239 ptc.noise[amp.getName()] = 0.0
2240 ptc.ptcTurnoff[amp.getName()] = numpy.inf
2241 elif self.config.useGainsFrom == "LINEARIZER":
2242 self.log.info("Using gains from linearizer.")
2243 # Create a dummy ptc object to hold the gains from the linearizer.
2244 ptc = PhotonTransferCurveDataset([amp.getName() for amp in detector], "NOMINAL_PTC", 1)
2245 for amp in detector:
2246 ptc.gain[amp.getName()] = linearizer.inputGain[amp.getName()]
2247 ptc.noise[amp.getName()] = 0.0
2248 ptc.ptcTurnoff[amp.getName()] = linearizer.inputTurnoff[amp.getName()]
2249
2250 exposureMetadata["LSST ISR BOOTSTRAP"] = self.config.doBootstrap
2251
2252 # Choose the gains to use
2253 gains = copy.copy(ptc.gain)
2254
2255 # And check if we have configured gains to override. This is
2256 # also a warning, since it should not be typical usage.
2257 for amp in detector:
2258 if not math.isnan(gain := overscanDetectorConfig.getOverscanAmpConfig(amp).gain):
2259 gains[amp.getName()] = gain
2260 self.log.warning(
2261 "Overriding gain for amp %s with configured value of %.3f.",
2262 amp.getName(),
2263 gain,
2264 )
2265
2266 # First we convert the exposure to floating point values
2267 # (if necessary).
2268 self.log.debug("Converting exposure to floating point values.")
2269 ccdExposure = self.convertIntToFloat(ccdExposure)
2270
2271 # Then we mark which amplifiers are completely bad from defects.
2272 badAmpDict = self.maskFullAmplifiers(ccdExposure, detector, defects, gains=gains)
2273
2274 self.checkAllBadAmps(badAmpDict, detector)
2275
2276 # Now we go through ISR steps.
2277
2278 # Differential non-linearity correction.
2279 # Units: adu
2280 if self.config.doDiffNonLinearCorrection:
2281 self.diffNonLinearCorrection(ccdExposure, dnlLUT)
2282
2283 # Dither the integer counts.
2284 # Input units: integerized adu
2285 # Output units: floating-point adu
2286 self.ditherCounts(ccdExposure, overscanDetectorConfig)
2287
2288 # Serial overscan correction.
2289 # Input units: adu
2290 # Output units: adu
2291 if overscanDetectorConfig.doAnySerialOverscan:
2292 serialOverscans = self.overscanCorrection(
2293 "SERIAL",
2294 overscanDetectorConfig,
2295 detector,
2296 badAmpDict,
2297 ccdExposure,
2298 )
2299
2300 if self.config.doBootstrap or self.config.useGainsFrom == "LINEARIZER":
2301 # Get the empirical read noise
2302 for amp, serialOverscan in zip(detector, serialOverscans):
2303 if serialOverscan is None:
2304 ptc.noise[amp.getName()] = 0.0
2305 else:
2306 # All PhotonTransferCurveDataset objects should contain
2307 # noise attributes in units of electrons. The read
2308 # noise measured from overscans is always in adu, so we
2309 # scale it by the gain.
2310 # Note that in bootstrap mode, these gains will always
2311 # be 1.0, but we put this conversion here for clarity.
2312 ptc.noise[amp.getName()] = serialOverscan.residualSigma * gains[amp.getName()]
2313 else:
2314 serialOverscans = [None]*len(detector)
2315
2316 # After serial overscan correction, we can mask SATURATED and
2317 # SUSPECT pixels. This updates badAmpDict if any amplifier
2318 # is fully saturated after serial overscan correction.
2319
2320 # The saturation is currently assumed to be recorded in
2321 # overscan-corrected adu.
2322 badAmpDict = self.maskSaturatedPixels(
2323 badAmpDict,
2324 ccdExposure,
2325 detector,
2326 overscanDetectorConfig,
2327 ptc=ptc,
2328 )
2329
2330 self.checkAllBadAmps(badAmpDict, detector)
2331
2332 if self.config.doCorrectGains and gainCorrection is not None:
2333 self.log.info("Correcting gains based on input GainCorrection.")
2334 gainCorrection.correctGains(gains, exposure=ccdExposure)
2335 exposureMetadata["LSST ISR GAINCORRECTION APPLIED"] = True
2336 elif self.config.doCorrectGains:
2337 self.log.info("Skipping gain correction because no GainCorrection available.")
2338
2339 # Do gain normalization.
2340 # Input units: adu
2341 # Output units: electron
2342 if self.config.doApplyGains:
2343 self.log.info("Using gain values to convert from adu to electron units.")
2344 isrFunctions.applyGains(ccdExposure, normalizeGains=False, ptcGains=gains, isTrimmed=False)
2345 # The units are now electron.
2346 exposureMetadata["LSST ISR UNITS"] = "electron"
2347
2348 # Update the saturation units in the metadata if there.
2349 # These will always have the same units as the image.
2350 for amp in detector:
2351 ampName = amp.getName()
2352 if (key := f"LSST ISR SATURATION LEVEL {ampName}") in exposureMetadata:
2353 exposureMetadata[key] *= gains[ampName]
2354 if (key := f"LSST ISR SUSPECT LEVEL {ampName}") in exposureMetadata:
2355 exposureMetadata[key] *= gains[ampName]
2356
2357 # Record gain and read noise in header.
2358 metadata = ccdExposure.metadata
2359 metadata["LSST ISR READNOISE UNITS"] = "electron"
2360 metadata["LSST ISR PTCTURNOFF UNITS"] = "electron"
2361 metadata["LSST ISR GAIN SOURCE"] = self.config.useGainsFrom
2362 for amp in detector:
2363 # This includes any gain correction (if applied).
2364 metadata[f"LSST ISR GAIN {amp.getName()}"] = gains[amp.getName()]
2365
2366 # At this stage, the read noise is always in electrons.
2367 metadata[f"LSST ISR READNOISE {amp.getName()}"] = ptc.noise[amp.getName()]
2368
2369 # And the ptc turnoff will be in electrons.
2370 turnoff = ptc.ptcTurnoff[amp.getName()] * gains[amp.getName()]
2371 metadata[f"LSST ISR PTCTURNOFF {amp.getName()}"] = turnoff
2372
2373 # Do crosstalk correction in the full region.
2374 # Output units: electron (adu if doBootstrap=True)
2375 if self.config.doCrosstalk:
2376 self.log.info("Applying crosstalk corrections to full amplifier region.")
2377 if self.config.doBootstrap and numpy.any(crosstalk.fitGains != 0):
2378 crosstalkGains = None
2379 else:
2380 crosstalkGains = gains
2381 self.crosstalk.run(
2382 ccdExposure,
2383 crosstalk=crosstalk,
2384 gains=crosstalkGains,
2385 fullAmplifier=True,
2386 badAmpDict=badAmpDict,
2387 ignoreVariance=True,
2388 )
2389 ccdExposure.metadata["LSST ISR CROSSTALK APPLIED"] = True
2390
2391 # After crosstalk, we check for amplifier noise and state changes.
2392 if numpy.isfinite(self.config.serialOverscanMedianShiftSigmaThreshold):
2393 badAmpDict = self.checkAmpOverscanLevel(badAmpDict, ccdExposure, ptc)
2394 ccdExposure.metadata["LSST ISR OVERSCANLEVEL CHECKED"] = True
2395
2396 if numpy.isfinite(self.config.ampNoiseThreshold):
2397 badAmpDict = self.checkAmpNoise(badAmpDict, ccdExposure, ptc)
2398 ccdExposure.metadata["LSST ISR NOISE CHECKED"] = True
2399
2400 if numpy.isfinite(self.config.serialOverscanMedianShiftSigmaThreshold) or \
2401 numpy.isfinite(self.config.ampNoiseThreshold):
2402 self.checkAllBadAmps(badAmpDict, detector)
2403
2404 # Parallel overscan correction.
2405 # Output units: electron (adu if doBootstrap=True)
2406 parallelOverscans = None
2407 if overscanDetectorConfig.doAnyParallelOverscan:
2408 # At the moment we do not use the return values from this task.
2409 parallelOverscans = self.overscanCorrection(
2410 "PARALLEL",
2411 overscanDetectorConfig,
2412 detector,
2413 badAmpDict,
2414 ccdExposure,
2415 )
2416
2417 # Linearity correction
2418 # Output units: electron (adu if doBootstrap=True)
2419 if self.config.doLinearize:
2420 self.log.info("Applying linearizer.")
2421 # The linearizer is in units of adu.
2422 # If our units are electron, then pass in the gains
2423 # for conversion.
2424 if exposureMetadata["LSST ISR UNITS"] == "electron":
2425 linearityGains = gains
2426 else:
2427 linearityGains = None
2428 linearizer.applyLinearity(
2429 image=ccdExposure.image,
2430 detector=detector,
2431 log=self.log,
2432 gains=linearityGains,
2433 )
2434 ccdExposure.metadata["LSST ISR LINEARIZER APPLIED"] = True
2435
2436 # Serial CTI (deferred charge) correction
2437 # This will be performed in electron units
2438 # Output units: same as input units
2439 if self.config.doDeferredCharge:
2440 if self.config.doBootstrap:
2441 self.log.info("Applying deferred charge correction with doBootstrap=True: "
2442 "will need to use deferredChargeCalib.inputGain to apply "
2443 "CTI correction in electron units.")
2444 deferredChargeGains = deferredChargeCalib.inputGain
2445 if numpy.all(numpy.isnan(list(deferredChargeGains.values()))):
2446 self.log.warning("All gains contained in the deferredChargeCalib are "
2447 "NaN, approximating with gain of 1.0.")
2448 deferredChargeGains = gains
2449 else:
2450 deferredChargeGains = gains
2451 self.deferredChargeCorrection.run(
2452 ccdExposure,
2453 deferredChargeCalib,
2454 gains=deferredChargeGains,
2455 )
2456 ccdExposure.metadata["LSST ISR CTI APPLIED"] = True
2457
2458 # Save the untrimmed version for later statistics,
2459 # which still contains the overscan information
2460 untrimmedCcdExposure = None
2461 if self.config.isrStats.doCtiStatistics:
2462 untrimmedCcdExposure = ccdExposure.clone()
2463
2464 # Assemble/trim
2465 # Output units: electron (adu if doBootstrap=True)
2466 if self.config.doAssembleCcd:
2467 self.log.info("Assembling CCD from amplifiers.")
2468 ccdExposure = self.assembleCcd.assembleCcd(ccdExposure)
2469
2470 if self.config.expectWcs and not ccdExposure.getWcs():
2471 self.log.warning("No WCS found in input exposure.")
2472
2473 # E2V edge bleed
2474 if self.config.doE2VEdgeBleedMask and detector.getPhysicalType() == "E2V":
2475 isrFunctions.maskE2VEdgeBleed(
2476 exposure=ccdExposure,
2477 e2vEdgeBleedSatMinArea=self.config.e2vEdgeBleedSatMinArea,
2478 e2vEdgeBleedSatMaxArea=self.config.e2vEdgeBleedSatMaxArea,
2479 e2vEdgeBleedYMax=self.config.e2vEdgeBleedYMax,
2480 saturatedMaskName=self.config.saturatedMaskName,
2481 log=self.log,
2482 )
2483
2484 # ITL Dip Masking
2485 for maskPlane in self.config.itlDipMaskPlanes:
2486 if maskPlane not in ccdExposure.mask.getMaskPlaneDict():
2487 self.log.info("Adding %s mask plane to image.", maskPlane)
2488 ccdExposure.mask.addMaskPlane(maskPlane)
2489
2490 if self.config.doITLDipMask:
2491 isrFunctions.maskITLDip(
2492 exposure=ccdExposure,
2493 detectorConfig=overscanDetectorConfig,
2494 log=self.log,
2495 maskPlaneNames=self.config.itlDipMaskPlanes,
2496 )
2497
2498 if (self.config.doITLSatSagMask or self.config.doITLEdgeBleedMask) \
2499 and detector.getPhysicalType() == 'ITL':
2500 self.maskITLSatEdgesAndColumns(exposure=ccdExposure,
2501 badAmpDict=badAmpDict)
2502
2503 # Bias subtraction
2504 # Output units: electron (adu if doBootstrap=True)
2505 if self.config.doBias:
2506 self.log.info("Applying bias correction.")
2507 # Bias frame and ISR unit consistency is checked at the top of
2508 # the run method.
2509 isrFunctions.biasCorrection(
2510 ccdExposure.maskedImage,
2511 bias.maskedImage,
2512 imageOnly=not self.config.doVariance,
2513 )
2514 ccdExposure.metadata["LSST ISR BIAS APPLIED"] = True
2515
2516 # Dark subtraction
2517 # Output units: electron (adu if doBootstrap=True)
2518 if self.config.doDark:
2519 self.log.info("Applying dark subtraction.")
2520 # Dark frame and ISR unit consistency is checked at the top of
2521 # the run method.
2522 self.darkCorrection(ccdExposure, dark)
2523 ccdExposure.metadata["LSST ISR DARK APPLIED"] = True
2524
2525 # Defect masking
2526 # Masking block (defects, NAN pixels and trails).
2527 # Saturated and suspect pixels have already been masked.
2528 # Output units: electron (adu if doBootstrap=True)
2529 if self.config.doDefect:
2530 self.log.info("Applying defect masking.")
2531 self.maskDefects(ccdExposure, defects)
2532 ccdExposure.metadata["LSST ISR DEFECTS APPLIED"] = True
2533
2534 self.log.info("Adding UNMASKEDNAN mask plane to image.")
2535 ccdExposure.mask.addMaskPlane("UNMASKEDNAN")
2536 if self.config.doNanMasking:
2537 self.log.info("Masking non-finite (NAN, inf) value pixels.")
2538 self.maskNan(ccdExposure)
2539
2540 if self.config.doWidenSaturationTrails:
2541 self.log.info("Widening saturation trails.")
2542 isrFunctions.widenSaturationTrails(ccdExposure.getMaskedImage().getMask())
2543
2544 # Brighter-Fatter
2545 # Output units: electron (adu if doBootstrap=True)
2546 if self.config.doBrighterFatter:
2547 if "ASTIER23" in self.config.brighterFatterCorrectionMethod:
2548 # Do the Astier et al. 2023 Brighter-Fatter correction
2549 self.log.info("Applying electrostatic brighter-fatter "
2550 "correction.")
2551 bfCalib = electroBfDistortionMatrix
2552 bfGains = electroBfDistortionMatrix.gain
2553 bfCorrFunction = self.applyElectrostaticBrighterFatterCorrection
2554 elif self.config.brighterFatterCorrectionMethod == "COULTON18":
2555 # Do the Coulton et al. 2018 Brighter-Fatter correction
2556 self.log.info("Applying brighter-fatter correction.")
2557
2558 # Use the original gains used to compute the BFE
2559 bfCalib, bfGains = self.getBrighterFatterKernel(detector, bfKernel)
2560 bfCorrFunction = self.applyBrighterFatterCorrection
2561 elif self.config.brighterFatterCorrectionMethod == "COULTON18_FLUX_CONSERVING":
2562 # Do the Coulton et al. 2018 correction with flux conserving
2563 # corrections
2564 bfCalib, bfGains = self.getBrighterFatterKernel(detector, bfKernel)
2566 else:
2567 # This is an unknown BF correction type
2568 raise RuntimeError("Cannot perform brighter-fatter correction with unknown"
2569 "correction type.")
2570
2571 # Needs to be done in electrons; applyBrighterFatterCorrection
2572 # will convert the image if necessary.
2573 if exposureMetadata["LSST ISR UNITS"] == "electron":
2574 brighterFatterApplyGain = False
2575 else:
2576 brighterFatterApplyGain = True
2577
2578 if brighterFatterApplyGain and (ptc is not None) and (bfGains != gains):
2579 # The supplied ptc should be the same as the ptc used to
2580 # generate the bfKernel, in which case they will have the
2581 # same stored amp-keyed dictionary of gains. If not, there
2582 # is a mismatch in the calibrations being used. This should
2583 # not be always be a fatal error, but ideally, everything
2584 # should to be consistent.
2585 self.log.warning("Need to apply gain for brighter-fatter, but the stored"
2586 "gains in the kernel are not the same as the gains used"
2587 f"by {self.config.useGainsFrom}. Using the gains stored"
2588 "in the kernel.")
2589
2590 # Apply the BF correction
2591 ccdExposure = bfCorrFunction(
2592 ccdExposure,
2593 flat,
2594 dark,
2595 bfCalib,
2596 brighterFatterApplyGain,
2597 bfGains,
2598 )
2599
2600 ccdExposure.metadata["LSST ISR BF APPLIED"] = True
2601 ccdExposure.metadata["LSST ISR BF CORR METHOD"] = self.config.brighterFatterCorrectionMethod
2602
2603 # Variance plane creation
2604 # Output units: electron (adu if doBootstrap=True)
2605 if self.config.doVariance:
2606 self.addVariancePlane(ccdExposure, detector)
2607
2608 # Flat-fielding
2609 # This may move elsewhere, but this is the most convenient
2610 # location for simple flat-fielding for attractive backgrounds.
2611 # Output units: electron (adu if doBootstrap=True)
2612 if self.config.doFlat:
2613 self.log.info("Applying flat correction.")
2614 isrFunctions.flatCorrection(
2615 maskedImage=ccdExposure.maskedImage,
2616 flatMaskedImage=flat.maskedImage,
2617 scalingType=self.config.flatScalingType,
2618 userScale=self.config.flatUserScale,
2619 imageOnly=not self.config.doVariance,
2620 )
2621
2622 # Copy over valid polygon from flat if it is
2623 # available, and set NO_DATA to 0.0 (which may
2624 # be inherited from the flat in the fully
2625 # vignetted region).
2626 if (validPolygon := flat.info.getValidPolygon()) is not None:
2627 ccdExposure.info.setValidPolygon(validPolygon)
2628
2629 noData = (ccdExposure.mask.array & ccdExposure.mask.getPlaneBitMask("NO_DATA")) > 0
2630 ccdExposure.image.array[noData] = 0.0
2631 ccdExposure.variance.array[noData] = self.config.noDataVariance
2632
2633 ccdExposure.metadata["LSST ISR FLAT APPLIED"] = True
2634 ccdExposure.metadata["LSST ISR FLAT SOURCE"] = flat.metadata.get("FLATSRC", "UNKNOWN")
2635
2636 # Pixel values for masked regions are set here
2637 preInterpExp = None
2638 if self.config.doSaveInterpPixels:
2639 preInterpExp = ccdExposure.clone()
2640
2641 if self.config.doSetBadRegions:
2642 self.log.info('Setting values in large contiguous bad regions.')
2643 self.setBadRegions(ccdExposure)
2644
2645 if self.config.doInterpolate:
2646 self.log.info("Interpolating masked pixels.")
2647 isrFunctions.interpolateFromMask(
2648 maskedImage=ccdExposure.getMaskedImage(),
2649 fwhm=self.config.brighterFatterFwhmForInterpolation,
2650 growSaturatedFootprints=self.config.growSaturationFootprintSize,
2651 maskNameList=list(self.config.maskListToInterpolate),
2652 useLegacyInterp=self.config.useLegacyInterp,
2653 )
2654
2655 # Calculate amp offset corrections within the CCD.
2656 if self.config.doAmpOffset:
2657 if self.config.ampOffset.doApplyAmpOffset:
2658 self.log.info("Measuring and applying amp offset corrections.")
2659 else:
2660 self.log.info("Measuring amp offset corrections only, without applying them.")
2661 self.ampOffset.run(ccdExposure)
2662
2663 # Calculate standard image quality statistics
2664 if self.config.doStandardStatistics:
2665 metadata = ccdExposure.metadata
2666 for amp in detector:
2667 ampExposure = ccdExposure.Factory(ccdExposure, amp.getBBox())
2668 ampName = amp.getName()
2669 metadata[f"LSST ISR MASK SAT {ampName}"] = isrFunctions.countMaskedPixels(
2670 ampExposure.getMaskedImage(),
2671 [self.config.saturatedMaskName]
2672 )
2673 metadata[f"LSST ISR MASK BAD {ampName}"] = isrFunctions.countMaskedPixels(
2674 ampExposure.getMaskedImage(),
2675 ["BAD"]
2676 )
2677 metadata[f"LSST ISR MASK SUSPECT {ampName}"] = isrFunctions.countMaskedPixels(
2678 ampExposure.getMaskedImage(),
2679 ["SUSPECT"],
2680 )
2681 qaStats = afwMath.makeStatistics(ampExposure.getImage(),
2682 afwMath.MEAN | afwMath.MEDIAN | afwMath.STDEVCLIP)
2683
2684 metadata[f"LSST ISR FINAL MEAN {ampName}"] = qaStats.getValue(afwMath.MEAN)
2685 metadata[f"LSST ISR FINAL MEDIAN {ampName}"] = qaStats.getValue(afwMath.MEDIAN)
2686 metadata[f"LSST ISR FINAL STDEV {ampName}"] = qaStats.getValue(afwMath.STDEVCLIP)
2687
2688 k1 = f"LSST ISR FINAL MEDIAN {ampName}"
2689 k2 = f"LSST ISR OVERSCAN SERIAL MEDIAN {ampName}"
2690 if overscanDetectorConfig.doAnySerialOverscan and k1 in metadata and k2 in metadata:
2691 metadata[f"LSST ISR LEVEL {ampName}"] = metadata[k1] - metadata[k2]
2692 else:
2693 metadata[f"LSST ISR LEVEL {ampName}"] = numpy.nan
2694
2695 # calculate additional statistics.
2696 outputStatistics = None
2697 if self.config.doCalculateStatistics:
2698 outputStatistics = self.isrStats.run(ccdExposure,
2699 untrimmedInputExposure=untrimmedCcdExposure,
2700 serialOverscanResults=serialOverscans,
2701 parallelOverscanResults=parallelOverscans,
2702 bias=bias, dark=dark, flat=flat,
2703 ptc=ptc, defects=defects).results
2704
2705 # do image binning.
2706 outputBin1Exposure = None
2707 outputBin2Exposure = None
2708 if self.config.doBinnedExposures:
2709 self.log.info("Creating binned exposures.")
2710 outputBin1Exposure = self.binning.run(
2711 ccdExposure,
2712 binFactor=self.config.binFactor1,
2713 ).outputData
2714 outputBin2Exposure = self.binning.run(
2715 ccdExposure,
2716 binFactor=self.config.binFactor2,
2717 ).outputData
2718
2719 return pipeBase.Struct(
2720 exposure=ccdExposure,
2721
2722 outputBin1Exposure=outputBin1Exposure,
2723 outputBin2Exposure=outputBin2Exposure,
2724
2725 preInterpExposure=preInterpExp,
2726 outputExposure=ccdExposure,
2727 outputStatistics=outputStatistics,
2728 )
runQuantum(self, butlerQC, inputRefs, outputRefs)
ditherCounts(self, exposure, detectorConfig, fallbackSeed=12345)
flatContext(self, exp, flat, dark=None)
run(self, ccdExposure, *, dnlLUT=None, bias=None, deferredChargeCalib=None, linearizer=None, ptc=None, gainCorrection=None, crosstalk=None, defects=None, bfKernel=None, electroBfDistortionMatrix=None, dark=None, flat=None, camera=None)
checkAmpOverscanLevel(self, badAmpDict, exposure, ptc)
getBrighterFatterKernel(self, detector, bfKernel)
darkCorrection(self, exposure, darkExposure, invert=False)
compareUnits(self, calibMetadata, calibName)
overscanCorrection(self, mode, detectorConfig, detector, badAmpDict, ccdExposure)
applyBrighterFatterCorrection(self, ccdExposure, flat, dark, bfKernel, brighterFatterApplyGain, bfGains)
addVariancePlane(self, exposure, detector)
checkAmpNoise(self, badAmpDict, exposure, ptc)
diffNonLinearCorrection(self, ccdExposure, dnlLUT, **kwargs)
maskEdges(self, exposure, numEdgePixels=0, maskPlane="SUSPECT", level='DETECTOR')
maskDefects(self, exposure, defectBaseList)
checkAllBadAmps(self, badAmpDict, detector)
maskITLSatEdgesAndColumns(self, exposure, badAmpDict)
maskSaturatedPixels(self, badAmpDict, ccdExposure, detector, detectorConfig, ptc=None)
applyElectrostaticBrighterFatterCorrection(self, ccdExposure, flat, dark, electroBfDistortionMatrix, brighterFatterApplyGain, bfGains)
maskFullAmplifiers(self, ccdExposure, detector, defects, gains=None)
applyFluxConservingBrighterFatterCorrection(self, ccdExposure, flat, dark, bfKernel, brighterFatterApplyGain, bfGains)
fluxConservingBrighterFatterCorrection(exposure, kernel, maxIter, threshold, applyGain, gains=None, correctionMode=True)
brighterFatterCorrection(exposure, kernel, maxIter, threshold, applyGain, gains=None)
electrostaticBrighterFatterCorrection(log, exposure, electroBfDistortionMatrix, applyGain, gains=None, applyFilterCorrection=False)
compareCameraKeywords(doRaiseOnCalibMismatch, cameraKeywordsToCompare, exposureMetadata, calib, calibName, log=None)
size_t maskNans(afw::image::MaskedImage< PixelT > const &mi, afw::image::MaskPixel maskVal, afw::image::MaskPixel allow=0)
Mask NANs in an image.
Definition Isr.cc:35