lsst.ip.isr g9e598d6448+8c28d2aaf4
Loading...
Searching...
No Matches
overscan.py
Go to the documentation of this file.
1# This file is part of ip_isr.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (https://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <https://www.gnu.org/licenses/>.
21
22__all__ = ["OverscanCorrectionTaskConfig", "OverscanCorrectionTask",
23 "SerialOverscanCorrectionTaskConfig", "SerialOverscanCorrectionTask",
24 "ParallelOverscanCorrectionTaskConfig", "ParallelOverscanCorrectionTask",
25 ]
26
27import numpy as np
28from scipy.signal import medfilt
29import warnings
30
31import lsst.afw.math as afwMath
32import lsst.afw.image as afwImage
33import lsst.geom as geom
34import lsst.pipe.base as pipeBase
35import lsst.pex.config as pexConfig
36
37from .isr import fitOverscanImage, fitOverscanImageMean
38from .isrFunctions import makeThresholdMask
39
40
41class OverscanCorrectionTaskConfigBase(pexConfig.Config):
42 """Overscan correction options.
43 """
44 fitType = pexConfig.ChoiceField(
45 dtype=str,
46 doc="The method for fitting the overscan bias level.",
47 default='MEDIAN',
48 allowed={
49 "POLY": "Fit ordinary polynomial to the longest axis of the overscan region",
50 "CHEB": "Fit Chebyshev polynomial to the longest axis of the overscan region",
51 "LEG": "Fit Legendre polynomial to the longest axis of the overscan region",
52 "NATURAL_SPLINE": "Fit natural spline to the longest axis of the overscan region",
53 "CUBIC_SPLINE": "Fit cubic spline to the longest axis of the overscan region",
54 "AKIMA_SPLINE": "Fit Akima spline to the longest axis of the overscan region",
55 "MEAN": "Correct using the mean of the overscan region",
56 "MEANCLIP": "Correct using a clipped mean of the overscan region",
57 "MEDIAN": "Correct using the median of the overscan region",
58 "MEDIAN_PER_ROW": "Correct using the median per row of the overscan region",
59 "MEAN_PER_ROW": "Correct using the mean per row of the overscan region",
60 },
61 )
62 order = pexConfig.Field(
63 dtype=int,
64 doc=("Order of polynomial to fit if overscan fit type is a polynomial, "
65 "or number of spline knots if overscan fit type is a spline."),
66 default=1,
67 )
68 numSigmaClip = pexConfig.Field(
69 dtype=float,
70 doc="Rejection threshold (sigma) for collapsing overscan before fit",
71 default=3.0,
72 )
73 maskPlanes = pexConfig.ListField(
74 dtype=str,
75 doc="Mask planes to reject when measuring overscan",
76 default=['BAD', 'SAT'],
77 )
78 overscanIsInt = pexConfig.Field(
79 dtype=bool,
80 doc="Treat overscan as an integer image for purposes of fitType=MEDIAN"
81 " and fitType=MEDIAN_PER_ROW.",
82 default=True,
83 )
84 maxDeviation = pexConfig.Field(
85 dtype=float,
86 doc="Maximum deviation from median (in ADU) to mask in overscan correction; "
87 "Will be applied to the absolute deviation if doAbsoluteMaxDeviation=True.",
88 default=1000.0, check=lambda x: x > 0,
89 )
90 doAbsoluteMaxDeviation = pexConfig.Field(
91 dtype=bool,
92 doc="Apply the maxDeviation to the absolute value of the deviation? If "
93 "False, this will be a one-sided cut for positive-only deviations "
94 "(typically for parallel overscan subtraction.",
95 default=True,
96 )
97
98
100 doParallelOverscan = pexConfig.Field(
101 dtype=bool,
102 doc="Correct using parallel overscan after serial overscan correction?",
103 default=False,
104 )
105 parallelOverscanMaskThreshold = pexConfig.Field(
106 dtype=int,
107 doc="Threshold above which pixels in the parallel overscan are masked as bleeds.",
108 default=100000,
109 )
110 parallelOverscanMaskGrowSize = pexConfig.Field(
111 dtype=int,
112 doc="Grow the SAT mask in the parallel overscan region by this many pixels. "
113 "This value was determined from the ITL chip in the LATISS camera.",
114 default=7,
115 )
116 leadingColumnsToSkip = pexConfig.Field(
117 dtype=int,
118 doc="Number of leading columns to skip in serial overscan correction.",
119 default=0,
120 )
121 trailingColumnsToSkip = pexConfig.Field(
122 dtype=int,
123 doc="Number of trailing columns to skip in serial overscan correction.",
124 default=0,
125 )
126 leadingRowsToSkip = pexConfig.Field(
127 dtype=int,
128 doc="Number of leading rows to skip in parallel overscan correction.",
129 default=0,
130 )
131 trailingRowsToSkip = pexConfig.Field(
132 dtype=int,
133 doc="Number of trailing rows to skip in parallel overscan correction.",
134 default=0,
135 )
136
137
138class OverscanCorrectionTaskBase(pipeBase.Task):
139 """Base Correction task for overscan.
140
141 This class contains a number of utilities that are easier to
142 understand and use when they are not embedded in nested if/else
143 loops.
144
145 Parameters
146 ----------
147 statControl : `lsst.afw.math.StatisticsControl`, optional
148 Statistics control object.
149 """
150 ConfigClass = OverscanCorrectionTaskConfigBase
151 _DefaultName = "overscanBase"
152
153 def __init__(self, statControl=None, **kwargs):
154 super().__init__(**kwargs)
155 self.allowDebug = True
156
157 if statControl:
158 self.statControl = statControl
159 else:
160 self.statControl = afwMath.StatisticsControl()
161 self.statControl.setNumSigmaClip(self.config.numSigmaClip)
162 self.statControl.setAndMask(afwImage.Mask.getPlaneBitMask(self.config.maskPlanes))
163
164 def run(self, exposure, amp, isTransposed=False):
165 raise NotImplementedError("run method is not defined for OverscanCorrectionTaskBase")
166
167 @staticmethod
169 exposure,
170 overscanBBox,
171 overscanMaskedImage,
172 overscanMask,
173 maxDeviation,
174 maskedRowColumnGrowSize,
175 medianSmoothingKernel,
176 medianSmoothingOutlierThreshold,
177 doAbsoluteMaxDeviation,
178 isTransposed,
179 ):
180 """Mask overscan rows (~serial) or columns (~parallel).
181
182 Parameters
183 ----------
184 exposure : `lsst.afw.image.Exposure`
185 Exposure containing the data.
186 overscanBBox: `lsst.geom.Box2I`
187 Bounding box for the overscan data.
188 overscanMaskedImage : `lsst.afw.image.MaskedImage`
189 Masked image containing the overscan data.
190 overscanMask : `np.ndarray`
191 Numpy array of the mask bits, anded with appropriate
192 mask planes.
193 maxDeviation : `float`
194 Maximum deviation from median (overscan units) to mask in overscan
195 correction. For parallel overscan this is a one-sided (positive
196 only) cut.
197 maskedRowColumnGrowSize : `int`
198 If a column (parallel overscan) or row (serial overscan) is
199 completely masked, then grow the mask by this radius. If the
200 value is <=0 then this will not be checked.
201 medianSmoothingKernel : `int`
202 Kernel (pixels) to smooth rows/columns. If <=0, median smoothing
203 is skipped. Otherwise must be odd.
204 medianSmoothingOutlierThreshold : `float`
205 Outlier threshold after median smoothing (overscan units). This
206 is applied only to positive outliers.
207 doAbsoluteMaxDeviation : `bool`
208 If true, deviation comparisons will use the absolute value;
209 otherwise it will cut positive outliers only.
210 isTransposed : `bool`
211 If true, then the data will be transposed before fitting
212 the overscan.
213
214 Returns
215 -------
216 badRowsOrColumns : `np.ndarray`
217 Array of bad rows (serial) or columns (parallel) that were
218 found, prior to dilation by maskedRowColumnGrowSize.
219 """
220 overscanArray = overscanMaskedImage.image.array
221
222 badRowsOrColumns = np.zeros(0, dtype=np.int64)
223
224 median = np.ma.median(np.ma.masked_where(overscanMask, overscanArray))
225 if doAbsoluteMaxDeviation:
226 delta = np.abs(overscanArray - median)
227 else:
228 delta = overscanArray - median
229
230 bad = np.where((delta > maxDeviation) & (~overscanMask))
231 # Mark the bad pixels as BAD
232 overscanMaskedImage.mask.array[bad] |= overscanMaskedImage.mask.getPlaneBitMask("BAD")
233
234 if isTransposed:
235 axis = 0
236 nComp = overscanArray.shape[0]
237 else:
238 axis = 1
239 nComp = overscanArray.shape[1]
240
241 # Check for completely masked row/column (from maxDeviation or
242 # previously applied SAT flag.)
243 if len(bad) > 0:
244 # We only need to look at the bad pixels set here for this
245 # mask growth.
246 overscanMaskTemp = np.zeros_like(overscanMask)
247 overscanMaskTemp[bad] = True
248
249 nMaskedArray = np.sum(overscanMaskTemp, axis=axis, dtype=np.int32)
250 badRowsOrColumns, = np.where(nMaskedArray == nComp)
251
252 # Perform median-smoothing outlier rejection if desired.
253 if medianSmoothingKernel > 0:
254 # We do a straight numpy median ignoring the mask.
255 # This will be fine because it avoids missing values,
256 # and very large deviations have already been flagged by
257 # maxDeviation or SAT.
258 rowsCols = np.median(overscanArray, axis=axis)
259 filtered = medfilt(rowsCols, kernel_size=medianSmoothingKernel)
260 delta = rowsCols - filtered
261
262 # We cannot reliably look for outliers within a kernel length
263 # of the edges.
264 high, = np.where(delta[medianSmoothingKernel: -medianSmoothingKernel]
265 >= medianSmoothingOutlierThreshold)
266 high += medianSmoothingKernel
267
268 if len(high) > 0:
269 badRowsOrColumns = np.unique(np.append(badRowsOrColumns, high))
270
271 # If we have any bad rows/columns, we need to dilate them
272 # and apply the mask to the parent overscan image.
273 if len(badRowsOrColumns) > 0:
274 dataView = afwImage.MaskedImageF(exposure.maskedImage,
275 overscanBBox,
276 afwImage.PARENT)
277 if isTransposed:
278 pixelsCopy = dataView.image.array[:, badRowsOrColumns].copy()
279 dataView.image.array[:, badRowsOrColumns] = 1e30
280 else:
281 pixelsCopy = dataView.image.array[badRowsOrColumns, :].copy()
282 dataView.image.array[badRowsOrColumns, :] = 1e30
283
285 maskedImage=dataView,
286 threshold=1e30,
287 growFootprints=maskedRowColumnGrowSize,
288 maskName="BAD",
289 )
290
291 if isTransposed:
292 dataView.image.array[:, badRowsOrColumns] = pixelsCopy
293 else:
294 dataView.image.array[badRowsOrColumns, :] = pixelsCopy
295
296 return badRowsOrColumns
297
299 self,
300 exposure,
301 amp,
302 imageBBox,
303 overscanBBox,
304 isTransposed=True,
305 leadingToSkip=0,
306 trailingToSkip=0,
307 overscanFraction=1.0,
308 imageThreshold=np.inf,
309 maskedRowColumnGrowSize=0,
310 medianSmoothingKernel=0,
311 medianSmoothingOutlierThreshold=np.inf,
312 ):
313 """Trim the exposure, fit the overscan, subtract the fit, and
314 calculate statistics.
315
316 Parameters
317 ----------
318 exposure : `lsst.afw.image.Exposure`
319 Exposure containing the data.
320 amp : `lsst.afw.cameraGeom.Amplifier`
321 The amplifier that is to be corrected.
322 imageBBox: `lsst.geom.Box2I`
323 Bounding box of the image data that will have the overscan
324 subtracted. If parallel overscan will be performed, that
325 area is added to the image bounding box during serial
326 overscan correction.
327 overscanBBox: `lsst.geom.Box2I`
328 Bounding box for the overscan data.
329 isTransposed: `bool`
330 If true, then the data will be transposed before fitting
331 the overscan.
332 leadingToSkip : `int`, optional
333 Leading rows/columns to skip.
334 trailingToSkip : `int`, optional
335 Leading rows/columns to skip.
336 overscanFraction : `float`, optional
337 If the overscan region median is greater than overscanFraction
338 and the imaging region median is greater than imageThreshold
339 then overscan correction will be skipped.
340 maxLevel : `float`, optional
341 If the overscan region median is greater than overscanFraction
342 and the imaging region median is greater than imageThreshold
343 then overscan correction will be skipped.
344 maskedRowColumnGrowSize : `int`, optional
345 If a column (parallel overscan) or row (serial overscan) is
346 completely masked, then grow the mask by this radius. If the
347 value is <=0 then this will not be checked.
348 medianSmoothingKernel : `int`, optional
349 Kernel (pixels) to use to smooth rows/columns for row/column
350 outlier rejection. Must be odd if positive; if <=0 median
351 smoothing will not be used to find outliers.
352 medianSmoothingOutlierThreshold : `float`, optional
353 Threshold to look for outliers after median smoothing (adu).
354
355 Returns
356 -------
357 results : `lsst.pipe.base.Struct`
358 ``ampOverscanModel``
359 Overscan model broadcast to the full image size.
360 (`lsst.afw.image.Exposure`)
361 ``overscanOverscanModel``
362 Overscan model broadcast to the full overscan image
363 size. (`lsst.afw.image.Exposure`)
364 ``overscanImage``
365 Overscan image with the overscan fit subtracted.
366 (`lsst.afw.image.Exposure`)
367 ``overscanValue``
368 Overscan model. (`float` or `np.array`)
369 ``overscanMean``
370 Mean value of the overscan fit. (`float`)
371 ``overscanMedian``
372 Median value of the overscan fit. (`float`)
373 ``overscanSigma``
374 Standard deviation of the overscan fit. (`float`)
375 ``overscanMeanResidual``
376 Mean value of the overscan region after overscan
377 subtraction. (`float`)
378 ``overscanMedianResidual``
379 Median value of the overscan region after overscan
380 subtraction. (`float`)
381 ``overscanSigmaResidual``
382 Standard deviation of the overscan region after
383 overscan subtraction. (`float`)
384 """
385 overscanBox = self.trimOverscan(exposure, amp, overscanBBox,
386 leadingToSkip,
387 trailingToSkip,
388 transpose=isTransposed)
389 overscanImage = exposure[overscanBox].getMaskedImage()
390
391 # Record the gain value if necessary to convert configs from
392 # electron to adu.
393 if exposure.metadata.get("LSST ISR UNITS", "adu") == "electron":
394 gain = exposure.metadata[f"LSST ISR GAIN {amp.getName()}"]
395 else:
396 gain = 1.0
397
398 # Mask pixels.
399 maskVal = overscanImage.mask.getPlaneBitMask(self.config.maskPlanes)
400 overscanMask = ~((overscanImage.mask.array & maskVal) == 0)
401
402 badResults = False
403
404 checkOverscanLevel = False
405 overscanMedian = 0.0
406 imageMedian = 0.0
407 if np.isfinite(imageThreshold):
408 checkOverscanLevel = True
409
410 # Protect against warnings with all-nan amps.
411 with warnings.catch_warnings():
412 warnings.simplefilter("ignore")
413 overscanMedian = np.nanmedian(overscanImage.image.array)
414 imageMedian = np.nanmedian(exposure[imageBBox].image.array)
415
416 if np.all(overscanMask):
417 self.log.warning(
418 "All overscan pixels masked when attempting overscan correction for %s",
419 amp.getName(),
420 )
421 badResults = True
422 elif (checkOverscanLevel and overscanMedian/imageMedian > overscanFraction
423 and imageMedian > imageThreshold):
424 self.log.warning(
425 "The level in the overscan region (%.2f) compared to the image region (%.2f) is "
426 "greater than the maximum fraction (%.2f) for %s",
427 overscanMedian,
428 imageMedian,
429 overscanFraction,
430 amp.getName(),
431 )
432 badResults = True
433
434 if badResults:
435 # Do not do overscan subtraction at all.
436 badRowsOrColumns = np.zeros(0, dtype=np.int64)
437 overscanResults = pipeBase.Struct(
438 overscanValue=0.0,
439 overscanMean=0.0,
440 overscanMedian=0.0,
441 overscanSigma=0.0,
442 )
443 else:
444 badRowsOrColumns = self._maskRowsOrColumns(
445 exposure,
446 overscanBBox,
447 overscanImage,
448 overscanMask,
449 gain * self.config.maxDeviation,
450 maskedRowColumnGrowSize,
451 medianSmoothingKernel,
452 gain * medianSmoothingOutlierThreshold,
453 self.config.doAbsoluteMaxDeviation,
454 isTransposed,
455 )
456 # Do overscan fit.
457 # CZW: Handle transposed correctly.
458 overscanResults = self.fitOverscan(overscanImage, isTransposed=isTransposed)
459
460 # Correct image region (and possibly parallel-overscan region).
461 ampImage = exposure[imageBBox]
462 ampOverscanModel = self.broadcastFitToImage(overscanResults.overscanValue,
463 ampImage.image.array,
464 transpose=isTransposed)
465 ampImage.image.array -= ampOverscanModel
466
467 # Correct overscan region (and possibly doubly-overscaned
468 # region).
469 overscanImage = exposure[overscanBBox]
470 # CZW: Transposed?
471 overscanOverscanModel = self.broadcastFitToImage(overscanResults.overscanValue,
472 overscanImage.image.array)
473 self.debugView(overscanImage, overscanResults.overscanValue, amp, isTransposed=isTransposed)
474 overscanImage.image.array -= overscanOverscanModel
475
476 # Find residual fit statistics.
477 stats = afwMath.makeStatistics(overscanImage.getMaskedImage(),
478 afwMath.MEAN | afwMath.MEDIAN | afwMath.STDEVCLIP, self.statControl)
479 residualMean = stats.getValue(afwMath.MEAN)
480 residualMedian = stats.getValue(afwMath.MEDIAN)
481 residualSigma = stats.getValue(afwMath.STDEVCLIP)
482
483 return pipeBase.Struct(
484 ampOverscanModel=ampOverscanModel,
485 overscanOverscanModel=overscanOverscanModel,
486 overscanImage=overscanImage,
487 overscanValue=overscanResults.overscanValue,
488 overscanMean=overscanResults.overscanMean,
489 overscanMedian=overscanResults.overscanMedian,
490 overscanSigma=overscanResults.overscanSigma,
491 overscanMeanResidual=residualMean,
492 overscanMedianResidual=residualMedian,
493 overscanSigmaResidual=residualSigma,
494 overscanBadRowsOrColumns=badRowsOrColumns,
495 )
496
497 def broadcastFitToImage(self, overscanValue, imageArray, transpose=False):
498 """Broadcast 0 or 1 dimension fit to appropriate shape.
499
500 Parameters
501 ----------
502 overscanValue : `numpy.ndarray`, (Nrows, ) or scalar
503 Overscan fit to broadcast.
504 imageArray : `numpy.ndarray`, (Nrows, Ncols)
505 Image array that we want to match.
506 transpose : `bool`, optional
507 Switch order to broadcast along the other axis.
508
509 Returns
510 -------
511 overscanModel : `numpy.ndarray`, (Nrows, Ncols) or scalar
512 Expanded overscan fit.
513
514 Raises
515 ------
516 RuntimeError
517 Raised if no axis has the appropriate dimension.
518 """
519 if isinstance(overscanValue, np.ndarray):
520 overscanModel = np.zeros_like(imageArray)
521
522 if transpose is False:
523 if imageArray.shape[0] == overscanValue.shape[0]:
524 overscanModel[:, :] = overscanValue[:, np.newaxis]
525 elif imageArray.shape[1] == overscanValue.shape[0]:
526 overscanModel[:, :] = overscanValue[np.newaxis, :]
527 elif imageArray.shape[0] == overscanValue.shape[1]:
528 overscanModel[:, :] = overscanValue[np.newaxis, :]
529 else:
530 raise RuntimeError(f"Could not broadcast {overscanValue.shape} to "
531 f"match {imageArray.shape}")
532 else:
533 if imageArray.shape[1] == overscanValue.shape[0]:
534 overscanModel[:, :] = overscanValue[np.newaxis, :]
535 elif imageArray.shape[0] == overscanValue.shape[0]:
536 overscanModel[:, :] = overscanValue[:, np.newaxis]
537 elif imageArray.shape[1] == overscanValue.shape[1]:
538 overscanModel[:, :] = overscanValue[:, np.newaxis]
539 else:
540 raise RuntimeError(f"Could not broadcast {overscanValue.shape} to "
541 f"match {imageArray.shape}")
542 else:
543 overscanModel = overscanValue
544
545 return overscanModel
546
547 def trimOverscan(self, exposure, amp, bbox, skipLeading, skipTrailing, transpose=False):
548 """Trim overscan region to remove edges.
549
550 Parameters
551 ----------
552 exposure : `lsst.afw.image.Exposure`
553 Exposure containing data.
554 amp : `lsst.afw.cameraGeom.Amplifier`
555 Amplifier containing geometry information.
556 bbox : `lsst.geom.Box2I`
557 Bounding box of the overscan region.
558 skipLeading : `int`
559 Number of leading (towards data region) rows/columns to skip.
560 skipTrailing : `int`
561 Number of trailing (away from data region) rows/columns to skip.
562 transpose : `bool`, optional
563 Operate on the transposed array.
564
565 Returns
566 -------
567 overscanArray : `numpy.array`, (N, M)
568 Data array to fit.
569 overscanMask : `numpy.array`, (N, M)
570 Data mask.
571 """
572 dx0, dy0, dx1, dy1 = (0, 0, 0, 0)
573 dataBBox = amp.getRawDataBBox()
574 if transpose:
575 if dataBBox.getBeginY() < bbox.getBeginY():
576 dy0 += skipLeading
577 dy1 -= skipTrailing
578 else:
579 dy0 += skipTrailing
580 dy1 -= skipLeading
581 else:
582 if dataBBox.getBeginX() < bbox.getBeginX():
583 dx0 += skipLeading
584 dx1 -= skipTrailing
585 else:
586 dx0 += skipTrailing
587 dx1 -= skipLeading
588
589 overscanBBox = geom.Box2I(bbox.getBegin() + geom.Extent2I(dx0, dy0),
590 geom.Extent2I(bbox.getWidth() - dx0 + dx1,
591 bbox.getHeight() - dy0 + dy1))
592 return overscanBBox
593
594 def fitOverscan(self, overscanImage, isTransposed=False):
595 if self.config.fitType in ('MEAN', 'MEANCLIP', 'MEDIAN'):
596 # Transposition has no effect here.
597 overscanResult = self.measureConstantOverscan(overscanImage)
598 overscanValue = overscanResult.overscanValue
599 overscanMean = overscanValue
600 overscanMedian = overscanValue
601 overscanSigma = 0.0
602 elif self.config.fitType in ('MEDIAN_PER_ROW', 'MEAN_PER_ROW', 'POLY', 'CHEB', 'LEG',
603 'NATURAL_SPLINE', 'CUBIC_SPLINE', 'AKIMA_SPLINE'):
604 # Force transposes as needed
605 overscanResult = self.measureVectorOverscan(overscanImage, isTransposed)
606 overscanValue = overscanResult.overscanValue
607
608 stats = afwMath.makeStatistics(overscanResult.overscanValue,
609 afwMath.MEAN | afwMath.MEDIAN | afwMath.STDEVCLIP,
610 self.statControl)
611 overscanMean = stats.getValue(afwMath.MEAN)
612 overscanMedian = stats.getValue(afwMath.MEDIAN)
613 overscanSigma = stats.getValue(afwMath.STDEVCLIP)
614 else:
615 raise ValueError('%s : %s an invalid overscan type' %
616 ("overscanCorrection", self.config.fitType))
617
618 return pipeBase.Struct(overscanValue=overscanValue,
619 overscanMean=overscanMean,
620 overscanMedian=overscanMedian,
621 overscanSigma=overscanSigma,
622 )
623
624 def maskParallelOverscan(self, exposure, detector):
625 """Mask the union of high values on all amplifiers in the parallel
626 overscan.
627
628 This operates on the image in-place.
629
630 Parameters
631 ----------
632 exposure : `lsst.afw.image.Exposure`
633 An untrimmed raw exposure.
634 detector : `lsst.afw.cameraGeom.Detector`
635 The detetor to use for amplifier geometry.
636 """
637 parallelMask = None
638
639 for amp in detector:
640 dataView = afwImage.MaskedImageF(exposure.getMaskedImage(),
641 amp.getRawParallelOverscanBBox(),
642 afwImage.PARENT)
643 # This should mark all the saturated pixels as SAT.
645 maskedImage=dataView,
646 threshold=self.config.parallelOverscanMaskThreshold,
647 growFootprints=self.config.parallelOverscanMaskGrowSize,
648 maskName="SAT"
649 )
650 if parallelMask is None:
651 parallelMask = dataView.mask.array
652 else:
653 parallelMask |= dataView.mask.array
654 for amp in detector:
655 dataView = afwImage.MaskedImageF(exposure.getMaskedImage(),
656 amp.getRawParallelOverscanBBox(),
657 afwImage.PARENT)
658 dataView.mask.array |= parallelMask
659
660 # Constant methods
661 def measureConstantOverscan(self, image):
662 """Measure a constant overscan value.
663
664 Parameters
665 ----------
666 image : `lsst.afw.image.Image` or `lsst.afw.image.MaskedImage`
667 Image data to measure the overscan from.
668
669 Returns
670 -------
671 results : `lsst.pipe.base.Struct`
672 Overscan result with entries:
673 - ``overscanValue``: Overscan value to subtract (`float`)
674 - ``isTransposed``: Orientation of the overscan (`bool`)
675 """
676 fitType = afwMath.stringToStatisticsProperty(self.config.fitType)
677 overscanValue = afwMath.makeStatistics(image, fitType, self.statControl).getValue()
678
679 return pipeBase.Struct(overscanValue=overscanValue,
680 isTransposed=False)
681
682 # Vector correction utilities
683 def getImageArray(self, image):
684 """Extract the numpy array from the input image.
685
686 Parameters
687 ----------
688 image : `lsst.afw.image.Image` or `lsst.afw.image.MaskedImage`
689 Image data to pull array from.
690
691 calcImage : `numpy.ndarray`
692 Image data array for numpy operating.
693 """
694 if hasattr(image, "getImage"):
695 calcImage = image.getImage().getArray()
696 calcImage = np.ma.masked_where(image.getMask().getArray() & self.statControl.getAndMask(),
697 calcImage)
698 else:
699 calcImage = image.getArray()
700 return calcImage
701
702 def maskOutliers(self, imageArray):
703 """Mask outliers in a row of overscan data from a robust sigma
704 clipping procedure.
705
706 Parameters
707 ----------
708 imageArray : `numpy.ndarray`
709 Image to filter along numpy axis=1.
710
711 Returns
712 -------
713 maskedArray : `numpy.ma.masked_array`
714 Masked image marking outliers.
715 """
716 lq, median, uq = np.percentile(np.ma.getdata(imageArray),
717 [25.0, 50.0, 75.0], axis=1)
718 axisMedians = median
719 axisStdev = 0.74*(uq - lq) # robust stdev
720
721 # Replace pixels that have excessively large stdev values
722 # with the median of stdev values. A large stdev likely
723 # indicates a bleed is spilling into the overscan.
724 axisStdev = np.where(axisStdev > 2.0 * np.median(axisStdev),
725 np.median(axisStdev), axisStdev)
726
727 # Mask pixels that are N-sigma away from their array medians.
728 diff = np.abs(imageArray - axisMedians[:, np.newaxis])
729 masked = np.ma.masked_where(diff > self.statControl.getNumSigmaClip()
730 * axisStdev[:, np.newaxis], imageArray)
731
732 return masked
733
734 def fillMaskedPixels(self, overscanVector):
735 """Fill masked/NaN pixels in the overscan.
736
737 Parameters
738 ----------
739 overscanVector : `np.array` or `np.ma.masked_array`
740 Overscan vector to fill.
741
742 Returns
743 -------
744 overscanVector : `np.ma.masked_array`
745 Filled vector.
746
747 Notes
748 -----
749 Each maskSlice is a section of overscan with contiguous masks.
750 Ideally this adds 5 pixels from the left and right of that
751 mask slice, and takes the median of those values to fill the
752 slice. If this isn't possible, the median of all non-masked
753 values is used. The mask is removed for the pixels filled.
754 """
755 workingCopy = overscanVector
756 if not isinstance(overscanVector, np.ma.MaskedArray):
757 workingCopy = np.ma.masked_array(overscanVector,
758 mask=~np.isfinite(overscanVector))
759
760 with warnings.catch_warnings():
761 warnings.simplefilter("ignore")
762 defaultValue = np.median(workingCopy.data[~workingCopy.mask])
763 for maskSlice in np.ma.clump_masked(workingCopy):
764 neighborhood = []
765 if maskSlice.start > 5:
766 neighborhood.extend(workingCopy[maskSlice.start - 5:maskSlice.start].data)
767 if maskSlice.stop < workingCopy.size - 5:
768 neighborhood.extend(workingCopy[maskSlice.stop:maskSlice.stop+5].data)
769 if len(neighborhood) > 0:
770 workingCopy.data[maskSlice] = np.nanmedian(neighborhood)
771 workingCopy.mask[maskSlice] = False
772 else:
773 workingCopy.data[maskSlice] = defaultValue
774 workingCopy.mask[maskSlice] = False
775 return workingCopy
776
777 def collapseArray(self, maskedArray, fillMasked=True):
778 """Collapse overscan array (and mask) to a 1-D vector of values.
779
780 Parameters
781 ----------
782 maskedArray : `numpy.ma.masked_array`
783 Masked array of input overscan data.
784 fillMasked : `bool`, optional
785 If true, fill any pixels that are masked with a median of
786 neighbors.
787
788 Returns
789 -------
790 collapsed : `numpy.ma.masked_array`
791 Single dimensional overscan data, combined with the mean.
792
793 """
794 collapsed = np.mean(maskedArray, axis=1)
795 if collapsed.mask.sum() > 0 and fillMasked:
796 collapsed = self.fillMaskedPixels(collapsed)
797
798 return collapsed
799
800 def splineFit(self, indices, collapsed, numBins):
801 """Wrapper function to match spline fit API to polynomial fit API.
802
803 Parameters
804 ----------
805 indices : `numpy.ndarray`
806 Locations to evaluate the spline.
807 collapsed : `numpy.ndarray`
808 Collapsed overscan values corresponding to the spline
809 evaluation points.
810 numBins : `int`
811 Number of bins to use in constructing the spline.
812
813 Returns
814 -------
815 interp : `lsst.afw.math.Interpolate`
816 Interpolation object for later evaluation.
817 """
818 if not np.ma.is_masked(collapsed):
819 collapsed.mask = np.array(len(collapsed)*[np.ma.nomask])
820
821 numPerBin, binEdges = np.histogram(indices, bins=numBins,
822 weights=1 - collapsed.mask.astype(int))
823 with np.errstate(invalid="ignore"):
824 values = np.histogram(indices, bins=numBins,
825 weights=collapsed.data*~collapsed.mask)[0]/numPerBin
826 binCenters = np.histogram(indices, bins=numBins,
827 weights=indices*~collapsed.mask)[0]/numPerBin
828
829 if len(binCenters[numPerBin > 0]) < 5:
830 self.log.warning("Cannot do spline fitting for overscan: %s valid points.",
831 len(binCenters[numPerBin > 0]))
832 # Return a scalar value if we have one, otherwise
833 # return zero. This amplifier is hopefully already
834 # masked.
835 if len(values[numPerBin > 0]) != 0:
836 return float(values[numPerBin > 0][0])
837 else:
838 return 0.0
839
840 interp = afwMath.makeInterpolate(binCenters.astype(float)[numPerBin > 0],
841 values.astype(float)[numPerBin > 0],
842 afwMath.stringToInterpStyle(self.config.fitType))
843 return interp
844
845 @staticmethod
846 def splineEval(indices, interp):
847 """Wrapper function to match spline evaluation API to polynomial fit
848 API.
849
850 Parameters
851 ----------
852 indices : `numpy.ndarray`
853 Locations to evaluate the spline.
854 interp : `lsst.afw.math.interpolate`
855 Interpolation object to use.
856
857 Returns
858 -------
859 values : `numpy.ndarray`
860 Evaluated spline values at each index.
861 """
862
863 return interp.interpolate(indices.astype(float))
864
865 @staticmethod
866 def maskExtrapolated(collapsed):
867 """Create mask if edges are extrapolated.
868
869 Parameters
870 ----------
871 collapsed : `numpy.ma.masked_array`
872 Masked array to check the edges of.
873
874 Returns
875 -------
876 maskArray : `numpy.ndarray`
877 Boolean numpy array of pixels to mask.
878 """
879 maskArray = np.full_like(collapsed, False, dtype=bool)
880 if np.ma.is_masked(collapsed):
881 num = len(collapsed)
882 for low in range(num):
883 if not collapsed.mask[low]:
884 break
885 if low > 0:
886 maskArray[:low] = True
887 for high in range(1, num):
888 if not collapsed.mask[-high]:
889 break
890 if high > 1:
891 maskArray[-high:] = True
892 return maskArray
893
894 def measureVectorOverscan(self, image, isTransposed=False):
895 """Calculate the 1-d vector overscan from the input overscan image.
896
897 Parameters
898 ----------
899 image : `lsst.afw.image.MaskedImage`
900 Image containing the overscan data.
901 isTransposed : `bool`
902 If true, the image has been transposed.
903
904 Returns
905 -------
906 results : `lsst.pipe.base.Struct`
907 Overscan result with entries:
908
909 ``overscanValue``
910 Overscan value to subtract (`float`)
911 ``maskArray``
912 List of rows that should be masked as ``SUSPECT`` when the
913 overscan solution is applied. (`list` [ `bool` ])
914 ``isTransposed``
915 Indicates if the overscan data was transposed during
916 calcuation, noting along which axis the overscan should be
917 subtracted. (`bool`)
918 """
919 calcImage = self.getImageArray(image)
920
921 # operate on numpy-arrays from here
922 if isTransposed:
923 calcImage = np.transpose(calcImage)
924 masked = self.maskOutliers(calcImage)
925
926 if self.config.fitType in ('MEDIAN_PER_ROW', "MEAN_PER_ROW"):
927 if self.config.overscanIsInt:
928 mi = afwImage.MaskedImageI(image.getBBox())
929 masked = masked.astype(int)
930 else:
931 mi = image.clone()
932
933 if isTransposed:
934 masked = masked.transpose()
935
936 mi.image.array[:, :] = masked.data[:, :]
937 if bool(masked.mask.shape):
938 mi.mask.array[:, :] = masked.mask[:, :]
939
940 if self.config.fitType == "MEDIAN_PER_ROW":
941 overscanVector = fitOverscanImage(mi, self.config.maskPlanes, isTransposed)
942 else:
943 overscanVector = fitOverscanImageMean(mi, self.config.maskPlanes, isTransposed)
944
945 overscanVector = self.fillMaskedPixels(overscanVector)
946 maskArray = self.maskExtrapolated(overscanVector)
947 else:
948 collapsed = self.collapseArray(masked)
949
950 num = len(collapsed)
951 indices = 2.0*np.arange(num)/float(num) - 1.0
952
953 poly = np.polynomial
954 fitter, evaler = {
955 'POLY': (poly.polynomial.polyfit, poly.polynomial.polyval),
956 'CHEB': (poly.chebyshev.chebfit, poly.chebyshev.chebval),
957 'LEG': (poly.legendre.legfit, poly.legendre.legval),
958 'NATURAL_SPLINE': (self.splineFit, self.splineEval),
959 'CUBIC_SPLINE': (self.splineFit, self.splineEval),
960 'AKIMA_SPLINE': (self.splineFit, self.splineEval)
961 }[self.config.fitType]
962
963 # These are the polynomial coefficients, or an
964 # interpolation object.
965 coeffs = fitter(indices, collapsed, self.config.order)
966
967 if isinstance(coeffs, float):
968 self.log.warning("Using fallback value %f due to fitter failure. Amplifier will be masked.",
969 coeffs)
970 overscanVector = np.full_like(indices, coeffs)
971 maskArray = np.full_like(collapsed, True, dtype=bool)
972 else:
973 # Otherwise we can just use things as normal.
974 overscanVector = evaler(indices, coeffs)
975 maskArray = self.maskExtrapolated(collapsed)
976
977 return pipeBase.Struct(overscanValue=np.array(overscanVector),
978 maskArray=maskArray,
979 isTransposed=isTransposed)
980
981 def debugView(self, image, model, amp=None, isTransposed=True):
982 """Debug display for the final overscan solution.
983
984 Parameters
985 ----------
986 image : `lsst.afw.image.Image`
987 Input image the overscan solution was determined from.
988 model : `numpy.ndarray` or `float`
989 Overscan model determined for the image.
990 amp : `lsst.afw.cameraGeom.Amplifier`, optional
991 Amplifier to extract diagnostic information.
992 isTransposed : `bool`, optional
993 Does the data need to be transposed before display?
994 """
995 import lsstDebug
996 if not lsstDebug.Info(__name__).display:
997 return
998 if not self.allowDebug:
999 return
1000
1001 calcImage = self.getImageArray(image)
1002 # CZW: Check that this is ok
1003 if isTransposed:
1004 calcImage = np.transpose(calcImage)
1005 masked = self.maskOutliers(calcImage)
1006 collapsed = self.collapseArray(masked, fillMasked=False)
1007
1008 num = len(collapsed)
1009 indices = 2.0 * np.arange(num)/float(num) - 1.0
1010 indices = np.arange(num)
1011
1012 if np.ma.is_masked(collapsed):
1013 collapsedMask = collapsed.mask
1014 else:
1015 collapsedMask = np.array(num*[np.ma.nomask])
1016
1017 import matplotlib.pyplot as plot
1018 figure = plot.figure(1)
1019 figure.clear()
1020 axes = figure.add_axes((0.1, 0.1, 0.8, 0.8))
1021 axes.plot(indices[~collapsedMask], collapsed[~collapsedMask], 'k+')
1022 if collapsedMask.sum() > 0:
1023 axes.plot(indices[collapsedMask], collapsed.data[collapsedMask], 'b+')
1024 if isinstance(model, np.ndarray):
1025 plotModel = model
1026 else:
1027 plotModel = np.zeros_like(indices)
1028 plotModel += model
1029
1030 axes.plot(indices, plotModel, 'r-')
1031 plot.xlabel("position along overscan region")
1032 plot.ylabel("pixel value/fit value")
1033 if amp:
1034 plot.title(f"{amp.getName()} DataX: "
1035 f"[{amp.getRawDataBBox().getBeginX()}:{amp.getRawBBox().getEndX()}]"
1036 f"OscanX: [{amp.getRawHorizontalOverscanBBox().getBeginX()}:"
1037 f"{amp.getRawHorizontalOverscanBBox().getEndX()}] {self.config.fitType}")
1038 else:
1039 plot.title("No amp supplied.")
1040 figure.show()
1041 prompt = "Press Enter or c to continue [chp]..."
1042 while True:
1043 ans = input(prompt).lower()
1044 if ans in ("", " ", "c",):
1045 break
1046 elif ans in ("p", ):
1047 import pdb
1048 pdb.set_trace()
1049 elif ans in ('x', ):
1050 self.allowDebug = False
1051 break
1052 elif ans in ("h", ):
1053 print("[h]elp [c]ontinue [p]db e[x]itDebug")
1054 plot.close()
1055
1056
1058 """Correction task for serial/parallel overscan.
1059
1060 (Will be deprecated)
1061
1062 This class contains a number of utilities that are easier to
1063 understand and use when they are not embedded in nested if/else
1064 loops.
1065
1066 Parameters
1067 ----------
1068 statControl : `lsst.afw.math.StatisticsControl`, optional
1069 Statistics control object.
1070 """
1071 ConfigClass = OverscanCorrectionTaskConfig
1072 _DefaultName = "overscan"
1073
1074 def run(self, exposure, amp, isTransposed=False):
1075 """Measure and remove serial/parallel overscan from an amplifier image.
1076
1077 This will be deprecated.
1078
1079 Parameters
1080 ----------
1081 exposure : `lsst.afw.image.Exposure`
1082 Image data that will have the overscan corrections applied.
1083 amp : `lsst.afw.cameraGeom.Amplifier`
1084 Amplifier to use for debugging purposes.
1085 isTransposed : `bool`, optional
1086 Is the image transposed, such that serial and parallel
1087 overscan regions are reversed? Default is False.
1088
1089 Returns
1090 -------
1091 overscanResults : `lsst.pipe.base.Struct`
1092 Result struct with components:
1093
1094 ``imageFit``
1095 Value or fit subtracted from the amplifier image data
1096 (scalar or `lsst.afw.image.Image`).
1097 ``overscanFit``
1098 Value or fit subtracted from the serial overscan image
1099 data (scalar or `lsst.afw.image.Image`).
1100 ``overscanImage``
1101 Image of the serial overscan region with the serial
1102 overscan correction applied
1103 (`lsst.afw.image.Image`). This quantity is used to
1104 estimate the amplifier read noise empirically.
1105 ``parallelOverscanFit``
1106 Value or fit subtracted from the parallel overscan
1107 image data (scalar, `lsst.afw.image.Image`, or None).
1108 ``parallelOverscanImage``
1109 Image of the parallel overscan region with the
1110 parallel overscan correction applied
1111 (`lsst.afw.image.Image` or None).
1112 ``overscanMean``
1113 Mean of the fit serial overscan region.
1114 This and the following values will be tuples of
1115 (serial, parallel) if doParallelOverscan=True.
1116 ``overscanMedian``
1117 Median of the fit serial overscan region.
1118 ``overscanSigma``
1119 Sigma of the fit serial overscan region.
1120 ``residualMean``
1121 Mean of the residual of the serial overscan region after
1122 correction.
1123 ``residualMedian``
1124 Median of the residual of the serial overscan region after
1125 correction.
1126 ``residualSigma``
1127 Mean of the residual of the serial overscan region after
1128 correction.
1129
1130
1131 Raises
1132 ------
1133 RuntimeError
1134 Raised if an invalid overscan type is set.
1135 """
1136 # Do Serial overscan first.
1137 serialOverscanBBox = amp.getRawSerialOverscanBBox()
1138 imageBBox = amp.getRawDataBBox()
1139
1140 if self.config.doParallelOverscan:
1141 # We need to extend the serial overscan BBox to the full
1142 # size of the detector.
1143 parallelOverscanBBox = amp.getRawParallelOverscanBBox()
1144 imageBBox = imageBBox.expandedTo(parallelOverscanBBox)
1145
1146 if isTransposed:
1147 serialOverscanBBox = geom.Box2I(
1148 geom.Point2I(serialOverscanBBox.getMinX(), imageBBox.getEndY()),
1149 geom.Extent2I(imageBBox.getWidth(), serialOverscanBBox.getHeight()),
1150 )
1151 else:
1152 serialOverscanBBox = geom.Box2I(
1153 geom.Point2I(serialOverscanBBox.getMinX(),
1154 imageBBox.getMinY()),
1155 geom.Extent2I(serialOverscanBBox.getWidth(),
1156 imageBBox.getHeight()),
1157 )
1158
1159 serialResults = self.correctOverscan(
1160 exposure,
1161 amp,
1162 imageBBox,
1163 serialOverscanBBox,
1164 isTransposed=isTransposed,
1165 leadingToSkip=self.config.leadingColumnsToSkip,
1166 trailingToSkip=self.config.trailingColumnsToSkip,
1167 )
1168 overscanMean = serialResults.overscanMean
1169 overscanMedian = serialResults.overscanMedian
1170 overscanSigma = serialResults.overscanSigma
1171 residualMean = serialResults.overscanMeanResidual
1172 residualMedian = serialResults.overscanMedianResidual
1173 residualSigma = serialResults.overscanSigmaResidual
1174
1175 # Do Parallel Overscan
1176 parallelResults = None
1177 if self.config.doParallelOverscan:
1178 # This does not need any extensions, as we'll only
1179 # subtract it from the data region.
1180 parallelOverscanBBox = amp.getRawParallelOverscanBBox()
1181 imageBBox = amp.getRawDataBBox()
1182
1183 # The serial overscan correction has removed some signal
1184 # from the parallel overscan region, but that is largely a
1185 # constant offset. The collapseArray method now attempts
1186 # to fill fully masked columns with the median of
1187 # neighboring values, with a fallback to the median of the
1188 # correction in all other columns. Filling with neighbor
1189 # values ensures that large variations in the parallel
1190 # overscan do not create new outlier points. The
1191 # MEDIAN_PER_ROW method does this filling as a separate
1192 # operation, using the same method.
1193 parallelResults = self.correctOverscan(
1194 exposure,
1195 amp,
1196 imageBBox,
1197 parallelOverscanBBox,
1198 isTransposed=not isTransposed,
1199 leadingToSkip=self.config.leadingRowsToSkip,
1200 trailingToSkip=self.config.trailingRowsToSkip,
1201 )
1202 overscanMean = (overscanMean, parallelResults.overscanMean)
1203 overscanMedian = (overscanMedian, parallelResults.overscanMedian)
1204 overscanSigma = (overscanSigma, parallelResults.overscanSigma)
1205 residualMean = (residualMean, parallelResults.overscanMeanResidual)
1206 residualMedian = (residualMedian, parallelResults.overscanMedianResidual)
1207 residualSigma = (residualSigma, parallelResults.overscanSigmaResidual)
1208
1209 parallelOverscanFit = parallelResults.overscanOverscanModel if parallelResults else None
1210 parallelOverscanImage = parallelResults.overscanImage if parallelResults else None
1211
1212 return pipeBase.Struct(imageFit=serialResults.ampOverscanModel,
1213 overscanFit=serialResults.overscanOverscanModel,
1214 overscanImage=serialResults.overscanImage,
1215
1216 parallelOverscanFit=parallelOverscanFit,
1217 parallelOverscanImage=parallelOverscanImage,
1218 overscanMean=overscanMean,
1219 overscanMedian=overscanMedian,
1220 overscanSigma=overscanSigma,
1221 residualMean=residualMean,
1222 residualMedian=residualMedian,
1223 residualSigma=residualSigma)
1224
1225
1227 leadingToSkip = pexConfig.Field(
1228 dtype=int,
1229 doc="Number of leading values to skip in serial overscan correction.",
1230 default=0,
1231 )
1232 trailingToSkip = pexConfig.Field(
1233 dtype=int,
1234 doc="Number of trailing values to skip in serial overscan correction.",
1235 default=0,
1236 )
1237
1238
1240 """Correction task for serial overscan.
1241
1242 Parameters
1243 ----------
1244 statControl : `lsst.afw.math.StatisticsControl`, optional
1245 Statistics control object.
1246 """
1247 ConfigClass = SerialOverscanCorrectionTaskConfig
1248 _DefaultName = "serialOverscan"
1249
1250 def run(self, exposure, amp, isTransposed=False):
1251 """Measure and remove serial overscan from an amplifier image.
1252
1253 Parameters
1254 ----------
1255 exposure : `lsst.afw.image.Exposure`
1256 Image data that will have the overscan corrections applied.
1257 amp : `lsst.afw.cameraGeom.Amplifier`
1258 Amplifier to use for debugging purposes.
1259 isTransposed : `bool`, optional
1260 Is the image transposed, such that serial and parallel
1261 overscan regions are reversed? Default is False.
1262
1263 Returns
1264 -------
1265 overscanResults : `lsst.pipe.base.Struct`
1266 Result struct with components:
1267
1268 ``imageFit``
1269 Value or fit subtracted from the amplifier image data
1270 (scalar or `lsst.afw.image.Image`).
1271 ``overscanFit``
1272 Value or fit subtracted from the serial overscan image
1273 data (scalar or `lsst.afw.image.Image`).
1274 ``overscanImage``
1275 Image of the serial overscan region with the serial
1276 overscan correction applied
1277 (`lsst.afw.image.Image`). This quantity is used to
1278 estimate the amplifier read noise empirically.
1279 ``overscanMean``
1280 Mean of the fit serial overscan region.
1281 ``overscanMedian``
1282 Median of the fit serial overscan region.
1283 ``overscanSigma``
1284 Sigma of the fit serial overscan region.
1285 ``residualMean``
1286 Mean of the residual of the serial overscan region after
1287 correction.
1288 ``residualMedian``
1289 Median of the residual of the serial overscan region after
1290 correction.
1291 ``residualSigma``
1292 Mean of the residual of the serial overscan region after
1293 correction.
1294
1295 Raises
1296 ------
1297 RuntimeError
1298 Raised if an invalid overscan type is set.
1299 """
1300 serialOverscanBBox = amp.getRawSerialOverscanBBox()
1301 imageBBox = amp.getRawDataBBox()
1302
1303 # We always want to extend the serial overscan bounding box to
1304 # the full size of the detector.
1305 parallelOverscanBBox = amp.getRawParallelOverscanBBox()
1306 imageBBox = imageBBox.expandedTo(parallelOverscanBBox)
1307
1308 if isTransposed:
1309 serialOverscanBBox = geom.Box2I(
1310 geom.Point2I(serialOverscanBBox.getMinX(), imageBBox.getEndY()),
1311 geom.Extent2I(imageBBox.getWidth(), serialOverscanBBox.getHeight()),
1312 )
1313 else:
1314 serialOverscanBBox = geom.Box2I(
1315 geom.Point2I(serialOverscanBBox.getMinX(),
1316 imageBBox.getMinY()),
1317 geom.Extent2I(serialOverscanBBox.getWidth(),
1318 imageBBox.getHeight()),
1319 )
1320
1321 results = self.correctOverscan(
1322 exposure,
1323 amp,
1324 imageBBox,
1325 serialOverscanBBox,
1326 isTransposed=isTransposed,
1327 leadingToSkip=self.config.leadingToSkip,
1328 trailingToSkip=self.config.trailingToSkip,
1329 )
1330 overscanMean = results.overscanMean
1331 overscanMedian = results.overscanMedian
1332 overscanSigma = results.overscanSigma
1333 residualMean = results.overscanMeanResidual
1334 residualMedian = results.overscanMedianResidual
1335 residualSigma = results.overscanSigmaResidual
1336 badRowsOrColumns = results.overscanBadRowsOrColumns
1337
1338 return pipeBase.Struct(
1339 imageFit=results.ampOverscanModel,
1340 overscanFit=results.overscanOverscanModel,
1341 overscanImage=results.overscanImage,
1342 overscanMean=overscanMean,
1343 overscanMedian=overscanMedian,
1344 overscanSigma=overscanSigma,
1345 residualMean=residualMean,
1346 residualMedian=residualMedian,
1347 residualSigma=residualSigma,
1348 overscanBadRowsOrColumns=badRowsOrColumns,
1349 )
1350
1351
1353 doParallelOverscanSaturation = pexConfig.Field(
1354 dtype=bool,
1355 doc="Mask saturated pixels in parallel overscan region?",
1356 default=True,
1357 )
1358 parallelOverscanSaturationLevel = pexConfig.Field(
1359 dtype=float,
1360 doc="The saturation level (adu) to use if not specified in call to "
1361 "maskParallelOverscanAmp. This should be low enough to capture "
1362 "all possible amplifiers for defect detection.",
1363 default=20000.,
1364 )
1365 parallelOverscanSaturationLevelAdjustmentFactor = pexConfig.Field(
1366 dtype=float,
1367 doc="The parallel overscan saturation level may be below that of "
1368 "the data region. This factor is applied to the amplifier "
1369 "saturation value when evaluating saturation in the parallel "
1370 "overscan region.",
1371 default=0.75,
1372 )
1373 parallelOverscanMaskGrowSize = pexConfig.Field(
1374 dtype=int,
1375 doc="Grow the SAT mask in the parallel overscan region by this many pixels. "
1376 "This value was determined from the ITL chip in the LATISS camera.",
1377 default=7,
1378 )
1379 parallelOverscanMaskedColumnGrowSize = pexConfig.Field(
1380 dtype=int,
1381 doc="When a full column is masked in the parallel overscan (at less "
1382 "than saturation) the mask should be grown by this many pixels. "
1383 "This value is determined from ITL chips in LATISS and LSSTCam.",
1384 default=2,
1385 )
1386 leadingToSkip = pexConfig.Field(
1387 dtype=int,
1388 doc="Number of leading values to skip in parallel overscan correction.",
1389 default=0,
1390 )
1391 trailingToSkip = pexConfig.Field(
1392 dtype=int,
1393 doc="Number of trailing values to skip in parallel overscan correction.",
1394 default=0,
1395 )
1396 parallelOverscanFraction = pexConfig.Field(
1397 dtype=float,
1398 doc="When the parallel overscan region median is greater than parallelOverscanFraction "
1399 "and the imaging region median is greater than parallelOverscanImageThreshold "
1400 "then parallel overscan subtraction will be turned off, as this is usually "
1401 "due to the region being flooded with spillover from a super-saturated flat.",
1402 default=0.5,
1403 )
1404 parallelOverscanImageThreshold = pexConfig.Field(
1405 dtype=float,
1406 doc="When the parallel overscan region median is greater than parallelOverscanFraction "
1407 "and the imaging region median is greater than parallelOverscanImageThreshold "
1408 "then parallel overscan subtraction will be turned off, as this is usually "
1409 "due to the region being flooded with spillover from a super-saturated flat.",
1410 default=10000.0,
1411 )
1412 doMedianSmoothingOutlierRejection = pexConfig.Field(
1413 dtype=bool,
1414 doc="Do column-by-column median smoothing outlier rejection? Columns that are rejected "
1415 "in this way will be grown by parallelOverscanMaskedColumnGrowSize.",
1416 default=True,
1417 )
1418 medianSmoothingKernel = pexConfig.Field(
1419 dtype=int,
1420 doc="Kernel (pixels) to use to smooth the parallel overscan columns. Must be odd.",
1421 default=5,
1422 check=lambda x: x // 2 != x / 2,
1423 )
1424 medianSmoothingOutlierThreshold = pexConfig.Field(
1425 dtype=float,
1426 doc="Outlier threshold after parallel median smoothing (adu). This is applied only "
1427 "to positive outliers.",
1428 default=5.0,
1429 check=lambda x: x > 0.0,
1430 )
1431
1432 def setDefaults(self):
1433 super().setDefaults()
1434
1435 # For parallel overscan, this should be a one-sided cut.
1437
1438
1440 """Correction task for parallel overscan.
1441
1442 Parameters
1443 ----------
1444 statControl : `lsst.afw.math.StatisticsControl`, optional
1445 Statistics control object.
1446 """
1447 ConfigClass = ParallelOverscanCorrectionTaskConfig
1448 _DefaultName = "parallelOverscan"
1449
1450 def run(self, exposure, amp, isTransposed=False):
1451 """Measure and remove parallel overscan from an amplifier image.
1452
1453 This method assumes that serial overscan has already been
1454 removed from the amplifier.
1455
1456 Parameters
1457 ----------
1458 exposure : `lsst.afw.image.Exposure`
1459 Image data that will have the overscan corrections applied.
1460 amp : `lsst.afw.cameraGeom.Amplifier`
1461 Amplifier to use for debugging purposes.
1462 isTransposed : `bool`, optional
1463 Is the image transposed, such that serial and parallel
1464 overscan regions are reversed? Default is False.
1465
1466 Returns
1467 -------
1468 overscanResults : `lsst.pipe.base.Struct`
1469 Result struct with components:
1470
1471 ``imageFit``
1472 Value or fit subtracted from the amplifier image data
1473 (scalar or `lsst.afw.image.Image`).
1474 ``overscanFit``
1475 Value or fit subtracted from the parallel overscan image
1476 data (scalar or `lsst.afw.image.Image`).
1477 ``overscanImage``
1478 Image of the parallel overscan region with the parallel
1479 overscan correction applied
1480 (`lsst.afw.image.Image`). This quantity is used to
1481 estimate the amplifier read noise empirically.
1482 ``overscanMean``
1483 Mean of the fit parallel overscan region.
1484 ``overscanMedian``
1485 Median of the fit parallel overscan region.
1486 ``overscanSigma``
1487 Sigma of the fit parallel overscan region.
1488 ``residualMean``
1489 Mean of the residual of the parallel overscan region after
1490 correction.
1491 ``residualMedian``
1492 Median of the residual of the parallel overscan region after
1493 correction.
1494 ``residualSigma``
1495 Mean of the residual of the parallel overscan region after
1496 correction.
1497
1498 Raises
1499 ------
1500 RuntimeError
1501 Raised if an invalid overscan type is set.
1502 """
1503 # This does not need any extending, as we only subtract
1504 # from the data region.
1505 parallelOverscanBBox = amp.getRawParallelOverscanBBox()
1506 imageBBox = amp.getRawDataBBox()
1507
1508 medianSmoothingKernel = self.config.medianSmoothingKernel if \
1509 self.config.doMedianSmoothingOutlierRejection else 0
1510
1511 # The serial overscan correction has removed some signal
1512 # from the parallel overscan region, but that is largely a
1513 # constant offset. The collapseArray method now attempts
1514 # to fill fully masked columns with the median of
1515 # neighboring values, with a fallback to the median of the
1516 # correction in all other columns. Filling with neighbor
1517 # values ensures that large variations in the parallel
1518 # overscan do not create new outlier points. The
1519 # MEDIAN_PER_ROW method does this filling as a separate
1520 # operation, using the same method.
1521 results = self.correctOverscan(
1522 exposure,
1523 amp,
1524 imageBBox,
1525 parallelOverscanBBox,
1526 isTransposed=not isTransposed,
1527 leadingToSkip=self.config.leadingToSkip,
1528 trailingToSkip=self.config.trailingToSkip,
1529 overscanFraction=self.config.parallelOverscanFraction,
1530 imageThreshold=self.config.parallelOverscanImageThreshold,
1531 maskedRowColumnGrowSize=self.config.parallelOverscanMaskedColumnGrowSize,
1532 medianSmoothingKernel=medianSmoothingKernel,
1533 medianSmoothingOutlierThreshold=self.config.medianSmoothingOutlierThreshold,
1534 )
1535 overscanMean = results.overscanMean
1536 overscanMedian = results.overscanMedian
1537 overscanSigma = results.overscanSigma
1538 residualMean = results.overscanMeanResidual
1539 residualMedian = results.overscanMedianResidual
1540 residualSigma = results.overscanSigmaResidual
1541 badRowsOrColumns = results.overscanBadRowsOrColumns
1542
1543 return pipeBase.Struct(
1544 imageFit=results.ampOverscanModel,
1545 overscanFit=results.overscanOverscanModel,
1546 overscanImage=results.overscanImage,
1547 overscanMean=overscanMean,
1548 overscanMedian=overscanMedian,
1549 overscanSigma=overscanSigma,
1550 residualMean=residualMean,
1551 residualMedian=residualMedian,
1552 residualSigma=residualSigma,
1553 badRowsOrColumns=badRowsOrColumns,
1554 )
1555
1556 def maskParallelOverscanAmp(self, exposure, amp, saturationLevel=None):
1557 """Mask parallel overscan, growing saturated pixels.
1558
1559 This operates on the image in-place.
1560
1561 Parameters
1562 ----------
1563 exposure : `lsst.afw.image.Exposure`
1564 An untrimmed raw exposure.
1565 amp : `lsst.afw.cameraGeom.Amplifier`
1566 The amplifier to use for masking.
1567 saturationLevel : `float`, optional
1568 Saturation level to use for masking.
1569 """
1570 if not self.config.doParallelOverscanSaturation:
1571 # This is a no-op.
1572 return
1573
1574 if saturationLevel is None:
1575 saturationLevel = self.config.parallelOverscanSaturationLevel
1576
1577 dataView = afwImage.MaskedImageF(exposure.getMaskedImage(),
1578 amp.getRawParallelOverscanBBox(),
1579 afwImage.PARENT)
1580 # This should mark all of these saturated pixels as SAT.
1582 maskedImage=dataView,
1583 threshold=saturationLevel,
1584 growFootprints=self.config.parallelOverscanMaskGrowSize,
1585 maskName="SAT",
1586 )
debugView(self, image, model, amp=None, isTransposed=True)
Definition overscan.py:981
fitOverscan(self, overscanImage, isTransposed=False)
Definition overscan.py:594
collapseArray(self, maskedArray, fillMasked=True)
Definition overscan.py:777
trimOverscan(self, exposure, amp, bbox, skipLeading, skipTrailing, transpose=False)
Definition overscan.py:547
maskParallelOverscan(self, exposure, detector)
Definition overscan.py:624
broadcastFitToImage(self, overscanValue, imageArray, transpose=False)
Definition overscan.py:497
correctOverscan(self, exposure, amp, imageBBox, overscanBBox, isTransposed=True, leadingToSkip=0, trailingToSkip=0, overscanFraction=1.0, imageThreshold=np.inf, maskedRowColumnGrowSize=0, medianSmoothingKernel=0, medianSmoothingOutlierThreshold=np.inf)
Definition overscan.py:312
splineFit(self, indices, collapsed, numBins)
Definition overscan.py:800
run(self, exposure, amp, isTransposed=False)
Definition overscan.py:164
__init__(self, statControl=None, **kwargs)
Definition overscan.py:153
measureVectorOverscan(self, image, isTransposed=False)
Definition overscan.py:894
_maskRowsOrColumns(exposure, overscanBBox, overscanMaskedImage, overscanMask, maxDeviation, maskedRowColumnGrowSize, medianSmoothingKernel, medianSmoothingOutlierThreshold, doAbsoluteMaxDeviation, isTransposed)
Definition overscan.py:179
run(self, exposure, amp, isTransposed=False)
Definition overscan.py:1074
maskParallelOverscanAmp(self, exposure, amp, saturationLevel=None)
Definition overscan.py:1556
run(self, exposure, amp, isTransposed=False)
Definition overscan.py:1450
run(self, exposure, amp, isTransposed=False)
Definition overscan.py:1250
makeThresholdMask(maskedImage, threshold, growFootprints=1, maskName='SAT')
std::vector< double > fitOverscanImageMean(lsst::afw::image::MaskedImage< ImagePixelT > const &overscan, std::vector< std::string > badPixelMask, bool isTransposed)
Definition Isr.cc:99
std::vector< double > fitOverscanImage(lsst::afw::image::MaskedImage< ImagePixelT > const &overscan, std::vector< std::string > badPixelMask, bool isTransposed)
Definition Isr.cc:53