-
Notifications
You must be signed in to change notification settings - Fork 14
/
isrTask.py
2769 lines (2472 loc) · 112 KB
/
isrTask.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This file is part of ip_isr.
#
# Developed for the LSST Data Management System.
# This product includes software developed by the LSST Project
# (https://www.lsst.org).
# See the COPYRIGHT file at the top-level directory of this distribution
# for details of code ownership.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
__all__ = ["IsrTask", "IsrTaskConfig"]
import math
import numpy
import lsst.geom
import lsst.afw.image as afwImage
import lsst.afw.math as afwMath
import lsst.pex.config as pexConfig
import lsst.pipe.base as pipeBase
import lsst.pipe.base.connectionTypes as cT
from contextlib import contextmanager
from lsstDebug import getDebugFrame
from lsst.afw.cameraGeom import NullLinearityType
from lsst.afw.display import getDisplay
from lsst.meas.algorithms.detection import SourceDetectionTask
from lsst.utils.timer import timeMethod
from . import isrFunctions
from . import isrQa
from . import linearize
from .defects import Defects
from .assembleCcdTask import AssembleCcdTask
from .crosstalk import CrosstalkTask, CrosstalkCalib
from .fringe import FringeTask
from .isr import maskNans
from .masking import MaskingTask
from .overscan import OverscanCorrectionTask
from .straylight import StrayLightTask
from .vignette import VignetteTask
from .ampOffset import AmpOffsetTask
from .deferredCharge import DeferredChargeTask
from .isrStatistics import IsrStatisticsTask
from .ptcDataset import PhotonTransferCurveDataset
def crosstalkSourceLookup(datasetType, registry, quantumDataId, collections):
"""Lookup function to identify crosstalkSource entries.
This should return an empty list under most circumstances. Only
when inter-chip crosstalk has been identified should this be
populated.
Parameters
----------
datasetType : `str`
Dataset to lookup.
registry : `lsst.daf.butler.Registry`
Butler registry to query.
quantumDataId : `lsst.daf.butler.DataCoordinate`
Expanded data id to transform to identify crosstalkSources. The
``detector`` entry will be stripped.
collections : `lsst.daf.butler.CollectionSearch`
Collections to search through.
Returns
-------
results : `list` [`lsst.daf.butler.DatasetRef`]
List of datasets that match the query that will be used as
crosstalkSources.
"""
newDataId = quantumDataId.subset(registry.dimensions.conform(["instrument", "exposure"]))
results = set(registry.queryDatasets(datasetType, collections=collections, dataId=newDataId,
findFirst=True))
# In some contexts, calling `.expanded()` to expand all data IDs in the
# query results can be a lot faster because it vectorizes lookups. But in
# this case, expandDataId shouldn't need to hit the database at all in the
# steady state, because only the detector record is unknown and those are
# cached in the registry.
records = {k: newDataId.records[k] for k in newDataId.dimensions.elements}
return [ref.expanded(registry.expandDataId(ref.dataId, records=records)) for ref in results]
class IsrTaskConnections(pipeBase.PipelineTaskConnections,
dimensions={"instrument", "exposure", "detector"},
defaultTemplates={}):
ccdExposure = cT.Input(
name="raw",
doc="Input exposure to process.",
storageClass="Exposure",
dimensions=["instrument", "exposure", "detector"],
)
camera = cT.PrerequisiteInput(
name="camera",
storageClass="Camera",
doc="Input camera to construct complete exposures.",
dimensions=["instrument"],
isCalibration=True,
)
crosstalk = cT.PrerequisiteInput(
name="crosstalk",
doc="Input crosstalk object",
storageClass="CrosstalkCalib",
dimensions=["instrument", "detector"],
isCalibration=True,
minimum=0, # can fall back to cameraGeom
)
crosstalkSources = cT.PrerequisiteInput(
name="isrOverscanCorrected",
doc="Overscan corrected input images.",
storageClass="Exposure",
dimensions=["instrument", "exposure", "detector"],
deferLoad=True,
multiple=True,
lookupFunction=crosstalkSourceLookup,
minimum=0, # not needed for all instruments, no config to control this
)
bias = cT.PrerequisiteInput(
name="bias",
doc="Input bias calibration.",
storageClass="ExposureF",
dimensions=["instrument", "detector"],
isCalibration=True,
)
dark = cT.PrerequisiteInput(
name='dark',
doc="Input dark calibration.",
storageClass="ExposureF",
dimensions=["instrument", "detector"],
isCalibration=True,
)
flat = cT.PrerequisiteInput(
name="flat",
doc="Input flat calibration.",
storageClass="ExposureF",
dimensions=["instrument", "physical_filter", "detector"],
isCalibration=True,
)
ptc = cT.PrerequisiteInput(
name="ptc",
doc="Input Photon Transfer Curve dataset",
storageClass="PhotonTransferCurveDataset",
dimensions=["instrument", "detector"],
isCalibration=True,
)
fringes = cT.PrerequisiteInput(
name="fringe",
doc="Input fringe calibration.",
storageClass="ExposureF",
dimensions=["instrument", "physical_filter", "detector"],
isCalibration=True,
minimum=0, # only needed for some bands, even when enabled
)
strayLightData = cT.PrerequisiteInput(
name='yBackground',
doc="Input stray light calibration.",
storageClass="StrayLightData",
dimensions=["instrument", "physical_filter", "detector"],
deferLoad=True,
isCalibration=True,
minimum=0, # only needed for some bands, even when enabled
)
bfKernel = cT.PrerequisiteInput(
name='bfKernel',
doc="Input brighter-fatter kernel.",
storageClass="NumpyArray",
dimensions=["instrument"],
isCalibration=True,
minimum=0, # can use either bfKernel or newBFKernel
)
newBFKernel = cT.PrerequisiteInput(
name='brighterFatterKernel',
doc="Newer complete kernel + gain solutions.",
storageClass="BrighterFatterKernel",
dimensions=["instrument", "detector"],
isCalibration=True,
minimum=0, # can use either bfKernel or newBFKernel
)
defects = cT.PrerequisiteInput(
name='defects',
doc="Input defect tables.",
storageClass="Defects",
dimensions=["instrument", "detector"],
isCalibration=True,
)
linearizer = cT.PrerequisiteInput(
name='linearizer',
storageClass="Linearizer",
doc="Linearity correction calibration.",
dimensions=["instrument", "detector"],
isCalibration=True,
minimum=0, # can fall back to cameraGeom
)
opticsTransmission = cT.PrerequisiteInput(
name="transmission_optics",
storageClass="TransmissionCurve",
doc="Transmission curve due to the optics.",
dimensions=["instrument"],
isCalibration=True,
)
filterTransmission = cT.PrerequisiteInput(
name="transmission_filter",
storageClass="TransmissionCurve",
doc="Transmission curve due to the filter.",
dimensions=["instrument", "physical_filter"],
isCalibration=True,
)
sensorTransmission = cT.PrerequisiteInput(
name="transmission_sensor",
storageClass="TransmissionCurve",
doc="Transmission curve due to the sensor.",
dimensions=["instrument", "detector"],
isCalibration=True,
)
atmosphereTransmission = cT.PrerequisiteInput(
name="transmission_atmosphere",
storageClass="TransmissionCurve",
doc="Transmission curve due to the atmosphere.",
dimensions=["instrument"],
isCalibration=True,
)
illumMaskedImage = cT.PrerequisiteInput(
name="illum",
doc="Input illumination correction.",
storageClass="MaskedImageF",
dimensions=["instrument", "physical_filter", "detector"],
isCalibration=True,
)
deferredChargeCalib = cT.PrerequisiteInput(
name="cpCtiCalib",
doc="Deferred charge/CTI correction dataset.",
storageClass="IsrCalib",
dimensions=["instrument", "detector"],
isCalibration=True,
)
outputExposure = cT.Output(
name='postISRCCD',
doc="Output ISR processed exposure.",
storageClass="Exposure",
dimensions=["instrument", "exposure", "detector"],
)
preInterpExposure = cT.Output(
name='preInterpISRCCD',
doc="Output ISR processed exposure, with pixels left uninterpolated.",
storageClass="ExposureF",
dimensions=["instrument", "exposure", "detector"],
)
outputBin1Exposure = cT.Output(
name="postIsrBin1",
doc="First binned image.",
storageClass="ExposureF",
dimensions=["instrument", "exposure", "detector"],
)
outputBin2Exposure = cT.Output(
name="postIsrBin2",
doc="Second binned image.",
storageClass="ExposureF",
dimensions=["instrument", "exposure", "detector"],
)
outputOssThumbnail = cT.Output(
name="OssThumb",
doc="Output Overscan-subtracted thumbnail image.",
storageClass="Thumbnail",
dimensions=["instrument", "exposure", "detector"],
)
outputFlattenedThumbnail = cT.Output(
name="FlattenedThumb",
doc="Output flat-corrected thumbnail image.",
storageClass="Thumbnail",
dimensions=["instrument", "exposure", "detector"],
)
outputStatistics = cT.Output(
name="isrStatistics",
doc="Output of additional statistics table.",
storageClass="StructuredDataDict",
dimensions=["instrument", "exposure", "detector"],
)
def __init__(self, *, config=None):
super().__init__(config=config)
if config.doBias is not True:
self.prerequisiteInputs.remove("bias")
if config.doLinearize is not True:
self.prerequisiteInputs.remove("linearizer")
if config.doCrosstalk is not True:
self.prerequisiteInputs.remove("crosstalkSources")
self.prerequisiteInputs.remove("crosstalk")
if config.doBrighterFatter is not True:
self.prerequisiteInputs.remove("bfKernel")
self.prerequisiteInputs.remove("newBFKernel")
if config.doDefect is not True:
self.prerequisiteInputs.remove("defects")
if config.doDark is not True:
self.prerequisiteInputs.remove("dark")
if config.doFlat is not True:
self.prerequisiteInputs.remove("flat")
if config.doFringe is not True:
self.prerequisiteInputs.remove("fringes")
if config.doStrayLight is not True:
self.prerequisiteInputs.remove("strayLightData")
if config.usePtcGains is not True and config.usePtcReadNoise is not True:
self.prerequisiteInputs.remove("ptc")
if config.doAttachTransmissionCurve is not True:
self.prerequisiteInputs.remove("opticsTransmission")
self.prerequisiteInputs.remove("filterTransmission")
self.prerequisiteInputs.remove("sensorTransmission")
self.prerequisiteInputs.remove("atmosphereTransmission")
else:
if config.doUseOpticsTransmission is not True:
self.prerequisiteInputs.remove("opticsTransmission")
if config.doUseFilterTransmission is not True:
self.prerequisiteInputs.remove("filterTransmission")
if config.doUseSensorTransmission is not True:
self.prerequisiteInputs.remove("sensorTransmission")
if config.doUseAtmosphereTransmission is not True:
self.prerequisiteInputs.remove("atmosphereTransmission")
if config.doIlluminationCorrection is not True:
self.prerequisiteInputs.remove("illumMaskedImage")
if config.doDeferredCharge is not True:
self.prerequisiteInputs.remove("deferredChargeCalib")
if config.doWrite is not True:
self.outputs.remove("outputExposure")
self.outputs.remove("preInterpExposure")
self.outputs.remove("outputFlattenedThumbnail")
self.outputs.remove("outputOssThumbnail")
self.outputs.remove("outputStatistics")
self.outputs.remove("outputBin1Exposure")
self.outputs.remove("outputBin2Exposure")
else:
if config.doBinnedExposures is not True:
self.outputs.remove("outputBin1Exposure")
self.outputs.remove("outputBin2Exposure")
if config.doSaveInterpPixels is not True:
self.outputs.remove("preInterpExposure")
if config.qa.doThumbnailOss is not True:
self.outputs.remove("outputOssThumbnail")
if config.qa.doThumbnailFlattened is not True:
self.outputs.remove("outputFlattenedThumbnail")
if config.doCalculateStatistics is not True:
self.outputs.remove("outputStatistics")
class IsrTaskConfig(pipeBase.PipelineTaskConfig,
pipelineConnections=IsrTaskConnections):
"""Configuration parameters for IsrTask.
Items are grouped in the order in which they are executed by the task.
"""
datasetType = pexConfig.Field(
dtype=str,
doc="Dataset type for input data; users will typically leave this alone, "
"but camera-specific ISR tasks will override it",
default="raw",
)
fallbackFilterName = pexConfig.Field(
dtype=str,
doc="Fallback default filter name for calibrations.",
optional=True
)
useFallbackDate = pexConfig.Field(
dtype=bool,
doc="Pass observation date when using fallback filter.",
default=False,
)
expectWcs = pexConfig.Field(
dtype=bool,
default=True,
doc="Expect input science images to have a WCS (set False for e.g. spectrographs)."
)
fwhm = pexConfig.Field(
dtype=float,
doc="FWHM of PSF in arcseconds (currently unused).",
default=1.0,
)
qa = pexConfig.ConfigField(
dtype=isrQa.IsrQaConfig,
doc="QA related configuration options.",
)
doHeaderProvenance = pexConfig.Field(
dtype=bool,
default=True,
doc="Write calibration identifiers into output exposure header?",
)
# Calib checking configuration:
doRaiseOnCalibMismatch = pexConfig.Field(
dtype=bool,
default=False,
doc="Should IsrTask halt if exposure and calibration header values do not match?",
)
cameraKeywordsToCompare = pexConfig.ListField(
dtype=str,
doc="List of header keywords to compare between exposure and calibrations.",
default=[],
)
# Image conversion configuration
doConvertIntToFloat = pexConfig.Field(
dtype=bool,
doc="Convert integer raw images to floating point values?",
default=True,
)
# Saturated pixel handling.
doSaturation = pexConfig.Field(
dtype=bool,
doc="Mask saturated pixels? NB: this is totally independent of the"
" interpolation option - this is ONLY setting the bits in the mask."
" To have them interpolated make sure doSaturationInterpolation=True",
default=True,
)
saturatedMaskName = pexConfig.Field(
dtype=str,
doc="Name of mask plane to use in saturation detection and interpolation",
default="SAT",
)
saturation = pexConfig.Field(
dtype=float,
doc="The saturation level to use if no Detector is present in the Exposure (ignored if NaN)",
default=float("NaN"),
)
growSaturationFootprintSize = pexConfig.Field(
dtype=int,
doc="Number of pixels by which to grow the saturation footprints",
default=1,
)
# Suspect pixel handling.
doSuspect = pexConfig.Field(
dtype=bool,
doc="Mask suspect pixels?",
default=False,
)
suspectMaskName = pexConfig.Field(
dtype=str,
doc="Name of mask plane to use for suspect pixels",
default="SUSPECT",
)
numEdgeSuspect = pexConfig.Field(
dtype=int,
doc="Number of edge pixels to be flagged as untrustworthy.",
default=0,
)
edgeMaskLevel = pexConfig.ChoiceField(
dtype=str,
doc="Mask edge pixels in which coordinate frame: DETECTOR or AMP?",
default="DETECTOR",
allowed={
'DETECTOR': 'Mask only the edges of the full detector.',
'AMP': 'Mask edges of each amplifier.',
},
)
# Initial masking options.
doSetBadRegions = pexConfig.Field(
dtype=bool,
doc="Should we set the level of all BAD patches of the chip to the chip's average value?",
default=True,
)
badStatistic = pexConfig.ChoiceField(
dtype=str,
doc="How to estimate the average value for BAD regions.",
default='MEANCLIP',
allowed={
"MEANCLIP": "Correct using the (clipped) mean of good data",
"MEDIAN": "Correct using the median of the good data",
},
)
# Overscan subtraction configuration.
doOverscan = pexConfig.Field(
dtype=bool,
doc="Do overscan subtraction?",
default=True,
)
overscan = pexConfig.ConfigurableField(
target=OverscanCorrectionTask,
doc="Overscan subtraction task for image segments.",
)
# Amplifier to CCD assembly configuration
doAssembleCcd = pexConfig.Field(
dtype=bool,
default=True,
doc="Assemble amp-level exposures into a ccd-level exposure?"
)
assembleCcd = pexConfig.ConfigurableField(
target=AssembleCcdTask,
doc="CCD assembly task",
)
# General calibration configuration.
doAssembleIsrExposures = pexConfig.Field(
dtype=bool,
default=False,
doc="Assemble amp-level calibration exposures into ccd-level exposure?"
)
doTrimToMatchCalib = pexConfig.Field(
dtype=bool,
default=False,
doc="Trim raw data to match calibration bounding boxes?"
)
# Bias subtraction.
doBias = pexConfig.Field(
dtype=bool,
doc="Apply bias frame correction?",
default=True,
)
biasDataProductName = pexConfig.Field(
dtype=str,
doc="Name of the bias data product",
default="bias",
)
doBiasBeforeOverscan = pexConfig.Field(
dtype=bool,
doc="Reverse order of overscan and bias correction.",
default=False
)
# Deferred charge correction.
doDeferredCharge = pexConfig.Field(
dtype=bool,
doc="Apply deferred charge correction?",
default=False,
)
deferredChargeCorrection = pexConfig.ConfigurableField(
target=DeferredChargeTask,
doc="Deferred charge correction task.",
)
# Variance construction
doVariance = pexConfig.Field(
dtype=bool,
doc="Calculate variance?",
default=True
)
gain = pexConfig.Field(
dtype=float,
doc="The gain to use if no Detector is present in the Exposure (ignored if NaN)",
default=float("NaN"),
)
readNoise = pexConfig.Field(
dtype=float,
doc="The read noise to use if no Detector is present in the Exposure",
default=0.0,
)
doEmpiricalReadNoise = pexConfig.Field(
dtype=bool,
default=False,
doc="Calculate empirical read noise instead of value from AmpInfo data?"
)
usePtcReadNoise = pexConfig.Field(
dtype=bool,
default=False,
doc="Use readnoise values from the Photon Transfer Curve?"
)
maskNegativeVariance = pexConfig.Field(
dtype=bool,
default=True,
doc="Mask pixels that claim a negative variance? This likely indicates a failure "
"in the measurement of the overscan at an edge due to the data falling off faster "
"than the overscan model can account for it."
)
negativeVarianceMaskName = pexConfig.Field(
dtype=str,
default="BAD",
doc="Mask plane to use to mark pixels with negative variance, if `maskNegativeVariance` is True.",
)
# Linearization.
doLinearize = pexConfig.Field(
dtype=bool,
doc="Correct for nonlinearity of the detector's response?",
default=True,
)
# Crosstalk.
doCrosstalk = pexConfig.Field(
dtype=bool,
doc="Apply intra-CCD crosstalk correction?",
default=False,
)
doCrosstalkBeforeAssemble = pexConfig.Field(
dtype=bool,
doc="Apply crosstalk correction before CCD assembly, and before trimming?",
default=False,
)
crosstalk = pexConfig.ConfigurableField(
target=CrosstalkTask,
doc="Intra-CCD crosstalk correction",
)
# Masking options.
doDefect = pexConfig.Field(
dtype=bool,
doc="Apply correction for CCD defects, e.g. hot pixels?",
default=True,
)
doNanMasking = pexConfig.Field(
dtype=bool,
doc="Mask non-finite (NAN, inf) pixels?",
default=True,
)
doWidenSaturationTrails = pexConfig.Field(
dtype=bool,
doc="Widen bleed trails based on their width?",
default=True
)
# Brighter-Fatter correction.
doBrighterFatter = pexConfig.Field(
dtype=bool,
default=False,
doc="Apply the brighter-fatter correction?"
)
doFluxConservingBrighterFatterCorrection = pexConfig.Field(
dtype=bool,
default=False,
doc="Apply the flux-conserving BFE correction by Miller et al.?"
)
brighterFatterLevel = pexConfig.ChoiceField(
dtype=str,
default="DETECTOR",
doc="The level at which to correct for brighter-fatter.",
allowed={
"AMP": "Every amplifier treated separately.",
"DETECTOR": "One kernel per detector",
}
)
brighterFatterMaxIter = pexConfig.Field(
dtype=int,
default=10,
doc="Maximum number of iterations for the brighter-fatter correction"
)
brighterFatterThreshold = pexConfig.Field(
dtype=float,
default=1000,
doc="Threshold used to stop iterating the brighter-fatter correction. It is the "
"absolute value of the difference between the current corrected image and the one "
"from the previous iteration summed over all the pixels."
)
brighterFatterApplyGain = pexConfig.Field(
dtype=bool,
default=True,
doc="Should the gain be applied when applying the brighter-fatter correction?"
)
brighterFatterMaskListToInterpolate = pexConfig.ListField(
dtype=str,
doc="List of mask planes that should be interpolated over when applying the brighter-fatter "
"correction.",
default=["SAT", "BAD", "NO_DATA", "UNMASKEDNAN"],
)
brighterFatterMaskGrowSize = pexConfig.Field(
dtype=int,
default=0,
doc="Number of pixels to grow the masks listed in config.brighterFatterMaskListToInterpolate "
"when brighter-fatter correction is applied."
)
# Dark subtraction.
doDark = pexConfig.Field(
dtype=bool,
doc="Apply dark frame correction?",
default=True,
)
darkDataProductName = pexConfig.Field(
dtype=str,
doc="Name of the dark data product",
default="dark",
)
# Camera-specific stray light removal.
doStrayLight = pexConfig.Field(
dtype=bool,
doc="Subtract stray light in the y-band (due to encoder LEDs)?",
default=False,
)
strayLight = pexConfig.ConfigurableField(
target=StrayLightTask,
doc="y-band stray light correction"
)
# Flat correction.
doFlat = pexConfig.Field(
dtype=bool,
doc="Apply flat field correction?",
default=True,
)
flatDataProductName = pexConfig.Field(
dtype=str,
doc="Name of the flat data product",
default="flat",
)
flatScalingType = pexConfig.ChoiceField(
dtype=str,
doc="The method for scaling the flat on the fly.",
default='USER',
allowed={
"USER": "Scale by flatUserScale",
"MEAN": "Scale by the inverse of the mean",
"MEDIAN": "Scale by the inverse of the median",
},
)
flatUserScale = pexConfig.Field(
dtype=float,
doc="If flatScalingType is 'USER' then scale flat by this amount; ignored otherwise",
default=1.0,
)
doTweakFlat = pexConfig.Field(
dtype=bool,
doc="Tweak flats to match observed amplifier ratios?",
default=False
)
# Amplifier normalization based on gains instead of using flats
# configuration.
doApplyGains = pexConfig.Field(
dtype=bool,
doc="Correct the amplifiers for their gains instead of applying flat correction",
default=False,
)
usePtcGains = pexConfig.Field(
dtype=bool,
doc="Use the gain values from the input Photon Transfer Curve?",
default=False,
)
normalizeGains = pexConfig.Field(
dtype=bool,
doc="Normalize all the amplifiers in each CCD to have the same median value.",
default=False,
)
# Fringe correction.
doFringe = pexConfig.Field(
dtype=bool,
doc="Apply fringe correction?",
default=True,
)
fringe = pexConfig.ConfigurableField(
target=FringeTask,
doc="Fringe subtraction task",
)
fringeAfterFlat = pexConfig.Field(
dtype=bool,
doc="Do fringe subtraction after flat-fielding?",
default=True,
)
# Amp offset correction.
doAmpOffset = pexConfig.Field(
doc="Calculate and apply amp offset corrections?",
dtype=bool,
default=False,
)
ampOffset = pexConfig.ConfigurableField(
doc="Amp offset correction task.",
target=AmpOffsetTask,
)
# Initial CCD-level background statistics options.
doMeasureBackground = pexConfig.Field(
dtype=bool,
doc="Measure the background level on the reduced image?",
default=False,
)
# Camera-specific masking configuration.
doCameraSpecificMasking = pexConfig.Field(
dtype=bool,
doc="Mask camera-specific bad regions?",
default=False,
)
masking = pexConfig.ConfigurableField(
target=MaskingTask,
doc="Masking task."
)
# Interpolation options.
doInterpolate = pexConfig.Field(
dtype=bool,
doc="Interpolate masked pixels?",
default=True,
)
doSaturationInterpolation = pexConfig.Field(
dtype=bool,
doc="Perform interpolation over pixels masked as saturated?"
" NB: This is independent of doSaturation; if that is False this plane"
" will likely be blank, resulting in a no-op here.",
default=True,
)
doNanInterpolation = pexConfig.Field(
dtype=bool,
doc="Perform interpolation over pixels masked as NaN?"
" NB: This is independent of doNanMasking; if that is False this plane"
" will likely be blank, resulting in a no-op here.",
default=True,
)
doNanInterpAfterFlat = pexConfig.Field(
dtype=bool,
doc=("If True, ensure we interpolate NaNs after flat-fielding, even if we "
"also have to interpolate them before flat-fielding."),
default=False,
)
maskListToInterpolate = pexConfig.ListField(
dtype=str,
doc="List of mask planes that should be interpolated.",
default=['SAT', 'BAD'],
)
doSaveInterpPixels = pexConfig.Field(
dtype=bool,
doc="Save a copy of the pre-interpolated pixel values?",
default=False,
)
# Default photometric calibration options.
fluxMag0T1 = pexConfig.DictField(
keytype=str,
itemtype=float,
doc="The approximate flux of a zero-magnitude object in a one-second exposure, per filter.",
default=dict((f, pow(10.0, 0.4*m)) for f, m in (("Unknown", 28.0),
))
)
defaultFluxMag0T1 = pexConfig.Field(
dtype=float,
doc="Default value for fluxMag0T1 (for an unrecognized filter).",
default=pow(10.0, 0.4*28.0)
)
# Vignette correction configuration.
doVignette = pexConfig.Field(
dtype=bool,
doc=("Compute and attach the validPolygon defining the unvignetted region to the exposure "
"according to vignetting parameters?"),
default=False,
)
doMaskVignettePolygon = pexConfig.Field(
dtype=bool,
doc=("Add a mask bit for pixels within the vignetted region. Ignored if doVignette "
"is False"),
default=True,
)
vignetteValue = pexConfig.Field(
dtype=float,
doc="Value to replace image array pixels with in the vignetted region? Ignored if None.",
optional=True,
default=None,
)
vignette = pexConfig.ConfigurableField(
target=VignetteTask,
doc="Vignetting task.",
)
# Transmission curve configuration.
doAttachTransmissionCurve = pexConfig.Field(
dtype=bool,
default=False,
doc="Construct and attach a wavelength-dependent throughput curve for this CCD image?"
)
doUseOpticsTransmission = pexConfig.Field(
dtype=bool,
default=True,
doc="Load and use transmission_optics (if doAttachTransmissionCurve is True)?"
)
doUseFilterTransmission = pexConfig.Field(
dtype=bool,
default=True,
doc="Load and use transmission_filter (if doAttachTransmissionCurve is True)?"
)
doUseSensorTransmission = pexConfig.Field(
dtype=bool,
default=True,
doc="Load and use transmission_sensor (if doAttachTransmissionCurve is True)?"
)
doUseAtmosphereTransmission = pexConfig.Field(
dtype=bool,
default=True,
doc="Load and use transmission_atmosphere (if doAttachTransmissionCurve is True)?"
)
# Illumination correction.
doIlluminationCorrection = pexConfig.Field(
dtype=bool,
default=False,
doc="Perform illumination correction?"
)
illuminationCorrectionDataProductName = pexConfig.Field(
dtype=str,
doc="Name of the illumination correction data product.",
default="illumcor",
)
illumScale = pexConfig.Field(
dtype=float,
doc="Scale factor for the illumination correction.",
default=1.0,
)
illumFilters = pexConfig.ListField(
dtype=str,
default=[],
doc="Only perform illumination correction for these filters."
)
# Calculate image quality statistics?
doStandardStatistics = pexConfig.Field(
dtype=bool,
doc="Should standard image quality statistics be calculated?",
default=True,
)
# Calculate additional statistics?
doCalculateStatistics = pexConfig.Field(
dtype=bool,
doc="Should additional ISR statistics be calculated?",
default=False,
)
isrStats = pexConfig.ConfigurableField(
target=IsrStatisticsTask,
doc="Task to calculate additional statistics.",
)
# Make binned images?
doBinnedExposures = pexConfig.Field(
dtype=bool,
doc="Should binned exposures be calculated?",
default=False,
)
binFactor1 = pexConfig.Field(
dtype=int,
doc="Binning factor for first binned exposure. This is intended for a finely binned output.",
default=8,
check=lambda x: x > 1,
)
binFactor2 = pexConfig.Field(
dtype=int,
doc="Binning factor for second binned exposure. This is intended for a coarsely binned output.",
default=64,
check=lambda x: x > 1,
)
# Write the outputs to disk. If ISR is run as a subtask, this may not
# be needed.
doWrite = pexConfig.Field(
dtype=bool,
doc="Persist postISRCCD?",
default=True,
)
def validate(self):
super().validate()
if self.doFlat and self.doApplyGains:
raise ValueError("You may not specify both doFlat and doApplyGains")
if self.doBiasBeforeOverscan and self.doTrimToMatchCalib:
raise ValueError("You may not specify both doBiasBeforeOverscan and doTrimToMatchCalib")
if self.doSaturationInterpolation and self.saturatedMaskName not in self.maskListToInterpolate:
self.maskListToInterpolate.append(self.saturatedMaskName)
if not self.doSaturationInterpolation and self.saturatedMaskName in self.maskListToInterpolate:
self.maskListToInterpolate.remove(self.saturatedMaskName)
if self.doNanInterpolation and "UNMASKEDNAN" not in self.maskListToInterpolate:
self.maskListToInterpolate.append("UNMASKEDNAN")
if self.doCalculateStatistics and self.isrStats.doCtiStatistics:
if self.doApplyGains != self.isrStats.doApplyGainsForCtiStatistics:
raise ValueError("doApplyGains must match isrStats.applyGainForCtiStatistics.")
class IsrTask(pipeBase.PipelineTask):
"""Apply common instrument signature correction algorithms to a raw frame.
The process for correcting imaging data is very similar from
camera to camera. This task provides a vanilla implementation of
doing these corrections, including the ability to turn certain
corrections off if they are not needed. The inputs to the primary
method, `run()`, are a raw exposure to be corrected and the
calibration data products. The raw input is a single chip sized
mosaic of all amps including overscans and other non-science
pixels.
The __init__ method sets up the subtasks for ISR processing, using
the defaults from `lsst.ip.isr`.
Parameters
----------
args : `list`